answer stringlengths 17 10.2M |
|---|
package nl.fixx.asset.data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@SpringBootApplication
@EnableGlobalMethodSecurity
@ComponentScan(basePackages = "nl.fixx.asset.data")
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
System.getProperties().put("server.port", 8085);
SpringApplication.run(Application.class, args);
}
} |
package org.cojen.tupl.repl;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Consumer;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.function.LongConsumer;
import org.cojen.tupl.util.Latch;
import static org.cojen.tupl.io.Utils.*;
/**
*
*
* @author Brian S O'Neill
*/
final class Controller extends Latch implements StreamReplicator, Channel {
private static final int ROLE_FOLLOWER = 0, ROLE_CANDIDATE = 1, ROLE_LEADER = 2;
private static final int ELECTION_DELAY_LOW_MILLIS = 200, ELECTION_DELAY_HIGH_MILLIS = 300;
private static final int QUERY_TERMS_RATE_MILLIS = 1;
private static final int MISSING_DELAY_LOW_MILLIS = 400, MISSING_DELAY_HIGH_MILLIS = 600;
private static final int MISSING_DATA_REQUEST_SIZE = 100_000;
private final Scheduler mScheduler;
private final ChannelManager mChanMan;
private final StateLog mStateLog;
private int mLocalRole;
private Peer[] mPeers;
private Channel[] mPeerChannels;
private long mCurrentTerm;
private long mVotedFor;
private int mGrantsRemaining;
private int mElectionValidated;
private LogWriter mLeaderLogWriter;
private ReplWriter mLeaderReplWriter;
// Index used to check for missing data.
private long mMissingContigIndex = Long.MAX_VALUE; // unknown initially
private boolean mSkipMissingDataTask;
private volatile boolean mReceivingMissingData;
// Limit the rate at which missing terms are queried.
private volatile long mNextQueryTermTime = Long.MIN_VALUE;
Controller(StateLog log, long groupId) {
mStateLog = log;
mScheduler = new Scheduler();
mChanMan = new ChannelManager(mScheduler, groupId);
}
/**
* @param localSocket optional; used for testing
*/
void init(Map<Long, SocketAddress> members, long localMemberId, ServerSocket localSocket)
throws IOException
{
acquireExclusive();
try {
Peer[] peers = new Peer[members.size() - 1];
Channel[] peerChannels = new Channel[peers.length];
if (localSocket == null) {
mChanMan.setLocalMemberId(localMemberId, members.get(localMemberId));
} else {
mChanMan.setLocalMemberId(localMemberId, localSocket);
}
int i = 0;
for (Map.Entry<Long, SocketAddress> e : members.entrySet()) {
long memberId = e.getKey();
if (memberId != localMemberId) {
Peer peer = new Peer(memberId, e.getValue());
peers[i] = peer;
peerChannels[i] = mChanMan.connect(peer, this);
i++;
}
}
mPeers = peers;
mPeerChannels = peerChannels;
} finally {
releaseExclusive();
}
scheduleElectionTask();
scheduleMissingDataTask();
}
@Override
public void start(long index) throws IOException {
if (index < 0) {
throw new IllegalArgumentException("Start index: " + index);
}
long commitIndex = mStateLog.captureHighest().mCommitIndex;
if (index > commitIndex) {
throw new IllegalArgumentException
("Cannot start higher than the commit index: " + index + " > " + commitIndex);
}
// FIXME: do something with index
mChanMan.start(this);
}
@Override
public Reader newReader(long index, boolean follow) {
if (follow) {
return mStateLog.openReader(index);
}
acquireShared();
try {
Reader reader;
if (mLeaderLogWriter != null
&& index >= mLeaderLogWriter.termStartIndex()
&& index < mLeaderLogWriter.termEndIndex())
{
reader = null;
} else {
reader = mStateLog.openReader(index);
}
return reader;
} finally {
releaseShared();
}
}
@Override
public Writer newWriter() {
return createWriter(-1);
}
@Override
public Writer newWriter(long index) {
if (index < 0) {
throw new IllegalArgumentException();
}
return createWriter(index);
}
private Writer createWriter(long index) {
acquireExclusive();
try {
if (mLeaderReplWriter != null) {
throw new IllegalStateException("Writer already exists");
}
if (mLeaderLogWriter == null || (index >= 0 && index != mLeaderLogWriter.index())) {
return null;
}
ReplWriter writer = new ReplWriter(mLeaderLogWriter, mPeerChannels);
mLeaderReplWriter = writer;
return writer;
} finally {
releaseExclusive();
}
}
void writerClosed(ReplWriter writer) {
acquireExclusive();
if (mLeaderReplWriter == writer) {
mLeaderReplWriter = null;
}
releaseExclusive();
}
@Override
public void sync() throws IOException {
mStateLog.sync();
}
@Override
public long getLocalMemberId() {
return mChanMan.getLocalMemberId();
}
@Override
public SocketAddress getLocalAddress() {
return mChanMan.getLocalAddress();
}
@Override
public Socket connect(SocketAddress addr) throws IOException {
return mChanMan.connectPlain(addr);
}
@Override
public void socketAcceptor(Consumer<Socket> acceptor) {
mChanMan.socketAcceptor(acceptor);
}
@Override
public SnapshotReceiver requestSnapshot(Map<String, String> options) throws IOException {
// FIXME
throw null;
}
@Override
public void snapshotRequestAcceptor(Consumer<SnapshotSender> acceptor) {
// FIXME
throw null;
}
class ReplWriter implements Writer {
private final LogWriter mWriter;
private Channel[] mPeerChannels;
ReplWriter(LogWriter writer, Channel[] peerChannels) {
mWriter = writer;
mPeerChannels = peerChannels;
}
@Override
public long term() {
return mWriter.term();
}
@Override
public long termStartIndex() {
return mWriter.termStartIndex();
}
@Override
public long termEndIndex() {
return mWriter.termEndIndex();
}
@Override
public long index() {
return mWriter.index();
}
@Override
public int write(byte[] data, int offset, int length, long highestIndex)
throws IOException
{
Channel[] peerChannels;
long prevTerm, term, index, commitIndex;
int amt;
synchronized (this) {
peerChannels = mPeerChannels;
if (peerChannels == null) {
return -1;
}
LogWriter writer = mWriter;
index = writer.index();
amt = writer.write(data, offset, length, highestIndex);
if (amt <= 0) {
if (length > 0) {
mPeerChannels = null;
}
return amt;
}
mStateLog.captureHighest(writer);
highestIndex = writer.mHighestIndex;
if (peerChannels.length == 0) {
// Only a group of one, so commit changes immediately.
mStateLog.commit(highestIndex);
return amt;
}
prevTerm = writer.prevTerm();
term = writer.term();
commitIndex = writer.mCommitIndex;
}
// FIXME: stream it
data = Arrays.copyOfRange(data, offset, offset + length);
for (Channel peerChan : peerChannels) {
peerChan.writeData(null, prevTerm, term, index, highestIndex, commitIndex, data);
}
return amt;
}
@Override
public long waitForCommit(long index, long nanosTimeout) throws InterruptedIOException {
return mWriter.waitForCommit(index, nanosTimeout);
}
@Override
public void uponCommit(long index, LongConsumer task) {
mWriter.uponCommit(index, task);
}
@Override
public void close() {
mWriter.close();
writerClosed(this);
}
@Override
public synchronized boolean isDeactivated() {
return mPeerChannels == null;
}
synchronized void deactivate() {
mPeerChannels = null;
}
}
@Override
public void close() throws IOException {
mChanMan.stop();
mScheduler.shutdown();
mStateLog.close();
}
private void scheduleMissingDataTask() {
int delayMillis = ThreadLocalRandom.current()
.nextInt(MISSING_DELAY_LOW_MILLIS, MISSING_DELAY_HIGH_MILLIS);
mScheduler.schedule(this::missingDataTask, delayMillis);
}
private void missingDataTask() {
if (tryAcquireShared()) {
if (mLocalRole == ROLE_LEADER) {
// Leader doesn't need to check for missing data.
mMissingContigIndex = Long.MAX_VALUE; // reset to unknown
mSkipMissingDataTask = true;
releaseShared();
return;
}
releaseShared();
}
if (mReceivingMissingData) {
// Avoid overlapping requests for missing data if results are flowing in.
mReceivingMissingData = false;
}
class Collector implements IndexRange {
long[] mRanges;
int mSize;
@Override
public void range(long startIndex, long endIndex) {
if (mRanges == null) {
mRanges = new long[16];
} else if (mSize >= mRanges.length) {
mRanges = Arrays.copyOf(mRanges, mRanges.length << 1);
}
mRanges[mSize++] = startIndex;
mRanges[mSize++] = endIndex;
}
};
Collector collector = new Collector();
mMissingContigIndex = mStateLog.checkForMissingData(mMissingContigIndex, collector);
for (int i=0; i<collector.mSize; ) {
long startIndex = collector.mRanges[i++];
long endIndex = collector.mRanges[i++];
requestMissingData(startIndex, endIndex);
}
scheduleMissingDataTask();
}
private void requestMissingData(long startIndex, long endIndex) {
// FIXME: Need a way to abort outstanding requests.
System.out.println("must call queryData! " + startIndex + ".." + endIndex);
long remaining = endIndex - startIndex;
// Distribute the request among the channels at random.
ThreadLocalRandom rnd = ThreadLocalRandom.current();
acquireShared();
Channel[] channels = mPeerChannels;
releaseShared();
doRequestData: while (remaining > 0) {
long amt = Math.min(remaining, MISSING_DATA_REQUEST_SIZE);
int selected = rnd.nextInt(channels.length);
int attempts = 0;
while (true) {
Channel channel = channels[selected];
if (channel.queryData(this, startIndex, startIndex + amt)) {
break;
}
// Peer not available, so try another.
if (++attempts >= channels.length) {
// Attempted all peers, and none are available.
break doRequestData;
}
selected++;
if (selected >= channels.length) {
selected = 0;
}
}
startIndex += amt;
remaining -= amt;
}
}
private void scheduleElectionTask() {
int delayMillis = ThreadLocalRandom.current()
.nextInt(ELECTION_DELAY_LOW_MILLIS, ELECTION_DELAY_HIGH_MILLIS);
mScheduler.schedule(this::electionTask, delayMillis);
}
private void electionTask() {
try {
doElectionTask();
} finally {
scheduleElectionTask();
}
}
private void doElectionTask() {
Channel[] peerChannels;
long term, candidateId;
LogInfo info = new LogInfo();
acquireExclusive();
try {
if (mLocalRole == ROLE_LEADER) {
// FIXME: If commit index is lagging behind and not moving, switch to follower.
// This isn't in the Raft algorithm, but it really should be.
affirmLeadership();
return;
}
if (mLocalRole == ROLE_CANDIDATE) {
// Abort current election and start a new one.
toFollower();
}
if (mElectionValidated >= 0) {
// Current leader is still active, so don't start an election yet.
mElectionValidated
releaseExclusive();
return;
}
// Convert to candidate.
// FIXME: Don't permit rogue members to steal leadership if process is
// suspended. Need to double check against local clock to detect this. Or perhaps
// check with peers to see if leader is up.
mLocalRole = ROLE_CANDIDATE;
peerChannels = mPeerChannels;
mStateLog.captureHighest(info);
try {
mCurrentTerm = term = mStateLog.incrementCurrentTerm(1);
} catch (IOException e) {
releaseExclusive();
uncaught(e);
return;
}
candidateId = mChanMan.getLocalMemberId();
mVotedFor = candidateId;
// Only need a majority of vote grants (already voted for self).
mGrantsRemaining = (peerChannels.length + 1) / 2;
} catch (Throwable e) {
releaseExclusive();
throw e;
}
if (mGrantsRemaining == 0) {
// Only a group of one, so become leader immediately.
toLeader(term, info.mHighestIndex);
} else {
releaseExclusive();
for (Channel peerChan : peerChannels) {
peerChan.requestVote(null, term, candidateId, info.mTerm, info.mHighestIndex);
}
}
}
// Caller must acquire exclusive latch, which is released by this method.
private void affirmLeadership() {
Channel[] peerChannels = mPeerChannels;
LogWriter writer = mLeaderLogWriter;
releaseExclusive();
if (writer == null) {
// Not leader anymore.
return;
}
long prevTerm = writer.prevTerm();
long term = writer.term();
long index = writer.index();
mStateLog.captureHighest(writer);
long highestIndex = writer.mHighestIndex;
long commitIndex = writer.mCommitIndex;
// FIXME: use a custom command
// FIXME: ... or use standard client write method
byte[] EMPTY_DATA = new byte[0];
for (Channel peerChan : peerChannels) {
peerChan.writeData(null, prevTerm, term, index, highestIndex, commitIndex, EMPTY_DATA);
}
}
// Caller must hold exclusive latch.
private void toFollower() {
final int originalRole = mLocalRole;
if (originalRole != ROLE_FOLLOWER) {
System.out.println("follower: " + mCurrentTerm);
mLocalRole = ROLE_FOLLOWER;
mVotedFor = 0;
mGrantsRemaining = 0;
if (mLeaderLogWriter != null) {
mLeaderLogWriter.release();
mLeaderLogWriter = null;
}
if (mLeaderReplWriter != null) {
mLeaderReplWriter.deactivate();
}
if (originalRole == ROLE_LEADER && mSkipMissingDataTask) {
mSkipMissingDataTask = false;
scheduleMissingDataTask();
}
}
}
@Override
public boolean nop(Channel from) {
return true;
}
@Override
public boolean requestVote(Channel from, long term, long candidateId,
long highestTerm, long highestIndex)
{
long currentTerm;
acquireExclusive();
try {
final long originalTerm = mCurrentTerm;
try {
mCurrentTerm = currentTerm = mStateLog.checkCurrentTerm(term);
} catch (IOException e) {
uncaught(e);
return false;
}
if (currentTerm > originalTerm) {
toFollower();
}
if (currentTerm >= originalTerm
&& ((mVotedFor == 0 || mVotedFor == candidateId)
&& !isBehind(highestTerm, highestIndex)))
{
mVotedFor = candidateId;
// Set voteGranted result bit to true.
currentTerm |= 1L << 63;
mElectionValidated = 1;
}
} finally {
releaseExclusive();
}
from.requestVoteReply(null, currentTerm);
return true;
}
private boolean isBehind(long term, long index) {
LogInfo info = mStateLog.captureHighest();
return term < info.mTerm || (term == info.mTerm && index < info.mHighestIndex);
}
@Override
public boolean requestVoteReply(Channel from, long term) {
acquireExclusive();
final long originalTerm = mCurrentTerm;
if (term < 0 && (term &= ~(1L << 63)) == originalTerm) {
// Vote granted.
if (--mGrantsRemaining > 0 || mLocalRole != ROLE_CANDIDATE) {
// Majority not received yet, or voting is over.
releaseExclusive();
return true;
}
if (mLocalRole == ROLE_CANDIDATE) {
LogInfo info = mStateLog.captureHighest();
toLeader(term, info.mHighestIndex);
return true;
}
} else {
// Vote denied.
try {
mCurrentTerm = mStateLog.checkCurrentTerm(term);
} catch (IOException e) {
releaseExclusive();
uncaught(e);
return false;
}
if (mCurrentTerm <= originalTerm) {
// Remain candidate for now, waiting for more votes.
releaseExclusive();
return true;
}
}
toFollower();
releaseExclusive();
return true;
}
// Caller must acquire exclusive latch, which is released by this method.
private void toLeader(long term, long index) {
try {
System.out.println("leader: " + term + ", " + index);
mLeaderLogWriter = mStateLog.openWriter(0, term, index);
mLocalRole = ROLE_LEADER;
for (Channel channel : mPeerChannels) {
channel.peer().mMatchIndex = 0;
}
} catch (Throwable e) {
releaseExclusive();
uncaught(e);
}
affirmLeadership();
}
@Override
public boolean queryTerms(Channel from, long startIndex, long endIndex) {
mStateLog.queryTerms(startIndex, endIndex, (prevTerm, term, index) -> {
from.queryTermsReply(null, prevTerm, term, index);
});
return true;
}
@Override
public boolean queryTermsReply(Channel from, long prevTerm, long term, long startIndex) {
try {
queryReplyTermCheck(term);
mStateLog.defineTerm(prevTerm, term, startIndex);
} catch (IOException e) {
uncaught(e);
}
return true;
}
/**
* Term check to apply when receiving results from a query. Forces a conversion to follower
* if necessary, although leaders don't issue queries.
*/
private void queryReplyTermCheck(long term) throws IOException {
acquireShared();
long originalTerm = mCurrentTerm;
if (term < originalTerm) {
releaseShared();
return;
}
if (!tryUpgrade()) {
releaseShared();
acquireExclusive();
originalTerm = mCurrentTerm;
}
try {
if (term > originalTerm) {
mCurrentTerm = mStateLog.checkCurrentTerm(term);
if (mCurrentTerm > originalTerm) {
toFollower();
}
}
} finally {
releaseExclusive();
}
}
@Override
public boolean queryData(Channel from, long startIndex, long endIndex) {
if (endIndex <= startIndex) {
return true;
}
try {
LogReader reader = mStateLog.openReader(startIndex);
try {
long remaining = endIndex - startIndex;
byte[] buf = new byte[(int) Math.min(9000, remaining)];
while (true) {
long prevTerm = reader.prevTerm();
long index = reader.index();
long term = reader.term();
int amt = reader.readAny(buf, 0, (int) Math.min(buf.length, remaining));
if (amt <= 0) {
if (amt < 0) {
// Move to next term.
reader.release();
reader = mStateLog.openReader(startIndex);
}
break;
}
// FIXME: stream it
byte[] data = new byte[amt];
System.arraycopy(buf, 0, data, 0, amt);
from.queryDataReply(null, prevTerm, term, index, data);
startIndex += amt;
remaining -= amt;
if (remaining <= 0) {
break;
}
}
} finally {
reader.release();
}
} catch (IOException e) {
uncaught(e);
}
return true;
}
@Override
public boolean queryDataReply(Channel from, long prevTerm, long term,
long index, byte[] data)
{
mReceivingMissingData = true;
try {
queryReplyTermCheck(term);
LogWriter writer = mStateLog.openWriter(prevTerm, term, index);
if (writer != null) {
try {
writer.write(data, 0, data.length, 0);
} finally {
writer.release();
}
}
} catch (IOException e) {
uncaught(e);
}
return true;
}
@Override
public boolean writeData(Channel from, long prevTerm, long term, long index,
long highestIndex, long commitIndex, byte[] data)
{
checkTerm: {
acquireShared();
long originalTerm = mCurrentTerm;
if (term == originalTerm) {
if (mElectionValidated > 0) {
releaseShared();
break checkTerm;
} else if (tryUpgrade()) {
mElectionValidated = 1;
releaseExclusive();
break checkTerm;
}
}
if (!tryUpgrade()) {
releaseShared();
acquireExclusive();
originalTerm = mCurrentTerm;
}
try {
if (term == originalTerm) {
mElectionValidated = 1;
} else {
try {
mCurrentTerm = mStateLog.checkCurrentTerm(term);
} catch (IOException e) {
uncaught(e);
return false;
}
if (mCurrentTerm > originalTerm) {
toFollower();
}
}
} finally {
releaseExclusive();
}
}
try {
LogWriter writer = mStateLog.openWriter(prevTerm, term, index);
if (writer == null) {
// FIXME: stash the write for later
// Cannot write because terms are missing, so request them.
long now = System.currentTimeMillis();
if (now >= mNextQueryTermTime) {
LogInfo info = mStateLog.captureHighest();
if (highestIndex > info.mCommitIndex && index > info.mCommitIndex) {
from.queryTerms(null, info.mCommitIndex, index);
}
mNextQueryTermTime = now + QUERY_TERMS_RATE_MILLIS;
}
return true;
}
try {
writer.write(data, 0, data.length, highestIndex);
mStateLog.commit(commitIndex);
mStateLog.captureHighest(writer);
long highestTerm = writer.mTerm;
if (highestTerm < term) {
// If the highest term is lower than the leader's, don't bother reporting
// it. The leader will just reject the reply.
return true;
}
term = highestTerm;
highestIndex = writer.mHighestIndex;
} finally {
writer.release();
}
} catch (IOException e) {
uncaught(e);
}
// TODO: can skip reply if successful and highest didn't change
from.writeDataReply(null, term, highestIndex);
return true;
}
@Override
public boolean writeDataReply(Channel from, long term, long highestIndex) {
LogWriter writer;
long commitIndex;
acquireExclusive();
try {
if (mLocalRole != ROLE_LEADER) {
return true;
}
final long originalTerm = mCurrentTerm;
if (term != originalTerm) {
try {
mCurrentTerm = mStateLog.checkCurrentTerm(term);
} catch (IOException e) {
uncaught(e);
return false;
}
if (mCurrentTerm > originalTerm) {
toFollower();
} else {
// Cannot commit on behalf of older terms.
}
return true;
}
Peer peer = from.peer();
long matchIndex = peer.mMatchIndex;
if (highestIndex <= matchIndex) {
return true;
}
// Updating and sorting the peers by match index is simple, but for large groups
// (>10?), a tree data structure should be used instead.
peer.mMatchIndex = highestIndex;
Arrays.sort(mPeers);
commitIndex = mPeers[mPeers.length >> 1].mMatchIndex;
} finally {
releaseExclusive();
}
mStateLog.commit(commitIndex);
return true;
}
} |
package org.dynmap.bukkit;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.world.ChunkPopulateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
import org.dynmap.DynmapAPI;
import org.dynmap.DynmapChunk;
import org.dynmap.DynmapCommonAPIListener;
import org.dynmap.DynmapCore;
import org.dynmap.DynmapLocation;
import org.dynmap.DynmapWebChatEvent;
import org.dynmap.DynmapWorld;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.MapType;
import org.dynmap.PlayerList;
import org.dynmap.bukkit.permissions.BukkitPermissions;
import org.dynmap.bukkit.permissions.NijikokunPermissions;
import org.dynmap.bukkit.permissions.OpPermissions;
import org.dynmap.bukkit.permissions.PEXPermissions;
import org.dynmap.bukkit.permissions.PermBukkitPermissions;
import org.dynmap.bukkit.permissions.GroupManagerPermissions;
import org.dynmap.bukkit.permissions.PermissionProvider;
import org.dynmap.bukkit.permissions.bPermPermissions;
import org.dynmap.common.BiomeMap;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.common.DynmapServerInterface;
import org.dynmap.common.DynmapListenerManager.EventType;
import org.dynmap.hdmap.HDMap;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.modsupport.ModSupportImpl;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.VisibilityLimit;
public class DynmapPlugin extends JavaPlugin implements DynmapAPI {
private DynmapCore core;
private PermissionProvider permissions;
private String version;
public SnapshotCache sscache;
private boolean has_spout = false;
public PlayerList playerList;
private MapManager mapManager;
public static DynmapPlugin plugin;
public SpoutPluginBlocks spb;
public PluginManager pm;
private Metrics metrics;
private BukkitEnableCoreCallback enabCoreCB = new BukkitEnableCoreCallback();
private Method ismodloaded;
private Method instance;
private Method getindexedmodlist;
private Method getversion;
private HashMap<String, BukkitWorld> world_by_name = new HashMap<String, BukkitWorld>();
private HashSet<String> modsused = new HashSet<String>();
// TPS calculator
private double tps;
private long lasttick;
private long perTickLimit;
private long cur_tick_starttime;
private long avgticklen = 50000000;
private int chunks_in_cur_tick = 0;
private long cur_tick;
private long prev_tick;
private HashMap<String, Integer> sortWeights = new HashMap<String, Integer>();
/* Lookup cache */
private World last_world;
private BukkitWorld last_bworld;
private BukkitVersionHelper helper;
private final BukkitWorld getWorldByName(String name) {
if((last_world != null) && (last_world.getName().equals(name))) {
return last_bworld;
}
return world_by_name.get(name);
}
private final BukkitWorld getWorld(World w) {
if(last_world == w) {
return last_bworld;
}
BukkitWorld bw = world_by_name.get(w.getName());
if(bw == null) {
bw = new BukkitWorld(w);
world_by_name.put(w.getName(), bw);
}
else if(bw.isLoaded() == false) {
bw.setWorldLoaded(w);
}
last_world = w;
last_bworld = bw;
return bw;
}
final void removeWorld(World w) {
world_by_name.remove(w.getName());
if(w == last_world) {
last_world = null;
last_bworld = null;
}
}
private class BukkitEnableCoreCallback extends DynmapCore.EnableCoreCallbacks {
@Override
public void configurationLoaded() {
/* Check for Spout */
if(detectSpout()) {
if(core.configuration.getBoolean("spout/enabled", true)) {
has_spout = true;
Log.info("Detected Spout");
if(spb == null) {
spb = new SpoutPluginBlocks(DynmapPlugin.this);
}
modsused.add("SpoutPlugin");
}
else {
Log.info("Detected Spout - Support Disabled");
}
}
if(!has_spout) { /* If not, clean up old spout texture, if needed */
File st = new File(core.getDataFolder(), "renderdata/spout-texture.txt");
if(st.exists())
st.delete();
}
}
}
private static class BlockToCheck {
Location loc;
int typeid;
byte data;
String trigger;
};
private LinkedList<BlockToCheck> blocks_to_check = null;
private LinkedList<BlockToCheck> blocks_to_check_accum = new LinkedList<BlockToCheck>();
public DynmapPlugin() {
plugin = this;
try {
Class<?> c = Class.forName("cpw.mods.fml.common.Loader");
ismodloaded = c.getMethod("isModLoaded", String.class);
instance = c.getMethod("instance");
getindexedmodlist = c.getMethod("getIndexedModList");
c = Class.forName("cpw.mods.fml.common.ModContainer");
getversion = c.getMethod("getVersion");
} catch (NoSuchMethodException nsmx) {
} catch (ClassNotFoundException e) {
}
}
/**
* Server access abstraction class
*/
public class BukkitServer implements DynmapServerInterface {
/* Chunk load handling */
private Object loadlock = new Object();
@Override
public int getBlockIDAt(String wname, int x, int y, int z) {
World w = getServer().getWorld(wname);
if((w != null) && w.isChunkLoaded(x >> 4, z >> 4)) {
return w.getBlockTypeIdAt(x, y, z);
}
return -1;
}
@Override
public void scheduleServerTask(Runnable run, long delay) {
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay);
}
@Override
public DynmapPlayer[] getOnlinePlayers() {
Player[] players = getServer().getOnlinePlayers();
DynmapPlayer[] dplay = new DynmapPlayer[players.length];
for(int i = 0; i < players.length; i++)
dplay[i] = new BukkitPlayer(players[i]);
return dplay;
}
@Override
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.disablePlugin(DynmapPlugin.this);
pluginManager.enablePlugin(DynmapPlugin.this);
}
@Override
public DynmapPlayer getPlayer(String name) {
Player p = getServer().getPlayerExact(name);
if(p != null) {
return new BukkitPlayer(p);
}
return null;
}
@Override
public Set<String> getIPBans() {
return getServer().getIPBans();
}
@Override
public <T> Future<T> callSyncMethod(Callable<T> task) {
if(DynmapPlugin.this.isEnabled())
return getServer().getScheduler().callSyncMethod(DynmapPlugin.this, task);
else
return null;
}
@Override
public String getServerName() {
return getServer().getServerName();
}
@Override
public boolean isPlayerBanned(String pid) {
OfflinePlayer p = getServer().getOfflinePlayer(pid);
if((p != null) && p.isBanned())
return true;
return false;
}
@Override
public String stripChatColor(String s) {
return ChatColor.stripColor(s);
}
private Set<EventType> registered = new HashSet<EventType>();
@Override
public boolean requestEventNotification(EventType type) {
if(registered.contains(type))
return true;
switch(type) {
case WORLD_LOAD:
case WORLD_UNLOAD:
/* Already called for normal world activation/deactivation */
break;
case WORLD_SPAWN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onSpawnChange(SpawnChangeEvent evt) {
BukkitWorld w = getWorld(evt.getWorld());
core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w);
}
}, DynmapPlugin.this);
break;
case PLAYER_JOIN:
case PLAYER_QUIT:
/* Already handled */
break;
case PLAYER_BED_LEAVE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerBedLeave(PlayerBedLeaveEvent evt) {
DynmapPlayer p = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p);
}
}, DynmapPlugin.this);
break;
case PLAYER_CHAT:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerChat(AsyncPlayerChatEvent evt) {
final Player p = evt.getPlayer();
final String msg = evt.getMessage();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() {
public void run() {
DynmapPlayer dp = null;
if(p != null)
dp = new BukkitPlayer(p);
core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, dp, msg);
}
});
}
}, DynmapPlugin.this);
break;
case BLOCK_BREAK:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBreak(BlockBreakEvent evt) {
Block b = evt.getBlock();
if(b == null) return; /* Work around for stupid mods.... */
Location l = b.getLocation();
core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getType().getId(),
getWorld(l.getWorld()).getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
}, DynmapPlugin.this);
break;
case SIGN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onSignChange(SignChangeEvent evt) {
Block b = evt.getBlock();
Location l = b.getLocation();
String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */
DynmapPlayer dp = null;
Player p = evt.getPlayer();
if(p != null) dp = new BukkitPlayer(p);
core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().getId(),
getWorld(l.getWorld()).getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp);
}
}, DynmapPlugin.this);
break;
default:
Log.severe("Unhandled event type: " + type);
return false;
}
registered.add(type);
return true;
}
@Override
public boolean sendWebChatEvent(String source, String name, String msg) {
DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg);
getServer().getPluginManager().callEvent(evt);
return ((evt.isCancelled() == false) && (evt.isProcessed() == false));
}
@Override
public void broadcastMessage(String msg) {
getServer().broadcastMessage(msg);
}
@Override
public String[] getBiomeIDs() {
BiomeMap[] b = BiomeMap.values();
String[] bname = new String[b.length];
for(int i = 0; i < bname.length; i++)
bname[i] = b[i].toString();
return bname;
}
@Override
public double getCacheHitRate() {
return sscache.getHitRate();
}
@Override
public void resetCacheStats() {
sscache.resetStats();
}
@Override
public DynmapWorld getWorldByName(String wname) {
return DynmapPlugin.this.getWorldByName(wname);
}
@Override
public DynmapPlayer getOfflinePlayer(String name) {
OfflinePlayer op = getServer().getOfflinePlayer(name);
if(op != null) {
return new BukkitPlayer(op);
}
return null;
}
@Override
public Set<String> checkPlayerPermissions(String player, Set<String> perms) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if(p.isBanned())
return new HashSet<String>();
Set<String> rslt = permissions.hasOfflinePermissions(player, perms);
if (rslt == null) {
rslt = new HashSet<String>();
if(p.isOp()) {
rslt.addAll(perms);
}
}
return rslt;
}
@Override
public boolean checkPlayerPermission(String player, String perm) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if(p.isBanned())
return false;
boolean rslt = permissions.hasOfflinePermission(player, perm);
return rslt;
}
/**
* Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread
*/
@Override
public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) {
MapChunkCache c = w.getChunkCache(chunks);
if(c == null) { /* Can fail if not currently loaded */
return null;
}
if(w.visibility_limits != null) {
for(VisibilityLimit limit: w.visibility_limits) {
c.setVisibleRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if(w.hidden_limits != null) {
for(VisibilityLimit limit: w.hidden_limits) {
c.setHiddenRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) {
Log.severe("CraftBukkit build does not support biome APIs");
}
if(chunks.size() == 0) { /* No chunks to get? */
c.loadChunks(0);
return c;
}
final MapChunkCache cc = c;
while(!cc.isDoneLoading()) {
Future<Boolean> f = core.getServer().callSyncMethod(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean exhausted = true;
synchronized(loadlock) {
if (prev_tick != cur_tick) {
prev_tick = cur_tick;
cur_tick_starttime = System.nanoTime();
}
if(chunks_in_cur_tick > 0) {
boolean done = false;
while (!done) {
int cnt = chunks_in_cur_tick;
if (cnt > 5) cnt = 5;
chunks_in_cur_tick -= cc.loadChunks(cnt);
exhausted = (chunks_in_cur_tick == 0) || ((System.nanoTime() - cur_tick_starttime) > perTickLimit);
done = exhausted || cc.isDoneLoading();
}
}
}
return exhausted;
}
});
if (f == null) {
return null;
}
Boolean delay;
try {
delay = f.get();
} catch (CancellationException cx) {
return null;
} catch (ExecutionException ex) {
Log.severe("Exception while fetching chunks: ", ex.getCause());
return null;
} catch (Exception ix) {
Log.severe(ix);
return null;
}
if((delay != null) && delay.booleanValue()) {
try { Thread.sleep(25); } catch (InterruptedException ix) {}
}
}
/* If cancelled due to world unload return nothing */
if(w.isLoaded() == false)
return null;
return c;
}
@Override
public int getMaxPlayers() {
return getServer().getMaxPlayers();
}
@Override
public int getCurrentPlayers() {
return getServer().getOnlinePlayers().length;
}
@Override
public boolean isModLoaded(String name) {
if(ismodloaded != null) {
try {
Object rslt =ismodloaded.invoke(null, name);
if(rslt instanceof Boolean) {
if(((Boolean)rslt).booleanValue()) {
modsused.add(name);
return true;
}
}
} catch (IllegalArgumentException iax) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return false;
}
@Override
public String getModVersion(String name) {
if((instance != null) && (getindexedmodlist != null) && (getversion != null)) {
try {
Object inst = instance.invoke(null);
Map<?,?> modmap = (Map<?,?>) getindexedmodlist.invoke(inst);
Object mod = modmap.get(name);
if (mod != null) {
return (String) getversion.invoke(mod);
}
} catch (IllegalArgumentException iax) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return null;
}
@Override
public double getServerTPS() {
return tps;
}
@Override
public String getServerIP() {
return Bukkit.getServer().getIp();
}
@Override
public File getModContainerFile(String mod) {
return null;
}
}
/**
* Player access abstraction class
*/
public class BukkitPlayer extends BukkitCommandSender implements DynmapPlayer {
private Player player;
private OfflinePlayer offplayer;
public BukkitPlayer(Player p) {
super(p);
player = p;
offplayer = p.getPlayer();
}
public BukkitPlayer(OfflinePlayer p) {
super(null);
offplayer = p;
}
@Override
public boolean isConnected() {
return offplayer.isOnline();
}
@Override
public String getName() {
return offplayer.getName();
}
@Override
public String getDisplayName() {
if(player != null)
return player.getDisplayName();
else
return offplayer.getName();
}
@Override
public boolean isOnline() {
return offplayer.isOnline();
}
@Override
public DynmapLocation getLocation() {
if(player == null) {
return null;
}
Location loc = player.getEyeLocation(); // Use eye location, since we show head
return toLoc(loc);
}
@Override
public String getWorld() {
if(player == null) {
return null;
}
World w = player.getWorld();
if(w != null)
return DynmapPlugin.this.getWorld(w).getName();
return null;
}
@Override
public InetSocketAddress getAddress() {
if(player != null)
return player.getAddress();
return null;
}
@Override
public boolean isSneaking() {
if(player != null)
return player.isSneaking();
return false;
}
@Override
public int getHealth() {
if(player != null)
return player.getHealth();
else
return 0;
}
@Override
public int getArmorPoints() {
if(player != null)
return Armor.getArmorPoints(player);
else
return 0;
}
@Override
public DynmapLocation getBedSpawnLocation() {
Location loc = offplayer.getBedSpawnLocation();
if(loc != null) {
return toLoc(loc);
}
return null;
}
@Override
public long getLastLoginTime() {
return offplayer.getLastPlayed();
}
@Override
public long getFirstLoginTime() {
return offplayer.getFirstPlayed();
}
@Override
public boolean isInvisible() {
if(player != null) {
return player.hasPotionEffect(PotionEffectType.INVISIBILITY);
}
return false;
}
@Override
public int getSortWeight() {
Integer wt = sortWeights.get(getName());
if (wt != null)
return wt;
return 0;
}
@Override
public void setSortWeight(int wt) {
if (wt == 0) {
sortWeights.remove(getName());
}
else {
sortWeights.put(getName(), wt);
}
}
}
/* Handler for generic console command sender */
public class BukkitCommandSender implements DynmapCommandSender {
private CommandSender sender;
public BukkitCommandSender(CommandSender send) {
sender = send;
}
@Override
public boolean hasPrivilege(String privid) {
if(sender != null)
return permissions.has(sender, privid);
return false;
}
@Override
public void sendMessage(String msg) {
if(sender != null)
sender.sendMessage(msg);
}
@Override
public boolean isConnected() {
if(sender != null)
return true;
return false;
}
@Override
public boolean isOp() {
if(sender != null)
return sender.isOp();
else
return false;
}
@Override
public boolean hasPermissionNode(String node) {
if (sender != null) {
return sender.hasPermission(node);
}
return false;
}
}
public void loadExtraBiomes() {
int cnt = 0;
/* Find array of biomes in biomebase */
Object[] biomelist = helper.getBiomeBaseList();
/* Loop through list, starting afer well known biomes */
for(int i = BiomeMap.LAST_WELL_KNOWN+1; i < biomelist.length; i++) {
Object bb = biomelist[i];
if(bb != null) {
String id = helper.getBiomeBaseIDString(bb);
if(id == null) {
id = "BIOME_" + i;
}
float tmp = helper.getBiomeBaseTemperature(bb);
float hum = helper.getBiomeBaseHumidity(bb);
BiomeMap m = new BiomeMap(i, id, tmp, hum);
Log.verboseinfo("Add custom biome [" + m.toString() + "] (" + i + ")");
cnt++;
}
}
if(cnt > 0) {
Log.info("Added " + cnt + " custom biome mappings");
}
}
@Override
public void onLoad() {
Log.setLogger(this.getLogger(), "");
helper = BukkitVersionHelper.getHelper();
pm = this.getServer().getPluginManager();
ModSupportImpl.init();
}
@Override
public void onEnable() {
if (helper == null) {
Log.info("Dynmap is disabled (unsupported platform)");
return;
}
PluginDescriptionFile pdfFile = this.getDescription();
version = pdfFile.getVersion();
/* Load extra biomes, if any */
loadExtraBiomes();
/* Set up player login/quit event handler */
registerPlayerLoginListener();
Map<String, Boolean> perdefs = new HashMap<String, Boolean>();
List<Permission> pd = plugin.getDescription().getPermissions();
for(Permission p : pd) {
perdefs.put(p.getName(), p.getDefault() == PermissionDefault.TRUE);
}
permissions = PEXPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = bPermPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = PermBukkitPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = NijikokunPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = GroupManagerPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = BukkitPermissions.create("dynmap", perdefs);
if (permissions == null)
permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload", "purgequeue", "pause", "ips-for-id", "ids-for-ip", "add-id-for-ip", "del-id-for-ip" });
/* Get and initialize data folder */
File dataDirectory = this.getDataFolder();
if(dataDirectory.exists() == false)
dataDirectory.mkdirs();
/* Get MC version */
String bukkitver = getServer().getVersion();
String mcver = "1.0.0";
int idx = bukkitver.indexOf("(MC: ");
if(idx > 0) {
mcver = bukkitver.substring(idx+5);
idx = mcver.indexOf(")");
if(idx > 0) mcver = mcver.substring(0, idx);
}
/* Instantiate core */
if(core == null)
core = new DynmapCore();
/* Inject dependencies */
core.setPluginJarFile(this.getFile());
core.setPluginVersion(version, "CraftBukkit");
core.setMinecraftVersion(mcver);
core.setDataFolder(dataDirectory);
core.setServer(new BukkitServer());
core.setBlockNames(helper.getBlockShortNames());
core.setBlockMaterialMap(helper.getBlockMaterialMap());
core.setBiomeNames(helper.getBiomeNames());
/* Load configuration */
if(!core.initConfiguration(enabCoreCB)) {
this.setEnabled(false);
return;
}
/* See if we need to wait before enabling core */
if(!readyToEnable()) {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPluginEnabled(PluginEnableEvent evt) {
if (!readyToEnable()) {
spb.markPluginEnabled(evt.getPlugin());
if (readyToEnable()) { /* If we;re ready now, finish enable */
doEnable(); /* Finish enable */
}
}
}
};
pm.registerEvents(pl, this);
}
else {
doEnable();
}
// Start tps calculation
lasttick = System.nanoTime();
tps = 20.0;
perTickLimit = core.getMaxTickUseMS() * 1000000;
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
processTick();
}
}, 1, 1);
}
private boolean readyToEnable() {
if (spb != null) {
return spb.isReady();
}
return true;
}
private void doEnable() {
/* Prep spout support, if needed */
if(spb != null) {
spb.processSpoutBlocks(this, core);
}
/* Enable core */
if(!core.enableCore(enabCoreCB)) {
this.setEnabled(false);
return;
}
playerList = core.playerList;
sscache = new SnapshotCache(core.getSnapShotCacheSize(), core.useSoftRefInSnapShotCache());
/* Get map manager from core */
mapManager = core.getMapManager();
/* Initialized the currently loaded worlds */
for (World world : getServer().getWorlds()) {
BukkitWorld w = getWorld(world);
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
/* Register our update trigger events */
registerEvents();
/* Submit metrics to mcstats.org */
initMetrics();
/* Core is ready - notify API availability */
DynmapCommonAPIListener.apiInitialized(this);
Log.info("Enabled");
}
@Override
public void onDisable() {
/* Core is being disabled - notify API disable */
DynmapCommonAPIListener.apiTerminated();
if (metrics != null) {
metrics = null;
}
/* Disable core */
core.disableCore();
if(sscache != null) {
sscache.cleanup();
sscache = null;
}
Log.info("Disabled");
}
private void processTick() {
long now = System.nanoTime();
long elapsed = now - lasttick;
lasttick = now;
avgticklen = ((avgticklen * 99) / 100) + (elapsed / 100);
tps = (double)1E9 / (double)avgticklen;
if (mapManager != null) {
chunks_in_cur_tick = mapManager.getMaxChunkLoadsPerTick();
}
cur_tick++;
// Tick core
if (core != null) {
core.serverTick(tps);
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
DynmapCommandSender dsender;
if(sender instanceof Player) {
dsender = new BukkitPlayer((Player)sender);
}
else {
dsender = new BukkitCommandSender(sender);
}
return core.processCommand(dsender, cmd.getName(), commandLabel, args);
}
@Override
public final MarkerAPI getMarkerAPI() {
return core.getMarkerAPI();
}
@Override
public final boolean markerAPIInitialized() {
return core.markerAPIInitialized();
}
@Override
public final boolean sendBroadcastToWeb(String sender, String msg) {
return core.sendBroadcastToWeb(sender, msg);
}
@Override
public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz,
int maxx, int maxy, int maxz) {
return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz);
}
@Override
public final int triggerRenderOfBlock(String wid, int x, int y, int z) {
return core.triggerRenderOfBlock(wid, x, y, z);
}
@Override
public final void setPauseFullRadiusRenders(boolean dopause) {
core.setPauseFullRadiusRenders(dopause);
}
@Override
public final boolean getPauseFullRadiusRenders() {
return core.getPauseFullRadiusRenders();
}
@Override
public final void setPauseUpdateRenders(boolean dopause) {
core.setPauseUpdateRenders(dopause);
}
@Override
public final boolean getPauseUpdateRenders() {
return core.getPauseUpdateRenders();
}
@Override
public final void setPlayerVisiblity(String player, boolean is_visible) {
core.setPlayerVisiblity(player, is_visible);
}
@Override
public final boolean getPlayerVisbility(String player) {
return core.getPlayerVisbility(player);
}
@Override
public final void postPlayerMessageToWeb(String playerid, String playerdisplay,
String message) {
core.postPlayerMessageToWeb(playerid, playerdisplay, message);
}
@Override
public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay,
boolean isjoin) {
core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin);
}
@Override
public final String getDynmapCoreVersion() {
return core.getDynmapCoreVersion();
}
@Override
public final int triggerRenderOfVolume(Location l0, Location l1) {
int x0 = l0.getBlockX(), y0 = l0.getBlockY(), z0 = l0.getBlockZ();
int x1 = l1.getBlockX(), y1 = l1.getBlockY(), z1 = l1.getBlockZ();
return core.triggerRenderOfVolume(getWorld(l0.getWorld()).getName(), Math.min(x0, x1), Math.min(y0, y1),
Math.min(z0, z1), Math.max(x0, x1), Math.max(y0, y1), Math.max(z0, z1));
}
@Override
public final void setPlayerVisiblity(Player player, boolean is_visible) {
core.setPlayerVisiblity(player.getName(), is_visible);
}
@Override
public final boolean getPlayerVisbility(Player player) {
return core.getPlayerVisbility(player.getName());
}
@Override
public final void postPlayerMessageToWeb(Player player, String message) {
core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message);
}
@Override
public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) {
core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin);
}
@Override
public String getDynmapVersion() {
return version;
}
private static DynmapLocation toLoc(Location l) {
return new DynmapLocation(DynmapWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
private void registerPlayerLoginListener() {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerJoin(PlayerJoinEvent evt) {
final DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
// Give other handlers a change to prep player (nicknames and such from Essentials)
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() {
@Override
public void run() {
core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp);
}
}, 2);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerQuit(PlayerQuitEvent evt) {
DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp);
}
};
pm.registerEvents(pl, this);
}
private class BlockCheckHandler implements Runnable {
public void run() {
BlockToCheck btt;
while(blocks_to_check.isEmpty() != true) {
btt = blocks_to_check.pop();
Location loc = btt.loc;
World w = loc.getWorld();
if(!w.isChunkLoaded(loc.getBlockX()>>4, loc.getBlockZ()>>4))
continue;
int bt = w.getBlockTypeIdAt(loc);
/* Avoid stationary and moving water churn */
if(bt == 9) bt = 8;
if(btt.typeid == 9) btt.typeid = 8;
if((bt != btt.typeid) || (btt.data != w.getBlockAt(loc).getData())) {
String wn = getWorld(w).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), btt.trigger);
}
}
blocks_to_check = null;
/* Kick next run, if one is needed */
startIfNeeded();
}
public void startIfNeeded() {
if((blocks_to_check == null) && (blocks_to_check_accum.isEmpty() == false)) { /* More pending? */
blocks_to_check = blocks_to_check_accum;
blocks_to_check_accum = new LinkedList<BlockToCheck>();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, this, 10);
}
}
}
private BlockCheckHandler btth = new BlockCheckHandler();
private void checkBlock(Block b, String trigger) {
BlockToCheck btt = new BlockToCheck();
btt.loc = b.getLocation();
btt.typeid = b.getTypeId();
btt.data = b.getData();
btt.trigger = trigger;
blocks_to_check_accum.add(btt); /* Add to accumulator */
btth.startIfNeeded();
}
private boolean onplace;
private boolean onbreak;
private boolean onblockform;
private boolean onblockfade;
private boolean onblockspread;
private boolean onblockfromto;
private boolean onblockphysics;
private boolean onleaves;
private boolean onburn;
private boolean onpiston;
private boolean onplayerjoin;
private boolean onplayermove;
private boolean ongeneratechunk;
private boolean onexplosion;
private boolean onstructuregrow;
private boolean onblockgrow;
private boolean onblockredstone;
private void registerEvents() {
// To trigger rendering.
onplace = core.isTrigger("blockplaced");
onbreak = core.isTrigger("blockbreak");
onleaves = core.isTrigger("leavesdecay");
onburn = core.isTrigger("blockburn");
onblockform = core.isTrigger("blockformed");
onblockfade = core.isTrigger("blockfaded");
onblockspread = core.isTrigger("blockspread");
onblockfromto = core.isTrigger("blockfromto");
onblockphysics = core.isTrigger("blockphysics");
onpiston = core.isTrigger("pistonmoved");
onblockfade = core.isTrigger("blockfaded");
onblockredstone = core.isTrigger("blockredstone");
if(onplace) {
Listener placelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPlace(BlockPlaceEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace");
}
};
pm.registerEvents(placelistener, this);
}
if(onbreak) {
Listener breaklistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBreak(BlockBreakEvent event) {
Block b = event.getBlock();
if(b == null) return; /* Stupid mod workaround */
Location loc = b.getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak");
}
};
pm.registerEvents(breaklistener, this);
}
if(onleaves) {
Listener leaveslistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onLeavesDecay(LeavesDecayEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onleaves) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay");
}
}
};
pm.registerEvents(leaveslistener, this);
}
if(onburn) {
Listener burnlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBurn(BlockBurnEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onburn) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn");
}
}
};
pm.registerEvents(burnlistener, this);
}
if(onblockphysics) {
Listener physlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block b = event.getBlock();
Material m = b.getType();
if(m == null) return;
switch(m) {
case STATIONARY_WATER:
case WATER:
case STATIONARY_LAVA:
case LAVA:
case GRAVEL:
case SAND:
checkBlock(b, "blockphysics");
break;
default:
break;
}
}
};
pm.registerEvents(physlistener, this);
}
if(onblockfromto) {
Listener fromtolistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockFromTo(BlockFromToEvent event) {
Block b = event.getBlock();
Material m = b.getType();
if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null))
checkBlock(b, "blockfromto");
b = event.getToBlock();
m = b.getType();
if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null))
checkBlock(b, "blockfromto");
}
};
pm.registerEvents(fromtolistener, this);
}
if(onpiston) {
Listener pistonlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try {
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = getWorld(loc.getWorld()).getName();
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
sscache.invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 2; i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
sscache.invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try {
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = getWorld(loc.getWorld()).getName();
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
sscache.invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 1+event.getLength(); i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
sscache.invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
};
pm.registerEvents(pistonlistener, this);
}
if(onblockspread) {
Listener spreadlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockSpread(BlockSpreadEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread");
}
};
pm.registerEvents(spreadlistener, this);
}
if(onblockform) {
Listener formlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockForm(BlockFormEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform");
}
};
pm.registerEvents(formlistener, this);
}
if(onblockfade) {
Listener fadelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockFade(BlockFadeEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade");
}
};
pm.registerEvents(fadelistener, this);
}
onblockgrow = core.isTrigger("blockgrow");
if(onblockgrow) {
Listener growTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockGrow(BlockGrowEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockgrow");
}
};
pm.registerEvents(growTrigger, this);
}
if(onblockredstone) {
Listener redstoneTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockRedstone(BlockRedstoneEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockredstone");
}
};
pm.registerEvents(redstoneTrigger, this);
}
/* Register player event trigger handlers */
Listener playerTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerJoin(PlayerJoinEvent event) {
if(onplayerjoin) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playerjoin");
}
}
};
onplayerjoin = core.isTrigger("playerjoin");
onplayermove = core.isTrigger("playermove");
pm.registerEvents(playerTrigger, this);
if(onplayermove) {
Listener playermove = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerMove(PlayerMoveEvent event) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playermove");
}
};
pm.registerEvents(playermove, this);
Log.warning("playermove trigger enabled - this trigger can cause excessive tile updating: use with caution");
}
/* Register entity event triggers */
Listener entityTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onEntityExplode(EntityExplodeEvent event) {
Location loc = event.getLocation();
String wname = getWorld(loc.getWorld()).getName();
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<Block> blocks = event.blockList();
for(Block b: blocks) {
Location l = b.getLocation();
int x = l.getBlockX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = l.getBlockY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = l.getBlockZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onexplosion) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode");
}
}
};
onexplosion = core.isTrigger("explosion");
pm.registerEvents(entityTrigger, this);
/* Register world event triggers */
Listener worldTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onWorldLoad(WorldLoadEvent event) {
BukkitWorld w = getWorld(event.getWorld());
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onWorldUnload(WorldUnloadEvent event) {
BukkitWorld w = getWorld(event.getWorld());
if(w != null) {
core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w);
w.setWorldUnloaded();
core.processWorldUnload(w);
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onStructureGrow(StructureGrowEvent event) {
Location loc = event.getLocation();
String wname = getWorld(loc.getWorld()).getName();
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<BlockState> blocks = event.getBlocks();
for(BlockState b: blocks) {
int x = b.getX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = b.getY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = b.getZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onstructuregrow) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "structuregrow");
}
}
};
onstructuregrow = core.isTrigger("structuregrow");
// To link configuration to real loaded worlds.
pm.registerEvents(worldTrigger, this);
ongeneratechunk = core.isTrigger("chunkgenerated");
if(ongeneratechunk) {
Listener chunkTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onChunkPopulate(ChunkPopulateEvent event) {
Chunk c = event.getChunk();
ChunkSnapshot cs = c.getChunkSnapshot();
int ymax = 0;
for(int i = 0; i < c.getWorld().getMaxHeight() / 16; i++) {
if(!cs.isSectionEmpty(i)) {
ymax = (i+1)*16;
}
}
/* Touch extreme corners */
int x = c.getX() << 4;
int z = c.getZ() << 4;
mapManager.touchVolume(getWorld(event.getWorld()).getName(), x, 0, z, x+15, ymax, z+16, "chunkpopulate");
}
};
pm.registerEvents(chunkTrigger, this);
}
}
private boolean detectSpout() {
Plugin p = this.getServer().getPluginManager().getPlugin("Spout");
if(p != null) {
return p.isEnabled();
}
return false;
}
public boolean hasSpout() {
return has_spout;
}
@Override
public void assertPlayerInvisibility(String player, boolean is_invisible,
String plugin_id) {
core.assertPlayerInvisibility(player, is_invisible, plugin_id);
}
@Override
public void assertPlayerInvisibility(Player player, boolean is_invisible,
Plugin plugin) {
core.assertPlayerInvisibility(player.getName(), is_invisible, plugin.getDescription().getName());
}
@Override
public void assertPlayerVisibility(String player, boolean is_visible,
String plugin_id) {
core.assertPlayerVisibility(player, is_visible, plugin_id);
}
@Override
public void assertPlayerVisibility(Player player, boolean is_visible,
Plugin plugin) {
core.assertPlayerVisibility(player.getName(), is_visible, plugin.getDescription().getName());
}
@Override
public boolean setDisableChatToWebProcessing(boolean disable) {
return core.setDisableChatToWebProcessing(disable);
}
@Override
public boolean testIfPlayerVisibleToPlayer(String player, String player_to_see) {
return core.testIfPlayerVisibleToPlayer(player, player_to_see);
}
@Override
public boolean testIfPlayerInfoProtected() {
return core.testIfPlayerInfoProtected();
}
private void initMetrics() {
try {
metrics = new Metrics(this);
Metrics.Graph features = metrics.createGraph("Features Used");
features.addPlotter(new Metrics.Plotter("Internal Web Server") {
@Override
public int getValue() {
if (!core.configuration.getBoolean("disable-webserver", false))
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Spout") {
@Override
public int getValue() {
if(plugin.has_spout)
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Login Security") {
@Override
public int getValue() {
if(core.configuration.getBoolean("login-enabled", false))
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Player Info Protected") {
@Override
public int getValue() {
if(core.player_info_protected)
return 1;
return 0;
}
});
Metrics.Graph maps = metrics.createGraph("Map Data");
maps.addPlotter(new Metrics.Plotter("Worlds") {
@Override
public int getValue() {
if(core.mapManager != null)
return core.mapManager.getWorlds().size();
return 0;
}
});
maps.addPlotter(new Metrics.Plotter("Maps") {
@Override
public int getValue() {
int cnt = 0;
if(core.mapManager != null) {
for(DynmapWorld w :core.mapManager.getWorlds()) {
cnt += w.maps.size();
}
}
return cnt;
}
});
maps.addPlotter(new Metrics.Plotter("HD Maps") {
@Override
public int getValue() {
int cnt = 0;
if(core.mapManager != null) {
for(DynmapWorld w :core.mapManager.getWorlds()) {
for(MapType mt : w.maps) {
if(mt instanceof HDMap) {
cnt++;
}
}
}
}
return cnt;
}
});
for (String mod : modsused) {
features.addPlotter(new Metrics.Plotter(mod + " Blocks") {
@Override
public int getValue() {
return 1;
}
});
}
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
}
} |
package org.gitlab4j.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Branch;
import org.gitlab4j.api.models.CompareResults;
import org.gitlab4j.api.models.Contributor;
import org.gitlab4j.api.models.Tag;
import org.gitlab4j.api.models.TreeItem;
import org.gitlab4j.api.utils.FileUtils;
/**
* This class provides an entry point to all the GitLab API repository calls.
*/
public class RepositoryApi extends AbstractApi {
public RepositoryApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* GET /projects/:id/repository/branches
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the list of repository branches for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Branch> getBranches(Object projectIdOrPath) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "branches");
return (response.readEntity(new GenericType<List<Branch>>() {}));
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* GET /projects/:id/repository/branches
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page to get
* @param perPage the number of Branch instances per page
* @return the list of repository branches for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Branch> getBranches(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches");
return (response.readEntity(new GenericType<List<Branch>>() {}));
}
/**
* Get a Pager of repository branches from a project, sorted by name alphabetically.
*
* GET /projects/:id/repository/branches
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the list of repository branches for the specified project ID
*
* @throws GitLabApiException if any exception occurs
*/
public Pager<Branch> getBranches(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (new Pager<Branch>(this, Branch.class, itemsPerPage, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches"));
}
/**
* Get a single project repository branch.
*
* GET /projects/:id/repository/branches/:branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to get
* @return the branch info for the specified project ID/branch name pair
* @throws GitLabApiException if any exception occurs
*/
public Branch getBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName));
return (response.readEntity(Branch.class));
}
/**
* Get an Optional instance with the value for the specific repository branch.
*
* GET /projects/:id/repository/branches/:branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to get
* @return an Optional instance with the info for the specified project ID/branch name pair as the value
* @throws GitLabApiException if any exception occurs
*/
public Optional<Branch> getOptionalBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
try {
return (Optional.ofNullable(getBranch(projectIdOrPath, branchName)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Creates a branch for the project. Support as of version 6.8.x
*
* POST /projects/:id/repository/branches
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to create
* @param ref Source to create the branch from, can be an existing branch, tag or commit SHA
* @return the branch info for the created branch
* @throws GitLabApiException if any exception occurs
*/
public Branch createBranch(Object projectIdOrPath, String branchName, String ref) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam(isApiVersion(ApiVersion.V3) ? "branch_name" : "branch", branchName, true)
.withParam("ref", ref, true);
Response response = post(Response.Status.CREATED, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches");
return (response.readEntity(Branch.class));
}
/**
* Delete a single project repository branch.
*
* DELETE /projects/:id/repository/branches/:branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName));
}
/**
* Protects a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/protect
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to protect
* @return the branch info for the protected branch
* @throws GitLabApiException if any exception occurs
*/
public Branch protectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "protect");
return (response.readEntity(Branch.class));
}
/**
* Unprotects a single project repository branch. This is an idempotent function, unprotecting an
* already unprotected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/unprotect
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to un-protect
* @return the branch info for the unprotected branch
* @throws GitLabApiException if any exception occurs
*/
public Branch unprotectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "unprotect");
return (response.readEntity(Branch.class));
}
/**
* Get a list of repository tags from a project, sorted by name in reverse alphabetical order.
*
* GET /projects/:id/repository/tags
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the list of tags for the specified project ID
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.getTags(Object)
*/
public List<Tag> getTags(Object projectIdOrPath) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tags");
return (response.readEntity(new GenericType<List<Tag>>() {}));
}
/**
* Get a list of repository tags from a project, sorted by name in reverse alphabetical order and in the specified page range.
*
* GET /projects/:id/repository/tags
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page to get
* @param perPage the number of Tag instances per page
* @return the list of tags for the specified project ID
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.getTags(Object, int, int)
*/
public List<Tag> getTags(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tags");
return (response.readEntity(new GenericType<List<Tag>>() {}));
}
/**
* Get a list of repository tags from a project, sorted by name in reverse alphabetical order.
*
* GET /projects/:id/repository/tags
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the list of tags for the specified project ID
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.getTags(Object, int)
*/
public Pager<Tag> getTags(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (new Pager<Tag>(this, Tag.class, itemsPerPage, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tags"));
}
/**
* Creates a tag on a particular ref of the given project. A message and release notes are optional.
*
* POST /projects/:id/repository/tags
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param tagName The name of the tag Must be unique for the project
* @param ref the git ref to place the tag on
* @param message the message to included with the tag (optional)
* @param releaseNotes the release notes for the tag (optional)
* @return a Tag instance containing info on the newly created tag
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.createTag(Object, String, String, String, String)
*/
public Tag createTag(Object projectIdOrPath, String tagName, String ref, String message, String releaseNotes) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("tag_name", tagName, true)
.withParam("ref", ref, true)
.withParam("message", message, false)
.withParam("release_description", releaseNotes, false);
Response response = post(Response.Status.CREATED, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tags");
return (response.readEntity(Tag.class));
}
/**
* Creates a tag on a particular ref of a given project. A message and a File instance containing the
* release notes are optional. This method is the same as {@link #createTag(Object, String, String, String, String)},
* but instead allows the release notes to be supplied in a file.
*
* POST /projects/:id/repository/tags
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param tagName the name of the tag, must be unique for the project
* @param ref the git ref to place the tag on
* @param message the message to included with the tag (optional)
* @param releaseNotesFile a whose contents are the release notes (optional)
* @return a Tag instance containing info on the newly created tag
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.CreateTag(Object, String, String, String, File)
*/
public Tag createTag(Object projectIdOrPath, String tagName, String ref, String message, File releaseNotesFile) throws GitLabApiException {
String releaseNotes;
if (releaseNotesFile != null) {
try {
releaseNotes = FileUtils.readFileContents(releaseNotesFile);
} catch (IOException ioe) {
throw (new GitLabApiException(ioe));
}
} else {
releaseNotes = null;
}
return (createTag(projectIdOrPath, tagName, ref, message, releaseNotes));
}
/**
* Deletes the tag from a project with the specified tag name.
*
* DELETE /projects/:id/repository/tags/:tag_name
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param tagName The name of the tag to delete
* @throws GitLabApiException if any exception occurs
* @deprecated Replaced by TagsApi.deleteTag(Object, String)
*/
public void deleteTag(Object projectIdOrPath, String tagName) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags", tagName);
}
/**
* Get a list of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a tree with the root directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath) throws GitLabApiException {
return (getTree(projectIdOrPath, "/", "master"));
}
/**
* Get a Pager of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing a tree with the root directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (getTree(projectIdOrPath, "/", "master", false, itemsPerPage));
}
/**
* Get a list of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get content of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, false));
}
/**
* Get a Pager of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get content of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, int itemsPerPage) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, false, itemsPerPage));
}
/**
* Get a list of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get contend of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
* recursive (optional) - Boolean value used to get a recursive tree (false by default)
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param recursive flag to get a recursive tree or not
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, Boolean recursive) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("id", getProjectIdOrPath(projectIdOrPath), true)
.withParam("path", filePath, false)
.withParam(isApiVersion(ApiVersion.V3) ? "ref_name" : "ref", refName, false)
.withParam("recursive", recursive, false)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tree");
return (response.readEntity(new GenericType<List<TreeItem>>() {}));
}
/**
* Get a Pager of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get contend of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
* recursive (optional) - Boolean value used to get a recursive tree (false by default)
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param recursive flag to get a recursive tree or not
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, Boolean recursive, int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("id", getProjectIdOrPath(projectIdOrPath), true)
.withParam("path", filePath, false)
.withParam(isApiVersion(ApiVersion.V3) ? "ref_name" : "ref", refName, false)
.withParam("recursive", recursive, false);
return (new Pager<TreeItem>(this, TreeItem.class, itemsPerPage, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tree"));
}
/**
* Get the raw file contents for a blob by blob SHA.
*
* GET /projects/:id/repository/raw_blobs/:sha
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the file to get the contents for
* @return the raw file contents for the blob on an InputStream
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRawBlobContent(Object projectIdOrPath, String sha) throws GitLabApiException {
Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", sha, "raw");
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @return an input stream that can be used to save as a file
* or to read the content of the archive
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive");
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param format The archive format, defaults to "tar.gz" if null
* @return an input stream that can be used to save as a file or to read the content of the archive
* @throws GitLabApiException if format is not a valid archive format or any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, archiveFormat));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param format The archive format, defaults to TAR_GZ if null
* @return an input stream that can be used to save as a file or to read the content of the archive
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha, ArchiveFormat format) throws GitLabApiException {
if (format == null) {
format = ArchiveFormat.TAR_GZ;
}
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive" + "." + format.toString());
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive");
try {
if (directory == null)
directory = new File(System.getProperty("java.io.tmpdir"));
String filename = FileUtils.getFilenameFromContentDisposition(response);
File file = new File(directory, filename);
InputStream in = response.readEntity(InputStream.class);
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return (file);
} catch (IOException ioe) {
throw new GitLabApiException(ioe);
}
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @param format The archive format, defaults to "tar.gz" if null
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if format is not a valid archive format or any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, directory, archiveFormat));
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* GET /projects/:id/repository/archive
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @param format The archive format, defaults to TAR_GZ if null
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, ArchiveFormat format) throws GitLabApiException {
if (format == null) {
format = ArchiveFormat.TAR_GZ;
}
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive" + "." + format.toString());
try {
if (directory == null)
directory = new File(System.getProperty("java.io.tmpdir"));
String filename = FileUtils.getFilenameFromContentDisposition(response);
File file = new File(directory, filename);
InputStream in = response.readEntity(InputStream.class);
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return (file);
} catch (IOException ioe) {
throw new GitLabApiException(ioe);
}
}
/**
* Compare branches, tags or commits. This can be accessed without authentication
* if the repository is publicly accessible.
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param from the commit SHA or branch name
* @param to the commit SHA or branch name
* @return a CompareResults containing the results of the comparison
* @throws GitLabApiException if any exception occurs
*/
public CompareResults compare(Object projectIdOrPath, String from, String to) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("from", from, true).withParam("to", to, true);
Response response = get(Response.Status.OK, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "compare");
return (response.readEntity(CompareResults.class));
}
/**
* Get a list of contributors from a project.
*
* GET /projects/:id/repository/contributors
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a List containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public List<Contributor> getContributors(Object projectIdOrPath) throws GitLabApiException {
return (getContributors(projectIdOrPath, 1, getDefaultPerPage()));
}
/**
* Get a list of contributors from a project and in the specified page range.
*
* GET /projects/:id/repository/contributors
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page to get
* @param perPage the number of projects per page
* @return a List containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public List<Contributor> getContributors(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage),
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "contributors");
return (response.readEntity(new GenericType<List<Contributor>>() { }));
}
/**
* Get a Pager of contributors from a project.
*
* GET /projects/:id/repository/contributors
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public Pager<Contributor> getContributors(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return new Pager<Contributor>(this, Contributor.class, itemsPerPage, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "contributors");
}
} |
package org.gitlab4j.api.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
/**
* This class provides utility methods for parsing and formatting ISO8601 formatted dates.
*/
public class ISO8601 {
public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
public static final String MSEC_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public static final String SPACEY_PATTERN = "yyyy-MM-dd HH:mm:ss Z";
public static final String SPACEY_MSEC_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS Z";
public static final String PATTERN_MSEC = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public static final String OUTPUT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String OUTPUT_MSEC_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public static final String UTC_PATTERN = "yyyy-MM-dd HH:mm:ss 'UTC'";
private static final DateTimeFormatter ODT_WITH_MSEC_PARSER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd[['T'][ ]HH:mm:ss.SSS[ ][XXXXX][XXXX]]").toFormatter();
private static final DateTimeFormatter ODT_PARSER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd[['T'][ ]HH:mm:ss[.SSS][ ][X][XXX]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
// Set up ThreadLocal storage to save a thread local SimpleDateFormat keyed with the format string
private static final class SafeDateFormatter {
private static final ThreadLocal<Map<String, SimpleDateFormat>> safeFormats = new ThreadLocal<Map<String, SimpleDateFormat>>() {
@Override
public Map<String, SimpleDateFormat> initialValue() {
return (new ConcurrentHashMap<>());
}
};
private static SimpleDateFormat getDateFormat(String formatSpec) {
Map<String, SimpleDateFormat> formatMap = safeFormats.get();
SimpleDateFormat format = formatMap.get(formatSpec);
if (format == null) {
format = new SimpleDateFormat(formatSpec);
format.setLenient(true);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
formatMap.put(formatSpec, format);
}
return (format);
}
}
/**
* Get a ISO8601 formatted string for the current date and time.
*
* @return a ISO8601 formatted string for the current date and time
*/
public static String getTimestamp() {
return (SafeDateFormatter.getDateFormat(PATTERN).format(new Date()));
}
/**
* Get a ISO8601formatted string for the current date and time.
*
* @param withMsec flag indicating whether to include milliseconds
* @return a ISO8601 formatted string for the current date and time
*/
public static String getTimestamp(boolean withMsec) {
return (withMsec ? SafeDateFormatter.getDateFormat(PATTERN_MSEC).format(new Date()) :
SafeDateFormatter.getDateFormat(PATTERN).format(new Date()));
}
/**
* Get a ISO8601 formatted string for the provided Calendar instance.
*
* @param cal the Calendar instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Calendar instance, or null if call is null
*/
public static String toString(Calendar cal) {
if (cal == null) {
return (null);
}
return (toString(cal.getTime()));
}
/**
* Get a ISO8601 formatted string for the provided Date instance.
*
* @param date the Date instance to get the ISO8601 formatted string for
* @param withMsec flag indicating whether to include milliseconds
* @return a ISO8601 formatted string for the provided Date instance, or null if date is null
*/
public static String toString(Date date, boolean withMsec) {
if (date == null) {
return (null);
}
long time = date.getTime();
return (withMsec && time % 1000 != 0 ?
SafeDateFormatter.getDateFormat(OUTPUT_MSEC_PATTERN).format(date) :
SafeDateFormatter.getDateFormat(OUTPUT_PATTERN).format(date));
}
/**
* Get a ISO8601 formatted string for the provided Date instance.
*
* @param date the Date instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Date instance, or null if date is null
*/
public static String toString(Date date) {
return (toString(date, true));
}
/**
* Parses an ISO8601 formatted string a returns an Instant instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return an Instant instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Instant toInstant(String dateTimeString) throws ParseException {
if (dateTimeString == null) {
return (null);
}
dateTimeString = dateTimeString.trim();
if (dateTimeString.endsWith("Z") || dateTimeString.endsWith("UTC")) {
return (Instant.parse(dateTimeString));
} else {
OffsetDateTime odt = (dateTimeString.length() > 25 ?
OffsetDateTime.parse(dateTimeString, ODT_WITH_MSEC_PARSER) :
OffsetDateTime.parse(dateTimeString, ODT_PARSER));
return (odt.toInstant());
}
}
/**
* Parses an ISO8601 formatted string a returns a Date instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Date instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Date toDate(String dateTimeString) throws ParseException {
Instant instant = toInstant(dateTimeString);
return (instant != null ? Date.from(instant) : null);
}
/**
* Parses an ISO8601 formatted string a returns a Calendar instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Calendar instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Calendar toCalendar(String dateTimeString) throws ParseException {
Date date = toDate(dateTimeString);
if (date == null) {
return (null);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal);
}
} |
package org.jtrfp.trcl.core;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import javax.media.opengl.GL3;
import org.jtrfp.trcl.BriefingScreen;
import org.jtrfp.trcl.ObjectListWindow;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.gpu.GLProgram;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.mem.PagedByteBuffer;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.WorldObject;
public class RenderList {
public static final int NUM_SUBPASSES = 4;
public static final int NUM_BLOCKS_PER_SUBPASS = 1024 * 4;
public static final int NUM_BLOCKS_PER_PASS = NUM_BLOCKS_PER_SUBPASS
* NUM_SUBPASSES;
public static final int NUM_RENDER_PASSES = 2;// Opaque + transparent
private final TR tr;
private int[] hostRenderListPageTable;
private int dummyBufferID;
private int numOpaqueBlocks,
numTransparentBlocks,
numUnoccludedTBlocks;
private final int renderListIdx;
private long rootBufferReadFinishedSync;
private final Renderer renderer;
private final ArrayList<WorldObject> nearbyWorldObjects = new ArrayList<WorldObject>();
private final IntBuffer previousViewport;
private final ArrayList<ByteBuffer> opaqueObjectDefs = new ArrayList<ByteBuffer>(),
transparentObjectDefs = new ArrayList<ByteBuffer>(),
unoccludedTObjectDefs = new ArrayList<ByteBuffer>();
private final Submitter<PositionedRenderable>
submitter = new Submitter<PositionedRenderable>() {
@Override
public void submit(PositionedRenderable item) {
boolean isUnoccluded = false;
if (item instanceof WorldObject) {
final WorldObject wo = (WorldObject)item;
if (!wo.isActive())
return;
synchronized(nearbyWorldObjects)
{nearbyWorldObjects.add(wo);}
if(!wo.isVisible())return;
isUnoccluded = ((WorldObject)item).isImmuneToOpaqueDepthTest();
}//end if(WorldObject)
final ByteBuffer opOD = item.getOpaqueObjectDefinitionAddresses();
final ByteBuffer trOD = item.getTransparentObjectDefinitionAddresses();
numOpaqueBlocks += opOD.capacity() / 4;
if(opOD.capacity()>0)
synchronized(opaqueObjectDefs)
{opaqueObjectDefs.add(opOD);}
if(isUnoccluded){
final WorldObject wo = (WorldObject)item;
numUnoccludedTBlocks += trOD.capacity() / 4;
if(trOD.capacity()>0)
synchronized(unoccludedTObjectDefs)
{unoccludedTObjectDefs.add(trOD);}
}//end if(trOD)
else{numTransparentBlocks += trOD.capacity() / 4;
if(trOD.capacity()>0)
synchronized(transparentObjectDefs)
{transparentObjectDefs.add(trOD);}
}//end if(trOD)
}// end submit(...)
@Override
public void submit(Collection<PositionedRenderable> items) {
synchronized(items){
for(PositionedRenderable r:items){submit(r);}
}//end for(items)
}//end submit(...)
};
void flushObjectDefsToGPU(){
int byteIndex=0;
synchronized(opaqueObjectDefs){
for(ByteBuffer bb:opaqueObjectDefs){
synchronized(bb){
bb.clear();
tr.objectListWindow.get().opaqueIDs.set(renderListIdx, byteIndex, bb);
byteIndex += bb.capacity();}
}}
synchronized(transparentObjectDefs){
for(ByteBuffer bb:transparentObjectDefs){
synchronized(bb){
bb.clear();
tr.objectListWindow.get().opaqueIDs.set(renderListIdx, byteIndex, bb);
byteIndex += bb.capacity();}
}}
synchronized(unoccludedTObjectDefs){
for(ByteBuffer bb:unoccludedTObjectDefs){
synchronized(bb){
bb.clear();
tr.objectListWindow.get().opaqueIDs.set(renderListIdx, byteIndex, bb);
byteIndex += bb.capacity();}
}}
}//end flushObjectDefsToGPU()
public RenderList(final GL3 gl, final Renderer renderer, final TR tr) {
// Build VAO
final IntBuffer ib = IntBuffer.allocate(1);
this.tr = tr;
this.renderer = renderer;
this.previousViewport =ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asIntBuffer();
this.renderListIdx =tr.objectListWindow.get().create();
final TRFuture<Void> task0 = tr.getThreadManager().submitToGL(new Callable<Void>(){
@Override
public Void call() throws Exception {
gl.glGenBuffers(1, ib);
ib.clear();
dummyBufferID = ib.get();
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, dummyBufferID);
gl.glBufferData(GL3.GL_ARRAY_BUFFER, 1, null, GL3.GL_STATIC_DRAW);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 1, GL3.GL_BYTE, false, 0, 0);
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0);
return null;
}
});//end task0
hostRenderListPageTable = new int[((ObjectListWindow.OBJECT_LIST_SIZE_BYTES_PER_PASS
* RenderList.NUM_RENDER_PASSES)
/ PagedByteBuffer.PAGE_SIZE_BYTES)*3];
task0.get();
}// end constructor
private void sendRenderListPageTable(){
final ObjectListWindow olWindow = RenderList.this.tr
.objectListWindow.get();
final Renderer renderer = tr.renderer.get();
final int size = olWindow.numPages();
//////// Workaround for AMD bug where element zero always returns zero in frag. Shift up one.
for (int i = 0; i < size-1; i++) {
hostRenderListPageTable[i+1] = olWindow.logicalPage2PhysicalPage(i);
//System.out.print(" "+hostRenderListPageTable[i+1]);
}// end for(hostRenderListPageTable.length)
System.out.println();
final GLProgram objectProgram = renderer.objectProgram;
objectProgram.use();
objectProgram.getUniform("renderListPageTable").setArrayui(hostRenderListPageTable);
final GLProgram depthQueueProgram = renderer.getDepthQueueProgram();
depthQueueProgram.use();
final GLProgram primaryProgram = renderer.getOpaqueProgram();
primaryProgram.use();
final GLProgram vertexProgram = renderer.getVertexProgram();
vertexProgram.use();
vertexProgram.getUniform("renderListPageTable").setArrayui(hostRenderListPageTable);
tr.gpu.get().defaultProgram();
sentPageTable=true;
}
private static int frameCounter = 0;
private void updateStatesToGPU() {
synchronized(tr.getThreadManager().gameStateLock){
synchronized(nearbyWorldObjects){
final int size=nearbyWorldObjects.size();
for (int i=0; i<size; i++)
nearbyWorldObjects.get(i).updateStateToGPU();
}}
}//end updateStatesToGPU
public void sendToGPU(GL3 gl) {
frameCounter++;
frameCounter %= 100;
updateStatesToGPU();
}//end sendToGPU
private boolean sentPageTable=false;
private void revertViewportToWindow(GL3 gl){
gl.glViewport(
previousViewport.get(0),
previousViewport.get(1),
previousViewport.get(2),
previousViewport.get(3));
}//end revertViewportToWindow()
public void render(final GL3 gl) throws NotReadyException {
if(!sentPageTable)sendRenderListPageTable();
final GPU gpu = tr.gpu.get();
final ObjectListWindow olWindow = tr.objectListWindow.get();
final int opaqueRenderListLogicalVec4Offset = ((olWindow.getObjectSizeInBytes()*renderListIdx)/16);
final int primsPerBlock = GPU.GPU_VERTICES_PER_BLOCK/3;
final int numPrimitives = (numTransparentBlocks+numOpaqueBlocks+numUnoccludedTBlocks)*primsPerBlock;
renderer.getSkyCube().render(this,gl);
// OBJECT STAGE
final GLProgram objectProgram = renderer.getObjectProgram();
objectProgram.use();
objectProgram.getUniform("logicalVec4Offset").setui(opaqueRenderListLogicalVec4Offset);
gl.glProvokingVertex(GL3.GL_FIRST_VERTEX_CONVENTION);
objectProgram.getUniform("cameraMatrix").set4x4Matrix(renderer.getCameraMatrixAsFlatArray(), true);
renderer.getObjectFrameBuffer().bindToDraw();
gl.glGetIntegerv(GL3.GL_VIEWPORT, previousViewport);
gl.glViewport(0, 0, 1024, 128);
gpu.memoryManager.get().bindToUniform(0, objectProgram,
objectProgram.getUniform("rootBuffer"));
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_LINE_SMOOTH);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glLineWidth(1);
{//Start variable scope
int remainingBlocks = numOpaqueBlocks+numTransparentBlocks+numUnoccludedTBlocks;
int numRows = (int)Math.ceil(remainingBlocks/256.);
for(int i=0; i<numRows; i++){
gl.glDrawArrays(GL3.GL_LINE_STRIP, i*257, (remainingBlocks<=256?remainingBlocks:256)+1);
remainingBlocks -= 256;
}
/*
final int opaqueVtxOffset = numOpaqueRows*257;
int numTransRows = (int)Math.ceil(numTransparentBlocks/256.);
remainingBlocks = numTransparentBlocks;
*/
/*
//Need to shift over to the transparent list and then reverse-compensate for the vertex offset
objectProgram.getUniform("logicalVec4Offset").setui(
transRenderListLogicalVec4Offset-
(numOpaqueBlocks/4));//Each block entry is 4 bytes, or 1/4 of a VEC4
*/
/*
for(int i=0; i<numTransRows; i++){
gl.glDrawArrays(GL3.GL_LINE_STRIP, opaqueVtxOffset+i*257, (remainingBlocks<=256?remainingBlocks:256)+1);
remainingBlocks -= 256;
}*/
}//end variable scope
gpu.defaultFrameBuffers();
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultTexture();
///// VERTEX STAGE
final int relevantVertexBufferWidth = ((int)(Renderer.VERTEX_BUFFER_WIDTH/3))*3;
final GLProgram vertexProgram = renderer.getVertexProgram();
vertexProgram.use();
renderer.getVertexFrameBuffer().bindToDraw();
vertexProgram.getUniform("logicalVec4Offset").setui(opaqueRenderListLogicalVec4Offset);
gpu.memoryManager.get().bindToUniform(0, vertexProgram,
vertexProgram.getUniform("rootBuffer"));
renderer.getCamMatrixTexture().bindToTextureUnit(1, gl);
renderer.getNoCamMatrixTexture().bindToTextureUnit(2, gl);
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glViewport(0, 0,
relevantVertexBufferWidth,
(int)Math.ceil((double)(numPrimitives*3)/(double)relevantVertexBufferWidth));//256*256 = 65536, max we can handle.
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 6);//Opaque
//gl.glViewport(0, (NUM_BLOCKS_PER_PASS*GPU.GPU_VERTICES_PER_BLOCK)/relevantVertexBufferWidth, relevantVertexBufferWidth, 256);
//gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 6);//Transparent
//Cleanup
gpu.defaultFrameBuffers();
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultTexture();
///// PRIMITIVE STAGE
//Almost like a geometry shader, except writing lookup textures for each primitive.
renderer.getPrimitiveProgram().use();
renderer.getPrimitiveFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_COLOR_BUFFER_BIT);//TODO: See if this can be removed
renderer.getVertexXYTexture().bindToTextureUnit(0, gl);
renderer.getVertexWTexture().bindToTextureUnit(1, gl);
renderer.getVertexZTexture().bindToTextureUnit(2, gl);
renderer.getVertexUVTexture().bindToTextureUnit(3, gl);
renderer.getVertexNormXYTexture().bindToTextureUnit(4, gl);
renderer.getVertexNormZTexture().bindToTextureUnit(5, gl);
gl.glDisable(GL3.GL_PROGRAM_POINT_SIZE);//Asserts that point size is set only from CPU
gl.glPointSize(2*Renderer.PRIMITIVE_BUFFER_OVERSAMPLING);//2x2 frags
gl.glViewport(0, 0,
Renderer.PRIMITIVE_BUFFER_WIDTH*Renderer.PRIMITIVE_BUFFER_OVERSAMPLING,
Renderer.PRIMITIVE_BUFFER_HEIGHT*Renderer.PRIMITIVE_BUFFER_OVERSAMPLING);
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
//Everything
gl.glDrawArrays(GL3.GL_POINTS, 0, (numTransparentBlocks+numOpaqueBlocks+numUnoccludedTBlocks)*primsPerBlock);
//Cleanup
gl.glEnable(GL3.GL_PROGRAM_POINT_SIZE);
gl.glPointSize(1);
revertViewportToWindow(gl);
gl.glDepthMask(true);
// OPAQUE.DRAW STAGE
final GLProgram primaryProgram = tr.renderer.get().getOpaqueProgram();
primaryProgram.use();
renderer.getVertexXYTexture().bindToTextureUnit(1, gl);
renderer.getVertexUVTexture().bindToTextureUnit(2, gl);
renderer.getVertexTextureIDTexture().bindToTextureUnit(3, gl);
renderer.getVertexZTexture().bindToTextureUnit(4, gl);
renderer.getVertexWTexture().bindToTextureUnit(5, gl);
renderer.getVertexNormXYTexture().bindToTextureUnit(6, gl);
renderer.getVertexNormZTexture().bindToTextureUnit(7, gl);
renderer.getOpaqueFrameBuffer().bindToDraw();
final int numOpaqueVertices = numOpaqueBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
final int numTransparentVertices = numTransparentBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
final int numUnoccludedVertices = numUnoccludedTBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
// Turn on depth write, turn off transparency
gl.glDisable(GL3.GL_BLEND);
gl.glDepthFunc(GL3.GL_LESS);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glEnable(GL3.GL_DEPTH_CLAMP);
//gl.glDepthRange((BriefingScreen.MAX_Z_DEPTH+1)/2, 1);
if(tr.renderer.get().isBackfaceCulling())gl.glEnable(GL3.GL_CULL_FACE);
//final int verticesPerSubPass = (NUM_BLOCKS_PER_SUBPASS * GPU.GPU_VERTICES_PER_BLOCK);
//final int numSubPasses = (numOpaqueVertices / verticesPerSubPass) + 1;
//int remainingVerts = numOpaqueVertices;
if (frameCounter == 0) {
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numOpaqueBlocks",
"" + numOpaqueBlocks);
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numTransparentBlocks",
"" + numTransparentBlocks);
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numUnoccludedTransparentBlocks",
"" + numUnoccludedTBlocks);
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.approxNumSceneTriangles",
"" + ((numOpaqueBlocks+numTransparentBlocks)*GPU.GPU_VERTICES_PER_BLOCK)/3);
}
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, numOpaqueVertices);
/*
for (int sp = 0; sp < numSubPasses; sp++) {
final int numVerts = remainingVerts <= verticesPerSubPass ? remainingVerts
: verticesPerSubPass;
remainingVerts -= numVerts;
final int newOffset = sp
* NUM_BLOCKS_PER_SUBPASS * GPU.GPU_VERTICES_PER_BLOCK;
gl.glDrawArrays(GL3.GL_TRIANGLES, newOffset, numVerts);
}// end for(subpasses)
*/
// Cleanup
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// DEPTH QUEUE DRAW
// DRAW
final GLProgram depthQueueProgram = renderer.getDepthQueueProgram();
depthQueueProgram.use();
renderer.getDepthQueueFrameBuffer().bindToDraw();
gl.glDepthMask(false);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_DEPTH_CLAMP);
gl.glDepthRange(0, 1);
//gl.glEnable(GL3.GL_SAMPLE_MASK);
gl.glDepthFunc(GL3.GL_LEQUAL);
//gl.glDisable(GL3.GL_MULTISAMPLE);
//gl.glStencilFunc(GL3.GL_EQUAL, 0x1, 0xFF);
//gl.glStencilOp(GL3.GL_DECR, GL3.GL_DECR, GL3.GL_DECR);
//gl.glSampleMaski(0, 0xFF);
//Set up float shift queue blending
gl.glEnable(GL3.GL_BLEND);
gl.glBlendFunc(GL3.GL_ONE, GL3.GL_CONSTANT_COLOR);
gl.glBlendEquation(GL3.GL_FUNC_ADD);
gl.glBlendColor(16f, 16f, 16f, 16f);// upshift 4 bits
//object, root, depth, xy
renderer.getOpaqueDepthTexture().bindToTextureUnit(1,gl);
renderer.getVertexXYTexture().bindToTextureUnit(2, gl);
//renderer.getVertexUVTexture().bindToTextureUnit(3, gl);
renderer.getVertexTextureIDTexture().bindToTextureUnit(4, gl);
renderer.getVertexZTexture().bindToTextureUnit(5, gl);
renderer.getVertexWTexture().bindToTextureUnit(6, gl);
renderer.getVertexNormXYTexture().bindToTextureUnit(7, gl);
renderer.getVertexNormZTexture().bindToTextureUnit(8, gl);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices, numTransparentVertices);
//UNOCCLUDED TRANSPARENT
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices+numTransparentVertices, numUnoccludedVertices);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// FENCE
rootBufferReadFinishedSync = gl.glFenceSync(GL3.GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
//gl.glDisable(GL3.GL_MULTISAMPLE);
//gl.glStencilFunc(GL3.GL_ALWAYS, 0xFF, 0xFF);
//gl.glDisable(GL3.GL_STENCIL_TEST);
// DEFERRED STAGE
gl.glDepthMask(true);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glEnable(GL3.GL_BLEND);
if(tr.renderer.get().isBackfaceCulling())gl.glDisable(GL3.GL_CULL_FACE);
final GLProgram deferredProgram = tr.renderer.get().getDeferredProgram();
deferredProgram.use();
gl.glEnable(GL3.GL_BLEND);
gl.glBlendFunc(GL3.GL_SRC_ALPHA, GL3.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL3.GL_FUNC_ADD);
gpu.defaultFrameBuffers();
gpu.memoryManager.get().bindToUniform(0, deferredProgram,
deferredProgram.getUniform("rootBuffer"));
/// 1 UNUSED
/// 2 UNUSED
/// 3 UNUSED
gpu.textureManager.get().vqCodebookManager.get().getRGBATexture().bindToTextureUnit(4,gl);
renderer.getOpaquePrimitiveIDTexture().bindToTextureUnit(5,gl);
renderer.getLayerAccumulatorTexture().bindToTextureUnit(6,gl);
renderer.getVertexTextureIDTexture().bindToTextureUnit(7,gl);
renderer.getPrimitiveUVZWTexture().bindToTextureUnit(8,gl);
renderer.getPrimitiveNormTexture().bindToTextureUnit(9, gl);
//Execute the draw to a screen quad
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 6);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
// DEPTH QUEUE ERASE
renderer.getDepthQueueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_COLOR_BUFFER_BIT);
gpu.defaultFrameBuffers();
//Cleanup
gl.glDepthMask(true);
//gl.glDisable(GL3.GL_MULTISAMPLE);
//gl.glDisable(GL3.GL_SAMPLE_MASK);
//gl.glDisable(GL3.GL_STENCIL_TEST);
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultFrameBuffers();
//INTERMEDIATE ERASE
renderer.getOpaqueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_DEPTH_BUFFER_BIT|GL3.GL_COLOR_BUFFER_BIT);
gl.glFlush();
gl.glWaitSync(rootBufferReadFinishedSync, 0, GL3.GL_TIMEOUT_IGNORED);
}// end render()
public Submitter<PositionedRenderable> getSubmitter() {
return submitter;
}
public void reset() {
numOpaqueBlocks = 0;
numTransparentBlocks = 0;
numUnoccludedTBlocks = 0;
synchronized(nearbyWorldObjects)
{nearbyWorldObjects.clear();}
synchronized(opaqueObjectDefs){
opaqueObjectDefs.clear();}
synchronized(transparentObjectDefs){
transparentObjectDefs.clear();}
synchronized(unoccludedTObjectDefs){
unoccludedTObjectDefs.clear();}
}//end reset()
public List<WorldObject> getVisibleWorldObjectList(){
return nearbyWorldObjects;
}
public int getAttribDummyID() {
return dummyBufferID;
}
}// end RenderList |
package org.jtrfp.trcl.core;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
import javax.media.opengl.GL3;
import org.apache.commons.collections.CollectionUtils;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.ObjectListWindow;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.coll.CollectionActionDispatcher;
import org.jtrfp.trcl.coll.CollectionActionUnpacker;
import org.jtrfp.trcl.coll.DecoupledCollectionActionDispatcher;
import org.jtrfp.trcl.coll.ListActionTelemetry;
import org.jtrfp.trcl.coll.PartitionedList;
import org.jtrfp.trcl.gpu.GLFrameBuffer;
import org.jtrfp.trcl.gpu.GLProgram;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.mem.IntArrayVariableList;
import org.jtrfp.trcl.mem.PagedByteBuffer;
import org.jtrfp.trcl.mem.VEC4Address;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.WorldObject;
import org.jtrfp.trcl.pool.IndexList;
import com.ochafik.util.Adapter;
import com.ochafik.util.CollectionAdapter;
public class RenderList {
public static final int NUM_SUBPASSES = 4;
public static final int NUM_BLOCKS_PER_SUBPASS = 1024 * 4;
public static final int NUM_BLOCKS_PER_PASS = NUM_BLOCKS_PER_SUBPASS
* NUM_SUBPASSES;
public static final int NUM_RENDER_PASSES = 2;// Opaque + transparent //TODO: This is no longer the case
private final TR tr;
private int[] hostRenderListPageTable;
private int dummyBufferID;
/*private int numOpaqueBlocks,
numTransparentBlocks,
numUnoccludedTBlocks;*/
private static final int OPAQUE=0,TRANSPARENT=1,UNOCCLUDED=2;
private final int[] numBlocks = new int[3];
private final int renderListIdx;
private long rootBufferReadFinishedSync;
private final Renderer renderer;
private final RendererFactory rFactory;
//private final ArrayList<WorldObject> nearbyWorldObjects = new ArrayList<WorldObject>();
private final IntBuffer previousViewport;
private final IntArrayVariableList renderList;
private final ListActionTelemetry<VEC4Address> renderListTelemetry
= new ListActionTelemetry<VEC4Address>();
//private final PartitionedIndexPool<VEC4Address>renderListPool;
/*private final PartitionedIndexPool.Partition<VEC4Address>
opaquePartition,
transparentPartition,
unoccludedTPartition;*/
private final IndexList<VEC4Address> opaqueIL, transIL, unoccludedIL;
private final DecoupledCollectionActionDispatcher<PositionedRenderable>
relevantPositionedRenderables = new DecoupledCollectionActionDispatcher<PositionedRenderable>(new ArrayList<PositionedRenderable>(), Executors.newSingleThreadExecutor());
private final PartitionedList<VEC4Address>
renderListPoolNEW = new PartitionedList<VEC4Address>(renderListTelemetry);
private final CollectionAdapter<Collection<VEC4Address>,PositionedRenderable>
opaqueODAddrsColl = new CollectionAdapter<Collection<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(opaqueIL = new IndexList<VEC4Address>(renderListPoolNEW.newSubList())),new OpaqueODAddrAdapter()),
transODAddrsColl = new CollectionAdapter<Collection<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(transIL = new IndexList<VEC4Address>(renderListPoolNEW.newSubList())),new TransODAddrAdapter()),
unoccludedODAddrsColl= new CollectionAdapter<Collection<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(unoccludedIL= new IndexList<VEC4Address>(renderListPoolNEW.newSubList())),new UnoccludedODAddrAdapter());
/*private final ListActionAdapter<PartitionedIndexPool.Entry<VEC4Address>,VEC4Address>
renderingIndices;*/
private final Submitter<PositionedRenderable>
submitter = new Submitter<PositionedRenderable>() {
@Override
public void submit(PositionedRenderable item) {
synchronized(relevantPositionedRenderables)
{relevantPositionedRenderables.add(item);}
/*
boolean isUnoccluded = false;
if (item instanceof WorldObject) {
final WorldObject wo = (WorldObject)item;
if (!wo.isActive())
return;
synchronized(nearbyWorldObjects)
{nearbyWorldObjects.add(wo);}
if(!wo.isVisible())return;
isUnoccluded = ((WorldObject)item).isImmuneToOpaqueDepthTest();
final Collection<VEC4Address> opOD = wo.getOpaqueObjectDefinitionAddresses();
final Collection<VEC4Address> trOD = wo.getTransparentObjectDefinitionAddresses();
if(isUnoccluded){
numUnoccludedTBlocks += trOD.size();
if(trOD.size()>0)
synchronized(unoccludedTPartition)
{for(VEC4Address od:trOD)unoccludedTPartition.newEntry(od);}
numUnoccludedTBlocks += opOD.size();
if(opOD.size()>0)
synchronized(unoccludedTPartition)
{for(VEC4Address od:opOD)unoccludedTPartition.newEntry(od);}
}//end if(trOD)
else{
numTransparentBlocks += trOD.size();
if(trOD.size()>0)
synchronized(transparentPartition)
{for(VEC4Address od:trOD)transparentPartition.newEntry(od);}
numOpaqueBlocks += opOD.size();
if(opOD.size()>0)
synchronized(opaquePartition)
{for(VEC4Address od:opOD)opaquePartition.newEntry(od);}
}//end if(occluded)
}//end if(WorldObject)
*/
}// end submit(...)
@Override
public void submit(Collection<PositionedRenderable> items) {
synchronized(items){
for(PositionedRenderable r:items){submit(r);}
}//end for(items)
}//end submit(...)
};
public RenderList(final GL3 gl, final Renderer renderer, final TR tr) {
// Build VAO
final IntBuffer ib = IntBuffer.allocate(1);
this.tr = tr;
this.renderer = renderer;
this.rFactory = renderer.getRendererFactory();
this.previousViewport =ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asIntBuffer();
this.renderListIdx =tr.objectListWindow.get().create();
this.renderList = new IntArrayVariableList(tr.objectListWindow.get().opaqueIDs,renderListIdx);
//this.renderListPool = new PartitionedIndexPoolImpl<VEC4Address>();
//this.opaquePartition = renderListPool.newPartition();
//this.transparentPartition = renderListPool.newPartition();
//this.unoccludedTPartition = renderListPool.newPartition();
//this.renderingIndices = new ListActionAdapter<PartitionedIndexPool.Entry<VEC4Address>,VEC4Address>(new PartitionedIndexPool.EntryAdapter<VEC4Address>(VEC4Address.ZERO));
//renderListPool.getFlatEntries().addTarget(renderingIndices, true);//Convert entries to Integers
//((ListActionDispatcher)renderingIndices.getOutput()).addTarget(renderListTelemetry, true);//Pipe Integers to renderList
relevantPositionedRenderables.addTarget(opaqueODAddrsColl, false);
relevantPositionedRenderables.addTarget(transODAddrsColl, false);
relevantPositionedRenderables.addTarget(unoccludedODAddrsColl, false);
final TRFuture<Void> task0 = tr.getThreadManager().submitToGL(new Callable<Void>(){
@Override
public Void call() throws Exception {
gl.glGenBuffers(1, ib);
ib.clear();
dummyBufferID = ib.get();
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, dummyBufferID);
gl.glBufferData(GL3.GL_ARRAY_BUFFER, 1, null, GL3.GL_STATIC_DRAW);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 1, GL3.GL_BYTE, false, 0, 0);
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0);
return null;
}
});//end task0
hostRenderListPageTable = new int[((ObjectListWindow.OBJECT_LIST_SIZE_BYTES_PER_PASS
* RenderList.NUM_RENDER_PASSES)
/ PagedByteBuffer.PAGE_SIZE_BYTES)*3];
task0.get();
}// end constructor
private void sendRenderListPageTable(){
final ObjectListWindow olWindow = RenderList.this.tr
.objectListWindow.get();
//final Renderer renderer = tr.mainRenderer.get();
final int size = olWindow.numPages();
//////// Workaround for AMD bug where element zero always returns zero in frag. Shift up one.
for (int i = 0; i < size-1; i++) {
hostRenderListPageTable[i+1] = olWindow.logicalPage2PhysicalPage(i);
}// end for(hostRenderListPageTable.length)
final GLProgram objectProgram = rFactory.getObjectProgram();
objectProgram.use();
objectProgram.getUniform("renderListPageTable").setArrayui(hostRenderListPageTable);
final GLProgram depthQueueProgram = rFactory.getDepthQueueProgram();
depthQueueProgram.use();
final GLProgram primaryProgram = rFactory.getOpaqueProgram();
primaryProgram.use();
final GLProgram vertexProgram = rFactory.getVertexProgram();
vertexProgram.use();
vertexProgram.getUniform("renderListPageTable").setArrayui(hostRenderListPageTable);
tr.gpu.get().defaultProgram();
sentPageTable=true;
}
private static int frameCounter = 0;
private void updateStatesToGPU() {
synchronized(tr.getThreadManager().gameStateLock){
synchronized(relevantPositionedRenderables){
for (PositionedRenderable renderable:relevantPositionedRenderables)
renderable.updateStateToGPU();
}}
}//end updateStatesToGPU
private final CyclicBarrier renderListExecutorBarrier = new CyclicBarrier(2);
private void updateRenderListToGPU(){
if(renderListTelemetry.isModified()){
relevantPositionedRenderables.getExecutor().execute(new Runnable(){
@Override
public void run() {
//Defragment
opaqueIL .defragment();
transIL .defragment();
unoccludedIL.defragment();
numBlocks[OPAQUE] = opaqueIL .delegateSize();
numBlocks[TRANSPARENT]= transIL .delegateSize();
numBlocks[UNOCCLUDED] = unoccludedIL.delegateSize();
renderList.rewind();
renderListTelemetry.drainListStateTo(renderList);
try{renderListExecutorBarrier.await();}catch(Exception e){e.printStackTrace();}
}});
try{renderListExecutorBarrier.await();}catch(Exception e){e.printStackTrace();}
}//end if(modified)
}//end updateRenderingListToGPU()
public void sendToGPU(GL3 gl) {
frameCounter++;
frameCounter %= 100;
updateStatesToGPU();
updateRenderListToGPU();
}//end sendToGPU
private boolean sentPageTable=false;
private void revertViewportToWindow(GL3 gl){
gl.glViewport(
previousViewport.get(0),
previousViewport.get(1),
previousViewport.get(2),
previousViewport.get(3));
}//end revertViewportToWindow()
public void render(final GL3 gl) throws NotReadyException {
if(!sentPageTable)sendRenderListPageTable();
final GPU gpu = tr.gpu.get();
final ObjectListWindow olWindow = tr.objectListWindow.get();
final int opaqueRenderListLogicalVec4Offset = ((olWindow.getObjectSizeInBytes()*renderListIdx)/16);
final int primsPerBlock = GPU.GPU_VERTICES_PER_BLOCK/3;
final int numPrimitives = (numBlocks[TRANSPARENT]+numBlocks[OPAQUE]+numBlocks[UNOCCLUDED])*primsPerBlock;
// OBJECT STAGE
final GLProgram objectProgram = rFactory.getObjectProgram();
objectProgram.use();
objectProgram.getUniform("logicalVec4Offset").setui(opaqueRenderListLogicalVec4Offset);
gl.glProvokingVertex(GL3.GL_FIRST_VERTEX_CONVENTION);
Collection<Camera> cameras = renderer.getCameras();
rFactory.getObjectFrameBuffer().bindToDraw();
gl.glGetIntegerv(GL3.GL_VIEWPORT, previousViewport);
gl.glViewport(0, 0, 1024, 128);
gpu.memoryManager.get().bindToUniform(0, objectProgram,
objectProgram.getUniform("rootBuffer"));
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_LINE_SMOOTH);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glLineWidth(1);
int startBlock = 0;
for(int renderingMode=0; renderingMode<numBlocks.length; renderingMode++){
int remainingBlocks = numBlocks[renderingMode];
for(Camera camera:cameras){
objectProgram.getUniform("cameraMatrix").set4x4Matrix(camera.getCompleteMatrixAsFlatArray(), true);
//TODO: Split to per-type, then per-camera
//int remainingBlocks = numBlocks[TRANSPARENT]+numBlocks[OPAQUE]+numBlocks[UNOCCLUDED];
//final int startBlock = 0;
final int startRow = startBlock / 256;
final int startModulus= startBlock % 256;
final int endBlock = remainingBlocks+startBlock;
final int endRow = (int)Math.ceil(endBlock / 256f);
//int numRows = (int)Math.ceil(remainingBlocks/256f);
int startOffset = startModulus;
//TODO: Adjust offsets to camera
for(int i=startRow; i<endRow; i++){
gl.glDrawArrays(GL3.GL_LINE_STRIP, i*257+startOffset, (remainingBlocks<=256?remainingBlocks:(256-startOffset))+1);
remainingBlocks -= (256-startOffset);
startOffset=0;
}//end for(rows)
startBlock+=numBlocks[renderingMode];//TODO: Per-camera numBlocks
}//end for(cameras)
}//end for(renderingMode)
gpu.defaultFrameBuffers();
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultTexture();
///// VERTEX STAGE
final int relevantVertexBufferWidth = ((int)(RendererFactory.VERTEX_BUFFER_WIDTH/3))*3;
final GLProgram vertexProgram = rFactory.getVertexProgram();
vertexProgram.use();
rFactory.getVertexFrameBuffer().bindToDraw();
vertexProgram.getUniform("logicalVec4Offset").setui(opaqueRenderListLogicalVec4Offset);
gpu.memoryManager.get().bindToUniform(0, vertexProgram,
vertexProgram.getUniform("rootBuffer"));
rFactory.getCamMatrixTexture().bindToTextureUnit(1, gl);
rFactory.getNoCamMatrixTexture().bindToTextureUnit(2, gl);
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glViewport(0, 0,
relevantVertexBufferWidth,
(int)Math.ceil((double)(numPrimitives*3)/(double)relevantVertexBufferWidth));//256*256 = 65536, max we can handle.
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 3);//Opaque
//Cleanup
gpu.defaultFrameBuffers();
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultTexture();
///// PRIMITIVE STAGE
//Almost like a geometry shader, except writing lookup textures for each primitive.
rFactory.getPrimitiveProgram().use();
rFactory.getPrimitiveFrameBuffer().bindToDraw();
rFactory.getVertexXYTexture().bindToTextureUnit(0, gl);
rFactory.getVertexWTexture().bindToTextureUnit(1, gl);
rFactory.getVertexZTexture().bindToTextureUnit(2, gl);
rFactory.getVertexUVTexture().bindToTextureUnit(3, gl);
rFactory.getVertexNormXYTexture().bindToTextureUnit(4, gl);
rFactory.getVertexNormZTexture().bindToTextureUnit(5, gl);
gl.glDisable(GL3.GL_PROGRAM_POINT_SIZE);//Asserts that point size is set only from CPU
gl.glPointSize(2*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING);//2x2 frags
gl.glViewport(0, 0,
RendererFactory.PRIMITIVE_BUFFER_WIDTH*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING,
RendererFactory.PRIMITIVE_BUFFER_HEIGHT*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING);
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
//Everything
gl.glDrawArrays(GL3.GL_POINTS, 0, (numBlocks[TRANSPARENT]+numBlocks[OPAQUE]+numBlocks[UNOCCLUDED])*primsPerBlock);
//Cleanup
gl.glEnable(GL3.GL_PROGRAM_POINT_SIZE);
gl.glPointSize(1);
revertViewportToWindow(gl);
gl.glDepthMask(true);
// OPAQUE.DRAW STAGE
final GLProgram primaryProgram = rFactory.getOpaqueProgram();
primaryProgram.use();
rFactory.getVertexXYTexture().bindToTextureUnit(1, gl);
rFactory.getVertexUVTexture().bindToTextureUnit(2, gl);
rFactory.getVertexTextureIDTexture().bindToTextureUnit(3, gl);
rFactory.getVertexZTexture().bindToTextureUnit(4, gl);
rFactory.getVertexWTexture().bindToTextureUnit(5, gl);
rFactory.getVertexNormXYTexture().bindToTextureUnit(6, gl);
rFactory.getVertexNormZTexture().bindToTextureUnit(7, gl);
rFactory.getOpaqueFrameBuffer().bindToDraw();
final int numOpaqueVertices = numBlocks[OPAQUE]
* GPU.GPU_VERTICES_PER_BLOCK;
final int numTransparentVertices = numBlocks[TRANSPARENT]
* GPU.GPU_VERTICES_PER_BLOCK;
final int numUnoccludedVertices = numBlocks[UNOCCLUDED]
* GPU.GPU_VERTICES_PER_BLOCK;
// Turn on depth write, turn off transparency
gl.glDisable(GL3.GL_BLEND);
gl.glDepthFunc(GL3.GL_LESS);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glEnable(GL3.GL_DEPTH_CLAMP);
//gl.glDepthRange((BriefingScreen.MAX_Z_DEPTH+1)/2, 1);
if(rFactory.isBackfaceCulling())gl.glEnable(GL3.GL_CULL_FACE);
if (frameCounter == 0) {
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numOpaqueBlocks",
"" + opaqueIL.size());
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numTransparentBlocks",
"" + transIL.size());
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.numUnoccludedTransparentBlocks",
"" + unoccludedIL.size());
tr.getReporter().report(
"org.jtrfp.trcl.core.RenderList.approxNumSceneTriangles",
"" + ((opaqueIL.size()+transIL.size()+unoccludedIL.size())*GPU.GPU_VERTICES_PER_BLOCK)/3);
}
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, numOpaqueVertices);
// Cleanup
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// DEPTH QUEUE DRAW
// DRAW
final GLProgram depthQueueProgram = rFactory.getDepthQueueProgram();
depthQueueProgram.use();
rFactory.getDepthQueueFrameBuffer().bindToDraw();
gl.glDepthMask(false);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_DEPTH_CLAMP);
gl.glDepthRange(0, 1);
gl.glDepthFunc(GL3.GL_LEQUAL);
//Set up float shift queue blending
gl.glEnable(GL3.GL_BLEND);
gl.glBlendFunc(GL3.GL_ONE, GL3.GL_CONSTANT_COLOR);
gl.glBlendEquation(GL3.GL_FUNC_ADD);
gl.glBlendColor(16f, 16f, 16f, 16f);// upshift 4 bits
//object, root, depth, xy
rFactory.getOpaqueDepthTexture().bindToTextureUnit(1,gl);
rFactory.getVertexXYTexture().bindToTextureUnit(2, gl);
//renderer.getVertexUVTexture().bindToTextureUnit(3, gl);
rFactory.getVertexTextureIDTexture().bindToTextureUnit(4, gl);
rFactory.getVertexZTexture().bindToTextureUnit(5, gl);
rFactory.getVertexWTexture().bindToTextureUnit(6, gl);
rFactory.getVertexNormXYTexture().bindToTextureUnit(7, gl);
rFactory.getVertexNormZTexture().bindToTextureUnit(8, gl);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices, numTransparentVertices);
//UNOCCLUDED TRANSPARENT
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices+numTransparentVertices, numUnoccludedVertices);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// FENCE
rootBufferReadFinishedSync = gl.glFenceSync(GL3.GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
// DEFERRED STAGE
if(rFactory.isBackfaceCulling())gl.glDisable(GL3.GL_CULL_FACE);
final GLProgram deferredProgram = rFactory.getDeferredProgram();
deferredProgram.use();
gl.glDepthMask(false);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_BLEND);
final GLFrameBuffer renderTarget = renderer.getRenderingTarget();
if(renderTarget!=null)
renderTarget.bindToDraw();
else gpu.defaultFrameBuffers();
gpu.memoryManager.get().bindToUniform(0, deferredProgram,
deferredProgram.getUniform("rootBuffer"));
renderer.getSkyCube().getSkyCubeTexture().bindToTextureUnit(1,gl);
/// 2 UNUSED
gpu.textureManager.get().vqCodebookManager.get().getESTuTvTexture().bindToTextureUnit(3,gl);
gpu.textureManager.get().vqCodebookManager.get().getRGBATexture().bindToTextureUnit(4,gl);
rFactory.getOpaquePrimitiveIDTexture().bindToTextureUnit(5,gl);
rFactory.getLayerAccumulatorTexture().bindToTextureUnit(6,gl);
rFactory.getVertexTextureIDTexture().bindToTextureUnit(7,gl);
rFactory.getPrimitiveUVZWTexture().bindToTextureUnit(8,gl);
rFactory.getPrimitiveNormTexture().bindToTextureUnit(9, gl);
//TODO: Use master-camera's TranslationRotationProjectionMatrix
//Skycube setup
deferredProgram.getUniform("bypassAlpha").setui(!renderer.getCamera().isFogEnabled()?1:0);
deferredProgram.getUniform("projectionRotationMatrix")
.set4x4Matrix(renderer.getMasterCamera().getProjectionRotationMatrixAsFlatArray(), true);
//Execute the draw to a screen quad
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 36);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
// DEPTH QUEUE ERASE
rFactory.getDepthQueueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_COLOR_BUFFER_BIT);
gpu.defaultFrameBuffers();
//Cleanup
gl.glDepthMask(true);
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultFrameBuffers();
//INTERMEDIATE ERASE
rFactory.getOpaqueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_DEPTH_BUFFER_BIT|GL3.GL_COLOR_BUFFER_BIT);
gl.glFlush();
gl.glWaitSync(rootBufferReadFinishedSync, 0, GL3.GL_TIMEOUT_IGNORED);
}// end render()
public Submitter<PositionedRenderable> getSubmitter() {
return submitter;
}
public void reset() {
synchronized(relevantPositionedRenderables){
relevantPositionedRenderables.clear();
}//end sync(relevantObjects)
}//end reset()
public void repopulate(List<PositionedRenderable> renderables){
synchronized(relevantPositionedRenderables){
relevantPositionedRenderables.clear();
relevantPositionedRenderables.addAll(renderables);
}//end sync(relevantObjects)
}
public CollectionActionDispatcher<PositionedRenderable> getVisibleWorldObjectList(){
return relevantPositionedRenderables;
}
public int getAttribDummyID() {
return dummyBufferID;
}
final class OpaqueODAddrAdapter implements Adapter<Collection<VEC4Address>,PositionedRenderable>{
@Override
public Collection<VEC4Address> reAdapt(PositionedRenderable value) {
if(((WorldObject)value).isImmuneToOpaqueDepthTest())
return CollectionUtils.EMPTY_COLLECTION;
return value.getOpaqueObjectDefinitionAddresses();
}
@Override
public WorldObject adapt(Collection<VEC4Address> value) {
throw new UnsupportedOperationException();
}
}//end OpaqueODAddrAdapter
final class TransODAddrAdapter implements Adapter<Collection<VEC4Address>,PositionedRenderable>{
@Override
public Collection<VEC4Address> reAdapt(PositionedRenderable value) {
if(((WorldObject)value).isImmuneToOpaqueDepthTest())
return CollectionUtils.EMPTY_COLLECTION;
return value.getTransparentObjectDefinitionAddresses();
}
@Override
public WorldObject adapt(Collection<VEC4Address> value) {
throw new UnsupportedOperationException();
}
}//end TransODAddrAdapter
final class UnoccludedODAddrAdapter implements Adapter<Collection<VEC4Address>,PositionedRenderable>{
@Override
public Collection<VEC4Address> reAdapt(PositionedRenderable value) {
final Collection<VEC4Address> result = new ArrayList<VEC4Address>();
if(((WorldObject)value).isImmuneToOpaqueDepthTest()){
result.addAll(value.getOpaqueObjectDefinitionAddresses());
result.addAll(value.getTransparentObjectDefinitionAddresses());
}//end if(unoccluded)
return result;
}
@Override
public WorldObject adapt(Collection<VEC4Address> value) {
throw new UnsupportedOperationException();
}
}//end UnoccludedODAddrAdapter
}// end RenderList |
package org.jtrfp.trcl.obj;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.ObjectDefinitionWindow;
import org.jtrfp.trcl.PrimitiveList;
import org.jtrfp.trcl.SpacePartitioningGrid;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.WeakPropertyChangeSupport;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.beh.Behavior;
import org.jtrfp.trcl.beh.BehaviorNotFoundException;
import org.jtrfp.trcl.beh.CollisionBehavior;
import org.jtrfp.trcl.coll.CollectionActionDispatcher;
import org.jtrfp.trcl.coll.PropertyListenable;
import org.jtrfp.trcl.core.NotReadyException;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.TRFuture;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.gpu.RenderList;
import org.jtrfp.trcl.gpu.Renderer;
import org.jtrfp.trcl.math.Mat4x4;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.mem.VEC4Address;
public class WorldObject implements PositionedRenderable, PropertyListenable, Rotatable {
public static final String HEADING ="heading";
public static final String TOP ="top";
public static final String ACTIVE ="active";
private double[] heading = new double[] { 0, 0, 1 }, oldHeading= new double[] {Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY};
private double[] top = new double[] { 0, 1, 0 }, oldTop = new double[] {Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY};
protected volatile double[]
position = new double[3],
positionAfterLoop = new double[3],
oldPosition = new double[]{Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY};
private boolean loopedBefore = false;
protected double[] modelOffset= new double[3];
private final double[]positionWithOffset
= new double[3];
private boolean needToRecalcMatrix=true;
private final TR tr;
private boolean visible = true;
private TRFuture<Model>model;
private int[] triangleObjectDefinitions;
private int[] transparentTriangleObjectDefinitions;
protected Integer matrixID;
private volatile WeakReference<SpacePartitioningGrid> containingGrid;
private ArrayList<Behavior> inactiveBehaviors = new ArrayList<Behavior>();
private ArrayList<CollisionBehavior>collisionBehaviors = new ArrayList<CollisionBehavior>();
private ArrayList<Behavior> tickBehaviors = new ArrayList<Behavior>();
private boolean active = true;
private byte renderFlags=0;
private boolean immuneToOpaqueDepthTest = false;
private boolean objectDefsInitialized = false;
protected final double[] aX = new double[3];
protected final double[] aY = new double[3];
protected final double[] aZ = new double[3];
protected final double[] rotTransM = new double[16];
protected final double[] camM = new double[16];
protected final double[] rMd = new double[16];
protected final double[] tMd = new double[16];
protected double[] cMd = new double[16];
private boolean respondToTick = true;
private double scale = 1.;
private CollectionActionDispatcher<VEC4Address> opaqueObjectDefinitionAddressesInVEC4 = new CollectionActionDispatcher<VEC4Address>(new ArrayList<VEC4Address>());
private CollectionActionDispatcher<VEC4Address> transparentObjectDefinitionAddressesInVEC4 = new CollectionActionDispatcher<VEC4Address>(new ArrayList<VEC4Address>());
protected final WeakPropertyChangeSupport pcs = new WeakPropertyChangeSupport(new PropertyChangeSupport(this));
public enum RenderFlags{
IgnoreCamera((byte)0x1);
private final byte mask;
private RenderFlags(byte mask){
this.mask=mask;
}
public byte getMask() {
return mask;
}
};
public WorldObject(TR tr) {
this.tr = tr;
// Matrix constants setup
rMd[15] = 1;
tMd[0] = 1;
tMd[5] = 1;
tMd[10] = 1;
tMd[15] = 1;
}
public WorldObject(TR tr, Model m) {
this(tr);
setModel(m);
}// end constructor
void proposeCollision(WorldObject other) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
collisionBehaviors.get(i).proposeCollision(other);
}// end for(collisionBehaviors)
}// end proposeCollision(...)
public boolean isCollideable(){
return !collisionBehaviors.isEmpty();
}
public <T extends Behavior> T addBehavior(T ob) {
if (ob.isEnabled()) {
if (ob instanceof CollisionBehavior)
collisionBehaviors.add((CollisionBehavior) ob);
tickBehaviors.add(ob);
} else {
inactiveBehaviors.add(ob);
}
ob.setParent(this);
return ob;
}
public <T extends Behavior> T removeBehavior(T beh) {
if (beh.isEnabled()) {
if (beh instanceof CollisionBehavior)
collisionBehaviors.remove((CollisionBehavior) beh);
tickBehaviors.remove(beh);
} else
inactiveBehaviors.remove(beh);
return beh;
}//end removeBehavior()
protected boolean recalcMatrixWithEachFrame(){
return false;
}
public <T> T probeForBehavior(Class<T> bC) {
if (bC.isAssignableFrom(CollisionBehavior.class)) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
if (bC.isAssignableFrom(collisionBehaviors.get(i).getClass())) {
return (T) collisionBehaviors.get(i);
}
}// end if(instanceof)
}// emd if(isAssignableFrom(CollisionBehavior.class))
for (int i = 0; i < inactiveBehaviors.size(); i++) {
if (bC.isAssignableFrom(inactiveBehaviors.get(i).getClass())) {
return (T) inactiveBehaviors.get(i);
}
}// end if(instanceof)
for (int i = 0; i < tickBehaviors.size(); i++) {
if (bC.isAssignableFrom(tickBehaviors.get(i).getClass())) {
return (T) tickBehaviors.get(i);
}
}// end if(instanceof)
throw new BehaviorNotFoundException("Cannot find behavior of type "
+ bC.getName() + " in behavior sandwich owned by "
+ this.toString());
}// end probeForBehavior
public <T> void probeForBehaviors(Submitter<T> sub, Class<T> type) {
final ArrayList<T> result = new ArrayList<T>();
synchronized(collisionBehaviors){
if (type.isAssignableFrom(CollisionBehavior.class)) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
if (type.isAssignableFrom(collisionBehaviors.get(i).getClass())) {
result.add((T) collisionBehaviors.get(i));
}
}// end if(instanceof)
}// end isAssignableFrom(CollisionBehavior.class)
}synchronized(inactiveBehaviors){
for (int i = 0; i < inactiveBehaviors.size(); i++) {
if (type.isAssignableFrom(inactiveBehaviors.get(i).getClass()))
result.add((T) inactiveBehaviors.get(i));
}// end if(instanceof)
}synchronized(tickBehaviors){
for (int i = 0; i < tickBehaviors.size(); i++) {
if (type.isAssignableFrom(tickBehaviors.get(i).getClass()))
result.add((T) tickBehaviors.get(i));
}// end for (tickBehaviors)
}//end sync(tickBehaviors)
sub.submit(result);
}// end probeForBehaviors(...)
public void tick(long time) {
if(!respondToTick)return;
synchronized(tickBehaviors){
for (int i = 0; i < tickBehaviors.size() && isActive(); i++)
tickBehaviors.get(i).proposeTick(time);
}//end sync(tickBehaviors)
}// end tick(...)
private final int [] emptyIntArray = new int[0];
public void setModel(Model m) {
if (m == null)
throw new RuntimeException("Passed model cannot be null.");
final TRFuture<Model> thisModelFuture = this.model;
if(thisModelFuture != null)
releaseCurrentModel();
try{this.model = m.finalizeModel();}catch(Exception e){throw new RuntimeException(e);}
}// end setModel(...)
private void releaseCurrentModel(){
if(transparentTriangleObjectDefinitions!=null)
for(int def:transparentTriangleObjectDefinitions)
tr.gpu.get().objectDefinitionWindow.get().freeLater(def);
if(triangleObjectDefinitions!=null)
for(int def:triangleObjectDefinitions)
tr.gpu.get().objectDefinitionWindow.get().freeLater(def);
RenderList.RENDER_LIST_EXECUTOR.submit(new Runnable(){
@Override
public void run() {
getOpaqueObjectDefinitionAddressesInVEC4() .clear();
getTransparentObjectDefinitionAddressesInVEC4().clear();
}});
transparentTriangleObjectDefinitions = null;
triangleObjectDefinitions = null;
this.model = null;
objectDefsInitialized = false;
}//end releaseCurrentModel()
public synchronized void setDirection(ObjectDirection dir) {
if (dir.getHeading().getNorm() == 0 || dir.getTop().getNorm() == 0) {
System.err
.println("Warning: Rejecting zero-norm for object direction. "
+ dir);
new Exception().printStackTrace();
return;
}
setHeading(dir.getHeading());
setTop(dir.getTop());
}
@Override
public String toString() {
final String modelDebugName;
if(model!=null)modelDebugName=getModel().getDebugName();
else modelDebugName="[null model]";
return "WorldObject Model=" + modelDebugName + " pos="
+ this.getPosition() + " class=" + getClass().getName()+" hash="+hashCode();
}
public final void initializeObjectDefinitions() throws NotReadyException {
if(objectDefsInitialized)
return;
if (model == null)
throw new NullPointerException(
"Model is null. Did you forget to set it? Object in question is: \n"+this.toString());
final Model model = getModelRealtime();
tr.getThreadManager().submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
tr.getThreadManager().submitToGPUMemAccess(new Callable<Void>(){
@Override
public Void call() throws Exception {
processPrimitiveList(model.getTriangleList(),
getTriangleObjectDefinitions(), getOpaqueObjectDefinitionAddressesInVEC4());
processPrimitiveList(model.getTransparentTriangleList(),
getTransparentTriangleObjectDefinitions(), getTransparentObjectDefinitionAddressesInVEC4());
return null;
}}).get();
objectDefsInitialized = true;
return null;
}});
}// end initializeObjectDefinitions()
private void processPrimitiveList(PrimitiveList<?> primitiveList,
int[] objectDefinitions, final CollectionActionDispatcher<VEC4Address> objectDefinitionAddressesInVEC4) {
if (primitiveList == null)
return; // Nothing to do, no primitives here
final int gpuVerticesPerElement = primitiveList.getGPUVerticesPerElement();
final int elementsPerBlock = GPU.GPU_VERTICES_PER_BLOCK / gpuVerticesPerElement;
int gpuVerticesRemaining = primitiveList.getNumElements()*gpuVerticesPerElement;
// For each of the allocated-but-not-yet-initialized object definitions.
final ObjectDefinitionWindow odw = tr.gpu.get().objectDefinitionWindow.get();
int odCounter=0;
final int memoryWindowIndicesPerElement = primitiveList.getNumMemoryWindowIndicesPerElement();
final Integer matrixID = getMatrixID();
//Cache to hold new addresses for submission in bulk
final ArrayList<VEC4Address> addressesToAdd = new ArrayList<VEC4Address>();
for (final int index : objectDefinitions) {
final int vertexOffsetVec4s=new VEC4Address(primitiveList.getMemoryWindow().getPhysicalAddressInBytes(odCounter*elementsPerBlock*memoryWindowIndicesPerElement)).intValue();
final int matrixOffsetVec4s=new VEC4Address(tr.gpu.get().matrixWindow.get()
.getPhysicalAddressInBytes(matrixID)).intValue();
odw.matrixOffset.set(index,matrixOffsetVec4s);
odw.vertexOffset.set(index,vertexOffsetVec4s);
odw.mode.set(index, (byte)(primitiveList.getPrimitiveRenderMode() | (renderFlags << 4)&0xF0));
odw.modelScale.set(index, (byte) primitiveList.getPackedScale());
if (gpuVerticesRemaining >= GPU.GPU_VERTICES_PER_BLOCK) {
odw.numVertices.set(index,
(byte) GPU.GPU_VERTICES_PER_BLOCK);
} else if (gpuVerticesRemaining > 0) {
odw.numVertices.set(index,
(byte) (gpuVerticesRemaining));
} else {
throw new RuntimeException("Ran out of vec4s.");
}
gpuVerticesRemaining -= GPU.GPU_VERTICES_PER_BLOCK;
addressesToAdd.add(new VEC4Address(odw.getPhysicalAddressInBytes(index)));
odCounter++;
}// end for(ObjectDefinition)
RenderList.RENDER_LIST_EXECUTOR.submit(new Runnable(){
@Override
public void run() {
objectDefinitionAddressesInVEC4.addAll(addressesToAdd);
}});
}// end processPrimitiveList(...)
public synchronized final void updateStateToGPU(Renderer renderer) throws NotReadyException {
initializeObjectDefinitions();
System.arraycopy(position, 0, positionAfterLoop, 0, 3);
attemptLoop(renderer);
if(needToRecalcMatrix){
needToRecalcMatrix=recalcMatrixWithEachFrame();
recalculateTransRotMBuffer();
}
if(model!=null)getModel().proposeAnimationUpdate();
}//end updateStateToGPU()
public boolean supportsLoop(){
return true;
}
protected void attemptLoop(Renderer renderer){
if (supportsLoop()) {
boolean change = false;
final Vector3D camPos = renderer.getCamera().getCameraPosition();
final double [] delta = new double[]{
positionAfterLoop[0] - camPos.getX(),
positionAfterLoop[1] - camPos.getY(),
positionAfterLoop[2] - camPos.getZ()};
if (delta[0] > TR.mapWidth / 2.) {
positionAfterLoop[0] -= TR.mapWidth;
change = true;
needToRecalcMatrix=true;
} else if (delta[0] < -TR.mapWidth / 2.) {
positionAfterLoop[0] += TR.mapWidth;
change = true;
needToRecalcMatrix=true;
}
if (delta[1] > TR.mapWidth / 2.) {
positionAfterLoop[1] -= TR.mapWidth;
change = true;
needToRecalcMatrix=true;
} else if (delta[1] < -TR.mapWidth / 2.) {
positionAfterLoop[1] += TR.mapWidth;
change = true;
needToRecalcMatrix=true;
}
if (delta[2] > TR.mapWidth / 2.) {
positionAfterLoop[2] -= TR.mapWidth;
change = true;
needToRecalcMatrix=true;
} else if (delta[2] < -TR.mapWidth / 2.) {
positionAfterLoop[2] += TR.mapWidth;
change = true;
needToRecalcMatrix=true;
}
if(change){
needToRecalcMatrix = true;
loopedBefore = true;
}else{
if(loopedBefore)
needToRecalcMatrix = true;
loopedBefore = false;
}
}//end if(LOOP)
}//end attemptLoop()
protected void recalculateTransRotMBuffer() {
try {
Vect3D.normalize(heading, aZ);
Vect3D.normalize(top,aY);
Vect3D.cross(top, aZ, aX);
recalculateRotBuffer();
if (translate()) {
recalculateTransBuffer();
Mat4x4.mul(tMd, rMd, rotTransM);
} else {
System.arraycopy(rMd, 0, rotTransM, 0, 16);
}
tr.gpu.get().matrixWindow.get().setTransposed(rotTransM, getMatrixID(), scratchMatrixArray);//New version
} catch (MathArithmeticException e) {e.printStackTrace();
}// Don't crash.
}// end recalculateTransRotMBuffer()
protected void recalculateRotBuffer(){
//Scale
Vect3D.scalarMultiply(aX, getScale(), aX);
Vect3D.scalarMultiply(aY, getScale(), aY);
Vect3D.scalarMultiply(aZ, getScale(), aZ);
rMd[0] = aX[0];
rMd[1] = aY[0];
rMd[2] = aZ[0];
rMd[4] = aX[1];
rMd[5] = aY[1];
rMd[6] = aZ[1];
rMd[8] = aX[2];
rMd[9] = aY[2];
rMd[10] = aZ[2];
}//end recalculateRotBuffer
protected void recalculateTransBuffer(){
if(isVisible() && isActive()){
tMd[3] = positionAfterLoop[0]+modelOffset[0];
tMd[7] = positionAfterLoop[1]+modelOffset[1];
tMd[11]= positionAfterLoop[2]+modelOffset[2];
}else{
tMd[3] = Double.POSITIVE_INFINITY;
tMd[7] = Double.POSITIVE_INFINITY;
tMd[11]= Double.POSITIVE_INFINITY;
}//end (!visible)
}//end recalculateTransBuffer()
protected final double [] scratchMatrixArray = new double[16];
protected boolean translate() {
return true;
}
/**
* @return the visible
*/
public boolean isVisible() {
return visible;
}
/**
* @param visible
* the visible to set
*/
public void setVisible(boolean visible) {
if(this.visible==visible)
return;
needToRecalcMatrix=true;
if(!this.visible && visible){
this.visible = true;
}else this.visible = visible;
}//end setvisible()
/**
* @return the position
*/
public final double[] getPosition() {
return position;
}
/**
* @param position
* the position to set
*/
public WorldObject setPosition(double[] position) {
this.position[0]=position[0];
this.position[1]=position[1];
this.position[2]=position[2];
notifyPositionChange();
return this;
}// end setPosition()
public synchronized WorldObject notifyPositionChange(){
if(position[0]==Double.NaN)
throw new RuntimeException("Invalid position.");
pcs.firePropertyChange(POSITION, oldPosition, position);
needToRecalcMatrix=true;
updateOldPosition();
return this;
}//end notifyPositionChange()
private void updateOldPosition(){
System.arraycopy(position, 0, oldPosition, 0, 3);
}
/**
* @return the heading
*/
public final Vector3D getLookAt() {
return new Vector3D(heading);
}
/**
* @param heading
* the heading to set
*/
public synchronized void setHeading(Vector3D nHeading) {
System.arraycopy(heading, 0, oldHeading, 0, 3);
pcs.firePropertyChange(HEADING, oldHeading, nHeading);
heading[0] = nHeading.getX();
heading[1] = nHeading.getY();
heading[2] = nHeading.getZ();
needToRecalcMatrix=true;
}
public Vector3D getHeading() {
assert !(top[0]==0 && top[1]==0 && top[2]==0);
return new Vector3D(heading);
}
/**
* @return the top
*/
public final Vector3D getTop() {
assert !(top[0]==0 && top[1]==0 && top[2]==0);
return new Vector3D(top);
}
/**
* @param top
* the top to set
*/
public synchronized void setTop(Vector3D nTop) {
System.arraycopy(top, 0, oldTop, 0, 3);
pcs.firePropertyChange(TOP, oldTop, nTop);
top[0] = nTop.getX();
top[1] = nTop.getY();
top[2] = nTop.getZ();
needToRecalcMatrix=true;
}
public final CollectionActionDispatcher<VEC4Address> getOpaqueObjectDefinitionAddresses(){
return opaqueObjectDefinitionAddressesInVEC4;
}
public final CollectionActionDispatcher<VEC4Address> getTransparentObjectDefinitionAddresses(){
return transparentObjectDefinitionAddressesInVEC4;
}
/**
* @return the tr
*/
public TR getTr() {
return tr;
}
public synchronized void destroy() {
final SpacePartitioningGrid grid = getContainingGrid();
if(grid !=null){
try{World.relevanceExecutor.submit(new Runnable(){
@Override
public void run() {
grid.remove(WorldObject.this);
}}).get();}catch(Exception e){throw new RuntimeException(e);}
}//end if(NEW MODE and have grid)
setContainingGrid(null);
// Send it to the land of wind and ghosts.
setActive(false);
notifyPositionChange();
}//end destroy()
@Override
public void setContainingGrid(SpacePartitioningGrid grid) {
containingGrid = new WeakReference<SpacePartitioningGrid>(grid);
notifyPositionChange();
}
public SpacePartitioningGrid<PositionedRenderable> getContainingGrid() {
try{return containingGrid.get();}
catch(NullPointerException e){return null;}
}
public Model getModel() {
try{return model.get();}
catch(NullPointerException e){return null;}
catch(Exception e){throw new RuntimeException(e);}
}
public Model getModelRealtime() throws NotReadyException{
return model.getRealtime();
}
/**
* @return the active
*/
public boolean isActive() {
return active;
}
/**
* @param active
* the active to set
*/
public void setActive(boolean active) {
final boolean oldState = this.active;
if(this.active!=active)
needToRecalcMatrix=true;
if(!this.active && active && isVisible()){
this.active=true;
}
this.active = active;
pcs.firePropertyChange(ACTIVE,oldState,active);
}//end setActive(...)
public synchronized void movePositionBy(Vector3D delta) {
position[0] += delta.getX();
position[1] += delta.getY();
position[2] += delta.getZ();
notifyPositionChange();
}
public synchronized void setPosition(double x, double y, double z) {
position[0] = x;
position[1] = y;
position[2] = z;
notifyPositionChange();
}
public double[] getHeadingArray() {
return heading;
}
public double[] getTopArray() {
return top;
}
public void enableBehavior(Behavior behavior) {
if (!inactiveBehaviors.contains(behavior)) {
throw new RuntimeException(
"Tried to enabled an unregistered behavior.");
}
if (behavior instanceof CollisionBehavior) {
if (!collisionBehaviors.contains(behavior)
&& behavior instanceof CollisionBehavior) {
collisionBehaviors.add((CollisionBehavior) behavior);
}
}
if (!tickBehaviors.contains(behavior)) {
tickBehaviors.add(behavior);
}
}// end enableBehavior(...)
public void disableBehavior(Behavior behavior) {
if (!inactiveBehaviors.contains(behavior))
synchronized(inactiveBehaviors){
inactiveBehaviors.add(behavior);
}
if (behavior instanceof CollisionBehavior)
synchronized(collisionBehaviors){
collisionBehaviors.remove(behavior);
}
synchronized(tickBehaviors){
tickBehaviors.remove(behavior);
}
}//end disableBehavior(...)
/**
* @return the renderFlags
*/
public int getRenderFlags() {
return renderFlags;
}
/**
* @param renderFlags the renderFlags to set
*/
public void setRenderFlags(byte renderFlags) {
this.renderFlags = renderFlags;
}
/**
* @return the respondToTick
*/
public boolean isRespondToTick() {
return respondToTick;
}
/**
* @param respondToTick the respondToTick to set
*/
public void setRespondToTick(boolean respondToTick) {
this.respondToTick = respondToTick;
}
@Override
public void finalize() throws Throwable{
if(matrixID!=null)
tr.gpu.get().matrixWindow.get().freeLater(matrixID);
if(transparentTriangleObjectDefinitions!=null)
for(int def:transparentTriangleObjectDefinitions)
tr.gpu.get().objectDefinitionWindow.get().freeLater(def);
if(triangleObjectDefinitions!=null)
for(int def:triangleObjectDefinitions)
tr.gpu.get().objectDefinitionWindow.get().freeLater(def);
super.finalize();
}//end finalize()
/**
* @param modelOffset the modelOffset to set
*/
public void setModelOffset(double x, double y, double z) {
modelOffset[0]=x;
modelOffset[1]=y;
modelOffset[2]=z;
}
public double[] getPositionWithOffset() {
positionWithOffset[0]=position[0]+modelOffset[0];
positionWithOffset[1]=position[1]+modelOffset[1];
positionWithOffset[2]=position[2]+modelOffset[2];
return positionWithOffset;
}
public boolean isImmuneToOpaqueDepthTest() {
return immuneToOpaqueDepthTest;
}
/**
* @param immuneToDepthTest the immuneToDepthTest to set
*/
public WorldObject setImmuneToOpaqueDepthTest(boolean immuneToDepthTest) {
this.immuneToOpaqueDepthTest = immuneToDepthTest;
return this;
}
/**
* @param arg0
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(PropertyChangeListener arg0) {
pcs.addPropertyChangeListener(arg0);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propertyName, listener);
}
/**
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners()
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
return pcs.getPropertyChangeListeners();
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners(java.lang.String)
*/
public PropertyChangeListener[] getPropertyChangeListeners(
String propertyName) {
return pcs.getPropertyChangeListeners(propertyName);
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#hasListeners(java.lang.String)
*/
public boolean hasListeners(String propertyName) {
return pcs.hasListeners(propertyName);
}
/**
* @param arg0
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(PropertyChangeListener arg0) {
pcs.removePropertyChangeListener(arg0);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.removePropertyChangeListener(propertyName, listener);
}
public boolean hasBehavior(Class<? extends Behavior> behaviorClass) {
try{probeForBehavior(behaviorClass);}
catch(BehaviorNotFoundException e){return false;}
return true;
}
protected int[] getTriangleObjectDefinitions() {
return triangleObjectDefinitions =
getObjectDefinitions(triangleObjectDefinitions, getModel().getTriangleList());
}
protected int[] getTransparentTriangleObjectDefinitions() {
return transparentTriangleObjectDefinitions =
getObjectDefinitions(transparentTriangleObjectDefinitions, getModel().getTransparentTriangleList());
}
protected int[] getObjectDefinitions(int [] originalObjectDefs, PrimitiveList pList){
if(originalObjectDefs == null){
int numObjDefs, sizeInVerts;
if (pList == null)
originalObjectDefs = emptyIntArray;
else {
sizeInVerts = pList
.getTotalSizeInGPUVertices();
numObjDefs = sizeInVerts / GPU.GPU_VERTICES_PER_BLOCK;
if (sizeInVerts % GPU.GPU_VERTICES_PER_BLOCK != 0)
numObjDefs++;
originalObjectDefs = new int[numObjDefs];
for (int i = 0; i < numObjDefs; i++) {
originalObjectDefs[i] = tr.gpu.get()
.objectDefinitionWindow.get().create();
}//end for(numObjDefs)
}//end if(!null)
}//end if(null)
return originalObjectDefs;
}//end getObjectDefinitions(...)
protected CollectionActionDispatcher<VEC4Address> getOpaqueObjectDefinitionAddressesInVEC4() {
if(opaqueObjectDefinitionAddressesInVEC4==null)
opaqueObjectDefinitionAddressesInVEC4 = new CollectionActionDispatcher<VEC4Address>(new ArrayList<VEC4Address>());
return opaqueObjectDefinitionAddressesInVEC4;
}
protected CollectionActionDispatcher<VEC4Address> getTransparentObjectDefinitionAddressesInVEC4() {
if(transparentObjectDefinitionAddressesInVEC4==null)
transparentObjectDefinitionAddressesInVEC4 = new CollectionActionDispatcher<VEC4Address>(new ArrayList<VEC4Address>());
return transparentObjectDefinitionAddressesInVEC4;
}
protected Integer getMatrixID() {
if(matrixID == null)
matrixID = tr.gpu.get().matrixWindow.get().create();
return matrixID;
}
public void setMatrixID(Integer matrixID) {
this.matrixID = matrixID;
}
protected double getScale() {
return scale;
}
protected void setScale(double scale) {
this.scale = scale;
}
public void setRenderFlag(RenderFlags flag){
setRenderFlags((byte)(getRenderFlags() | flag.getMask()));
}
public void unsetRenderFlag(RenderFlags flag){
setRenderFlags((byte)(getRenderFlags() & ~flag.getMask()));
}
public boolean getRenderFlag(RenderFlags flag){
return ((getRenderFlags()&0xFF) & flag.getMask()) != 0;
}
}// end WorldObject |
package org.lantern.state;
import org.codehaus.jackson.annotate.JsonIgnore;
public class ClientFriend implements Friend {
private Long id;
private String email;
private String name = "";
private String userEmail = "";
private Status status = Status.pending;
/**
* The next time, in milliseconds since epoch, that we will ask the user
* about this friend, assuming status=requested.
*/
private long nextQuery;
/**
* Whether or not an XMPP subscription request from this user is pending.
*/
private boolean pendingSubscriptionRequest;
private Long lastUpdated = System.currentTimeMillis();
private boolean loggedIn;
private org.jivesoftware.smack.packet.Presence.Mode mode;
private boolean freeToFriend = false;
public ClientFriend() {
}
public ClientFriend(final String email) {
this.email = email.toLowerCase();
}
public ClientFriend(String email, Status status, String name,
long nextQuery, Long lastUpdated) {
this.email = email.toLowerCase();
this.status = status;
this.name = name;
this.nextQuery = nextQuery;
this.lastUpdated = lastUpdated;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public Status getStatus() {
return status;
}
@Override
public void setStatus(Status status) {
this.status = status;
}
public void setPendingSubscriptionRequest(boolean pending) {
pendingSubscriptionRequest = pending;
}
public boolean isPendingSubscriptionRequest() {
return pendingSubscriptionRequest;
}
@JsonIgnore
public boolean shouldNotifyAgain() {
if (status == Status.pending) {
long now = System.currentTimeMillis();
return nextQuery < now;
}
return false;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getUserEmail() {
return this.userEmail;
}
@Override
public void setUserEmail(final String email) {
this.userEmail = email.toLowerCase();
}
@Override
public long getLastUpdated() {
return this.lastUpdated;
}
@Override
public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated;
}
public void setNextQuery(final long nextQuery) {
this.nextQuery = nextQuery;
}
/**
* Whether or not this peer is online in the sense of logged in to the
* XMPP server.
*
* @return Whether the user is logged in to the XMPP server.
*/
public boolean isLoggedIn() {
return loggedIn;
}
/**
* Sets whether or not this peer is online in the sense of logged in to the
* XMPP server.
*
* @param loggedIn Whether the user is logged in to the XMPP server.
*/
public void setLoggedIn(final boolean loggedIn) {
this.loggedIn = loggedIn;
}
/**
* Gets the users presence mode, such as available, away, dnd, etc.
*
* @return The user's presence mode.
*/
public org.jivesoftware.smack.packet.Presence.Mode getMode() {
return mode;
}
/**
* Sets the users presence mode, such as available, away, dnd, etc.
*
* @param mode The user's presence mode.
*/
public void setMode(final org.jivesoftware.smack.packet.Presence.Mode mode) {
this.mode = mode;
}
@Override
public void setFreeToFriend(boolean freeToFriend) {
this.freeToFriend = freeToFriend;
}
@Override
public boolean isFreeToFriend() {
return this.freeToFriend;
}
/**
* Returns a dynamically calculated reason for a friend suggestion.
*
* TODO: since we may end up with more reasons, we may ultimately want
* to store this on the controller under LanternFriend.
*
* @return
*/
public String getReason() {
return freeToFriend ? "friendedYou" : "runningLantern";
}
@Override
public String toString() {
return "ClientFriend [email=" + email + ", name=" + name
+ ", userEmail=" + userEmail + ", status=" + status
+ ", nextQuery=" + nextQuery + ", pendingSubscriptionRequest="
+ pendingSubscriptionRequest + ", lastUpdated=" + lastUpdated
+ "]";
}
} |
package org.lightmare.ejb;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.handlers.BeanLocalHandler;
import org.lightmare.jpa.JPAManager;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.remote.rpc.RPCall;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.RpcUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Connector class for get ejb beans or call remote procedure in ejb bean (RPC)
* by interface class
*
* @author Levan
*
*/
public class EjbConnector {
/**
* Gets {@link MetaData} from {@link MetaContainer} if it is not locked or
* waits while {@link MetaData#isInProgress()} is true
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
private MetaData getMeta(String beanName) throws IOException {
MetaData metaData = MetaContainer.getSyncMetaData(beanName);
return metaData;
}
/**
* Gets connection for {@link javax.ejb.Stateless} bean {@link Class} from
* cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void getEntityManagerFactory(ConnectionData connection)
throws IOException {
if (connection.getEmf() == null) {
String unitName = connection.getUnitName();
if (ObjectUtils.available(unitName)) {
ConnectionSemaphore semaphore = JPAManager
.getConnection(unitName);
connection.setConnection(semaphore);
}
}
}
/**
* Gets connections for {@link Stateless} bean {@link Class} from cache
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private void getEntityManagerFactories(MetaData metaData)
throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (ObjectUtils.available(connections)) {
for (ConnectionData connection : connections) {
getEntityManagerFactory(connection);
}
}
}
/**
* Instantiates bean by class
*
* @param metaData
* @return Bean instance
* @throws IOException
*/
private <T> T getBeanInstance(MetaData metaData) throws IOException {
@SuppressWarnings("unchecked")
Class<? extends T> beanClass = (Class<? extends T>) metaData
.getBeanClass();
T beanInstance = MetaUtils.instantiate(beanClass);
return beanInstance;
}
/**
* Creates {@link InvocationHandler} implementation for server mode
*
* @param metaData
* @return {@link InvocationHandler}
* @throws IOException
*/
public <T> InvocationHandler getHandler(MetaData metaData)
throws IOException {
T beanInstance = getBeanInstance(metaData);
getEntityManagerFactories(metaData);
BeanHandler handler = new BeanHandler(metaData, beanInstance);
handler.configure();
return handler;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaces
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T>[] interfaces,
InvocationHandler handler, ClassLoader loader) {
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
} else {
LibraryLoader.loadCurrentLibraries(loader);
}
@SuppressWarnings("unchecked")
T beanInstance = (T) Proxy
.newProxyInstance(loader, interfaces, handler);
return beanInstance;
}
/**
* Instantiates bean with {@link Proxy} utility
*
* @param interfaceClass
* @param handler
* @return <code>T</code> implementation of bean interface
*/
private <T> T instatiateBean(Class<T> interfaceClass,
InvocationHandler handler, ClassLoader loader) {
@SuppressWarnings("unchecked")
Class<T>[] interfaceArray = (Class<T>[]) new Class<?>[] { interfaceClass };
T beanInstance = instatiateBean(interfaceArray, handler, loader);
return beanInstance;
}
/**
* Initializes and caches all interfaces for bean class from passed
* {@link MetaData} instance if it is not already cached
*
* @param metaData
* @return {@link Class}[]
*/
private Class<?>[] setInterfaces(MetaData metaData) {
Class<?>[] interfaceClasses = metaData.getInterfaceClasses();
if (ObjectUtils.notAvailable(interfaceClasses)) {
List<Class<?>> interfacesList = new ArrayList<Class<?>>();
Class<?>[] interfaces = metaData.getLocalInterfaces();
if (ObjectUtils.available(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
interfaces = metaData.getRemoteInterfaces();
if (ObjectUtils.available(interfaces)) {
interfacesList.addAll(Arrays.asList(interfaces));
}
int size = interfacesList.size();
interfaceClasses = interfacesList.toArray(new Class[size]);
}
return interfaceClasses;
}
/**
* Creates appropriate bean {@link Proxy} instance by interface
*
* @param metaData
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
@SuppressWarnings("unchecked")
public <T> T connectToBean(MetaData metaData, Object... rpcArgs)
throws IOException {
InvocationHandler handler = getHandler(metaData);
Class<?>[] interfaces = setInterfaces(metaData);
ClassLoader loader = metaData.getLoader();
T beanInstance = (T) instatiateBean((Class<T>[]) interfaces, handler,
loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface {@link Class} instance
*
* @param interfaceClass
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, Class<T> interfaceClass,
Object... rpcArgs) throws IOException {
InvocationHandler handler;
ClassLoader loader;
if (Configuration.isServer()) {
MetaData metaData = getMeta(beanName);
setInterfaces(metaData);
handler = getHandler(metaData);
loader = metaData.getLoader();
} else {
if (rpcArgs.length == RpcUtils.RPC_ARGS_LENGTH) {
String host = (String) rpcArgs[0];
int port = (Integer) rpcArgs[1];
handler = new BeanLocalHandler(new RPCall(host, port));
loader = null;
} else {
throw new IOException(RpcUtils.RPC_ARGS_ERROR);
}
}
T beanInstance = (T) instatiateBean(interfaceClass, handler, loader);
return beanInstance;
}
/**
* Creates custom implementation of bean {@link Class} by class name and its
* {@link Proxy} interface name
*
* @param beanName
* @param interfaceName
* @param rpcArgs
* @return <code>T</code> implementation of bean interface
* @throws IOException
*/
public <T> T connectToBean(String beanName, String interfaceName,
Object... rpcArgs) throws IOException {
MetaData metaData = getMeta(beanName);
ClassLoader loader = metaData.getLoader();
@SuppressWarnings("unchecked")
Class<T> interfaceClass = (Class<T>) MetaUtils.classForName(
interfaceName, Boolean.FALSE, loader);
T beanInstance = (T) connectToBean(beanName, interfaceClass);
return beanInstance;
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.Simulator;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider {
public final static Logger log = LoggerFactory.getLogger(InMoov2.class);
public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>();
// FIXME - why
@Deprecated
public static boolean RobotCanMoveBodyRandom = true;
@Deprecated
public static boolean RobotCanMoveHeadRandom = true;
@Deprecated
public static boolean RobotCanMoveEyesRandom = true;
@Deprecated
public static boolean RobotCanMoveRandom = true;
@Deprecated
public static boolean RobotIsSleeping = false;
@Deprecated
public static boolean RobotIsStarted = false;
private static final long serialVersionUID = 1L;
static String speechRecognizer = "WebkitSpeechRecognition";
/**
* execute a resource script
*
* @param someScriptName
*/
public boolean execScript(String someScriptName) {
try {
Python p = (Python) Runtime.start("python", "Python");
String script = getResourceAsString(someScriptName);
return p.exec(script, true);
} catch (Exception e) {
error("unable to execute script %s", someScriptName);
return false;
}
}
/**
* Part of service life cycle - a new servo has been started
*/
public void onStarted(String fullname) {
log.info("{} started", fullname);
try {
ServiceInterface si = Runtime.getService(fullname);
if ("Servo".equals(si.getSimpleName())) {
log.info("sending setAutoDisable true to {}", fullname);
send(fullname, "setAutoDisable", true);
// ServoControl sc = (ServoControl)Runtime.getService(name);
}
} catch (Exception e) {
log.error("onStarted threw", e);
}
}
public void startService() {
super.startService();
Runtime runtime = Runtime.getInstance();
runtime.subscribeToLifeCycleEvents(getName());
}
public void onCreated(String fullname) {
log.info("{} created", fullname);
}
/**
* This method will load a python file into the python interpreter.
*/
@Deprecated /* use execScript - this doesn't handle resources correctly */
public static boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
boolean result = false;
try {
// This will open a gazillion tabs in InMoov
// result = p.execFile(f.getAbsolutePath(), true);
// old way - not using execFile :(
String script = FileIO.toString(f.getAbsolutePath());
result = p.exec(script, true);
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Platform.setVirtual(true);
Runtime.main(new String[] { "--from-launcher", "--id", "inmoov" });
// Runtime.start("s01", "Servo");
Runtime.start("intro", "Intro");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
InMoov2 i01 = (InMoov2) Runtime.create("i01", "InMoov2");
i01.setVirtual(false);
i01.startService();
// Runtime.start("s02", "Servo");
boolean done = true;
if (done) {
return;
}
i01.startChatBot();
i01.startAll("COM3", "COM4");
Runtime.start("python", "Python");
// Runtime.start("log", "Log");
/*
* OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV");
* cv.setCameraIndex(2);
*/
// i01.startSimulator();
/*
* Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
* mega.connect("/dev/ttyACM0");
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
boolean autoStartBrowser = false;
transient ProgramAB chatBot;
String currentConfigurationName = "default";
transient SpeechRecognizer ear;
transient OpenCV opencv;
transient Tracking eyesTracking;
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
// FIXME - what the hell is this for ?
Set<String> gestures = new TreeSet<String>();
transient InMoov2Head head;
transient Tracking headTracking;
transient HtmlFilter htmlFilter;
transient UltrasonicSensor ultraSonicRight;
transient UltrasonicSensor ultraSonicLeft;
transient Pir pir;
// transient ImageDisplay imageDisplay;
/**
* simple booleans to determine peer state of existence FIXME - should be an
* auto-peer variable
*/
boolean isChatBotActivated = false;
boolean isEarActivated = false;
boolean isOpenCvActivated = false;
boolean isEyeLidsActivated = false;
boolean isHeadActivated = false;
boolean isLeftArmActivated = false;
boolean isLeftHandActivated = false;
boolean isMouthActivated = false;
boolean isRightArmActivated = false;
boolean isRightHandActivated = false;
boolean isSimulatorActivated = false;
boolean isTorsoActivated = false;
boolean isNeopixelActivated = false;
boolean isPirActivated = false;
boolean isUltraSonicRightActivated = false;
boolean isUltraSonicLeftActivated = false;
boolean isServoMixerActivated = false;
// TODO - refactor into a Simulator interface when more simulators are borgd
transient JMonkeyEngine simulator;
String lastGestureExecuted;
Long lastPirActivityTime;
transient InMoov2Arm leftArm;
// transient LanguagePack languagePack = new LanguagePack();
// transient InMoovEyelids eyelids; eyelids are in the head
transient InMoov2Hand leftHand;
/**
* supported locales
*/
Map<String, Locale> locales = null;
int maxInactivityTimeSeconds = 120;
transient SpeechSynthesis mouth;
// FIXME ugh - new MouthControl service that uses AudioFile output
transient public MouthControl mouthControl;
boolean mute = false;
transient NeoPixel neopixel;
transient ServoMixer servomixer;
transient Python python;
transient InMoov2Arm rightArm;
transient InMoov2Hand rightHand;
transient InMoov2Torso torso;
@Deprecated
public Vision vision;
// FIXME - remove all direct references
// transient private HashMap<String, InMoov2Arm> arms = new HashMap<>();
protected List<Voice> voices = null;
protected String voiceSelected;
transient WebGui webgui;
protected List<String> configList;
public InMoov2(String n, String id) {
super(n, id);
// by default all servos will auto-disable
// Servo.setAutoDisableDefault(true); //until peer servo services for
// InMoov2 have the auto disable behavior, we should keep this
// same as created in runtime - send asyc message to all
// registered services, this service has started
// find all servos - set them all to autoDisable(true)
// onStarted(name) will handle all future created servos
List<ServiceInterface> services = Runtime.getServices();
for (ServiceInterface si : services) {
if ("Servo".equals(si.getSimpleName())) {
send(si.getFullName(), "setAutoDisable", true);
}
}
locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT", "tr-TR");
locale = Runtime.getInstance().getLocale();
// REALLY NEEDS TO BE CLEANED UP - no direct references
// "publish" scripts which should be executed :(
// python = (Python) startPeer("python");
python = (Python) Runtime.start("python", "Python"); // this crud should
// stop
// load(locale.getTag()); WTH ?
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
subscribe(r.getName(), "publishConfigList");
// FIXME - Framework should auto-magically auto-start peers AFTER
// construction - unless explicitly told not to
// peers to start on construction
// imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
@Override /* local strong type - is to be avoided - use name string */
public void addTextListener(TextListener service) {
// CORRECT WAY ! - no direct reference - just use the name in a subscription
addListener("publishText", service.getName());
}
@Override
public void attachTextListener(TextListener service) {
attachTextListener(service.getName());
}
/**
* comes in from runtime which owns the config list
*/
public void onConfigList(List<String> configList){
this.configList = configList;
invoke("publishConfigList");
}
/**
* "re"-publishing runtime config list, because
* I don't want to fix the js subscribeTo :P
* @return
*/
public List<String> publishConfigList(){
return configList;
}
public void attachTextPublisher(String name) {
subscribe(name, "publishText");
}
@Override
public void attachTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
public void closeAllImages() {
// imageDisplay.closeAll();
log.error("implement webgui.closeAllImages");
}
public void cycleGestures() {
// if not loaded load -
// FIXME - this needs alot of "help" :P
// WHY IS THIS DONE ?
if (gestures.size() == 0) {
loadGestures();
}
for (String gesture : gestures) {
try {
String methodName = gesture.substring(0, gesture.length() - 3);
speakBlocking(methodName);
log.info("executing gesture {}", methodName);
python.eval(methodName + "()");
// wait for finish - or timeout ?
} catch (Exception e) {
error(e);
}
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
}
public void displayFullScreen(String src) {
try {
// imageDisplay.displayFullScreen(src);
log.error("implement webgui.displayFullScreen");
} catch (Exception e) {
error("could not display picture %s", src);
}
}
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
}
/**
* This method will try to launch a python command with error handling
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
public void fullSpeed() {
if (head != null) {
head.fullSpeed();
}
if (rightHand != null) {
rightHand.fullSpeed();
}
if (leftHand != null) {
leftHand.fullSpeed();
}
if (rightArm != null) {
rightArm.fullSpeed();
}
if (leftArm != null) {
leftArm.fullSpeed();
}
if (torso != null) {
torso.fullSpeed();
}
}
public String get(String key) {
String ret = localize(key);
if (ret != null) {
return ret;
}
return "not yet translated";
}
public InMoov2Arm getArm(String side) {
if ("left".equals(side)) {
return leftArm;
} else if ("right".equals(side)) {
return rightArm;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Hand getHand(String side) {
if ("left".equals(side)) {
return leftHand;
} else if ("right".equals(side)) {
return rightHand;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Head getHead() {
return head;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (lastPirActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public InMoov2Arm getLeftArm() {
return leftArm;
}
public InMoov2Hand getLeftHand() {
return leftHand;
}
@Override
public Map<String, Locale> getLocales() {
return locales;
}
public InMoov2Arm getRightArm() {
return rightArm;
}
public InMoov2Hand getRightHand() {
return rightHand;
}
public Simulator getSimulator() {
return simulator;
}
public InMoov2Torso getTorso() {
return torso;
}
public void halfSpeed() {
if (head != null) {
head.setSpeed(25.0, 25.0, 25.0, 25.0, 100.0, 25.0);
}
if (rightHand != null) {
rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setSpeed(20.0, 20.0, 20.0);
}
}
public boolean isCameraOn() {
if (opencv != null) {
if (opencv.isCapturing()) {
return true;
}
}
return false;
}
public boolean isEyeLidsActivated() {
return isEyeLidsActivated;
}
public boolean isHeadActivated() {
return isHeadActivated;
}
public boolean isLeftArmActivated() {
return isLeftArmActivated;
}
public boolean isLeftHandActivated() {
return isLeftHandActivated;
}
public boolean isMute() {
return mute;
}
public boolean isNeopixelActivated() {
return isNeopixelActivated;
}
public boolean isRightArmActivated() {
return isRightArmActivated;
}
public boolean isRightHandActivated() {
return isRightHandActivated;
}
public boolean isTorsoActivated() {
return isTorsoActivated;
}
public boolean isPirActivated() {
return isPirActivated;
}
public boolean isUltraSonicRightActivated() {
return isUltraSonicRightActivated;
}
public boolean isUltraSonicLeftActivated() {
return isUltraSonicLeftActivated;
}
// by default all servos will auto-disable
// TODO: KW : make peer servo services for InMoov2 have the auto disable
// behavior.
// Servo.setAutoDisableDefault(true);
public boolean isServoMixerActivated() {
return isServoMixerActivated;
}
public void loadGestures() {
loadGestures(getResourceDir() + fs + "gestures");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
*/
public boolean loadGestures(String directory) {
speakBlocking(get("STARTINGGESTURES"));
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = new File(directory);
dir.mkdirs();
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
String methodName = f.getName().substring(0, f.getName().length() - 3) + "()";
gestures.add(methodName);
} else {
error("could not load %s", f.getName());
totalError += 1;
}
} else {
log.info("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
broadcastState();
if (totalError > 0) {
speakAlert(get("GESTURE_ERROR"));
return false;
}
return true;
}
public void cameraOff() {
if (opencv != null) {
opencv.stopCapture();
opencv.disableAll();
}
}
public void cameraOn() {
try {
if (opencv == null) {
startOpenCV();
}
opencv.capture();
} catch (Exception e) {
error(e);
}
}
public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
info("%s arm not started", which);
return;
}
arm.moveTo(bicep, rotate, shoulder, omoplate);
}
public void moveEyelids(double eyelidleftPos, double eyelidrightPos) {
if (head != null) {
head.moveEyelidsTo(eyelidleftPos, eyelidrightPos);
} else {
log.warn("moveEyelids - I have a null head");
}
}
public void moveEyes(double eyeX, double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.warn("moveEyes - I have a null head");
}
}
public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
log.warn("{} hand does not exist");
return;
}
hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveHead(double neck, double rothead) {
moveHead(neck, rothead, null, null, null, null);
}
public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(rollNeck, rothead, null, null, null, rollNeck);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveHeadBlocking(double neck, double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(double neck, double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
public OpenCVData onOpenCVData(OpenCVData data) {
return data;
}
@Override
public void onText(String text) {
// FIXME - we should be able to "re"-publish text but text is coming from
// different sources
// some might be coming from the ear - some from the mouth ... - there has
// to be a distinction
log.info("onText - {}", text);
invoke("publishText", text);
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
/**
* all published text from InMoov2 - including ProgramAB
*/
@Override
public String publishText(String text) {
return text;
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
// FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest
public void rest() {
log.info("InMoov2.rest()");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
}
public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
warn("%s arm not started", which);
return;
}
arm.setSpeed(bicep, rotate, shoulder, omoplate);
}
@Deprecated
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
setArmSpeed(which, bicep, rotate, shoulder, omoplate);
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
/*
* if (eyelids != null) { eyelids.setAutoDisable(param); }
*/
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
warn("%s hand not started", which);
return;
}
hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head == null) {
warn("setHeadSpeed - head not started");
return;
}
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Override
public void setLocale(String code) {
if (code == null) {
log.warn("setLocale null");
return;
}
// filter of the set of supported locales
if (!Locale.hasLanguage(locales, code)) {
error("InMoov does not support %s only %s", code, locales.keySet());
return;
}
super.setLocale(code);
for (ServiceInterface si : Runtime.getLocalServices().values()) {
if (!si.equals(this)) {
si.setLocale(code);
}
}
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
sendToPeer("mouth", "setMute", mute);
broadcastState();
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public String setSpeechType(String speechType) {
serviceType.setPeer("mouth", speechType);
broadcastState();
return speechType;
}
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
@Deprecated
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
/**
* overridden setVirtual for InMoov sets "all" services to virtual
*/
public boolean setVirtual(boolean virtual) {
super.setVirtual(virtual);
Platform.setVirtual(virtual);
speakBlocking(get("STARTINGVIRTUALHARD"));
return virtual;
}
public void setVoice(String name) {
if (mouth != null) {
mouth.setVoice(name);
voiceSelected = name;
speakBlocking(String.format("%s %s", get("SETLANG"), name));
}
}
public void speak(String toSpeak) {
sendToPeer("mouth", "speak", toSpeak);
}
public void speakAlert(String toSpeak) {
speakBlocking(get("ALERT"));
speakBlocking(toSpeak);
}
public void speakBlocking(String speak) {
speakBlocking(speak, (Object[]) null);
}
// FIXME - publish text regardless if mouth exists ...
public void speakBlocking(String format, Object... args) {
if (format == null) {
return;
}
String toSpeak = format;
if (args != null) {
toSpeak = String.format(format, args);
}
// FIXME - publish onText when listening
invoke("publishText", toSpeak);
if (!mute) {
// sendToPeer("mouth", "speakBlocking", toSpeak);
invokePeer("mouth", "speakBlocking", toSpeak);
}
}
public void startAll() throws Exception {
startAll(null, null);
}
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startChatBot();
// startHeadTracking();
// startEyesTracking();
// startOpenCV();
startEar();
startServos(leftPort, rightPort);
// startMouthControl(head.jaw, mouth);
speakBlocking(get("STARTINGSEQUENCE"));
}
/**
* start servos - no controllers
*
* @throws Exception
*/
public void startServos() throws Exception {
startServos(null, null);
}
public ProgramAB startChatBot() {
try {
chatBot = (ProgramAB) startPeer("chatBot");
isChatBotActivated = true;
speakBlocking(get("CHATBOTACTIVATED"));
// GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions !
// attachTextPublisher(chatBot.getName());
/*
* not necessary - ear needs to be attached to mouth not chatBot if (ear
* != null) { ear.attachTextListener(chatBot); }
*/
chatBot.attachTextPublisher(ear);
// this.attach(chatBot); FIXME - attach as a TextPublisher - then
// re-publish
// FIXME - deal with language
// speakBlocking(get("CHATBOTACTIVATED"));
chatBot.repetitionCount(10);
chatBot.setPath(getResourceDir() + fs + "chatbot");
chatBot.startSession("default", locale.getTag());
// reset some parameters to default...
chatBot.setPredicate("topic", "default");
chatBot.setPredicate("questionfirstinit", "");
chatBot.setPredicate("tmpname", "");
chatBot.setPredicate("null", "");
// load last user session
if (!chatBot.getPredicate("name").isEmpty()) {
if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown")) {
chatBot.setPredicate("lastUsername", chatBot.getPredicate("name"));
}
}
chatBot.setPredicate("parameterHowDoYouDo", "");
try {
chatBot.savePredicates();
} catch (IOException e) {
log.error("saving predicates threw", e);
}
// start session based on last recognized person
if (!chatBot.getPredicate("default", "lastUsername").isEmpty() && !chatBot.getPredicate("default", "lastUsername").equals("unknown")) {
chatBot.startSession(chatBot.getPredicate("lastUsername"));
}
htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter",
// "HtmlFilter");
chatBot.attachTextListener(htmlFilter);
htmlFilter.attachTextListener((TextListener) getPeer("mouth"));
chatBot.attachTextListener(this);
} catch (Exception e) {
speak("could not load chatBot");
error(e.getMessage());
speak(e.getMessage());
}
broadcastState();
return chatBot;
}
public SpeechRecognizer startEar() {
ear = (SpeechRecognizer) startPeer("ear");
isEarActivated = true;
ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth"));
ear.attachTextListener(chatBot);
speakBlocking(get("STARTINGEAR"));
broadcastState();
return ear;
}
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
// FIXME - universal (good) way of handling all exceptions - ie - reporting
// back to the user the problem in a short concise way but have
// expandable detail in appropriate places
public OpenCV startOpenCV() throws Exception {
speakBlocking(get("STARTINGOPENCV"));
opencv = (OpenCV) startPeer("opencv");
subscribeTo(opencv.getName(), "publishOpenCVData");
isOpenCvActivated = true;
return opencv;
}
public Tracking startEyesTracking() throws Exception {
if (head == null) {
startHead();
}
return startHeadTracking(head.eyeX, head.eyeY);
}
public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception {
if (opencv == null) {
startOpenCV();
}
speakBlocking(get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.connect(opencv, head.eyeX, head.eyeY);
return eyesTracking;
}
public InMoov2Head startHead() throws Exception {
return startHead(null, null, null, null, null, null, null, null);
}
public InMoov2Head startHead(String port) throws Exception {
return startHead(port, null, null, null, null, null, null, null);
}
// legacy inmoov head exposed pins
public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) {
speakBlocking(get("STARTINGHEAD"));
head = (InMoov2Head) startPeer("head");
isHeadActivated = true;
if (headYPin != null) {
head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
// lame assumption - port is specified - it must be an Arduino :(
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(head.neck);
arduino.attach(head.rothead);
arduino.attach(head.eyeX);
arduino.attach(head.eyeY);
arduino.attach(head.jaw);
// FIXME rollNeck and eyelids must be connected to right controller
// arduino.attach(head.rollNeck);
// arduino.attach(head.eyelidLeft);
// arduino.attach(head.eyelidRight);
} catch (Exception e) {
error(e);
}
}
speakBlocking(get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) getPeer("mouth"));
mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for
// config !!!
return head;
}
public void startHeadTracking() throws Exception {
if (opencv == null) {
startOpenCV();
}
if (head == null) {
startHead();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.opencv, head.rothead, head.neck);
}
}
public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception {
if (opencv == null) {
startOpenCV();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.opencv, rothead, neck);
}
return headTracking;
}
public InMoov2Arm startLeftArm() {
return startLeftArm(null);
}
public InMoov2Arm startLeftArm(String port) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
speakBlocking(get("STARTINGLEFTARM"));
leftArm = (InMoov2Arm) startPeer("leftArm");
isLeftArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(leftArm.bicep);
arduino.attach(leftArm.omoplate);
arduino.attach(leftArm.rotate);
arduino.attach(leftArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return leftArm;
}
public InMoov2Hand startLeftHand() {
return startLeftHand(null);
}
public InMoov2Hand startLeftHand(String port) {
speakBlocking(get("STARTINGLEFTHAND"));
leftHand = (InMoov2Hand) startPeer("leftHand");
isLeftHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left");
arduino.connect(port);
arduino.attach(leftHand.thumb);
arduino.attach(leftHand.index);
arduino.attach(leftHand.majeure);
arduino.attach(leftHand.ringFinger);
arduino.attach(leftHand.pinky);
arduino.attach(leftHand.wrist);
} catch (Exception e) {
error(e);
}
}
return leftHand;
}
// TODO - general objective "might" be to reduce peers down to something
// that does not need a reference - where type can be switched before creation
// and the only thing needed is pubs/subs that are not handled in abstracts
public SpeechSynthesis startMouth() {
// FIXME - bad to have a reference, shuld only need the "name" of the
// service !!!
mouth = (SpeechSynthesis) startPeer("mouth");
voices = mouth.getVoices();
Voice voice = mouth.getVoice();
if (voice != null) {
voiceSelected = voice.getName();
}
isMouthActivated = true;
if (mute) {
mouth.setMute(true);
}
mouth.attachSpeechRecognizer(ear);
// mouth.attach(htmlFilter); // same as chatBot not needed
// this.attach((Attachable) mouth);
// if (ear != null) ....
broadcastState();
speakBlocking(get("STARTINGMOUTH"));
if (Platform.isVirtual()) {
speakBlocking(get("STARTINGVIRTUALHARD"));
}
speakBlocking(get("WHATISTHISLANGUAGE"));
return mouth;
}
public InMoov2Arm startRightArm() {
return startRightArm(null);
}
public InMoov2Arm startRightArm(String port) {
speakBlocking(get("STARTINGRIGHTARM"));
rightArm = (InMoov2Arm) startPeer("rightArm");
isRightArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right");
arduino.connect(port);
arduino.attach(rightArm.bicep);
arduino.attach(rightArm.omoplate);
arduino.attach(rightArm.rotate);
arduino.attach(rightArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return rightArm;
}
public InMoov2Hand startRightHand() {
return startRightHand(null);
}
public InMoov2Hand startRightHand(String port) {
speakBlocking(get("STARTINGRIGHTHAND"));
rightHand = (InMoov2Hand) startPeer("rightHand");
isRightHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right");
arduino.connect(port);
arduino.attach(rightHand.thumb);
arduino.attach(rightHand.index);
arduino.attach(rightHand.majeure);
arduino.attach(rightHand.ringFinger);
arduino.attach(rightHand.pinky);
arduino.attach(rightHand.wrist);
} catch (Exception e) {
error(e);
}
}
return rightHand;
}
public Double getUltraSonicRightDistance() {
if (ultraSonicRight != null) {
return ultraSonicRight.range();
} else {
warn("No UltraSonicRight attached");
return 0.0;
}
}
public Double getUltraSonicLeftDistance() {
if (ultraSonicLeft != null) {
return ultraSonicLeft.range();
} else {
warn("No UltraSonicLeft attached");
return 0.0;
}
}
// public void publishPin(Pin pin) {
// log.info("{} - {}", pin.pin, pin.value);
// if (pin.value == 1) {
// lastPIRActivityTime = System.currentTimeMillis();
/// if its PIR & PIR is active & was sleeping - then wake up !
// if (pin == pin.pin && startSleep != null && pin.value == 1) {
// powerUp();
public void startServos(String leftPort, String rightPort) throws Exception {
startHead(leftPort);
startLeftArm(leftPort);
startLeftHand(leftPort);
startRightArm(rightPort);
startRightHand(rightPort);
startTorso(leftPort);
}
// FIXME .. externalize in a json file included in InMoov2
public Simulator startSimulator() throws Exception {
speakBlocking(get("STARTINGVIRTUAL"));
if (simulator != null) {
log.info("start called twice - starting simulator is reentrant");
return simulator;
}
simulator = (JMonkeyEngine) startPeer("simulator");
// DEPRECATED - should just user peer info
isSimulatorActivated = true;
// adding InMoov2 asset path to the jmonkey simulator
String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName();
File check = new File(assetPath);
log.info("loading assets from {}", assetPath);
if (!check.exists()) {
log.warn("%s does not exist");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
// jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into
// /resource/JMonkeyEngine/assets
simulator.loadModels(assetPath);
simulator.setRotation(getName() + ".head.jaw", "x");
simulator.setRotation(getName() + ".head.neck", "x");
simulator.setRotation(getName() + ".head.rothead", "y");
simulator.setRotation(getName() + ".head.rollNeck", "z");
simulator.setRotation(getName() + ".head.eyeY", "x");
simulator.setRotation(getName() + ".head.eyeX", "y");
simulator.setRotation(getName() + ".head.eyelidLeft", "x");
simulator.setRotation(getName() + ".head.eyelidRight", "x");
simulator.setRotation(getName() + ".torso.topStom", "z");
simulator.setRotation(getName() + ".torso.midStom", "y");
simulator.setRotation(getName() + ".torso.lowStom", "x");
simulator.setRotation(getName() + ".rightArm.bicep", "x");
simulator.setRotation(getName() + ".leftArm.bicep", "x");
simulator.setRotation(getName() + ".rightArm.shoulder", "x");
simulator.setRotation(getName() + ".leftArm.shoulder", "x");
simulator.setRotation(getName() + ".rightArm.rotate", "y");
simulator.setRotation(getName() + ".leftArm.rotate", "y");
simulator.setRotation(getName() + ".rightArm.omoplate", "z");
simulator.setRotation(getName() + ".leftArm.omoplate", "z");
simulator.setRotation(getName() + ".rightHand.wrist", "y");
simulator.setRotation(getName() + ".leftHand.wrist", "y");
simulator.setMapper(getName() + ".head.jaw", 0, 180, -5, 80);
simulator.setMapper(getName() + ".head.neck", 0, 180, 20, -20);
simulator.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30);
simulator.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140);
simulator.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need
// to be
// two eyeX (left and
// right?)
simulator.setMapper(getName() + ".head.eyelidLeft", 0, 180, 40, 140);
simulator.setMapper(getName() + ".head.eyelidRight", 0, 180, 40, 140);
simulator.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150);
simulator.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150);
simulator.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80);
simulator.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80);
simulator.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180);
simulator.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180);
simulator.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60);
simulator.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60);
simulator.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30);
simulator.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130);
simulator.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30);
simulator.multiMap(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3");
simulator.setRotation(getName() + ".leftHand.thumb1", "y");
simulator.setRotation(getName() + ".leftHand.thumb2", "x");
simulator.setRotation(getName() + ".leftHand.thumb3", "x");
simulator.multiMap(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3");
simulator.setRotation(getName() + ".leftHand.index", "x");
simulator.setRotation(getName() + ".leftHand.index2", "x");
simulator.setRotation(getName() + ".leftHand.index3", "x");
simulator.multiMap(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3");
simulator.setRotation(getName() + ".leftHand.majeure", "x");
simulator.setRotation(getName() + ".leftHand.majeure2", "x");
simulator.setRotation(getName() + ".leftHand.majeure3", "x");
simulator.multiMap(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3");
simulator.setRotation(getName() + ".leftHand.ringFinger", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger2", "x");
simulator.setRotation(getName() + ".leftHand.ringFinger3", "x");
simulator.multiMap(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3");
simulator.setRotation(getName() + ".leftHand.pinky", "x");
simulator.setRotation(getName() + ".leftHand.pinky2", "x");
simulator.setRotation(getName() + ".leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
simulator.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179);
simulator.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100);
simulator.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20);
simulator.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20);
// right hand
simulator.multiMap(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3");
simulator.setRotation(getName() + ".rightHand.thumb1", "y");
simulator.setRotation(getName() + ".rightHand.thumb2", "x");
simulator.setRotation(getName() + ".rightHand.thumb3", "x");
simulator.multiMap(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3");
simulator.setRotation(getName() + ".rightHand.index", "x");
simulator.setRotation(getName() + ".rightHand.index2", "x");
simulator.setRotation(getName() + ".rightHand.index3", "x");
simulator.multiMap(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3");
simulator.setRotation(getName() + ".rightHand.majeure", "x");
simulator.setRotation(getName() + ".rightHand.majeure2", "x");
simulator.setRotation(getName() + ".rightHand.majeure3", "x");
simulator.multiMap(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3");
simulator.setRotation(getName() + ".rightHand.ringFinger", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger2", "x");
simulator.setRotation(getName() + ".rightHand.ringFinger3", "x");
simulator.multiMap(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3");
simulator.setRotation(getName() + ".rightHand.pinky", "x");
simulator.setRotation(getName() + ".rightHand.pinky2", "x");
simulator.setRotation(getName() + ".rightHand.pinky3", "x");
simulator.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10);
simulator.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10);
simulator.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10);
simulator.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110);
simulator.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150);
simulator.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160);
// We set the correct location view
simulator.cameraLookAt(getName() + ".torso.lowStom");
// additional experimental mappings
/*
* simulator.attach(getName() + ".leftHand.pinky", getName() +
* ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb",
* getName() + ".leftHand.index3"); simulator.setRotation(getName() +
* ".leftHand.index2", "x"); simulator.setRotation(getName() +
* ".leftHand.index3", "x"); simulator.setMapper(getName() +
* ".leftHand.index", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index2", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index3", 0, 180, -90, -270);
*/
return simulator;
}
public InMoov2Torso startTorso() {
return startTorso(null);
}
public InMoov2Torso startTorso(String port) {
if (torso == null) {
speakBlocking(get("STARTINGTORSO"));
isTorsoActivated = true;
torso = (InMoov2Torso) startPeer("torso");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(torso.lowStom);
left.attach(torso.midStom);
left.attach(torso.topStom);
} catch (Exception e) {
error(e);
}
}
}
return torso;
}
/**
* called with only port - will default with defaulted pins
*
* @param port
* @return
*/
public UltrasonicSensor startUltraSonicRight(String port) {
return startUltraSonicRight(port, 64, 63);
}
/**
* called explicitly with pin values
*
* @param port
* @param trigPin
* @param echoPin
* @return
*/
public UltrasonicSensor startUltraSonicRight(String port, int trigPin, int echoPin) {
if (ultraSonicRight == null) {
speakBlocking(get("STARTINGULTRASONIC"));
isUltraSonicRightActivated = true;
ultraSonicRight = (UltrasonicSensor) startPeer("ultraSonicRight");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attach(ultraSonicRight, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultraSonicRight;
}
public UltrasonicSensor startUltraSonicLeft(String port) {
return startUltraSonicLeft(port, 64, 63);
}
public UltrasonicSensor startUltraSonicLeft(String port, int trigPin, int echoPin) {
if (ultraSonicLeft == null) {
speakBlocking(get("STARTINGULTRASONIC"));
isUltraSonicLeftActivated = true;
ultraSonicLeft = (UltrasonicSensor) startPeer("ultraSonicLeft");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(ultraSonicLeft, trigPin, echoPin);
} catch (Exception e) {
error(e);
}
}
}
return ultraSonicLeft;
}
public Pir startPir(String port) {
return startPir(port, 23);
}
public Pir startPir(String port, int pin) {
if (pir == null) {
speakBlocking(get("STARTINGPIR"));
isPirActivated = true;
pir = (Pir) startPeer("pir");
if (port != null) {
try {
speakBlocking(port);
Arduino right = (Arduino) startPeer("right");
right.connect(port);
right.attach(pir, pin);
} catch (Exception e) {
error(e);
}
}
}
return pir;
}
public ServoMixer startServoMixer() {
servomixer = (ServoMixer) startPeer("servomixer");
isServoMixerActivated = true;
speakBlocking(get("STARTINGSERVOMIXER"));
broadcastState();
return servomixer;
}
public void stop() {
if (head != null) {
head.stop();
}
if (rightHand != null) {
rightHand.stop();
}
if (leftHand != null) {
leftHand.stop();
}
if (rightArm != null) {
rightArm.stop();
}
if (leftArm != null) {
leftArm.stop();
}
if (torso != null) {
torso.stop();
}
}
public void stopChatBot() {
speakBlocking(get("STOPCHATBOT"));
releasePeer("chatBot");
isChatBotActivated = false;
}
public void stopHead() {
speakBlocking(get("STOPHEAD"));
releasePeer("head");
releasePeer("mouthControl");
isHeadActivated = false;
}
public void stopEar() {
speakBlocking(get("STOPEAR"));
releasePeer("ear");
isEarActivated = false;
broadcastState();
}
public void stopOpenCV() {
speakBlocking(get("STOPOPENCV"));
isOpenCvActivated = false;
releasePeer("opencv");
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public void stopLeftArm() {
speakBlocking(get("STOPLEFTARM"));
releasePeer("leftArm");
isLeftArmActivated = false;
}
public void stopLeftHand() {
speakBlocking(get("STOPLEFTHAND"));
releasePeer("leftHand");
isLeftHandActivated = false;
}
public void stopMouth() {
speakBlocking(get("STOPMOUTH"));
releasePeer("mouth");
// TODO - potentially you could set the field to null in releasePeer
mouth = null;
isMouthActivated = false;
}
public void stopRightArm() {
speakBlocking(get("STOPRIGHTARM"));
releasePeer("rightArm");
isRightArmActivated = false;
}
public void stopRightHand() {
speakBlocking(get("STOPRIGHTHAND"));
releasePeer("rightHand");
isRightHandActivated = false;
}
public void stopTorso() {
speakBlocking(get("STOPTORSO"));
releasePeer("torso");
isTorsoActivated = false;
}
public void stopSimulator() {
speakBlocking(get("STOPVIRTUAL"));
releasePeer("simulator");
simulator = null;
isSimulatorActivated = false;
}
public void stopUltraSonicRight() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultraSonicRight");
isUltraSonicRightActivated = false;
}
public void stopUltraSonicLeft() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultraSonicLeft");
isUltraSonicLeftActivated = false;
}
public void stopPir() {
speakBlocking(get("STOPPIR"));
releasePeer("pir");
isPirActivated = false;
}
public void stopNeopixelAnimation() {
if (neopixel != null) {
neopixel.animationStop();
} else {
warn("No Neopixel attached");
}
}
public void stopServoMixer() {
speakBlocking(get("STOPSERVOMIXER"));
releasePeer("servomixer");
isServoMixerActivated = false;
}
public void waitTargetPos() {
if (head != null) {
head.waitTargetPos();
}
if (leftArm != null) {
leftArm.waitTargetPos();
}
if (rightArm != null) {
rightArm.waitTargetPos();
}
if (leftHand != null) {
leftHand.waitTargetPos();
}
if (rightHand != null) {
rightHand.waitTargetPos();
}
if (torso != null) {
torso.waitTargetPos();
}
}
public NeoPixel startNeopixel() {
return startNeopixel(getName() + ".right", 2, 16);
}
public NeoPixel startNeopixel(String controllerName) {
return startNeopixel(controllerName, 2, 16);
}
public NeoPixel startNeopixel(String controllerName, int pin, int numPixel) {
if (neopixel == null) {
try {
neopixel = (NeoPixel) startPeer("neopixel");
speakBlocking(get("STARTINGNEOPIXEL"));
// FIXME - lame use peers
isNeopixelActivated = true;
neopixel.attach(Runtime.getService(controllerName));
} catch (Exception e) {
error(e);
}
}
return neopixel;
}
@Override
public void attachTextListener(String name) {
addListener("publishText", name);
}
} |
package org.myrobotlab.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.inmoov.Utils;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.Simulator;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider {
public final static Logger log = LoggerFactory.getLogger(InMoov2.class);
public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>();
// FIXME - why
static boolean RobotCanMoveRandom = true;
private static final long serialVersionUID = 1L;
static String speechRecognizer = "WebkitSpeechRecognition";
/**
* This static method returns all the details of the class without it having to
* be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(InMoov2.class);
meta.addDescription("InMoov2 Service");
meta.addCategory("robot");
meta.sharePeer("mouthControl.mouth", "mouth", "MarySpeech", "shared Speech");
meta.addPeer("eye", "OpenCV", "eye");
meta.addPeer("servomixer", "ServoMixer", "for making gestures");
// the two legacy controllers .. :(
meta.addPeer("left", "Arduino", "legacy controller");
meta.addPeer("right", "Arduino", "legacy controller");
meta.addPeer("htmlFilter", "HtmlFilter", "filter speaking html");
meta.addPeer("brain", "ProgramAB", "brain");
meta.addPeer("simulator", "JMonkeyEngine", "simulator");
meta.addPeer("head", "InMoov2Head", "head");
meta.addPeer("torso", "InMoov2Torso", "torso");
// meta.addPeer("eyelids", "InMoovEyelids", "eyelids");
meta.addPeer("leftArm", "InMoov2Arm", "left arm");
meta.addPeer("leftHand", "InMoov2Hand", "left hand");
meta.addPeer("rightArm", "InMoov2Arm", "right arm");
meta.addPeer("rightHand", "InMoov2Hand", "right hand");
meta.addPeer("mouthControl", "MouthControl", "MouthControl");
// meta.addPeer("imageDisplay", "ImageDisplay", "image display service");
meta.addPeer("mouth", "MarySpeech", "InMoov speech service");
meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service");
meta.addPeer("headTracking", "Tracking", "Head tracking system");
meta.sharePeer("headTracking.opencv", "eye", "OpenCV", "shared head OpenCV");
// meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head
// Arduino"); NO !!!!
meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo");
meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo");
// Global - undecorated by self name
meta.addRootPeer("python", "Python", "shared Python service");
// latest - not ready until repo is ready
meta.addDependency("fr.inmoov", "inmoov2", null, "zip");
return meta;
}
/**
* This method will load a python file into the python interpreter.
*/
public static boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Platform.setVirtual(true);
// Runtime.main(new String[] { "--install", "InMoov2" });
// Runtime.main(new String[] { "--interactive", "--id", "inmoov",
// "--install-dependency","fr.inmoov", "inmoov2", "latest", "zip"});
Runtime.main(new String[] {
"--resource-override",
"InMoov2=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/InMoov2",
"WebGui=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/WebGui",
"ProgramAB=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/ProgramAB",
"--interactive", "--id", "inmoov" });
String[] langs = java.util.Locale.getISOLanguages();
java.util.Locale[] locales = java.util.Locale.getAvailableLocales();
log.info("{}", locales.length);
for (java.util.Locale l : locales) {
log.info("
log.info(CodecUtils.toJson(l));
log.info(l.getDisplayLanguage());
log.info(l.getLanguage());
log.info(l.getCountry());
log.info(l.getDisplayCountry());
log.info(CodecUtils.toJson(new Locale(l)));
if (l.getLanguage().equals("en")) {
log.info("here");
}
}
InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
boolean done = true;
if (done) {
return;
}
i01.startBrain();
i01.startAll("COM3", "COM4");
Runtime.start("python", "Python");
// Runtime.start("log", "Log");
/*
* OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); cv.setCameraIndex(2);
*/
// i01.startSimulator();
/*
* Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
* mega.connect("/dev/ttyACM0");
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
boolean autoStartBrowser = false;
transient ProgramAB brain;
Set<String> configs = null;
String currentConfigurationName = "default";
transient SpeechRecognizer ear;
transient OpenCV eye;
transient Tracking eyesTracking;
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
// FIXME - what the hell is this for ?
Set<String> gestures = new TreeSet<String>();
transient InMoov2Head head;
transient Tracking headTracking;
transient HtmlFilter htmlFilter;
// transient ImageDisplay imageDisplay;
/**
* simple booleans to determine peer state of existence FIXME - should be an
* auto-peer variable
*/
boolean isBrainActivated = false;
boolean isEarActivated = false;
boolean isEyeActivated = false;
boolean isEyeLidsActivated = false;
boolean isHeadActivated = false;
boolean isLeftArmActivated = false;
boolean isLeftHandActivated = false;
boolean isMouthActivated = false;
boolean isRightArmActivated = false;
boolean isRightHandActivated = false;
boolean isSimulatorActivated = false;
boolean isTorsoActivated = false;
boolean isNeopixelActivated = false;
boolean isPirActivated = false;
boolean isUltraSonicSensorActivated = false;
boolean isServoMixerActivated = false;
// TODO - refactor into a Simulator interface when more simulators are borgd
transient JMonkeyEngine jme;
String lastGestureExecuted;
Long lastPirActivityTime;
transient InMoov2Arm leftArm;
// transient LanguagePack languagePack = new LanguagePack();
// transient InMoovEyelids eyelids; eyelids are in the head
transient InMoov2Hand leftHand;
Locale locale;
/**
* supported locales
*/
Map<String, Locale> locales = null;
int maxInactivityTimeSeconds = 120;
transient SpeechSynthesis mouth;
// FIXME ugh - new MouthControl service that uses AudioFile output
transient public MouthControl mouthControl;
boolean mute = false;
transient NeoPixel neopixel;
transient ServoMixer servomixer;
transient Python python;
transient InMoov2Arm rightArm;
transient InMoov2Hand rightHand;
/**
* used to remember/serialize configuration the user's desired speech type
*/
String speechService = "MarySpeech";
transient InMoov2Torso torso;
@Deprecated
public Vision vision;
// FIXME - remove all direct references
// transient private HashMap<String, InMoov2Arm> arms = new HashMap<>();
protected List<Voice> voices = null;
protected String voiceSelected;
transient WebGui webgui;
public InMoov2(String n, String id) {
super(n, id);
// by default all servos will auto-disable
Servo.setAutoDisableDefault(true);
locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI",
"pt-PT");
locale = Runtime.getInstance().getLocale();
python = (Python) startPeer("python");
load(locale.getTag());
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
listConfigFiles();
// FIXME - Framework should auto-magically auto-start peers AFTER
// construction - unless explicitly told not to
// peers to start on construction
// imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
@Override /* local strong type - is to be avoided - use name string */
public void addTextListener(TextListener service) {
// CORRECT WAY ! - no direct reference - just use the name in a subscription
addListener("publishText", service.getName());
}
@Override
public void attachTextListener(TextListener service) {
addListener("publishText", service.getName());
}
public void attachTextPublisher(String name) {
subscribe(name, "publishText");
}
@Override
public void attachTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
public void closeAllImages() {
// imageDisplay.closeAll();
log.error("implement webgui.closeAllImages");
}
public void cycleGestures() {
// if not loaded load -
// FIXME - this needs alot of "help" :P
// WHY IS THIS DONE ?
if (gestures.size() == 0) {
loadGestures();
}
for (String gesture : gestures) {
try {
String methodName = gesture.substring(0, gesture.length() - 3);
speakBlocking(methodName);
log.info("executing gesture {}", methodName);
python.eval(methodName + "()");
// wait for finish - or timeout ?
} catch (Exception e) {
error(e);
}
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
}
public void displayFullScreen(String src) {
try {
// imageDisplay.displayFullScreen(src);
log.error("implement webgui.displayFullScreen");
} catch (Exception e) {
error("could not display picture %s", src);
}
}
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
}
/**
* This method will try to launch a python command with error handling
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
public void fullSpeed() {
if (head != null) {
head.fullSpeed();
}
if (rightHand != null) {
rightHand.fullSpeed();
}
if (leftHand != null) {
leftHand.fullSpeed();
}
if (rightArm != null) {
rightArm.fullSpeed();
}
if (leftArm != null) {
leftArm.fullSpeed();
}
if (torso != null) {
torso.fullSpeed();
}
}
public String get(String param) {
if (lpVars.containsKey(param.toUpperCase())) {
return lpVars.get(param.toUpperCase());
}
return "not yet translated";
}
public InMoov2Arm getArm(String side) {
if ("left".equals(side)) {
return leftArm;
} else if ("right".equals(side)) {
return rightArm;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Hand getHand(String side) {
if ("left".equals(side)) {
return leftHand;
} else if ("right".equals(side)) {
return rightHand;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Head getHead() {
return head;
}
/**
* get current language
*/
public String getLanguage() {
return locale.getLanguage();
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (lastPirActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public InMoov2Arm getLeftArm() {
return leftArm;
}
public InMoov2Hand getLeftHand() {
return leftHand;
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public Map<String, Locale> getLocales() {
return locales;
}
public InMoov2Arm getRightArm() {
return rightArm;
}
public InMoov2Hand getRightHand() {
return rightHand;
}
public Simulator getSimulator() {
return jme;
}
public InMoov2Torso getTorso() {
return torso;
}
public void halfSpeed() {
if (head != null) {
head.setSpeed(25.0, 25.0, 25.0, 25.0, -1.0, 25.0);
}
if (rightHand != null) {
rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setSpeed(20.0, 20.0, 20.0);
}
}
public boolean isCameraOn() {
if (eye != null) {
if (eye.isCapturing()) {
return true;
}
}
return false;
}
public boolean isEyeLidsActivated() {
return isEyeLidsActivated;
}
public boolean isHeadActivated() {
return isHeadActivated;
}
public boolean isLeftArmActivated() {
return isLeftArmActivated;
}
public boolean isLeftHandActivated() {
return isLeftHandActivated;
}
public boolean isMute() {
return mute;
}
public boolean isNeopixelActivated() {
return isNeopixelActivated;
}
public boolean isRightArmActivated() {
return isRightArmActivated;
}
public boolean isRightHandActivated() {
return isRightHandActivated;
}
public boolean isTorsoActivated() {
return isTorsoActivated;
}
public boolean isPirActivated() {
return isPirActivated;
}
public boolean isUltraSonicSensorActivated() {
return isUltraSonicSensorActivated;
}
public boolean isServoMixerActivated() {
return isServoMixerActivated;
}
public Set<String> listConfigFiles() {
configs = new HashSet<>();
// data list
String configDir = getResourceDir() + fs + "config";
File f = new File(configDir);
if (!f.exists()) {
f.mkdirs();
}
String[] files = f.list();
for (String config : files) {
configs.add(config);
}
// data list
configDir = getDataDir() + fs + "config";
f = new File(configDir);
if (!f.exists()) {
f.mkdirs();
}
files = f.list();
for (String config : files) {
configs.add(config);
}
return configs;
}
/*
* iterate over each txt files in the directory
*/
public void load(String locale) {
String extension = "lang";
File dir = Utils.makeDirectory(getResourceDir() + File.separator + "system" + File.separator + "languagePack"
+ File.separator + locale);
if (dir.exists()) {
lpVars.clear();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
continue;
}
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
log.info("Inmoov languagePack load : {}", f.getName());
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
for (String line = br.readLine(); line != null; line = br.readLine()) {
String[] parts = line.split("::");
if (parts.length > 1) {
lpVars.put(parts[0].toUpperCase(), parts[1]);
}
}
} catch (IOException e) {
log.error("LanguagePack : {}", e);
}
} else {
log.warn("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
}
// FIXME - what is this for ???
public void loadGestures() {
loadGestures(getResourceDir() + fs + "gestures");
}
/**
* This blocking method will look at all of the .py files in a directory. One by
* one it will load the files into the python interpreter. A gesture python file
* should contain 1 method definition that is the same as the filename.
*
* @param directory - the directory that contains the gesture python files.
*/
public boolean loadGestures(String directory) {
speakBlocking("loading gestures"); // FIXME - make polyglot
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = new File(directory);
dir.mkdirs();
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
String methodName = f.getName().substring(0, f.getName().length() - 3) + "()";
gestures.add(methodName);
} else {
error("could not load %s", f.getName());
totalError += 1;
}
} else {
log.info("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
broadcastState();
if (totalError > 0) {
speakAlert(get("GESTURE_ERROR"));
return false;
}
return true;
}
public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
info("%s arm not started", which);
return;
}
arm.moveTo(bicep, rotate, shoulder, omoplate);
}
public void moveEyelids(double eyelidleftPos, double eyelidrightPos) {
if (head != null) {
head.moveEyelidsTo(eyelidleftPos, eyelidrightPos);
} else {
log.warn("moveEyelids - I have a null head");
}
}
public void moveEyes(double eyeX, double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.warn("moveEyes - I have a null head");
}
}
public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky,
Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
log.warn("{} hand does not exist");
return;
}
hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveHead(double neck, double rothead) {
moveHead(neck, rothead, null);
}
public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(neck, rothead, null, null, null, rollNeck);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveHeadBlocking(double neck, double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(double neck, double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
public OpenCVData onOpenCVData(OpenCVData data) {
return data;
}
@Override
public void onText(String text) {
// FIXME - we should be able to "re"-publish text but text is coming from
// different sources
// some might be coming from the ear - some from the mouth ... - there has
// to be a distinction
log.info("onText - {}", text);
invoke("publishText", text);
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
/**
* all published text from InMoov2 - including ProgramAB
*/
@Override
public String publishText(String text) {
return text;
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
// FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest
public void rest() {
log.info("InMoov2.rest()");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
}
@Deprecated
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
if (arm == null) {
warn("%s hand not started", which);
return;
}
arm.setSpeed(bicep, rotate, shoulder, omoplate);
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
/*
* if (eyelids != null) { eyelids.setAutoDisable(param); }
*/
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger,
Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky,
Double wrist) {
InMoov2Hand hand = getHand(which);
if (hand == null) {
warn("%s hand not started", which);
return;
}
hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger,
Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger,
Double pinky, Double wrist) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed,
Double rollNeckSpeed) {
if (head == null) {
warn("setHeadSpeed - head not started");
return;
}
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed,
Double rollNeckSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
/**
* TODO : use system locale set language for InMoov service used by chatbot +
*
* @param code
* @return
*/
@Deprecated /* use setLocale */
public String setLanguage(String code) {
setLocale(code);
return code;
}
@Override
public void setLocale(String code) {
if (code == null) {
log.warn("setLocale null");
return;
}
// filter of the set of supported locales
if (!locales.containsKey(code)) {
error("InMooov does not support %s only %s", code, locales.keySet());
return;
}
locale = new Locale(code);
speakBlocking("setting language to %s", locale.getDisplayLanguage());
// attempt to set all other language providers to the same language as me
List<String> providers = Runtime.getServiceNamesFromInterface(LocaleProvider.class);
for (String provider : providers) {
if (!provider.equals(getName())) {
log.info("{} setting locale to %s", provider, code);
send(provider, "setLocale", code);
send(provider, "broadcastState");
}
}
load(locale.getTag());
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
sendToPeer("mouth", "setMute", mute);
broadcastState();
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null /* && neopixelArduino != null */) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public String setSpeechType(String speechType) {
speechService = speechType;
setPeer("mouth", speechType);
return speechType;
}
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
@Deprecated
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
/**
* overridden setVirtual for InMoov sets "all" services to virtual
*/
public boolean setVirtual(boolean virtual) {
super.setVirtual(virtual);
Platform.setVirtual(virtual);
return virtual;
}
public void setVoice(String name) {
if (mouth != null) {
mouth.setVoice(name);
voiceSelected = name;
speakBlocking("setting voice to %s", name);
}
}
public void speak(String toSpeak) {
sendToPeer("mouth", "speak", toSpeak);
}
public void speakAlert(String toSpeak) {
speakBlocking(get("ALERT"));
speakBlocking(toSpeak);
}
public void speakBlocking(String speak) {
speakBlocking(speak, null);
}
// FIXME - publish text regardless if mouth exists ...
public void speakBlocking(String format, Object... args) {
if (format == null) {
return;
}
String toSpeak = format;
if (args != null) {
toSpeak = String.format(format, args);
}
// FIXME - publish onText when listening
invoke("publishText", toSpeak);
if (!mute) {
// sendToPeer("mouth", "speakBlocking", toSpeak);
invokePeer("mouth", "speakBlocking", toSpeak);
}
}
public void startAll() throws Exception {
startAll(null, null);
}
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startBrain();
startHeadTracking();
// startEyesTracking();
// startOpenCV();
startEar();
startServos(leftPort, rightPort);
// startMouthControl(head.jaw, mouth);
speakBlocking("startup sequence completed");
}
public ProgramAB startBrain() {
try {
brain = (ProgramAB) startPeer("brain");
isBrainActivated = true;
speakBlocking(get("CHATBOTACTIVATED"));
// GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions !
// attachTextPublisher(brain.getName());
/*
* not necessary - ear needs to be attached to mouth not brain if (ear != null)
* { ear.attachTextListener(brain); }
*/
brain.attachTextPublisher(ear);
// this.attach(brain); FIXME - attach as a TextPublisher - then re-publish
// FIXME - deal with language
// speakBlocking(get("CHATBOTACTIVATED"));
brain.repetitionCount(10);
brain.setPath(getResourceDir() + fs + "chatbot");
brain.startSession("default", locale.getTag());
// reset some parameters to default...
brain.setPredicate("topic", "default");
brain.setPredicate("questionfirstinit", "");
brain.setPredicate("tmpname", "");
brain.setPredicate("null", "");
// load last user session
if (!brain.getPredicate("name").isEmpty()) {
if (brain.getPredicate("lastUsername").isEmpty()
|| brain.getPredicate("lastUsername").equals("unknown")) {
brain.setPredicate("lastUsername", brain.getPredicate("name"));
}
}
brain.setPredicate("parameterHowDoYouDo", "");
try {
brain.savePredicates();
} catch (IOException e) {
log.error("saving predicates threw", e);
}
// start session based on last recognized person
if (!brain.getPredicate("default", "lastUsername").isEmpty()
&& !brain.getPredicate("default", "lastUsername").equals("unknown")) {
brain.startSession(brain.getPredicate("lastUsername"));
}
htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter",
// "HtmlFilter");
brain.attachTextListener(htmlFilter);
htmlFilter.attachTextListener((TextListener) getPeer("mouth"));
brain.attachTextListener(this);
} catch (Exception e) {
speak("could not load brain");
error(e.getMessage());
speak(e.getMessage());
}
broadcastState();
return brain;
}
public SpeechRecognizer startEar() {
ear = (SpeechRecognizer) startPeer("ear");
isEarActivated = true;
ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth"));
ear.attachTextListener(brain);
speakBlocking(get("STARTINGEAR"));
broadcastState();
return ear;
}
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
// FIXME - universal (good) way of handling all exceptions - ie - reporting
// back to the user the problem in a short concise way but have
// expandable detail in appropriate places
public OpenCV startEye() throws Exception {
speakBlocking(get("STARTINGOPENCV"));
eye = (OpenCV) startPeer("eye", "OpenCV");
subscribeTo(eye.getName(), "publishOpenCVData");
isEyeActivated = true;
return eye;
}
public Tracking startEyesTracking() throws Exception {
if (head == null) {
startHead();
}
return startHeadTracking(head.eyeX, head.eyeY);
}
public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception {
if (eye == null) {
startEye();
}
speakBlocking(get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.connect(eye, head.eyeX, head.eyeY);
return eyesTracking;
}
public InMoov2Head startHead() throws Exception {
return startHead(null, null, null, null, null, null, null, null);
}
public InMoov2Head startHead(String port) throws Exception {
return startHead(port, null, null, null, null, null, null, null);
}
// legacy inmoov head exposed pins
public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin,
Integer eyeYPin, Integer jawPin, Integer rollNeckPin) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
speakBlocking(get("STARTINGHEAD"));
head = (InMoov2Head) startPeer("head");
isHeadActivated = true;
if (headYPin != null) {
head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
// lame assumption - port is specified - it must be an Arduino :(
if (port != null) {
try {
speakBlocking(get(port));
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(head.neck);
arduino.attach(head.rothead);
arduino.attach(head.eyeX);
arduino.attach(head.eyeY);
arduino.attach(head.jaw);
arduino.attach(head.rollNeck);
} catch (Exception e) {
error(e);
}
}
speakBlocking(get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) getPeer("mouth"));
mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for
// config !!!
return head;
}
public void startHeadTracking() throws Exception {
if (eye == null) {
startEye();
}
if (head == null) {
startHead();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.eye, head.rothead, head.neck);
}
}
public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception {
if (eye == null) {
startEye();
}
if (headTracking == null) {
speakBlocking(get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.eye, rothead, neck);
}
return headTracking;
}
public InMoov2Arm startLeftArm() {
return startLeftArm(null);
}
public InMoov2Arm startLeftArm(String port) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
speakBlocking(get("STARTINGLEFTARM"));
leftArm = (InMoov2Arm) startPeer("leftArm");
isLeftArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(leftArm.bicep);
arduino.attach(leftArm.omoplate);
arduino.attach(leftArm.rotate);
arduino.attach(leftArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return leftArm;
}
public InMoov2Hand startLeftHand() {
return startLeftHand(null);
}
public InMoov2Hand startLeftHand(String port) {
speakBlocking(get("STARTINGLEFTHAND"));
leftHand = (InMoov2Hand) startPeer("leftHand");
isLeftHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(leftHand.thumb);
arduino.attach(leftHand.index);
arduino.attach(leftHand.majeure);
arduino.attach(leftHand.ringFinger);
arduino.attach(leftHand.pinky);
arduino.attach(leftHand.wrist);
} catch (Exception e) {
error(e);
}
}
return leftHand;
}
// TODO - general objective "might" be to reduce peers down to something
// that does not need a reference - where type can be switched before creation
// and the onnly thing needed is pubs/subs that are not handled in abstracts
public SpeechSynthesis startMouth() {
mouth = (SpeechSynthesis) startPeer("mouth");
voices = mouth.getVoices();
Voice voice = mouth.getVoice();
if (voice != null) {
voiceSelected = voice.getName();
}
isMouthActivated = true;
if (mute) {
mouth.setMute(true);
}
mouth.attachSpeechRecognizer(ear);
// mouth.attach(htmlFilter); // same as brain not needed
// this.attach((Attachable) mouth);
// if (ear != null) ....
broadcastState();
speakBlocking(get("STARTINGMOUTH"));
if (Platform.isVirtual()) {
speakBlocking("in virtual hardware mode");
}
speakBlocking(get("WHATISTHISLANGUAGE"));
return mouth;
}
@Deprecated /* use start eye */
public void startOpenCV() throws Exception {
startEye();
}
public InMoov2Arm startRightArm() {
return startRightArm(null);
}
public InMoov2Arm startRightArm(String port) {
speakBlocking(get("STARTINGRIGHTARM"));
rightArm = (InMoov2Arm) startPeer("rightArm");
isRightArmActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right", "Arduino");
arduino.connect(port);
arduino.attach(rightArm.bicep);
arduino.attach(rightArm.omoplate);
arduino.attach(rightArm.rotate);
arduino.attach(rightArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return rightArm;
}
public InMoov2Hand startRightHand() {
return startRightHand(null);
}
public InMoov2Hand startRightHand(String port) {
speakBlocking(get("STARTINGRIGHTHAND"));
rightHand = (InMoov2Hand) startPeer("rightHand");
isRightHandActivated = true;
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("right", "Arduino");
arduino.connect(port);
arduino.attach(rightHand.thumb);
arduino.attach(rightHand.index);
arduino.attach(rightHand.majeure);
arduino.attach(rightHand.ringFinger);
arduino.attach(rightHand.pinky);
arduino.attach(rightHand.wrist);
} catch (Exception e) {
error(e);
}
}
return rightHand;
}
public void startServos(String leftPort, String rightPort) throws Exception {
startHead(leftPort);
startLeftArm(leftPort);
startLeftHand(leftPort);
startRightArm(rightPort);
startRightHand(rightPort);
startTorso(leftPort);
}
// FIXME .. externalize in a json file included in InMoov2
public Simulator startSimulator() throws Exception {
speakBlocking(get("STARTINGVIRTUAL"));
if (jme != null) {
log.info("start called twice - starting simulator is reentrant");
return jme;
}
jme = (JMonkeyEngine) startPeer("simulator");
isSimulatorActivated = true;
// adding InMoov2 asset path to the jonkey simulator
String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName();
File check = new File(assetPath);
log.info("loading assets from {}", assetPath);
if (!check.exists()) {
log.warn("%s does not exist");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
// jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into
// /resource/JMonkeyEngine/assets
jme.setRotation(getName() + ".head.jaw", "x");
jme.setRotation(getName() + ".head.neck", "x");
jme.setRotation(getName() + ".head.rothead", "y");
jme.setRotation(getName() + ".head.rollNeck", "z");
jme.setRotation(getName() + ".head.eyeY", "x");
jme.setRotation(getName() + ".head.eyeX", "y");
jme.setRotation(getName() + ".torso.topStom", "z");
jme.setRotation(getName() + ".torso.midStom", "y");
jme.setRotation(getName() + ".torso.lowStom", "x");
jme.setRotation(getName() + ".rightArm.bicep", "x");
jme.setRotation(getName() + ".leftArm.bicep", "x");
jme.setRotation(getName() + ".rightArm.shoulder", "x");
jme.setRotation(getName() + ".leftArm.shoulder", "x");
jme.setRotation(getName() + ".rightArm.rotate", "y");
jme.setRotation(getName() + ".leftArm.rotate", "y");
jme.setRotation(getName() + ".rightArm.omoplate", "z");
jme.setRotation(getName() + ".leftArm.omoplate", "z");
jme.setRotation(getName() + ".rightHand.wrist", "y");
jme.setRotation(getName() + ".leftHand.wrist", "y");
jme.setMapper(getName() + ".head.jaw", 0, 180, -5, 80);
jme.setMapper(getName() + ".head.neck", 0, 180, 20, -20);
jme.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30);
jme.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140);
jme.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need
// to be
// two eyeX (left and
// right?)
jme.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150);
jme.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150);
jme.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150);
jme.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150);
jme.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80);
jme.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80);
jme.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180);
jme.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180);
jme.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60);
jme.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60);
jme.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30);
jme.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130);
jme.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30);
jme.attach(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2",
getName() + ".leftHand.thumb3");
jme.setRotation(getName() + ".leftHand.thumb1", "y");
jme.setRotation(getName() + ".leftHand.thumb2", "x");
jme.setRotation(getName() + ".leftHand.thumb3", "x");
jme.attach(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2",
getName() + ".leftHand.index3");
jme.setRotation(getName() + ".leftHand.index", "x");
jme.setRotation(getName() + ".leftHand.index2", "x");
jme.setRotation(getName() + ".leftHand.index3", "x");
jme.attach(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2",
getName() + ".leftHand.majeure3");
jme.setRotation(getName() + ".leftHand.majeure", "x");
jme.setRotation(getName() + ".leftHand.majeure2", "x");
jme.setRotation(getName() + ".leftHand.majeure3", "x");
jme.attach(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger",
getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3");
jme.setRotation(getName() + ".leftHand.ringFinger", "x");
jme.setRotation(getName() + ".leftHand.ringFinger2", "x");
jme.setRotation(getName() + ".leftHand.ringFinger3", "x");
jme.attach(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2",
getName() + ".leftHand.pinky3");
jme.setRotation(getName() + ".leftHand.pinky", "x");
jme.setRotation(getName() + ".leftHand.pinky2", "x");
jme.setRotation(getName() + ".leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
jme.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100);
jme.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20);
jme.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20);
// right hand
jme.attach(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2",
getName() + ".rightHand.thumb3");
jme.setRotation(getName() + ".rightHand.thumb1", "y");
jme.setRotation(getName() + ".rightHand.thumb2", "x");
jme.setRotation(getName() + ".rightHand.thumb3", "x");
jme.attach(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2",
getName() + ".rightHand.index3");
jme.setRotation(getName() + ".rightHand.index", "x");
jme.setRotation(getName() + ".rightHand.index2", "x");
jme.setRotation(getName() + ".rightHand.index3", "x");
jme.attach(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure",
getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3");
jme.setRotation(getName() + ".rightHand.majeure", "x");
jme.setRotation(getName() + ".rightHand.majeure2", "x");
jme.setRotation(getName() + ".rightHand.majeure3", "x");
jme.attach(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger",
getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3");
jme.setRotation(getName() + ".rightHand.ringFinger", "x");
jme.setRotation(getName() + ".rightHand.ringFinger2", "x");
jme.setRotation(getName() + ".rightHand.ringFinger3", "x");
jme.attach(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2",
getName() + ".rightHand.pinky3");
jme.setRotation(getName() + ".rightHand.pinky", "x");
jme.setRotation(getName() + ".rightHand.pinky2", "x");
jme.setRotation(getName() + ".rightHand.pinky3", "x");
jme.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10);
jme.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110);
jme.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150);
jme.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160);
// additional experimental mappings
/*
* simulator.attach(getName() + ".leftHand.pinky", getName() +
* ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb",
* getName() + ".leftHand.index3"); simulator.setRotation(getName() +
* ".leftHand.index2", "x"); simulator.setRotation(getName() +
* ".leftHand.index3", "x"); simulator.setMapper(getName() + ".leftHand.index",
* 0, 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index2", 0,
* 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index3", 0, 180,
* -90, -270);
*/
return jme;
}
public InMoov2Torso startTorso() {
return startTorso(null);
}
public InMoov2Torso startTorso(String port) {
if (torso == null) {
speakBlocking(get("STARTINGTORSO"));
isTorsoActivated = true;
torso = (InMoov2Torso) startPeer("torso");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(torso.lowStom);
left.attach(torso.midStom);
left.attach(torso.topStom);
} catch (Exception e) {
error(e);
}
}
}
return torso;
}
public ServoMixer startServoMixer() {
servomixer = (ServoMixer) startPeer("servomixer");
isServoMixerActivated = true;
speakBlocking(get("STARTINGSERVOMIXER"));
broadcastState();
return servomixer;
}
public void stop() {
if (head != null) {
head.stop();
}
if (rightHand != null) {
rightHand.stop();
}
if (leftHand != null) {
leftHand.stop();
}
if (rightArm != null) {
rightArm.stop();
}
if (leftArm != null) {
leftArm.stop();
}
if (torso != null) {
torso.stop();
}
}
public void stopBrain() {
speakBlocking(get("STOPCHATBOT"));
releasePeer("brain");
isBrainActivated = false;
}
public void stopEar() {
speakBlocking(get("STOPEAR"));
releasePeer("ear");
isEarActivated = false;
broadcastState();
}
public void stopEye() {
speakBlocking(get("STOPOPENCV"));
isEyeActivated = false;
releasePeer("eye");
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public void stopLeftArm() {
speakBlocking(get("STOPLEFTARM"));
releasePeer("leftArm");
isLeftArmActivated = false;
}
public void stopLeftHand() {
speakBlocking(get("STOPLEFTHAND"));
releasePeer("leftHand");
isLeftHandActivated = false;
}
public void stopMouth() {
speakBlocking(get("STOPMOUTH"));
releasePeer("mouth");
// TODO - potentially you could set the field to null in releasePeer
mouth = null;
isMouthActivated = false;
}
public void stopRightArm() {
speakBlocking(get("STOPRIGHTARM"));
releasePeer("rightArm");
isRightArmActivated = false;
}
public void stopRightHand() {
speakBlocking(get("STOPRIGHTHAND"));
releasePeer("rightHand");
isRightHandActivated = false;
}
public void stopTorso() {
speakBlocking(get("STOPTORSO"));
releasePeer("torso");
isTorsoActivated = false;
}
public void stopSimulator() {
speakBlocking(get("STOPVIRTUAL"));
releasePeer("simulator");
jme = null;
isSimulatorActivated = false;
}
public void stopPir() {
speakBlocking(get("STOPPIR"));
releasePeer("pir");
isPirActivated = false;
}
public void stopUltraSonicSensor() {
speakBlocking(get("STOPULTRASONIC"));
releasePeer("ultraSonicSensor");
isPirActivated = false;
}
public void stopServoMixer() {
speakBlocking(get("STOPSERVOMIXER"));
releasePeer("ServoMixer");
isServoMixerActivated = false;
}
public void waitTargetPos() {
if (head != null) {
head.waitTargetPos();
}
if (leftArm != null) {
leftArm.waitTargetPos();
}
if (rightArm != null) {
rightArm.waitTargetPos();
}
if (leftHand != null) {
leftHand.waitTargetPos();
}
if (rightHand != null) {
rightHand.waitTargetPos();
}
if (torso != null) {
torso.waitTargetPos();
}
}
} |
package org.restheart.db;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
import org.restheart.utils.HttpStatus;
import java.util.ArrayList;
import java.util.Deque;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Data Access Object for the mongodb Collection resource. NOTE: this class
* is package-private and only meant to be used as a delagate within the DbsDAO
* class.
*
* @author Andrea Di Cesare <andrea@softinstigate.com>
*/
class CollectionDAO {
private final MongoClient client;
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionDAO.class);
private static final BasicDBObject FIELDS_TO_RETURN;
CollectionDAO(MongoClient client) {
this.client = client;
}
static {
FIELDS_TO_RETURN = new BasicDBObject();
FIELDS_TO_RETURN.put("_id", 1);
FIELDS_TO_RETURN.put("_etag", 1);
}
/**
* Returns the mongodb DBCollection object for the collection in db dbName.
*
* @param dbName the database name of the collection the database name of
* the collection
* @param collName the collection name
* @return the mongodb DBCollection object for the collection in db dbName
*/
DBCollection getCollection(final String dbName, final String collName) {
return client.getDB(dbName).getCollection(collName);
}
/**
* Checks if the given collection is empty. Note that RESTHeart creates a
* reserved properties document in every collection (with _id
* '_properties'). This method returns true even if the collection contains
* such document.
*
* @param coll the mongodb DBCollection object
* @return true if the commection is empty
*/
public boolean isCollectionEmpty(final DBCollection coll) {
return coll.count() == 0;
}
/**
* Returns the number of documents in the given collection (taking into
* account the filters in case).
*
* @param coll the mongodb DBCollection object.
* @param filters the filters to apply. it is a Deque collection of mongodb
* query conditions.
* @return the number of documents in the given collection (taking into
* account the filters in case)
*/
public long getCollectionSize(final DBCollection coll, final Deque<String> filters) {
final BasicDBObject query = new BasicDBObject();
if (filters != null) {
try {
filters.stream().forEach(f -> {
query.putAll((BSONObject) JSON.parse(f)); // this can throw JSONParseException for invalid filter parameters
});
} catch (JSONParseException jpe) {
LOGGER.warn("****** error parsing filter expression {}", filters, jpe);
}
}
return coll.count(query);
}
DBCursor getCollectionDBCursor(
final DBCollection coll,
final Deque<String> sortBy,
final Deque<String> filters,
final Deque<String> keys) throws JSONParseException {
// apply sort_by
DBObject sort = new BasicDBObject();
if (sortBy == null || sortBy.isEmpty()) {
sort.put("_id", -1);
} else {
sortBy.stream().forEach((s) -> {
String _s = s.trim(); // the + sign is decoded into a space, in case remove it
if (_s.startsWith("-")) {
sort.put(_s.substring(1), -1);
} else if (_s.startsWith("+")) {
sort.put(_s.substring(1), 1);
} else {
sort.put(_s, 1);
}
});
}
// apply filter
final BasicDBObject query = new BasicDBObject();
if (filters != null) {
if (filters.size() > 1) {
BasicDBList _filters = new BasicDBList();
filters.stream().forEach((String f) -> {
_filters.add((BSONObject) JSON.parse(f));
});
query.put("$and", _filters);
} else {
BSONObject filterQuery = (BSONObject)
JSON.parse(filters.getFirst());
query.putAll(filterQuery); // this can throw JSONParseException for invalid filter parameters
}
}
final BasicDBObject fields = new BasicDBObject();
if (keys
!= null) {
keys.stream().forEach((String f) -> {
BSONObject keyQuery = (BSONObject) JSON.parse(f);
fields.putAll(keyQuery); // this can throw JSONParseException for invalid filter parameters
});
}
return coll.find (query, fields)
.sort(sort);
}
ArrayList<DBObject> getCollectionData(
final DBCollection coll,
final int page,
final int pagesize,
final Deque<String> sortBy,
final Deque<String> filters,
final Deque<String> keys, DBCursorPool.EAGER_CURSOR_ALLOCATION_POLICY eager) throws JSONParseException {
ArrayList<DBObject> ret = new ArrayList<>();
int toskip = pagesize * (page - 1);
SkippedDBCursor _cursor = null;
if (eager != DBCursorPool.EAGER_CURSOR_ALLOCATION_POLICY.NONE) {
_cursor = DBCursorPool.getInstance().get(new DBCursorPoolEntryKey(coll, sortBy, filters, keys, toskip, 0), eager);
}
int _pagesize = pagesize;
// in case there is not cursor in the pool to reuse
DBCursor cursor;
if (_cursor == null) {
cursor = getCollectionDBCursor(coll, sortBy, filters, keys);
cursor.skip(toskip);
while (_pagesize > 0 && cursor.hasNext()) {
ret.add(cursor.next());
_pagesize
}
} else {
int alreadySkipped;
cursor = _cursor.getCursor();
alreadySkipped = _cursor.getAlreadySkipped();
while (toskip > alreadySkipped && cursor.hasNext()) {
cursor.next();
alreadySkipped++;
}
while (_pagesize > 0 && cursor.hasNext()) {
ret.add(cursor.next());
_pagesize
}
}
return ret;
}
/**
* Returns the collection properties document.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @return the collection properties document
*/
public DBObject getCollectionProps(final String dbName, final String collName, final boolean fixMissingProperties) {
DBCollection propsColl = getCollection(dbName, "_properties");
DBObject properties = propsColl.findOne(new BasicDBObject("_id", "_properties.".concat(collName)));
if (properties != null) {
properties.put("_id", collName);
} else if (fixMissingProperties) {
try {
new PropsFixer().addCollectionProps(dbName, collName);
return getCollectionProps(dbName, collName, false);
} catch (MongoException mce) {
int errCode = mce.getCode();
if (errCode == 13 || errCode == 1000) {
// mongodb user is not allowed to write (no readWrite role)
// just return properties with _id
properties = new BasicDBObject("_id", collName);
} else {
throw mce;
}
}
}
return properties;
}
/**
* Upsert the collection properties.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @param properties the new collection properties
* @param requestEtag the entity tag. must match to allow actual write
* (otherwise http error code is returned)
* @param updating true if updating existing document
* @param patching true if use patch semantic (update only specified fields)
* @return the HttpStatus code to set in the http response
*/
OperationResult upsertCollection(
final String dbName,
final String collName,
final DBObject properties,
final ObjectId requestEtag,
final boolean updating,
final boolean patching
) {
if (patching && !updating) {
return new OperationResult(HttpStatus.SC_NOT_FOUND);
}
DB db = client.getDB(dbName);
final DBCollection propsColl = db.getCollection("_properties");
final DBObject exists = propsColl.findOne(new BasicDBObject("_id", "_properties.".concat(collName)), FIELDS_TO_RETURN);
if (exists == null && updating) {
LOGGER.error("updating but cannot find collection _properties.{} for {}/{}", collName, dbName, collName);
return new OperationResult(HttpStatus.SC_NOT_FOUND);
} else if (exists != null) {
Object oldEtag = exists.get("_etag");
if (oldEtag != null) {
if (requestEtag == null) {
return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
}
if (!oldEtag.equals(requestEtag)) {
return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
}
}
}
ObjectId newEtag = new ObjectId();
final DBObject content = DAOUtils.validContent(properties);
content.removeField("_id"); // make sure we don't change this field
if (updating) {
content.removeField("_crated_on"); // don't allow to update this field
content.put("_etag", newEtag);
} else {
content.put("_id", "_properties.".concat(collName));
content.put("_etag", newEtag);
}
if (patching) {
propsColl.update(new BasicDBObject("_id", "_properties.".concat(collName)),
new BasicDBObject("$set", content), true, false);
return new OperationResult(HttpStatus.SC_OK, newEtag);
} else {
propsColl.update(new BasicDBObject("_id", "_properties.".concat(collName)),
content, true, false);
// create the default indexes
createDefaultIndexes(db.getCollection(collName));
if (updating) {
return new OperationResult(HttpStatus.SC_OK, newEtag);
} else {
return new OperationResult(HttpStatus.SC_CREATED, newEtag);
}
}
}
/**
* Deletes a collection.
*
* @param dbName the database name of the collection
* @param collName the collection name
* @param requestEtag the entity tag. must match to allow actual write
* (otherwise http error code is returned)
* @return the HttpStatus code to set in the http response
*/
OperationResult deleteCollection(final String dbName,
final String collName,
final ObjectId requestEtag
) {
DBCollection coll = getCollection(dbName, collName);
DBCollection propsColl = getCollection(dbName, "_properties");
final BasicDBObject checkEtag = new BasicDBObject("_id", "_properties.".concat(collName));
final DBObject exists = propsColl.findOne(checkEtag, FIELDS_TO_RETURN);
if (exists != null) {
Object oldEtag = exists.get("_etag");
if (oldEtag != null && requestEtag == null) {
return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
}
if (requestEtag.equals(oldEtag)) {
propsColl.remove(new BasicDBObject("_id", "_properties.".concat(collName)));
coll.drop();
return new OperationResult(HttpStatus.SC_NO_CONTENT);
} else {
return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
}
} else {
LOGGER.error("cannot find collection _properties.{} for {}/{}", collName, dbName, collName);
return new OperationResult(HttpStatus.SC_NOT_FOUND);
}
}
private void createDefaultIndexes(final DBCollection coll) {
coll.createIndex(new BasicDBObject("_id", 1).append("_etag", 1), new BasicDBObject("name", "_id_etag_idx"));
coll.createIndex(new BasicDBObject("_etag", 1), new BasicDBObject("name", "_etag_idx"));
}
} |
package org.scm4j.releaser;
import org.scm4j.commons.Version;
import org.scm4j.releaser.actions.ActionKind;
import org.scm4j.releaser.actions.ActionNone;
import org.scm4j.releaser.actions.IAction;
import org.scm4j.releaser.branch.DevelopBranch;
import org.scm4j.releaser.branch.DevelopBranchStatus;
import org.scm4j.releaser.branch.ReleaseBranch;
import org.scm4j.releaser.branch.ReleaseBranchStatus;
import org.scm4j.releaser.conf.*;
import org.scm4j.releaser.exceptions.EComponentConfig;
import org.scm4j.releaser.scmactions.ReleaseReason;
import org.scm4j.releaser.scmactions.SCMActionBuild;
import org.scm4j.releaser.scmactions.SCMActionFork;
import org.scm4j.releaser.scmactions.SCMActionTagRelease;
import org.scm4j.vcs.api.IVCS;
import org.scm4j.vcs.api.VCSTag;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class SCMReleaser {
public static final String MDEPS_FILE_NAME = "mdeps";
public static final String VER_FILE_NAME = "version";
public static final String DELAYED_TAGS_FILE_NAME = "delayed-tags.yml";
public static final File BASE_WORKING_DIR = new File(System.getProperty("user.home"), ".scm4j");
private final List<Option> options;
public SCMReleaser(List<Option> options) {
this.options = options;
}
public SCMReleaser() {
this(new ArrayList<Option>());
}
public static List<Option> parseOptions(String[] args) {
List<Option> options = new ArrayList<>();
for (String arg : args) {
if (Option.getArgsMap().containsKey(arg)) {
options.add(Option.getArgsMap().get(arg));
}
}
return options;
}
public static File getDelayedTagsFile() {
return new File(SCMReleaser.DELAYED_TAGS_FILE_NAME);
}
public IAction getProductionReleaseAction(String componentName) {
return getProductionReleaseActionFiltered(new Component(componentName, true), ActionKind.AUTO);
}
public IAction getProductionReleaseAction(String componentCoords, ActionKind actionKind) {
return getProductionReleaseActionFiltered(new Component(componentCoords, true), actionKind);
}
public IAction getProductionReleaseAction(Component comp) {
return getProductionReleaseActionFiltered(comp, ActionKind.AUTO);
}
private IAction getProductionReleaseActionFiltered(Component comp, ActionKind actionKind) {
IAction res = getProductionReleaseActionUnfiltered(comp);
filterUnsuitableActions(res, actionKind);
filterNonFirstParentKindActions(res, null);
return res;
}
private void filterNonFirstParentKindActions(IAction res, Class<?> firstParentActionClass) {
ListIterator<IAction> li = res.getChildActions().listIterator();
IAction action;
if (firstParentActionClass == null) {
if (res instanceof SCMActionBuild) {
firstParentActionClass = SCMActionBuild.class;
} else if (res instanceof SCMActionFork) {
firstParentActionClass = SCMActionFork.class;
}
}
while (li.hasNext()) {
action = li.next();
filterNonFirstParentKindActions(action, firstParentActionClass);
if (firstParentActionClass == SCMActionFork.class) {
if (action instanceof SCMActionBuild) {
li.set(new ActionNone(((SCMActionBuild) action).getComponent(), action.getChildActions(), ((SCMActionBuild) action).getTargetVersion() +
" build skipped because not all parent components forked"));
}
}
if (firstParentActionClass == SCMActionBuild.class) {
if (action instanceof SCMActionFork) {
li.set(new ActionNone(((SCMActionFork) action).getComponent(), action.getChildActions(), "fork skipped because not all parent components built"));
}
}
}
}
private void filterUnsuitableActions(IAction res, ActionKind actionKind) {
if (actionKind == ActionKind.AUTO) {
return;
}
ListIterator<IAction> li = res.getChildActions().listIterator();
IAction action;
while (li.hasNext()) {
action = li.next();
filterUnsuitableActions(action, actionKind);
switch (actionKind) {
case FORK:
if (action instanceof SCMActionBuild) {
li.set(new ActionNone(((SCMActionBuild) action).getComponent(), action.getChildActions(), ((SCMActionBuild) action).getTargetVersion() +
" build skipped because not all parent components forked"));
}
break;
case BUILD:
if (action instanceof SCMActionFork) {
li.set(new ActionNone(((SCMActionFork) action).getComponent(), action.getChildActions(), "fork skipped because not all parent components built"));
}
break;
default: {
throw new IllegalArgumentException("Unsupported action kind: " + actionKind);
}
}
}
}
private IAction getProductionReleaseActionUnfiltered(Component comp) {
List<IAction> childActions = new ArrayList<>();
/**
* all components are forked and ready o build. But Product is not changed. We have rb pointing to previous release.
* rb exists, so mdeps list will contain exact versions (for prev Product release) . So new versions of mdpes will not be taken. So need to use dev mdeps (snapshots) always.
*/
List<Component> mDeps = new DevelopBranch(comp).getMDeps();
boolean useSR = comp.getVersion().isExact();
for (Component mDep : mDeps) {
childActions.add(getProductionReleaseActionUnfiltered(useSR ? mDep.toServiceRelease() : mDep));
}
ReleaseBranch rb = new ReleaseBranch(comp);
return getProductionReleaseActionRoot(comp, rb, childActions);
}
private IAction getProductionReleaseActionRoot(Component comp, ReleaseBranch rb, List<IAction> childActions) {
DevelopBranch db = new DevelopBranch(comp);
if (!db.hasVersionFile()) {
throw new EComponentConfig("no " + VER_FILE_NAME + " file for " + comp.toString());
}
DevelopBranchStatus dbs = db.getStatus();
if (dbs == DevelopBranchStatus.IGNORED) {
return new ActionNone(comp, childActions, "develop branch is IGNORED");
}
ReleaseBranchStatus rbs = rb.getStatus();
if (rbs == ReleaseBranchStatus.MISSING) {
return new SCMActionFork(comp, rb, childActions, ReleaseBranchStatus.MISSING, ReleaseBranchStatus.MDEPS_ACTUAL, options);
}
if (rbs == ReleaseBranchStatus.BRANCHED) {
// need to freeze mdeps
return new SCMActionFork(comp, rb, childActions, ReleaseBranchStatus.BRANCHED, ReleaseBranchStatus.MDEPS_ACTUAL, options);
}
if (rbs == ReleaseBranchStatus.MDEPS_FROZEN) {
if (needToActualizeMDeps(rb)) {
// need to actualize
return new SCMActionFork(comp, rb, childActions, ReleaseBranchStatus.MDEPS_FROZEN, ReleaseBranchStatus.MDEPS_ACTUAL, options);
} else {
// All necessary version will be build by Child Actions. Need to build
return new SCMActionBuild(comp, rb, childActions, ReleaseReason.NEW_DEPENDENCIES, rb.getVersion(), options);
}
}
if (rbs == ReleaseBranchStatus.MDEPS_ACTUAL) {
// need to build
return new SCMActionBuild(comp, rb, childActions, ReleaseReason.NEW_FEATURES, rb.getVersion(), options);
}
// TODO: add test: product is ACTUAL, but child was forked sepearately. Product should be forked because component needs to be built.
if (hasSignificantActions(childActions)) {
// we are ACTUAL and have child forks or builds => we need to be forked
return new SCMActionFork(comp, new ReleaseBranch(comp, db.getVersion()), childActions, ReleaseBranchStatus.MISSING, ReleaseBranchStatus.MDEPS_ACTUAL, options);
}
return new ActionNone(comp, childActions, getReleaseBranchDetailsStr(rb, rbs));
}
private String getReleaseBranchDetailsStr(ReleaseBranch rb, ReleaseBranchStatus rbs) {
return rb.getName() + " " + rbs + ", target version " + rb.getVersion();
}
private boolean needToActualizeMDeps(ReleaseBranch currentCompRB) {
List<Component> mDeps = currentCompRB.getMDeps();
ReleaseBranch mDepRB;
for (Component mDep : mDeps) {
mDepRB = new ReleaseBranch(mDep);
ReleaseBranchStatus rbs = mDepRB.getStatus();
if (rbs == ReleaseBranchStatus.MDEPS_ACTUAL) {
if (!mDepRB.getHeadVersion().equals(mDep.getVersion())) {
return true;
}
} else if (rbs == ReleaseBranchStatus.ACTUAL) {
if (!mDepRB.getHeadVersion().toPreviousPatch().equals(mDep.getVersion())) {
return true;
}
} else {
if (needToActualizeMDeps(mDepRB)) {
return true;
}
}
}
return false;
}
private boolean hasSignificantActions(List<IAction> childActions) {
for (IAction action : childActions) {
if (action instanceof SCMActionFork || action instanceof SCMActionBuild) {
return true;
}
}
return false;
}
public IAction getTagReleaseAction(Component comp) {
List<IAction> childActions = new ArrayList<>();
DevelopBranch db = new DevelopBranch(comp);
List<Component> mDeps = db.getMDeps();
for (Component mDep : mDeps) {
childActions.add(getTagReleaseAction(mDep));
}
return getTagReleaseActionRoot(comp, childActions);
}
public IAction getTagReleaseAction(String compName) {
return getTagReleaseAction(new Component(compName));
}
private IAction getTagReleaseActionRoot(Component comp, List<IAction> childActions) {
DelayedTagsFile cf = new DelayedTagsFile();
IVCS vcs = comp.getVCS();
String delayedRevisionToTag = cf.getRevisitonByUrl(comp.getVcsRepository().getUrl());
if (delayedRevisionToTag == null) {
return new ActionNone(comp, childActions, "no delayed tags");
}
ReleaseBranch rb = new ReleaseBranch(comp);
List<VCSTag> tagsOnRevision = vcs.getTagsOnRevision(delayedRevisionToTag);
if (tagsOnRevision.isEmpty()) {
return new SCMActionTagRelease(comp, rb, childActions, options);
}
Version delayedTagVersion = new Version(vcs.getFileContent(rb.getName(), SCMReleaser.VER_FILE_NAME, delayedRevisionToTag));
for (VCSTag tag : tagsOnRevision) {
if (tag.getTagName().equals(delayedTagVersion.toReleaseString())) {
return new ActionNone(comp, childActions, "tag " + tag.getTagName() + " already exists");
}
}
return new SCMActionTagRelease(comp, rb, childActions, options);
}
public static TagDesc getTagDesc(String verStr) {
String tagMessage = verStr + " release";
return new TagDesc(verStr, tagMessage);
}
public List<Option> getOptions() {
return options;
}
} |
package org.smoothbuild.parse.ast;
import java.util.Optional;
import org.smoothbuild.lang.base.Loc;
import org.smoothbuild.lang.like.Obj;
import org.smoothbuild.util.collect.Named;
public sealed abstract class ArgP extends GenericP implements NamedP
permits DefaultArgP, ExplicitArgP {
private final Optional<String> name;
private final Obj obj;
public ArgP(Optional<String> name, Obj obj, Loc loc) {
super(loc);
this.name = name;
this.obj = obj;
}
public boolean declaresName() {
return nameO().isPresent();
}
@Override
public Optional<String> nameO() {
return name;
}
@Override
public String name() {
return name.get();
}
public abstract String nameSanitized();
public String typeAndName() {
return typeO().map(Named::name).orElse("<missing type>") + ":" + nameSanitized();
}
public Obj obj() {
return obj;
}
} |
package org.to2mbn.jmccc.util;
import java.nio.charset.Charset;
public enum Platform {
WINDOWS, LINUX, OSX, UNKNOWN;
/**
* Returns the file separator on the current platform.
* <p>
* This method refers to <code>System.getProperty("file.separator")</code>
*
* @return the file separator on the current platform
*/
public static String getFileSpearator() {
return System.getProperty("file.separator");
}
/**
* Returns the path separator on the current platform.
* <p>
* This method refers to <code>System.getProperty("path.separator")</code>
*
* @return the path separator on the current platform
*/
public static String getPathSpearator() {
return System.getProperty("path.separator");
}
/**
* Returns the line separator on the current platform.
* <p>
* This method refers to <code>System.lineSeparator()</code>
*
* @return the line separator on the current platform
*/
public static String getLineSpearator() {
return System.lineSeparator();
}
/**
* Returns the default encoding on the current platform.
* <p>
* This method refers to <code>System.getProperty("sun.jnu.encoding")</code>. If this property does not exist, the
* method will return <code>Charset.defaultCharset()</code>.
*
* @return the default encoding on the current platform
*/
public static String getEncoding() {
return System.getProperty("sun.jnu.encoding", Charset.defaultCharset().name());
}
/**
* The current platform, {@link Platform#UNKNOWN} if the current platform cannot be identified.
*/
public static final Platform CURRENT = getCurrent();
private static Platform getCurrent() {
String osName = System.getProperty("os.name");
if (osName.equals("Linux")) {
return LINUX;
} else if (osName.startsWith("Windows")) {
return WINDOWS;
} else if (osName.equals("Mac OS X")) {
return OSX;
} else {
return Platform.UNKNOWN;
}
}
} |
package org.vietabroader.view;
import org.vietabroader.GoogleAPIUtils;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import java.awt.Insets;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
class MainView extends JFrame {
MainView() {
initUI();
}
private void initUI() {
JPanel panelMain = new JPanel();
panelMain.setLayout(new GridBagLayout());
getContentPane().add(panelMain);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(4, 4, 4, 4); // Outer margin of each panel
panelMain.add(createSignInPanel(), c);
c.gridy = 2;
panelMain.add(createSpreadsheetPanel(), c);
c.gridy = 3;
panelMain.add(createWorkspacePanel(), c);
c.gridy = 4;
panelMain.add(createColumnPanel(), c);
c.gridy = 5;
c.gridwidth = 1;
c.gridx = 0;
panelMain.add(createGeneratePanel(), c);
c.gridx = 1;
panelMain.add(createWebcamPanel(), c);
setTitle("VAQR");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
pack();
setLocationRelativeTo(null);
}
private class TitledPanel extends JPanel {
private TitledPanel(String title) {
this.setLayout(new GridBagLayout());
this.setBorder(new CompoundBorder(
new TitledBorder(title),
new EmptyBorder(8, 8, 8, 8)) // Inner padding of each panel
);
}
}
private JPanel createSignInPanel() {
TitledPanel panel = new TitledPanel("Account");
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
final JButton btnSignIn = new JButton("Sign In");
final JLabel lblEmail = new JLabel("Please sign in with your Google account");
btnSignIn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String email = GoogleAPIUtils.signInAndGetEmail();
lblEmail.setText(email);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
panel.add(btnSignIn, c);
lblEmail.setPreferredSize(new Dimension(300, 15));
c.gridx = 1;
c.gridy = 0;
panel.add(lblEmail, c);
return panel;
}
private JPanel createSpreadsheetPanel() {
TitledPanel panel = new TitledPanel("Spreadsheet");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Spreadsheet ID: "), c);
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JTextField(15), c);
c.anchor = GridBagConstraints.CENTER;
c.gridx = 2;
panel.add(new JButton("Connect"));
return panel;
};
private JPanel createWorkspacePanel() {
TitledPanel panel = new TitledPanel("Workspace");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1/6.0;
c.anchor = GridBagConstraints.LINE_END;
panel.add(new JLabel("Sheet: "), c);
c.gridx = 1;
c.gridwidth = 3;
c.weightx = 5/6.0;
c.fill = GridBagConstraints.HORIZONTAL;
String[] sheet = {"Sheet1", "Sheet2"};
panel.add(new JComboBox(sheet), c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weightx = 1/6.0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_END;
panel.add(new JLabel("Column: "), c);
c.gridx = 1;
c.weightx = 2/6.0;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSpinner(), c);
c.gridx = 2;
c.weightx = 1/6.0;
c.fill = GridBagConstraints.NONE;
panel.add(new JLabel("to"), c);
c.gridx = 3;
c.weightx = 2/6.0;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSpinner(), c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.weightx = 1/6.0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_END;
panel.add(new JLabel("Row: "), c);
c.gridx = 1;
c.weightx = 2/6.0;
c.anchor = GridBagConstraints.LINE_END;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSpinner(), c);
c.gridx = 2;
c.weightx = 1/6.0;
c.fill = GridBagConstraints.NONE;
panel.add(new JLabel("to"), c);
c.gridx = 3;
c.weightx = 2/6.0;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSpinner(), c);
return panel;
}
private JPanel createColumnPanel() {
TitledPanel panel = new TitledPanel("Key Columns");
GridBagConstraints c = new GridBagConstraints();
String[] a = {"a", "b"};
c.weightx = 1/4.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
panel.add(createOneColumn("Key", a), c);
c.gridx = 1;
panel.add(createOneColumn("Secret", a), c);
c.gridx = 2;
panel.add(createOneColumn("QR", a), c);
c.gridx = 3;
panel.add(createOneColumn("Output", a), c);
return panel;
}
private JPanel createOneColumn(String label, String[] columnArray) {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
panel.add(new JLabel(label), c);
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSpinner(new SpinnerListModel(columnArray)), c);
return panel;
}
private JPanel createGeneratePanel() {
TitledPanel panel = new TitledPanel("Generate QR Code");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Drive folder ID"), c);
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JTextField(15), c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
panel.add(new JButton("Generate QR Code"), c);
return panel;
}
private JPanel createWebcamPanel() {
TitledPanel panel = new TitledPanel("Scan QR Code");
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.gridheight = GridBagConstraints.RELATIVE;
panel.add(new JLabel("Webcam"), c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
JButton webcamButton = new JButton("Start Webcam");
panel.add(webcamButton, c);
webcamButton.addActionListener(new MyAction());
return panel;
}
public class MyAction implements ActionListener {
private Webcam webcam = null;
private WebcamPanel panel = null;
public void actionPerformed(ActionEvent ae){
JFrame frame2 = new JFrame("QR code");
Dimension size = WebcamResolution.QVGA.getSize();
frame2.setVisible(true);
frame2.setSize(500, 500);
Webcam webcam = Webcam.getDefault();
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
frame2.add(panel);
frame2.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
panel.stop();
}
});
}
}
} |
package org.weasis.servlet;
import static org.weasis.dicom.wado.DicomQueryParams.AccessionNumber;
import static org.weasis.dicom.wado.DicomQueryParams.ObjectUID;
import static org.weasis.dicom.wado.DicomQueryParams.PatientID;
import static org.weasis.dicom.wado.DicomQueryParams.SeriesUID;
import static org.weasis.dicom.wado.DicomQueryParams.StudyUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weasis.dicom.data.Patient;
import org.weasis.dicom.data.Series;
import org.weasis.dicom.data.Study;
import org.weasis.dicom.data.xml.Base64;
import org.weasis.dicom.param.AdvancedParams;
import org.weasis.dicom.param.DicomNode;
import org.weasis.dicom.param.TlsOptions;
import org.weasis.dicom.util.StringUtil;
import org.weasis.dicom.util.StringUtil.Suffix;
import org.weasis.dicom.wado.BuildManifestDcmQR;
import org.weasis.dicom.wado.DicomQueryParams;
import org.weasis.dicom.wado.WadoParameters;
import org.weasis.dicom.wado.WadoQuery.WadoMessage;
import org.weasis.dicom.wado.thread.ManifestBuilder;
import org.weasis.util.EncryptUtils;
public class ServletUtil {
private static Logger LOGGER = LoggerFactory.getLogger(ServletUtil.class);
private ServletUtil() {
}
public static String getFirstParameter(Object val) {
if (val instanceof String[]) {
String[] params = (String[]) val;
if (params.length > 0) {
return params[0];
}
} else if (val != null) {
return val.toString();
}
return null;
}
public static String[] getParameters(Object val) {
if (val instanceof String[]) {
return (String[]) val;
} else if (val != null) {
return new String[] { val.toString() };
}
return null;
}
public static Object addParameter(Object val, String arg) {
if (val instanceof String[]) {
String[] array = (String[]) val;
String[] arr = Arrays.copyOf(array, array.length + 1);
arr[array.length] = arg;
return arr;
} else if (val != null) {
return new String[] { val.toString(), arg };
}
return arg;
}
public static int getIntProperty(Properties prop, String key, int def) {
int result = def;
final String value = prop.getProperty(key);
if (value != null) {
try {
result = Integer.parseInt(value);
} catch (NumberFormatException ignore) {
// return the default value
}
}
return result;
}
public static long getLongProperty(Properties prop, String key, long def) {
long result = def;
final String value = prop.getProperty(key);
if (value != null) {
try {
result = Long.parseLong(value);
} catch (NumberFormatException ignore) {
// return the default value
}
}
return result;
}
public static boolean isRequestAllowed(HttpServletRequest request, Properties pacsProperties, Logger logger)
throws IOException {
// Test if this client is allowed
String hosts = pacsProperties.getProperty("hosts.allow");
if (hosts != null && !hosts.trim().equals("")) {
String clientHost = request.getRemoteHost();
String clientIP = request.getRemoteAddr();
boolean accept = false;
for (String host : hosts.split(",")) {
if (host.equals(clientHost) || host.equals(clientIP)) {
accept = true;
break;
}
}
if (!accept) {
logger.warn("The request from {} is not allowed.", clientHost);
return false;
}
}
return true;
}
public static void logInfo(HttpServletRequest request, Logger logger) {
logger.debug("logRequestInfo() - getRequestQueryURL: {}{}", request.getRequestURL().toString(),
request.getQueryString() != null ? ("?" + request.getQueryString().trim()) : "");
logger.debug("logRequestInfo() - getContextPath: {}", request.getContextPath());
logger.debug("logRequestInfo() - getServletPath: {}", request.getServletPath());
}
public static String getFilename(List<Patient> patients) {
StringBuilder buffer = new StringBuilder();
if (patients.size() > 0) {
for (Patient patient : patients) {
buffer.append(StringUtil.hasText(patient.getPatientName()) ? patient.getPatientName() : patient
.getPatientID());
buffer.append(",");
}
buffer.deleteCharAt(buffer.length() - 1);
}
return StringUtil.getTruncatedString(buffer.toString(), 30, Suffix.NO);
}
public static WadoMessage getPatientList(DicomQueryParams params) {
WadoMessage wadoMessage = null;
try {
Properties properties = params.getProperties();
String key = properties.getProperty("encrypt.key", null);
String requestType = params.getRequestType();
if ("STUDY".equals(requestType)) {
String stuID = params.getReqStudyUID();
String anbID = params.getReqAccessionNumber();
if (StringUtil.hasText(anbID)) {
BuildManifestDcmQR.buildFromStudyAccessionNumber(params,
ServletUtil.decrypt(anbID, key, AccessionNumber));
} else if (StringUtil.hasText(stuID)) {
BuildManifestDcmQR.buildFromStudyInstanceUID(params, ServletUtil.decrypt(stuID, key, StudyUID));
} else {
LOGGER.info("Not ID found for STUDY request type: {}", requestType);
}
} else if ("PATIENT".equals(requestType)) {
String patID = params.getReqPatientID();
if (StringUtil.hasText(patID)) {
BuildManifestDcmQR.buildFromPatientID(params, ServletUtil.decrypt(patID, key, PatientID));
}
} else if (requestType != null) {
LOGGER.info("Not supported IID request type: {}", requestType);
} else {
String[] pat = params.getReqPatientIDs();
String[] stu = params.getReqStudyUIDs();
String[] anb = params.getReqAccessionNumbers();
String[] ser = params.getReqSeriesUIDs();
String[] obj = params.getReqObjectUIDs();
if (obj != null && obj.length > 0 && isRequestIDAllowed(ObjectUID, properties)) {
for (String id : obj) {
BuildManifestDcmQR.buildFromSopInstanceUID(params, decrypt(id, key, ObjectUID));
}
if (!isValidateAllIDs(ObjectUID, key, params, pat, stu, anb, ser)) {
params.getPatients().clear();
return null;
}
} else if (ser != null && ser.length > 0 && isRequestIDAllowed(SeriesUID, properties)) {
for (String id : ser) {
BuildManifestDcmQR.buildFromSeriesInstanceUID(params, decrypt(id, key, SeriesUID));
}
if (!isValidateAllIDs(SeriesUID, key, params, pat, stu, anb, null)) {
params.getPatients().clear();
return null;
}
} else if (anb != null && anb.length > 0 && isRequestIDAllowed(AccessionNumber, properties)) {
for (String id : anb) {
BuildManifestDcmQR.buildFromStudyAccessionNumber(params, decrypt(id, key, AccessionNumber));
}
if (!isValidateAllIDs(AccessionNumber, key, params, pat, null, null, null)) {
params.getPatients().clear();
return null;
}
} else if (stu != null && stu.length > 0 && isRequestIDAllowed(StudyUID, properties)) {
for (String id : stu) {
BuildManifestDcmQR.buildFromStudyInstanceUID(params, decrypt(id, key, StudyUID));
}
if (!isValidateAllIDs(StudyUID, key, params, pat, null, null, null)) {
params.getPatients().clear();
return null;
}
} else if (pat != null && pat.length > 0 && isRequestIDAllowed(PatientID, properties)) {
for (String id : pat) {
BuildManifestDcmQR.buildFromPatientID(params, decrypt(id, key, PatientID));
}
}
}
} catch (Exception e) {
StringUtil.logError(LOGGER, e, "Error when building the patient list");
}
return wadoMessage;
}
private static boolean isValidateAllIDs(String id, String key, DicomQueryParams params, String[] pat, String[] stu,
String[] anb, String[] ser) {
List<Patient> patients = params.getPatients();
Properties properties = params.getProperties();
if (id != null && patients != null && patients.size() > 0) {
String ids = properties.getProperty("request." + id);
if (ids != null) {
for (String val : ids.split(",")) {
if (val.trim().equals(PatientID)) {
if (pat == null) {
return false;
}
List<String> list = new ArrayList<String>(pat.length);
for (String s : pat) {
list.add(decrypt(s, key, PatientID));
}
for (Patient p : patients) {
if (!list.contains(p.getPatientID())) {
return false;
}
}
} else if (val.trim().equals(StudyUID)) {
if (stu == null) {
return false;
}
List<String> list = new ArrayList<String>(stu.length);
for (String s : stu) {
list.add(decrypt(s, key, StudyUID));
}
for (Patient p : patients) {
for (Study study : p.getStudies()) {
if (!list.contains(study.getStudyID())) {
return false;
}
}
}
} else if (val.trim().equals(AccessionNumber)) {
if (anb == null) {
return false;
}
List<String> list = new ArrayList<String>(anb.length);
for (String s : anb) {
list.add(decrypt(s, key, AccessionNumber));
}
for (Patient p : patients) {
for (Study study : p.getStudies()) {
if (!list.contains(study.getAccessionNumber())) {
return false;
}
}
}
} else if (val.trim().equals(SeriesUID)) {
if (ser == null) {
return false;
}
List<String> list = new ArrayList<String>(ser.length);
for (String s : ser) {
list.add(decrypt(s, key, SeriesUID));
}
for (Patient p : patients) {
for (Study study : p.getStudies()) {
for (Series series : study.getSeriesList()) {
if (!list.contains(series.getSeriesInstanceUID())) {
return false;
}
}
}
}
}
}
}
}
return true;
}
static String decrypt(String message, String key, String level) {
if (key != null) {
String decrypt = EncryptUtils.decrypt(message, key);
LOGGER.debug("Decrypt {}: {} to {}", new Object[] { level, message, decrypt });
return decrypt;
}
return message;
}
private static boolean isRequestIDAllowed(String id, Properties properties) {
if (id != null) {
return Boolean.valueOf(properties.getProperty(id));
}
return false;
}
public static String getBaseURL(HttpServletRequest request, boolean canonicalHostName) {
if (canonicalHostName) {
try {
/**
* To get Fully Qualified Domain Name behind bigIP it's better using
* InetAddress.getLocalHost().getCanonicalHostName() instead of req.getLocalAddr()<br>
* If not resolved from the DNS server FQDM is taken from the /etc/hosts on Unix server
*/
return request.getScheme() + "://" + InetAddress.getLocalHost().getCanonicalHostName() + ":"
+ request.getServerPort();
} catch (UnknownHostException e) {
StringUtil.logError(LOGGER, e, "Cannot get hostname");
}
}
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}
public static DicomQueryParams buildDicomQueryParams(HttpServletRequest request, Properties props) {
String pacsAET = props.getProperty("pacs.aet", "DCM4CHEE");
String pacsHost = props.getProperty("pacs.host", "localhost");
int pacsPort = Integer.parseInt(props.getProperty("pacs.port", "11112"));
DicomNode calledNode = new DicomNode(pacsAET, pacsHost, pacsPort);
String wadoQueriesURL = props.getProperty("pacs.wado.url", props.getProperty("server.base.url") + "/wado");
boolean onlysopuid = StringUtil.getNULLtoFalse(props.getProperty("wado.onlysopuid"));
String addparams = props.getProperty("wado.addparams", "");
String overrideTags = props.getProperty("wado.override.tags", null);
// If the web server requires an authentication (pacs.web.login=user:pwd)
String webLogin = props.getProperty("pacs.web.login", null);
if (webLogin != null) {
webLogin = Base64.encodeBytes(webLogin.trim().getBytes());
}
String httpTags = props.getProperty("wado.httpTags", null);
WadoParameters wado = new WadoParameters(wadoQueriesURL, onlysopuid, addparams, overrideTags, webLogin);
if (httpTags != null && !httpTags.trim().equals("")) {
for (String tag : httpTags.split(",")) {
String[] val = tag.split(":");
if (val.length == 2) {
wado.addHttpTag(val[0].trim(), val[1].trim());
}
}
}
boolean tls = StringUtil.getNULLtoFalse(props.getProperty("pacs.tls.mode"));
AdvancedParams params = null;
if (tls) {
try {
TlsOptions tlsOptions =
new TlsOptions(StringUtil.getNULLtoFalse(props.getProperty("pacs.tlsNeedClientAuth")),
props.getProperty("pacs.keystoreURL"), props.getProperty("pacs.keystoreType", "JKS"),
props.getProperty("pacs.keystorePass"), props.getProperty("pacs.keyPass",
props.getProperty("pacs.keystorePass")), props.getProperty("pacs.truststoreURL"),
props.getProperty("pacs.truststoreType", "JKS"), props.getProperty("pacs.truststorePass"));
params = new AdvancedParams();
params.setTlsOptions(tlsOptions);
} catch (Exception e) {
StringUtil.logError(LOGGER, e, "Cannot set TLS configuration");
}
}
return new DicomQueryParams(new DicomNode(props.getProperty("aet", "PACS-CONNECTOR")), calledNode, request,
wado, props.getProperty("pacs.db.encoding", "utf-8"), StringUtil.getNULLtoFalse(props
.getProperty("accept.noimage")), params, props);
}
public static ManifestBuilder buildManifest(HttpServletRequest request, Properties props) throws Exception {
final DicomQueryParams params = ServletUtil.buildDicomQueryParams(request, props);
return buildManifest(request, new ManifestBuilder(params));
}
public static ManifestBuilder buildManifest(HttpServletRequest request, ManifestBuilder builder) throws Exception {
ServletContext ctx = request.getSession().getServletContext();
final ConcurrentHashMap<Integer, ManifestBuilder> builderMap =
(ConcurrentHashMap<Integer, ManifestBuilder>) ctx.getAttribute("manifestBuilderMap");
ExecutorService executor = (ExecutorService) ctx.getAttribute("manifestExecutor");
builder.submit((ExecutorService) ctx.getAttribute("manifestExecutor"));
builderMap.put(builder.getRequestId(), builder);
return builder;
}
public static String buildManifestURL(HttpServletRequest request, ManifestBuilder builder, Properties props,
boolean gzip) throws Exception {
StringBuilder buf = new StringBuilder(props.getProperty("server.base.url"));
buf.append(request.getContextPath());
buf.append("/RequestManifest?");
buf.append(RequestManifest.PARAM_ID);
buf.append('=');
buf.append(builder.getRequestId());
if (!gzip) {
buf.append('&');
buf.append(RequestManifest.PARAM_NO_GZIP);
}
String wadoQueryUrl = buf.toString();
LOGGER.debug("wadoQueryUrl = " + wadoQueryUrl);
return wadoQueryUrl;
}
public static void write(InputStream in, OutputStream out) throws IOException {
try {
copy(in, out, 2048);
} catch (Exception e) {
handleException(e);
} finally {
try {
in.close();
out.flush();
} catch (IOException e) {
// jetty 6 throws broken pipe exception here too
handleException(e);
}
}
}
public static int copy(final InputStream in, final OutputStream out, final int bufSize) throws IOException {
final byte[] buffer = new byte[bufSize];
int bytesCopied = 0;
while (true) {
int byteCount = in.read(buffer, 0, buffer.length);
if (byteCount <= 0) {
break;
}
out.write(buffer, 0, byteCount);
bytesCopied += byteCount;
}
return bytesCopied;
}
private static void handleException(Exception e) {
Throwable throwable = e;
boolean ignoreException = false;
while (throwable != null) {
if (throwable instanceof SQLException) {
break; // leave false and quit loop
} else if (throwable instanceof SocketException) {
String message = throwable.getMessage();
ignoreException =
message != null
&& (message.indexOf("Connection reset") != -1 || message.indexOf("Broken pipe") != -1
|| message.indexOf("Socket closed") != -1 || message.indexOf("connection abort") != -1);
} else {
ignoreException =
throwable.getClass().getName().indexOf("ClientAbortException") >= 0
|| throwable.getClass().getName().indexOf("EofException") >= 0;
}
if (ignoreException) {
break;
}
throwable = throwable.getCause();
}
if (!ignoreException) {
throw new RuntimeException("Unable to write the response", e);
}
}
public static void write(String str, ServletOutputStream out) {
try {
byte[] bytes = str.getBytes();
out.write(bytes, 0, bytes.length);
} catch (Exception e) {
handleException(e);
} finally {
try {
out.flush();
} catch (IOException e) {
// jetty 6 throws broken pipe exception here too
handleException(e);
}
}
}
} |
package org.yinwang.pysonar.demos;
import org.jetbrains.annotations.NotNull;
import org.yinwang.pysonar.Indexer;
import org.yinwang.pysonar.Progress;
import org.yinwang.pysonar.Util;
import java.io.File;
import java.util.List;
public class Demo {
private static File OUTPUT_DIR;
private static final String CSS =
"body { color: #666666; } \n" +
"a {text-decoration: none; color: #5A82F7}\n" +
"table, th, td { border: 1px solid lightgrey; padding: 5px; corner: rounded; }\n" +
".builtin {color: #B17E41;}\n" +
".comment, .block-comment {color: #aaaaaa; font-style: italic;}\n" +
".constant {color: #888888;}\n" +
".decorator {color: #778899;}\n" +
".doc-string {color: #aaaaaa;}\n" +
".error {border-bottom: 1px solid red;}\n" +
".field-name {color: #2e8b57;}\n" +
".function {color: #4682b4;}\n" +
".identifier {color: #8b7765;}\n" +
".info {border-bottom: 1px dotted RoyalBlue;}\n" +
".keyword {color: #0000cd;}\n" +
".lineno {color: #aaaaaa;}\n" +
".number {color: #483d8b;}\n" +
".parameter {color: #777777;}\n" +
".string {color: #999999;}\n" +
".type-name {color: #4682b4;}\n" +
".warning {border-bottom: 1px dotted orange;}\n";
private static final String JS =
"<script language=\"JavaScript\" type=\"text/javascript\">\n" +
"var highlighted = new Array();\n" +
"function highlight()\n" +
"{\n" +
" // clear existing highlights\n" +
" for (var i = 0; i < highlighted.length; i++) {\n" +
" var elm = document.getElementById(highlighted[i]);\n" +
" if (elm != null) {\n" +
" elm.style.backgroundColor = 'white';\n" +
" }\n" +
" }\n" +
" highlighted = new Array();\n" +
" for (var i = 0; i < arguments.length; i++) {\n" +
" var elm = document.getElementById(arguments[i]);\n" +
" if (elm != null) {\n" +
" elm.style.backgroundColor='gold';\n" +
" }\n" +
" highlighted.push(arguments[i]);\n" +
" }\n" +
"} </script>\n";
private Indexer indexer;
private String rootPath;
private Linker linker;
private void makeOutputDir() {
if (!OUTPUT_DIR.exists()) {
OUTPUT_DIR.mkdirs();
Util.msg("Created directory: " + OUTPUT_DIR.getAbsolutePath());
}
}
private void start(@NotNull File fileOrDir) throws Exception {
long start = System.currentTimeMillis();
File rootDir = fileOrDir.isFile() ? fileOrDir.getParentFile() : fileOrDir;
try {
rootPath = rootDir.getCanonicalPath();
} catch (Exception e) {
Util.die("File not found: " + fileOrDir);
}
indexer = new Indexer();
Util.msg("Building index");
indexer.loadFileRecursive(fileOrDir.getCanonicalPath());
indexer.finish();
Util.msg(indexer.getStatusReport());
long end = System.currentTimeMillis();
Util.msg("Finished indexing in: " + Util.timeString(end - start));
start = System.currentTimeMillis();
generateHtml();
end = System.currentTimeMillis();
Util.msg("Finished generating HTML in: " + Util.timeString(end - start));
indexer.close();
}
private void generateHtml() {
Util.msg("\nGenerating HTML");
makeOutputDir();
linker = new Linker(rootPath, OUTPUT_DIR);
linker.findLinks(indexer);
int rootLength = rootPath.length();
Progress progress = new Progress(100, 100);
for (String path : indexer.getLoadedFiles()) {
if (path.startsWith(rootPath)) {
progress.tick();
File destFile = Util.joinPath(OUTPUT_DIR, path.substring(rootLength));
destFile.getParentFile().mkdirs();
String destPath = destFile.getAbsolutePath() + ".html";
String html = markup(path);
try {
Util.writeFile(destPath, html);
} catch (Exception e) {
Util.msg("Failed to write: " + destPath);
}
}
}
progress.end();
Util.msg("Wrote " + indexer.getLoadedFiles().size() + " files to " + OUTPUT_DIR);
}
@NotNull
private String markup(String path) {
String source;
try {
source = Util.readFile(path);
} catch (Exception e) {
Util.die("Failed to read file: " + path);
return "";
}
List<StyleRun> styles = new Styler(indexer, linker).addStyles(path, source);
styles.addAll(linker.getStyles(path));
String styledSource = new StyleApplier(path, source, styles).apply();
String outline = new HtmlOutline(indexer).generate(path);
StringBuilder sb = new StringBuilder();
sb.append("<html><head title=\"").append(path).append("\">")
.append("<style type='text/css'>\n").append(CSS).append("</style>\n")
.append(JS)
.append("</head>\n<body>\n")
.append("<table width=100% border='1px solid gray'><tr><td valign='top'>")
.append(outline)
.append("</td><td>")
.append("<pre>").append(addLineNumbers(styledSource)).append("</pre>")
.append("</td></tr></table></body></html>");
return sb.toString();
}
@NotNull
private String addLineNumbers(@NotNull String source) {
StringBuilder result = new StringBuilder((int)(source.length() * 1.2));
int count = 1;
for (String line : source.split("\n")) {
result.append("<span class='lineno'>");
result.append(count++);
result.append("</span> ");
result.append(line);
result.append("\n");
}
return result.toString();
}
private static void usage() {
Util.msg("Usage: java org.yinwang.pysonar.HtmlDemo <file-or-dir> <output-dir>");
Util.msg("Example that generates an index for Python 2.7 standard library:");
Util.msg(" java org.yinwang.pysonar.HtmlDemo /usr/lib/python2.7 ./html");
System.exit(0);
}
@NotNull
private static File checkFile(String path) {
File f = new File(path);
if (!f.canRead()) {
Util.die("Path not found or not readable: " + path);
}
return f;
}
public static void main(@NotNull String[] args) throws Exception {
if (args.length != 2) {
usage();
}
File fileOrDir = checkFile(args[0]);
OUTPUT_DIR = new File(args[1]);
new Demo().start(fileOrDir);
}
} |
package otanga.Controllers;
import com.google.appengine.api.files.*;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import sun.security.ssl.Debug;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.nio.channels.Channels;
import java.util.UUID;
import java.io.BufferedReader;
public class FileStorage {
// Get the file service
private final static FileService fileService = FileServiceFactory.getFileService();
private final static String _bucketName = "otangaimages";
private FileStorage() {}
public static String storeImage(byte[] fileContent, String contentType, java.io.PrintWriter responseWriter){
String key = UUID.randomUUID().toString().replace("-", "").toLowerCase() + "$" + contentType.replace('/','!');
responseWriter.println();
responseWriter.println("\t[FileStorage.storeImage] Key: " + key);
responseWriter.println("\t[FileStorage.storeImage] ContentType: " + contentType);
responseWriter.println("\t[FileStorage.storeImage] Length: " + fileContent.length);
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
.setBucket(_bucketName)
.setKey(key)
.setMimeType(contentType)
.setAcl("private");
try {
AppEngineFile writableFile = fileService.createNewGSFile(optionsBuilder.build());
FileWriteChannel writeChannel = fileService.openWriteChannel(writableFile, true);
ByteBuffer byteBuffer = ByteBuffer.allocate(fileContent.length);
byteBuffer.put(fileContent);
byteBuffer.rewind();
int writeResult = writeChannel.write(byteBuffer, "UTF-8");
responseWriter.println("\t[FileStorage.storeImage] WriteResult: " + writeResult);
responseWriter.println();
writeChannel.closeFinally();
} catch (IOException e) {
key = null;
responseWriter.println("\t[FileStorage.storeImage] IOException: " + e.getMessage());
e.printStackTrace(responseWriter);
e.printStackTrace();
}
return key;
}
public static String retrieveImage(String imageKey, java.io.PrintWriter responseWriter)
{
if (imageKey == null || imageKey.length() == 0)
throw new IllegalArgumentException("imageKey");
String output = null;
String filename = "/gs/" + _bucketName + "/" + imageKey;
String contentType = imageKey.substring(imageKey.indexOf('$') + 1).replace('!','/');
AppEngineFile readableFile = new AppEngineFile(filename);
try {
FileStat stat = fileService.stat(readableFile);
output = stat.getLength().toString() + " bytes";
responseWriter.println();
responseWriter.println("\t[FileStorage.retrieveImage] FileName: " + stat.getFilename());
responseWriter.println("\t[FileStorage.retrieveImage] ContentType: " + contentType);
responseWriter.println("\t[FileStorage.retrieveImage] Content: ");
responseWriter.println();
responseWriter.print("\t");
FileReadChannel readChannel = fileService.openReadChannel(readableFile, false);
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
int count;
while ((count = readChannel.read(buffer)) > 0)
{
buffer.rewind();
if (contentType.toLowerCase().startsWith("text/"))
{
byte[] byteArray = new byte[count];
buffer.get(byteArray, 0, count);
responseWriter.print(new String(byteArray));
}
else
{
for (int i = 0; i < count; i++)
{
responseWriter.print(Integer.toHexString(buffer.get() & 0xff) + " ");
}
}
buffer.clear();
}
responseWriter.println();
responseWriter.println();
readChannel.close();
} catch (IOException e) {
e.printStackTrace();
output = e.getMessage();
}
return output;
}
} |
package qualify.tools;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import qualify.TestCase;
import qualify.TestException;
import qualify.doc.DocList;
import qualify.doc.DocString;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* TestToolSelenium extends the FirefoxDriver object from Selenium 2 API. New convenient methods are added, such as isPresent, waitPresent
* and waitVanish. To better use that tool, you should use the object repositories (see the class called TestObject). The supported
* TestObject have the following structure: <element id="my element"> <identifier id="xpath" value="//body/h1[1]"/> </element> The following
* identifiers are supported: - id - name - xpath - linkText - partialLinkText - cssSelector - tagName - className
*
* @author Mathieu Bordas
*/
public abstract class TestToolSelenium {
private static final Logger logger = Logger.getLogger(TestToolSeleniumFirefox.class);
protected WebDriver driver = null;
protected TestCase testCase = null;
private double defaultTimeout_s = 10.0;
public TestToolSelenium(TestCase tc) {
testCase = tc;
}
public void get(String url) {
driver.get(url);
}
public void quit() {
if(driver != null) {
driver.quit();
}
}
/**
* Redefines the Selenium findElement(By) in order to catch exception
*/
public WebElement findElement(By by) {
try {
return driver.findElement(by);
} catch(NoSuchElementException e) {
return null;
}
}
/**
* Redefines the Selenium findElementById(String) in order to catch exception
*/
public WebElement findElementById(String id) {
try {
return driver.findElement(By.id(id));
} catch(NoSuchElementException e) {
return null;
}
}
/**
* Checks that the element identified by the specified ID is present in the actual web page
*
* @param elementId
* @return
*/
public boolean checkFindElementById(String elementId) {
boolean result = false;
result = (findElementById(elementId) != null);
if(result == true) {
testCase.addTestResult(true, "Expected dom element found from id '" + elementId + "'");
} else {
testCase.addTestResult(false, "Expected dom element not found from id '" + elementId + "'");
}
return result;
}
public WebElement find(String elementIdentifier) throws ElementNotFoundException {
By identifier = getElementIdentifier(elementIdentifier);
if(identifier == null) {
throw new ElementNotFoundException("Unparsed identifier: " + elementIdentifier);
}
WebElement element = find(identifier);
if(element != null) {
return element;
} else {
throw new ElementNotFoundException("Element not found with identifier: " + elementIdentifier);
}
}
public WebElement find(By by) {
WebElement result = findElement(by);
return result;
}
public void click(String elementIdentifier) {
By identifier = getElementIdentifier(elementIdentifier);
if(identifier == null) {
throw new TestException("Unparsed element identifier: " + elementIdentifier);
}
if(waitPresent(elementIdentifier, defaultTimeout_s)) {
WebElement w = findElement(identifier);
if(w != null) {
w.click();
} else {
testCase.addTestResult(false, "Cannot click on null element (identifier='" + elementIdentifier + "').");
}
} else {
testCase.addTestResult(false, "Cannot click on element not found (identifier='" + elementIdentifier + "').");
}
}
public TestObject click(TestObject testObject) {
if(testObject == null) {
throw new TestException("Cannot click on null TestObject");
}
click(testObject.getPath());
return testObject;
}
public void click(By by) {
waitPresent(by, defaultTimeout_s);
WebElement w = findElement(by);
if(w != null) {
w.click();
} else {
testCase.addTestResult(false, "Cannot click on null element (by='" + by.toString() + "').");
}
}
public void forceClick(String elementIdentifier) {
waitPresent(elementIdentifier, defaultTimeout_s);
WebElement w = findElement(getElementIdentifier(elementIdentifier));
if(w != null) {
((JavascriptExecutor) driver).executeScript("arguments[0].click();", w);
} else {
testCase.addTestResult(false, "Cannot click on null element (identifier='" + elementIdentifier + "').");
}
}
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch(Exception e) {
return false;
}
}
private Alert waitAlert(int timeout_s) {
logger.info("waitAlert(timeout_s) isAlertPresent=" + isAlertPresent());
long start_ms = System.currentTimeMillis();
while(!isAlertPresent() && System.currentTimeMillis() < start_ms + timeout_s * 1000) {
try {
Thread.sleep(500);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
if(isAlertPresent()) {
return driver.switchTo().alert();
} else {
throw new TestException("No alert present after %d seconds", (System.currentTimeMillis() - start_ms) / 1000);
}
}
private Alert waitAlert() {
logger.info("waitAlert() isAlertPresent=" + isAlertPresent());
return waitAlert((int) defaultTimeout_s);
}
private void waitNoAlert() {
logger.info("waitAlert(timeout_s) isAlertPresent=" + isAlertPresent());
long start_ms = System.currentTimeMillis();
while(isAlertPresent() && System.currentTimeMillis() < start_ms + defaultTimeout_s * 1000) {
try {
Thread.sleep(500);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean checkAlert(String textRegex) {
boolean result = false;
String alertText = waitAlert().getText();
if(TestToolStrings.matches(textRegex, alertText)) {
result = true;
} else {
result = false;
}
testCase.addTestResult(result, "regex=" + textRegex + " | tested=" + alertText);
return result;
}
/**
* Accepts alert and waits until it is no more displayed.
*
* @throws InterruptedException
*/
public void acceptAlert() throws InterruptedException {
Alert alert = waitAlert();
final String text = alert.getText();
logger.info("Accepting alert '" + text + "'");
alert.accept();
Thread.sleep(1000);
// When alert is accepted current Java thread goes on, but the alert could persist in the browser.
// Some milliseconds later, a call to checkAlert could check the same alert one more time (because it not
// closed in the browser).
// To prevent such an confusing state, here we wait until this alert is hidden.
// 2 cases: either there is no more alert displayed, either the alert displayed is another one.
boolean sameAlertIsStillDisplayed = true;
long start_ms = System.currentTimeMillis();
while(sameAlertIsStillDisplayed && System.currentTimeMillis() < start_ms + defaultTimeout_s * 1000) {
try {
Alert _alert = waitAlert(1);
sameAlertIsStillDisplayed = text.equals(_alert.getText());
Thread.sleep(500);
} catch(Exception e) {
sameAlertIsStillDisplayed = false;
}
}
}
public void dismissAlert() {
waitAlert().dismiss();
}
public void type(String elementIdentifier, String textToType) {
By by = getElementIdentifier(elementIdentifier);
type(by, textToType);
}
public void type(By elementIdentifier, String textToType) {
WebElement w = findElement(elementIdentifier);
if(w != null) {
if(textToType.endsWith("\n")) {
w.sendKeys(textToType.replaceAll("\n", ""));
w.sendKeys(Keys.ENTER);
} else {
w.sendKeys(textToType);
}
} else {
testCase.addTestResult(false, "Cannot type on null element (identifier='" + elementIdentifier + "').");
}
}
/**
* Clear text of element.
*
* @param elementIdentifier
*/
public void clear(String elementIdentifier) {
By by = getElementIdentifier(elementIdentifier);
clear(by);
}
public void clear(By elementIdentifier) {
WebElement w = findElement(elementIdentifier);
if(w != null) {
w.sendKeys(Keys.chord(Keys.CONTROL, "a"));
w.sendKeys(Keys.BACK_SPACE);
w.clear();
} else {
testCase.addTestResult(false, "Cannot clear null element (identifier='" + elementIdentifier + "').");
}
}
public boolean isPresent(String elementIdentifier) {
try {
return (find(elementIdentifier) != null);
} catch(ElementNotFoundException e) {
return false;
}
}
public boolean isPresent(By by) {
return (find(by) != null);
}
public boolean isDisplayed(String elementIdentifier) throws ElementNotFoundException {
WebElement element = find(elementIdentifier);
return element.isDisplayed();
}
public boolean isEnabled(String elementIdentifier) throws ElementNotFoundException {
WebElement element = find(elementIdentifier);
return element.isEnabled();
}
private boolean explicitWait(ExpectedCondition<Boolean> condition, final double timeout_s) {
boolean result;
try {
(new WebDriverWait(driver, Double.valueOf(timeout_s).intValue())).until(condition);
result = true;
} catch(TimeoutException e) {
result = false;
}
return result;
}
public boolean waitPresent(final String elementIdentifier, final double timeout_s) {
return explicitWait(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return isPresent(elementIdentifier);
}
}, timeout_s);
}
public boolean waitPresent(final By by, final double timeout_s) {
return explicitWait(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return isPresent(by);
}
}, timeout_s);
}
public boolean waitVanish(final String elementIdentifier, final double timeout_s) {
return explicitWait(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return !isPresent(elementIdentifier);
}
}, timeout_s);
}
public boolean waitText(final String elementIdentifier, final String text, final double timeout_s) {
return explicitWait(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return isPresent(elementIdentifier) && ((text != null && text.equals(getText(elementIdentifier)))
|| getText(elementIdentifier) == null);
}
}, timeout_s);
}
public boolean waitElementProperty(final String elementIdentifier, final String propertyName, final String expectedValue,
final double timeout_s) {
return explicitWait(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
WebElement element = findElementById(elementIdentifier);
if(element != null) {
String value = element.getAttribute(propertyName);
return expectedValue.equals(value);
}
return false;
}
}, timeout_s);
}
public String getPageSource() {
return driver.getPageSource();
}
public File capturePage() {
File page = null;
String htmlContent = getPageSource();
try {
page = TestToolFile.createNewTemporaryFile("html");
} catch(IOException e1) {
testCase.addTestResult(false, "IOException raised: " + e1.getLocalizedMessage());
testCase.addException(e1);
}
try {
FileUtils.writeStringToFile(page, htmlContent);
} catch(IOException e) {
e.printStackTrace();
}
testCase.attachFile(page);
return page;
}
/**
* Computes the By identifier (see the official Selenium documentation) from the TestObject found in the object repositories.
*
* @param webElementIdentifier The identifier from object repositories
* @return The By object supported by the Selenium 2 WebDriver
*/
public By getElementIdentifier(String webElementIdentifier) {
logger.debug("searching web element from identifier: '" + webElementIdentifier + "'");
By result = null;
if(webElementIdentifier.contains("(")) {
TestObject obj = TestObject.getFromRepo(webElementIdentifier);
if(obj != null) {
result = getElementIdentifier(obj);
} else {
testCase.addTestResult(false,
"Web element from identifier '" + webElementIdentifier + "' does not exist in object repositories.");
}
} else {
result = new By.ById(webElementIdentifier);
}
return result;
}
public By getElementIdentifier(TestObject obj) {
By result = null;
if(obj.get("identifier(id)") != null) {
result = By.id(obj.get("identifier(id)").attribute("value"));
} else if(obj.get("identifier(name)") != null) {
result = By.name(obj.get("identifier(name)").attribute("value"));
} else if(obj.get("identifier(xpath)") != null) {
result = By.xpath(obj.get("identifier(xpath)").attribute("value"));
} else if(obj.get("identifier(linkText)") != null) {
result = By.linkText(obj.get("identifier(linkText)").attribute("value"));
} else if(obj.get("identifier(partialLinkText)") != null) {
result = By.partialLinkText(obj.get("identifier(partialLinkText)").attribute("value"));
} else if(obj.get("identifier(cssSelector)") != null) {
result = By.cssSelector(obj.get("identifier(cssSelector)").attribute("value"));
} else if(obj.get("identifier(tagName)") != null) {
result = By.tagName(obj.get("identifier(tagName)").attribute("value"));
} else if(obj.get("identifier(className)") != null) {
result = By.className(obj.get("identifier(className)").attribute("value"));
} else {
logger.error("No identifier found for TestObject '" + obj.getPath() + "'.");
}
return result;
}
public void close() {
driver.close();
}
public String getElementTextById(String elementId) throws TestException {
WebElement element = findElementById(elementId);
if(element != null) {
return element.getText();
} else {
throw new TestException("Cannot get text from element with id '" + elementId + "': element not found.");
}
}
public boolean checkText(String elementId, String expectedValue) {
return checkText(elementId, expectedValue, true);
}
public boolean checkText(String elementId, String expectedValue, boolean caseSensitive) {
By element = getElementIdentifier(elementId);
if(element != null) {
return checkText(element, expectedValue, caseSensitive);
} else {
testCase.addTestResult(false, "Web element not found with identifier '" + elementId);
return false;
}
}
public boolean checkText(By elementId, String expectedValue, boolean caseSensitive) {
boolean result = false;
if(elementId != null) {
String text = getText(elementId);
result = TestToolStrings.checkEquality(testCase, expectedValue, text, caseSensitive);
} else {
result = false;
testCase.addTestResult(false, "Web element not found with null identifier");
}
return result;
}
public boolean checkText(String elementId, Double expectedValue, double epsilon) {
By by = getElementIdentifier(elementId);
if(by != null) {
return checkText(by, expectedValue, epsilon);
} else {
testCase.addTestResult(false, "Web element not found with identifier '" + elementId);
return false;
}
}
public boolean checkText(By elementId, Double expectedValue, double epsilon) {
boolean result = false;
Double testedValue = null;
try {
testedValue = Double.valueOf(getText(elementId));
} catch(NumberFormatException e) {
testCase.addError(e.getMessage());
}
TestToolNumbers numbers = new TestToolNumbers(testCase);
return numbers.checkEquality(expectedValue, testedValue, epsilon);
}
public boolean checkValue(String elementId, String expectedValue) {
return checkValue(elementId, expectedValue, true);
}
public boolean checkValue(String elementId, String expectedValue, boolean caseSensitive) {
boolean result = false;
WebElement element = findElementById(elementId);
if(element != null) {
result = TestToolStrings.checkEquality(testCase, expectedValue, element.getAttribute("value"), caseSensitive);
} else {
result = false;
testCase.addTestResult(false, "Web element not found with identifier '" + elementId);
}
return result;
}
public boolean checkSelection(String elementId, String expectedValue) {
return checkSelection(elementId, expectedValue, true);
}
public boolean checkSelection(String elementId, String expectedValue, boolean caseSensitive) {
boolean result = false;
WebElement element = findElementById(elementId);
if(element != null) {
Select option = new Select(element);
WebElement selectedOption = option.getFirstSelectedOption();
result = TestToolStrings.checkEquality(testCase, expectedValue, selectedOption.getText(), caseSensitive);
} else {
result = false;
testCase.addTestResult(false, "Web element not found with identifier '" + elementId);
}
return result;
}
/**
* Returns the text or the 'value' attribute of element.
*
* @param elementId
* @return
*/
public String getText(String elementId) {
By by = getElementIdentifier(elementId);
if(by != null) {
return getText(by);
} else {
throw new TestException("Web element not found with identifier '" + elementId + "'");
}
}
public String getText(By elementId) {
WebElement element = findElement(elementId);
if(element != null) {
String tagName = element.getTagName();
if(tagName != null && tagName.equals("input")) {
return element.getAttribute("value");
} else {
return element.getText();
}
} else {
throw new TestException("Web element not found with identifier '" + elementId + "'");
}
}
/**
* Returns the 'value' attribute of element.
*
* @param elementId
* @return
*/
public String getValue(String elementId) {
return getAttribute(elementId, "value");
}
public void commentOptions(String id) throws ElementNotFoundException {
DocList list = new DocList();
for(String option : getSelectOptions(id)) {
list.addItem(new DocString(option));
}
testCase.addComment(list, getClass());
}
public Collection<String> getSelectOptions(String id) throws ElementNotFoundException {
Collection<String> result = null;
WebElement element = findElementById(id);
if(element != null) {
result = new ArrayList<String>();
Select select = new Select(element);
for(WebElement option : select.getOptions()) {
result.add(option.getAttribute("value"));
}
}
return result;
}
/**
* Returns the value of element's attribute <code>key</code>.
*
* @param elementId
* @param key
* @return
*/
public String getAttribute(String elementId, String key) {
WebElement element = findElementById(elementId);
if(element != null) {
try {
return element.getAttribute(key);
} catch(StaleElementReferenceException e) {
// Such exception could be thrown when element is moved/modified between calls to 'find()' and 'getAttribute()'.
// To avoid this, we just re-find it.
element = findElementById(elementId);
return element.getAttribute(key);
}
} else {
throw new TestException("Web element not found with identifier '" + elementId + "'");
}
}
public String getHTML(String elementId) {
WebElement element = findElementById(elementId);
if(element != null) {
return element.getAttribute("innerHTML");
} else {
return null;
}
}
/**
* Clears input text then type <code>value</code>.
*
* @param elementId
* @param value
*/
public void setInput(String elementId, String value) {
clear(elementId);
type(elementId, value);
}
public void select(String identifier, String optionText) {
Select select = new Select(driver.findElement(getElementIdentifier(identifier)));
select.selectByVisibleText(optionText);
}
public void selectCheckbox(String identifier, boolean checked) {
WebElement element = findElement(getElementIdentifier(identifier));
if(element != null) {
if(element.isSelected() != checked) {
element.click();
}
}
}
/**
* Generate a screenshot of the current view of the WebDriver and save it as a file
*
* @param outputFile
* @throws Exception
*/
public void getScreenshotAsFile(File outputFile) throws Exception {
Class<? extends WebDriver> driverClass = driver.getClass();
// Check if the driver is implementing the interface TakesScreenshot
if(TakesScreenshot.class.isAssignableFrom(driverClass)) {
TakesScreenshot screenshotDriver = (TakesScreenshot) driver;
File screenFile = screenshotDriver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenFile, outputFile);
} else {
throw new Exception("Can not take screenshots with driver '" + driverClass.getName() + "'");
}
}
/**
* Generate a screenshot of the current view of the WebDriver and get it as a Base64 encoded string
*
* @return
* @throws Exception
*/
public String getScreenshotAsBase64() throws Exception {
Class<? extends WebDriver> driverClass = driver.getClass();
// Check if the driver is implementing the interface TakesScreenshot
if(TakesScreenshot.class.isAssignableFrom(driverClass)) {
TakesScreenshot screenshotDriver = (TakesScreenshot) driver;
String screenFile = screenshotDriver.getScreenshotAs(OutputType.BASE64);
return screenFile;
} else {
throw new Exception("Can not take screenshots with driver '" + driverClass.getName() + "'");
}
}
public static class ElementNotFoundException extends Exception {
public ElementNotFoundException(String message) {
super(message);
}
}
} |
package romelo333.rflux.blocks;
import elucent.albedo.lighting.ILightProvider;
import elucent.albedo.lighting.Light;
import mcjty.lib.bindings.DefaultValue;
import mcjty.lib.bindings.IValue;
import mcjty.lib.blocks.BaseBlock;
import mcjty.lib.blocks.GenericBlock;
import mcjty.lib.tileentity.GenericEnergyReceiverTileEntity;
import mcjty.lib.typed.Key;
import mcjty.lib.typed.Type;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional;
import romelo333.rflux.Config;
import romelo333.rflux.ModBlocks;
@Optional.InterfaceList({
@Optional.Interface(iface = "elucent.albedo.lighting.ILightProvider", modid = "albedo")
})
public class LightTE extends GenericEnergyReceiverTileEntity implements ITickable, ILightProvider {
private BlockColor color = BlockColor.WHITE;
private Object light = null;
private boolean lit = false;
private LightMode mode = LightMode.MODE_NORMAL;
private int checkLitCounter = 10;
public static final Key<Integer> VALUE_MODE = new Key<>("mode", Type.INTEGER);
@Override
public IValue<?>[] getValues() {
return new IValue[] {
new DefaultValue<>(VALUE_RSMODE, this::getRSModeInt, this::setRSModeInt),
new DefaultValue<>(VALUE_MODE, () -> this.getMode().ordinal(), (v) -> this.setMode(LightMode.values()[v])),
};
}
@Override
protected boolean needsRedstoneMode() {
return true;
}
public LightTE() {
super(Config.LIGHTBLOCK_MAXRF, Config.LIGHTBLOCK_RECEIVEPERTICK);
}
public boolean isLit() {
return lit;
}
@Optional.Method(modid = "albedo")
@Override
public Light provideLight() {
if (light == null) {
if (lit) {
light = new Light(pos.getX(), pos.getY(), pos.getZ(), color.getR(), color.getG(), color.getB(), 1.0f,
mode == LightMode.MODE_NORMAL ? 16.0f :
mode == LightMode.MODE_EXTENDED ? 20.0f :
24.0f);
}
}
return (Light) light;
}
@Override
public void update() {
if (!getWorld().isRemote) {
boolean newlit = isMachineEnabled();
if (newlit) {
// We are still potentially lit so do this.
int rf = mode.getRfUsage();
if (storage.getEnergyStored() >= rf) {
storage.extractEnergy(rf, false);
} else {
newlit = false;
}
}
if (newlit != lit) {
// State has changed so we must update.
lit = newlit;
light = null;
IBlockState oldState = getWorld().getBlockState(pos);
GenericLightBlock block = (GenericLightBlock) oldState.getBlock();
if (block.getRotationType() == BaseBlock.RotationType.NONE) {
if (lit) {
getWorld().setBlockState(pos, block.getLitBlock().getDefaultState(), 3);
} else {
getWorld().setBlockState(pos, block.getUnlitBlock().getDefaultState(), 3);
}
} else {
if (lit) {
getWorld().setBlockState(pos, block.getLitBlock().getDefaultState().withProperty(GenericBlock.FACING, oldState.getValue(GenericBlock.FACING)), 3);
} else {
getWorld().setBlockState(pos, block.getUnlitBlock().getDefaultState().withProperty(GenericBlock.FACING, oldState.getValue(GenericBlock.FACING)), 3);
}
}
// Restore the TE, needed since our block has changed
this.validate();
getWorld().setTileEntity(pos, this);
markDirtyClient();
updateLightBlocks(lit);
} else if (lit) {
// We are lit, check that our blocks are still there.
checkLitCounter
if (checkLitCounter <= 0) {
checkLitCounter = 10;
updateLightBlocks(lit);
}
}
}
}
private void updateLightBlocks(boolean lit) {
BlockPos.MutableBlockPos lpos = new BlockPos.MutableBlockPos();
int range = mode.getRange();
if (range == 0) {
return;
} else {
for (int x = -range; x <= range; x += range) {
for (int y = -range; y <= range; y += range) {
for (int z = -range; z <= range; z += range) {
if (x != 0 || y != 0 || z != 0) {
if (lit) {
lpos.setPos(pos.getX() + x, pos.getY() + y, pos.getZ() + z);
if (!isInvisibleLight(lpos)) {
if (getWorld().isAirBlock(lpos)) {
// This is not a light block but it is air. We can place a block
setInvisibleBlock(lpos);
} else {
// Not a light block and not air. Check adjacent locations
for (EnumFacing facing : EnumFacing.VALUES) {
BlockPos npos = lpos.offset(facing);
if (!isInvisibleLight(npos) && getWorld().isAirBlock(npos)) {
setInvisibleBlock(npos);
}
}
}
}
} else {
lpos.setPos(pos.getX() + x, pos.getY() + y, pos.getZ() + z);
if (isInvisibleLight(lpos)) {
getWorld().setBlockToAir(lpos);
}
for (EnumFacing facing : EnumFacing.VALUES) {
BlockPos npos = lpos.offset(facing);
if (isInvisibleLight(npos)) {
getWorld().setBlockToAir(npos);
}
}
}
}
}
}
}
}
}
private boolean setInvisibleBlock(BlockPos npos) {
return getWorld().setBlockState(npos, ModBlocks.invisibleLightBlock.getDefaultState(), 3);
}
private boolean isInvisibleLight(BlockPos lpos) {
return getWorld().getBlockState(lpos).getBlock() == ModBlocks.invisibleLightBlock;
}
@Override
public void onBlockBreak(World world, BlockPos pos, IBlockState state) {
updateLightBlocks(false);
}
public void setMode(LightMode mode) {
if (mode == this.mode) {
return;
}
light = null;
boolean oldlit = lit;
this.lit = false; // Force a relight
updateLightBlocks(lit);
this.mode = mode;
this.lit = oldlit;
markDirty();
}
public LightMode getMode() {
return mode;
}
public BlockColor getColor() {
return color;
}
public void setColor(BlockColor color) {
this.color = color;
this.light = null;
markDirtyClient();
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
lit = tagCompound.getBoolean("lit");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
tagCompound.setBoolean("lit", lit);
return tagCompound;
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
mode = LightMode.values()[tagCompound.getByte("mode")];
color = BlockColor.values()[tagCompound.getInteger("color")];
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
tagCompound.setInteger("color", color.ordinal());
tagCompound.setByte("mode", (byte) mode.ordinal());
}
} |
package seedu.geekeep.ui;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TabPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.geekeep.commons.core.LogsCenter;
import seedu.geekeep.commons.core.TaskCategory;
import seedu.geekeep.commons.events.ui.TaskPanelSelectionChangedEvent;
import seedu.geekeep.commons.util.FxViewUtil;
import seedu.geekeep.model.task.ReadOnlyTask;
/**
* Panel containing the list of tasks.
*/
public class TaskListPanel extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(TaskListPanel.class);
private static final String EVENTFXML = "EventListPanel.fxml";
private static final String FTASKFXML = "FloatingTaskListPanel.fxml";
private static final String DEADLINEFXML = "DeadlineListPanel.fxml";
private ListView<ReadOnlyTask> currentListView;
private String type;
@FXML
private TabPane tabPanePlaceHolder;
@FXML
private ListView<ReadOnlyTask> allListView;
@FXML
private ListView<ReadOnlyTask> upcomingListView;
@FXML
private ListView<ReadOnlyTask> completedListView;
public TaskListPanel(String type, AnchorPane taskListPlaceholder,
ObservableList<ReadOnlyTask> filteredList) {
super(getFxmlFromType(type));
this.type = type;
currentListView = allListView;
setConnections(filteredList, allListView);
setConnections(filteredList, completedListView);
setConnections(filteredList, upcomingListView);
addToPlaceholder(taskListPlaceholder);
selectTab(0);
}
//TODO to remove
private static String getFxmlFromType(String type) {
if ("deadline".equals(type)) {
return DEADLINEFXML;
} else if ("floatingTask".equals(type)) {
return FTASKFXML;
} else {
assert "event".equals(type);
return EVENTFXML;
}
}
private void setConnections(ObservableList<ReadOnlyTask> taskList,
ListView<ReadOnlyTask> taskListView) {
taskListView.setItems(taskList);
taskListView.setCellFactory(listView -> new TaskListViewCell());
setEventHandlerForSelectionChangeEvent(taskListView);
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
placeHolderPane.getChildren().add(getRoot());
}
private void setEventHandlerForSelectionChangeEvent(ListView<ReadOnlyTask> taskListView) {
taskListView.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
logger.fine("Selection in task list panel changed to : '" + newValue + "'");
raise(new TaskPanelSelectionChangedEvent(newValue));
}
});
}
public void scrollTo(int index) {
Platform.runLater(() -> {
currentListView.scrollTo(index);
currentListView.getSelectionModel().clearAndSelect(index);
});
}
public void switchListView(TaskCategory category) {
switch (category) {
case UNDONE:
selectTab(1);
break;
case DONE:
selectTab(2);
break;
default:
selectTab(0);
break;
}
logger.info("Switched to " + category + " in " + type);
}
public void selectTab(int tab) {
tabPanePlaceHolder.getTabs().get(tab).setDisable(false);
tabPanePlaceHolder.getSelectionModel().select(tab);
for (int i = 0; i < 3; i++) {
if (i != tab) {
tabPanePlaceHolder.getTabs().get(i).setDisable(true);
}
}
}
class TaskListViewCell extends ListCell<ReadOnlyTask> {
protected int getSourceIndex() {
FilteredList<ReadOnlyTask> filteredList = (FilteredList<ReadOnlyTask>) getListView().getItems();
return filteredList.getSourceIndex(getIndex());
}
@Override
protected void updateItem(ReadOnlyTask task, boolean empty) {
super.updateItem(task, empty);
if (empty || task == null) {
setGraphic(null);
setText(null);
} else {
setGraphic(new TaskCard(task, getSourceIndex() + 1).getRoot());
}
}
}
} |
package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class TaskName {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
public TaskName(String name) throws IllegalValueException {
assert name != null ;
if (name != null)
name = name.trim();
if (name == null || !isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskName // instanceof handles nulls
&& this.fullName.equals(((TaskName) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
} |
package seedu.tasklist.model.task;
import seedu.tasklist.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS =
"Task names should only contain alphanumeric characters and spaces, and it should not be blank";
/*
* The first character of the address must not be a whitespace,
* otherwise " " (a blank string) becomes a valid input.
*/
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum}][\\p{Alnum} ]*";
public final String fullName;
public Name(String name) throws IllegalValueException {
assert name != null;
String trimmedName = name.trim();
if (!isValidName(trimmedName)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = trimmedName;
}
/**
* Returns true if a given string is a valid person name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
} |
package seedu.unburden.model.task;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.unburden.commons.exceptions.IllegalValueException;
/**
* Represents a Task's time in the Task Manager. Guarantees: immutable; is valid
* as declared in {@link #isValidTime(String)}
*
* @@author A0143095H
*/
// @@ Gauri Joshi A0143095H
public class Time implements Comparable<Time> {
public static final String MESSAGE_TIME_CONSTRAINTS = "Task time should be in the format XXYY where X represents the number of hours and Y represents the number of minutes";
public static final String TIME_VALIDATION_REGEX = "([0-1][0-9][0-5][0-9])|([2][0-3][0-5][0-9])$";
// \\[0-9]{2}[0-9]{2}
private final String fullTime;
private int hours;
private int minutes;
public Time(String time) throws IllegalValueException {
assert time != null;
time = time.trim();
if (!time.equals("") && !isValidTime(time)) {
throw new IllegalValueException(MESSAGE_TIME_CONSTRAINTS);
}
if (time.equals("")) {
this.fullTime = "";
this.hours = 00;
this.minutes = 00;
} else {
this.fullTime = time;
this.hours = Integer.parseInt(time.substring(0, 2));
this.minutes = Integer.parseInt(time.substring(2));
}
}
/**
* Returns true if a given string is a valid time.
*/
public static boolean isValidTime(String test) {
final Pattern pattern = Pattern.compile(TIME_VALIDATION_REGEX);
final Matcher matcher = pattern.matcher(test);
return matcher.matches();
}
public String getFullTime() {
return this.fullTime;
}
public int getHours() {
return this.hours;
}
public int getMinutes() {
return this.minutes;
}
@Override
public String toString() {
return fullTime;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Time // instanceof handles nulls
&& this.fullTime.equals(((Time) other).fullTime)); // state
// check
}
@Override
public int compareTo(Time time) {
// entry check
if (this.equals(time)) { // check if same time or both dummy values
return 0;
} else if (this.getFullTime() == "") { // check if this Time
// object contains the
// dummy value
return 1;
} else if (time.getFullTime() == "") { // check if the Time
// object compared to
// contains the dummy
// value
return -1;
}
// comparing the values, hours and minutes.
if (this.getHours() == time.getHours() && this.getMinutes() == time.getMinutes()) {
return 0;
} else if (this.getHours() == time.getHours()) {
return this.getMinutes() - time.getMinutes();
} else {
return this.getHours() - time.getHours();
}
}
@Override
public int hashCode() {
return fullTime.hashCode();
}
} |
package tars.logic.commands;
import java.time.DateTimeException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import tars.commons.core.Messages;
import tars.commons.core.UnmodifiableObservableList;
import tars.commons.exceptions.DuplicateTaskException;
import tars.commons.exceptions.IllegalValueException;
import tars.commons.exceptions.InvalidTaskDisplayedException;
import tars.model.task.DateTime;
import tars.model.task.Name;
import tars.model.task.rsv.RsvTask;
import tars.model.task.rsv.UniqueRsvTaskList.RsvTaskNotFoundException;
/**
* Adds a reserved task which has a list of reserved datetimes that can
* confirmed later on.
*
* @@author A0124333U
*/
public class RsvCommand extends UndoableCommand {
public static final String COMMAND_WORD = "rsv";
public static final String COMMAND_WORD_DEL = "rsv -d";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Reserves one or more timeslot for a task.\n"
+ "Parameters: TASK [/dt DATETIME] [ADDITIONAL DATETIME]\n" + "Example: " + COMMAND_WORD
+ " Meet John Doe /dt 26/09/2016 0900 to 1030, 28/09/2016 1000 to 1130";
public static final String MESSAGE_USAGE_DEL = COMMAND_WORD_DEL
+ ": Deletes a reserved task in the last reserved task listing \n"
+ "Parameters: INDEX (must be a positive integer)\n " + "Example: " + COMMAND_WORD_DEL + " 1\n" + "OR "
+ COMMAND_WORD_DEL + " 1..3";
public static final String MESSAGE_DATETIME_NOTFOUND = "At least one DateTime is required!\n" + MESSAGE_USAGE;
public static final String MESSAGE_INVALID_RSV_TASK_DISPLAYED_INDEX = "The Reserved Task Index is invalid!";
public static final String MESSAGE_SUCCESS = "New task reserved: %1$s";
public static final String MESSAGE_SUCCESS_DEL = "Deleted Reserved Tasks: %1$s";
public static final String MESSAGE_UNDO = "Removed %1$s";
public static final String MESSAGE_REDO = "Reserved %1$s";
private RsvTask toReserve = null;
private String rangeIndexString = "";
private String conflictingTaskList = "";
private ArrayList<RsvTask> deletedRsvTasks = new ArrayList<RsvTask>();
public RsvCommand(String name, Set<String[]> dateTimeStringSet) throws IllegalValueException {
Set<DateTime> dateTimeSet = new HashSet<>();
for (String[] dateTimeStringArray : dateTimeStringSet) {
dateTimeSet.add(new DateTime(dateTimeStringArray[0], dateTimeStringArray[1]));
}
this.toReserve = new RsvTask(new Name(name), new ArrayList<DateTime>(dateTimeSet));
}
public RsvCommand(String rangeIndexString) {
this.rangeIndexString = rangeIndexString;
}
@Override
public CommandResult undo() {
// TODO Auto-generated method stub
return null;
}
@Override
public CommandResult redo() {
// TODO Auto-generated method stub
return null;
}
@Override
public CommandResult execute() {
assert model != null;
if (toReserve != null) {
return addRsvTask();
} else {
return delRsvTask();
}
}
private CommandResult addRsvTask() {
try {
for (DateTime dt : toReserve.getDateTimeList()) {
if (!model.getTaskConflictingDateTimeWarningMessage(dt).isEmpty()) {
conflictingTaskList += "\nConflicts for " + dt.toString() + ":";
conflictingTaskList += model.getTaskConflictingDateTimeWarningMessage(dt);
}
}
model.addRsvTask(toReserve);
model.getUndoableCmdHist().push(this);
return new CommandResult(getSuccessMessageSummary());
} catch (DuplicateTaskException e) {
return new CommandResult(Messages.MESSAGE_DUPLICATE_TASK);
}
}
private CommandResult delRsvTask() {
ArrayList<RsvTask> rsvTasksToDelete = new ArrayList<RsvTask>();
try {
rsvTasksToDelete = getRsvTasksFromIndexes(this.rangeIndexString.split(" "));
} catch (InvalidTaskDisplayedException itde) {
return new CommandResult(itde.getMessage());
}
for (RsvTask t : rsvTasksToDelete) {
try {
model.deleteRsvTask(t);
} catch (RsvTaskNotFoundException rtnfe) {
return new CommandResult(Messages.MESSAGE_RSV_TASK_CANNOT_BE_FOUND);
}
deletedRsvTasks.add(t);
}
model.getUndoableCmdHist().push(this);
String deletedRsvTasksList = CommandResult.formatRsvTasksList(deletedRsvTasks);
return new CommandResult(String.format(MESSAGE_SUCCESS_DEL, deletedRsvTasksList));
}
/**
* Gets Tasks to delete
*
* @param indexes
* @return
* @throws InvalidTaskDisplayedException
*/
private ArrayList<RsvTask> getRsvTasksFromIndexes(String[] indexes) throws InvalidTaskDisplayedException {
UnmodifiableObservableList<RsvTask> lastShownList = model.getFilteredRsvTaskList();
ArrayList<RsvTask> rsvTasksList = new ArrayList<RsvTask>();
for (int i = 0; i < indexes.length; i++) {
int targetIndex = Integer.parseInt(indexes[i]);
if (lastShownList.size() < targetIndex) {
indicateAttemptToExecuteIncorrectCommand();
throw new InvalidTaskDisplayedException(Messages.MESSAGE_INVALID_RSV_TASK_DISPLAYED_INDEX);
}
RsvTask rsvTask = lastShownList.get(targetIndex - 1);
rsvTasksList.add(rsvTask);
}
return rsvTasksList;
}
private String getSuccessMessageSummary() {
String summary = String.format(MESSAGE_SUCCESS, toReserve.toString());
if (!conflictingTaskList.isEmpty()) {
summary += "\n" + Messages.MESSAGE_CONFLICTING_TASKS_WARNING + conflictingTaskList;
}
return summary;
}
} |
package teropa.globetrotter.client;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import teropa.globetrotter.client.common.Bounds;
import teropa.globetrotter.client.common.Calc;
import teropa.globetrotter.client.common.Direction;
import teropa.globetrotter.client.common.LonLat;
import teropa.globetrotter.client.common.Point;
import teropa.globetrotter.client.common.Position;
import teropa.globetrotter.client.common.Rectangle;
import teropa.globetrotter.client.common.Size;
import teropa.globetrotter.client.controls.Control;
import teropa.globetrotter.client.event.MapZoomedEvent;
import teropa.globetrotter.client.event.internal.ViewPanEvent;
import teropa.globetrotter.client.proj.Projection;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
public class Map extends Composite implements ViewContext, ViewPanEvent.Handler {
private final AbsolutePanel container = new AbsolutePanel();
private final View view = new View(this);
private final Calc calc = new Calc(this);
private final List<Layer> layers = new ArrayList<Layer>();
private final LinkedHashMap<Control, Position> controls = new LinkedHashMap<Control, Position>();
private KeyboardControls keyboardControls;
private Layer baseLayer;
private Bounds maxExtent = new Bounds(-180, -90, 180, 90);
private LonLat center = new LonLat(0, 0);
private double[] resolutions = new double[] { 1.0, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01, 0.005 };
private int resolutionIndex = 4;
private Size tileSize = new Size(256, 256);
private Grid grid;
private Timer reinitTimer;
public Map(String width, String height) {
initWidget(container);
setWidth(width);
setHeight(height);
view.addViewPanHandler(this);
DeferredCommand.addCommand(new Command() {
public void execute() {
init();
}
});
}
private void init() {
container.add(view);
Size fullSize = calc.getVirtualPixelSize();
Point centerPoint = calc.getPoint(center);
view.position(centerPoint);
getGrid().init(fullSize);
view.draw(false);
positionControls();
this.keyboardControls = new KeyboardControls(this);
}
public void addLayer(Layer layer) {
layer.init(this);
layers.add(layer);
if (layer.isBase()) {
baseLayer = layer;
}
}
public Layer getLayerByName(String name) {
for (Layer each : layers) {
if (name.equals(each.getName())) {
return each;
}
}
return null;
}
public void removeLayer(String name) {
Layer theLayer = getLayerByName(name);
if (theLayer != null) {
layers.remove(theLayer);
}
}
public void setCenter(LonLat center) {
this.center = center;
}
public Projection getProjection() {
if (baseLayer != null) {
return baseLayer.getProjection();
} else {
return Projection.WGS_84;
}
}
public void setResolutions(double[] resolutions) {
this.resolutions = resolutions;
}
public double[] getResolutions() {
return resolutions;
}
public void zoomTo(int resolutionIndex) {
resizeView(resolutionIndex - this.resolutionIndex);
}
public void zoomTo(int resolutionIndex, LonLat point) {
resizeView(resolutionIndex - this.resolutionIndex, point);
}
public int getResolutionIndex() {
return this.resolutionIndex;
}
public Size getTileSize() {
return tileSize;
}
public View getView() {
return view;
}
public Bounds getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(Bounds maxExtent) {
this.maxExtent = maxExtent;
}
public double getResolution() {
return resolutions[resolutionIndex];
}
public Point getViewportLocation() {
return view.getTopLeft();
}
public LonLat getCenter() {
return center;
}
public Point getViewCenterPoint() {
return calc.getPoint(getCenter());
}
public Grid getGrid() {
if (grid == null) {
grid = new Grid(getTileSize(), this);
}
return grid;
}
public Rectangle getVisibleRectangle() {
Size portSize = view.getVisibleSize();
Point topLeft = getViewportLocation();
return new Rectangle(topLeft.getX(), topLeft.getY(), portSize.getWidth(), portSize.getHeight());
}
public void zoomIn() {
resizeView(1);
}
public void zoomIn(LonLat newCenter) {
resizeView(1, newCenter);
}
public void zoomOut() {
resizeView(-1);
}
public void onViewPanned(ViewPanEvent event) {
setCenter(calc.getLonLat(event.newCenterPoint));
}
public void move(Direction dir, int amountPx) {
switch(dir) {
case RIGHT: view.move(amountPx, 0); break;
case DOWN: view.move(0, amountPx); break;
case LEFT: view.move(-amountPx, 0); break;
case UP: view.move(0, -amountPx); break;
}
}
public void setKeyboardControlsEnabled(boolean enabled) {
if (enabled && keyboardControls == null) {
keyboardControls = new KeyboardControls(this);
} else if (!enabled && keyboardControls != null) {
keyboardControls.destroy();
keyboardControls = null;
}
}
private boolean newResolutionInBounds(int delta) {
if (delta > 0) {
return resolutionIndex + delta < resolutions.length;
} else {
return resolutionIndex + delta >= 0;
}
}
private void resizeView(int delta) {
resizeView(delta, center);
}
private void resizeView(int delta, LonLat newCenter) {
int prevResolutionIndex = resolutionIndex;
LonLat prevCenter = center;
if (newResolutionInBounds(delta)) {
resolutionIndex += delta;
}
setCenter(newCenter);
adjustView(resolutions[prevResolutionIndex], resolutions[resolutionIndex], prevCenter, newCenter);
fireEvent(new MapZoomedEvent());
}
private void adjustView(double fromRes, double toRes, LonLat fromCenter, LonLat toCenter) {
if (reinitTimer != null) reinitTimer.cancel();
zoomEffect(fromRes, toRes, fromCenter, toCenter);
reinitTimer = new Timer() {
public void run() {
reinitGrid();
reinitTimer = null;
}
};
reinitTimer.schedule(10);
}
private void zoomEffect(double fromRes, double toRes, LonLat fromCenter, LonLat toCenter) {
final double resScale = fromRes / toRes;
double width = getView().getVisibleSize().getWidth();
double height = getView().getVisibleSize().getHeight();
Point fromCenterPoint = calc().getPoint(fromCenter);
Point toCenterPoint = calc().getPoint(toCenter);
double xMove = fromCenterPoint.getX() - toCenterPoint.getX();
double yMove = fromCenterPoint.getY() - toCenterPoint.getY();
view.getCanvas().saveContext();
if (resScale >= 1) {
view.getCanvas().translate(
-view.getTopLeft().getX() - width / resScale + xMove,
-view.getTopLeft().getY() - height / resScale + yMove);
view.getCanvas().scale(resScale, resScale);
} else {
view.getCanvas().scale(resScale, resScale);
view.getCanvas().translate(
view.getTopLeft().getX() + width - width * resScale,
view.getTopLeft().getY() + height - height * resScale);
}
view.draw(true);
view.getCanvas().restoreContext();
}
private void reinitGrid() {
Size fullSize = calc.getVirtualPixelSize();
Point centerPoint = calc.getPoint(center);
view.position(centerPoint);
clearAreasOutsideGrid(fullSize, centerPoint);
getGrid().init(fullSize);
view.draw(false);
}
private void clearAreasOutsideGrid(Size fullSize, Point centerPoint) {
Size viewSize = view.getVisibleSize();
Point topLeft = view.getTopLeft();
GWTCanvas canvas = view.getCanvas();
canvas.saveContext();
canvas.setFillStyle(Color.WHITE);
int heightOutside = viewSize.getHeight() - fullSize.getHeight();
int heightTop = -topLeft.getY();
int heightBottom = viewSize.getHeight() - (-topLeft.getY() + fullSize.getHeight());
if (heightOutside > 0) {
canvas.fillRect(topLeft.getX(), topLeft.getY(), viewSize.getWidth(), heightTop);
canvas.fillRect(topLeft.getX(), topLeft.getY() + viewSize.getHeight() - heightBottom, viewSize.getWidth(), heightBottom);
}
int widthOutside = viewSize.getWidth() - fullSize.getWidth();
int widthLeft = -topLeft.getX();
int widthRight = viewSize.getWidth() - (-topLeft.getX() + fullSize.getWidth());
if (widthOutside > 0) {
canvas.fillRect(topLeft.getX(), topLeft.getY(), widthLeft, viewSize.getHeight());
canvas.fillRect(topLeft.getX() + viewSize.getWidth() - widthRight, topLeft.getY(), widthRight, viewSize.getHeight());
}
canvas.restoreContext();
}
public void addControl(Control control, Position at) {
control.init(this);
controls.put(control, at);
positionControl(control, at);
}
private void positionControls() {
for (Control each : controls.keySet()) {
positionControl(each, controls.get(each));
}
}
private void positionControl(Control control, Position at) {
switch (at) {
case TOP_LEFT: container.add(control.asWidget(), 10, 10); break;
case MIDDLE_LEFT: container.add(control.asWidget(), 10, 100); break;
case BOTTOM_LEFT: container.add(control.asWidget(), 10, getOffsetHeight() - 10 - control.asWidget().getOffsetHeight()); break;
}
}
public List<Layer> getLayers() {
return layers;
}
public Calc calc() {
return calc;
}
public void addMapZoomedHandler(MapZoomedEvent.Handler handler) {
addHandler(handler, MapZoomedEvent.TYPE);
}
} |
package uk.ac.edukapp.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* The persistent class for the userreview database table.
*
*/
@Entity
@Table(name="userreview")
@NamedQueries({
@NamedQuery(name="Userreview.findForWidgetProfile", query="SELECT r FROM Userreview r WHERE r.widgetProfile = :widgetprofile")
})
public class Userreview implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(unique=true, nullable=false)
private int id;
@Column(nullable=false)
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="comment_id", referencedColumnName="id")
private Comment comment;
@Column(nullable=false)
private byte rating;
@Column(nullable=false)
private Date time;
@JsonIgnore
@Column(nullable=false)
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="widgetprofile_id", referencedColumnName="id")
private Widgetprofile widgetProfile;
@Column(nullable=false)
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="user_id", referencedColumnName="id")
private Useraccount userAccount;
public Userreview() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public byte getRating() {
return this.rating;
}
public void setRating(byte rating) {
this.rating = rating;
}
public Date getTime() {
return this.time;
}
public void setTime(Date time) {
this.time = time;
}
/**
* @return the widgetProfile
*/
public Widgetprofile getWidgetProfile() {
return widgetProfile;
}
/**
* @param widgetProfile the widgetProfile to set
*/
public void setWidgetProfile(Widgetprofile widgetProfile) {
this.widgetProfile = widgetProfile;
}
/**
* @return the userAccount
*/
@JsonIgnore
public Useraccount getUserAccount() {
return userAccount;
}
/**
* @param userAccount the userAccount to set
*/
public void setUserAccount(Useraccount userAccount) {
this.userAccount = userAccount;
}
/**
* @return the comment
*/
@JsonIgnore
public Comment getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(Comment comment) {
this.comment = comment;
}
/**
* Return the actual comment text, e.g. for serialization
* @return
*/
public String getText(){
return this.getComment().getCommenttext();
}
/**
* Return just the user name, e.g. for serialization
* @return
*/
public String getUser(){
return this.getUserAccount().getUsername();
}
} |
package vontus.magicbottle;
import java.lang.reflect.Field;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.enchantments.EnchantmentWrapper;
import org.bukkit.inventory.ItemStack;
public class EnchantGlow extends EnchantmentWrapper
{
private static Enchantment glow;
public EnchantGlow()
{
super(8883);
}
@Override
public boolean canEnchantItem(ItemStack item)
{
return true;
}
@Override
public boolean conflictsWith(Enchantment other)
{
return false;
}
@Override
public EnchantmentTarget getItemTarget()
{
return null;
}
@Override
public int getMaxLevel()
{
return 10;
}
@Override
public String getName()
{
return "Glow";
}
@Override
public int getStartLevel()
{
return 1;
}
public static Enchantment getGlow()
{
if ( glow != null )
return glow;
try
{
Field f = Enchantment.class.getDeclaredField("acceptingNew");
f.setAccessible(true);
f.set(null , true);
}
catch (Exception e)
{
e.printStackTrace();
}
glow = new EnchantGlow();
try {
Enchantment.registerEnchantment(glow);
} catch (IllegalArgumentException e) {
Plugin.logger.severe("Can't register bottle enchantment. This can be ignored if MagicBottle has been reloaded by an external plugin.");
}
return glow;
}
public static void addGlow(ItemStack item)
{
Enchantment glow = getGlow();
item.addEnchantment(glow , 1);
}
} |
package paidia;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.BigDecimal;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class PlaygroundView extends JPanel {
private EditableView currentEditableView;
private MouseTool currentMouseTool;
private JPopupMenu mouseToolSelector;
private MouseAdapter currentMouseToolWrapper;
private Action createMouseToolSelector(String text, MouseTool mouseTool) {
return new AbstractAction(text) {
@Override
public void actionPerformed(ActionEvent e) {
if(currentMouseTool != null)
currentMouseTool.endTool(PlaygroundView.this);
currentMouseTool = mouseTool;
String title = ((JFrame) SwingUtilities.getWindowAncestor(PlaygroundView.this)).getTitle().split(" - ")[0];
((JFrame) SwingUtilities.getWindowAncestor(PlaygroundView.this)).setTitle(title + " - " + text);
currentMouseTool.startTool(PlaygroundView.this);
}
};
}
public PlaygroundView() {
setLayout(null);
currentMouseTool = new MouseTool() {
@Override
public void startTool(JComponent component) {
component.setToolTipText("Please right click and select a tool");
}
};
currentMouseTool.startTool(this);
mouseToolSelector = new JPopupMenu();
mouseToolSelector.setOpaque(false);
mouseToolSelector.setForeground(Color.BLACK);
mouseToolSelector.setBorder(new RoundedBorder(25, new Insets(5, 5, 5, 5)));
mouseToolSelector.add(createMouseToolSelector("Write", createWriteMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Move", createMoveMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Resize", createResizeMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Reduce", createReduceMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Derive", createDeriveMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Delete", createDeleteMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Name", createNameMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Apply", createApplyMouseTool()));
mouseToolSelector.add(createMouseToolSelector("Reference", createReferenceMouseTool()));
// What if each mouse button could be a tool reference, that can be changed on the run?
// - Then, which one should be used for mouse-over/enter/exit events?
//this.setComponentPopupMenu(mouseToolSelector);
ComponentAdapter componentAdapter = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
e.getComponent().revalidate();
e.getComponent().repaint();
System.out.println("Playground component resized");
}
};
addContainerListener(new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
revalidate();
repaint(e.getChild().getBounds());
e.getChild().addComponentListener(componentAdapter);
if(e.getChild() instanceof ValueView) {
((ValueView) e.getChild()).setup(PlaygroundView.this);
makeEditableByMouse((JComponent) e.getChild());
}
}
@Override
public void componentRemoved(ContainerEvent e) {
revalidate();
repaint(e.getChild().getBounds());
e.getChild().removeComponentListener(componentAdapter);
if(e.getChild() instanceof ValueView) {
((Container)e.getChild()).removeContainerListener(this);
((ValueView)e.getChild()).release();
}
}
});
currentMouseToolWrapper = createWrapperForMouseTool();
addMouseListener(currentMouseToolWrapper);
addMouseMotionListener(currentMouseToolWrapper);
}
private MouseAdapter createWrapperForMouseTool() {
return new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
currentMouseTool.mouseClicked(e);
}
boolean isPopupTrigger;
@Override
public void mousePressed(MouseEvent e) {
currentMouseTool.mousePressed(e);
Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), PlaygroundView.this);
if(e.isPopupTrigger()) {
isPopupTrigger = true;
mouseToolSelector.show(PlaygroundView.this, p.x, p.y);
}
}
@Override
public void mouseReleased(MouseEvent e) {
currentMouseTool.mouseReleased(e);
if(isPopupTrigger) {
mouseToolSelector.setVisible(false);
}
}
@Override
public void mouseDragged(MouseEvent e) {
currentMouseTool.mouseDragged(e);
}
@Override
public void mouseEntered(MouseEvent e) {
if(e.getComponent() != PlaygroundView.this)
currentMouseTool.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
if(e.getComponent() != PlaygroundView.this)
currentMouseTool.mouseExited(e);
}
@Override
public void mouseMoved(MouseEvent e) {
//if(e.getComponent() != PlaygroundView.this)
currentMouseTool.mouseMoved(e);
}
};
}
private MouseTool createWriteMouseTool() {
/*
What if editing simply begins when typing somewhere based on where the cursor was when the first key was typed?
What if editing is implicitly committed when editing an existing expression and starting to edit somewhere else
or, more generally, just losing focus? - I.e., "cancel" is caused by loss of focus.
*/
return new MouseTool() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
PlaygroundView.this.setToolTipText("");
EditableView editableView;
if(e.getComponent() == PlaygroundView.this) {
editableView = createRootEditableView(() -> "", editorComponent -> {
editorComponent.setLocation(e.getPoint());
editorComponent.setSize(80, 15);
}, newValueView -> {
}, () -> {
});
editableView.beginEdit();
} else {
((Value2ViewWrapper)e.getComponent()).beginEdit(PlaygroundView.this, e.getPoint());
//ValueViewContainer container = (ValueViewContainer) Stream.iterate(e.getComponent().getParent(), c -> (JComponent)c.getParent()).filter(x -> x instanceof ValueViewContainer).findFirst().get();
//editableView = container.getEditorFor((JComponent) e.getComponent());
}
//editableView.beginEdit();
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Click to create or edit an arithmetic expression - and hit enter to do the change.");
}
@Override
public void endTool(JComponent component) {
if(currentEditableView != null) {
currentEditableView.commitEdit();
//currentEditableView.cancelEdit();
}
}
};
}
private MouseTool createMoveMouseTool() {
return new MouseTool() {
private JComponent targetValueView;
private int mousePressX;
private int mousePressY;
private boolean moving;
private boolean canMove(JComponent x) {
if(x.getParent() == PlaygroundView.this)
return true;
if(x instanceof Value2ViewWrapper) {
Value2ViewWrapper parentViewWrapper = nearestValue2ViewWrapper((JComponent) x.getParent());
return parentViewWrapper.getValue().canMove(parentViewWrapper, (Value2ViewWrapper)x);
}
return false;
}
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
targetValueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> canMove(x)).findFirst().get();
moving = true;
targetValueView.getParent().setComponentZOrder(targetValueView, 0);
int cursorType = Cursor.MOVE_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
mousePressX = e.getX();
mousePressY = e.getY();
((Value2ViewWrapper)targetValueView).startMove();
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(moving) {
PlaygroundView.this.setToolTipText("");
int deltaX = e.getX() - mousePressX;
int deltaY = e.getY() - mousePressY;
targetValueView.setLocation(targetValueView.getX() + deltaX, targetValueView.getY() + deltaY);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && moving) {
moving = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
((Value2ViewWrapper)targetValueView).endMove();
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag an object to move it.");
}
};
}
private static final int NORTH = 0;
private static final int SOUTH = 1;
private static final int WEST = 0;
private static final int EAST = 1;
private static final int CENTER = 2;
private MouseTool createResizeMouseTool() {
return new MouseTool() {
private int hLocation;
private int vLocation;
private int marginSize = 5;
private JComponent targetValueView;
private int mousePressX;
private int mousePressY;
private boolean moving;
private boolean canResize(Container x) {
if(x.getParent() == PlaygroundView.this)
return true;
if(x instanceof Value2ViewWrapper) {
Value2ViewWrapper parentViewWrapper = nearestValue2ViewWrapper((JComponent) x.getParent());
return parentViewWrapper.getValue().canMove(parentViewWrapper, (Value2ViewWrapper)x);
}
return false;
}
@Override
public void mouseMoved(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
Container targetValueView = Stream.iterate((Container)valueView, c -> c.getParent()).filter(x -> x == PlaygroundView.this || canResize(x)).findFirst().get();
if(targetValueView == PlaygroundView.this) {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
return;
}
Point locationInTarget = SwingUtilities.convertPoint(valueView, e.getPoint(), targetValueView);
if(locationInTarget.x < marginSize)
hLocation = WEST;
else if(locationInTarget.x >= targetValueView.getWidth() - marginSize)
hLocation = EAST;
else
hLocation = CENTER;
if(locationInTarget.y < marginSize)
vLocation = NORTH;
else if(locationInTarget.y >= targetValueView.getHeight() - marginSize)
vLocation = SOUTH;
else
vLocation = CENTER;
switch(hLocation) {
case WEST:
switch(vLocation) {
case NORTH:
setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
break;
case CENTER:
setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
break;
case SOUTH:
setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
break;
}
break;
case CENTER:
switch(vLocation) {
case NORTH:
setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
break;
case CENTER:
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
break;
case SOUTH:
setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
break;
}
break;
case EAST:
switch(vLocation) {
case NORTH:
setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
break;
case CENTER:
setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
break;
case SOUTH:
setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
break;
}
break;
}
}
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
targetValueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> canResize(x)).findFirst().get();
moving = true;
targetValueView.getParent().setComponentZOrder(targetValueView, 0);
int cursorType = Cursor.MOVE_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(getCursor());
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
mousePressX = e.getX();
mousePressY = e.getY();
((Value2ViewWrapper)targetValueView).startMove();
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(moving) {
PlaygroundView.this.setToolTipText("");
int deltaX = 0;
int deltaY = 0;
int deltaWidth = 0;
int deltaHeight = 0;
if(hLocation == CENTER && vLocation == CENTER) {
deltaX = e.getX() - mousePressX;
deltaY = e.getY() - mousePressY;
} else {
switch(vLocation) {
case NORTH:
deltaY = e.getY() - mousePressY;
deltaHeight = deltaY * -1;
break;
case SOUTH:
deltaHeight = e.getY() - targetValueView.getHeight();
break;
}
switch(hLocation) {
case WEST:
deltaX = e.getX() - mousePressX;
deltaWidth = deltaX * -1;
break;
case EAST:
deltaWidth = e.getX() - targetValueView.getWidth();
break;
}
}
targetValueView.setLocation(targetValueView.getX() + deltaX, targetValueView.getY() + deltaY);
((Value2ViewWrapper)targetValueView).getView().setSize(targetValueView.getWidth() + deltaWidth, targetValueView.getHeight() + deltaHeight);
((Value2ViewWrapper)targetValueView).getView().setPreferredSize(((Value2ViewWrapper)targetValueView).getView().getSize());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && moving) {
moving = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
((Value2ViewWrapper)targetValueView).endMove();
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag an object to resize it.");
}
@Override
public void endTool(JComponent component) {
super.endTool(component);
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
};
}
private Value2ViewWrapper nearestValue2ViewWrapper(JComponent component) {
Container container = Stream.iterate((Container)component,
c -> c.getParent())
.filter(x -> x instanceof Value2ViewWrapper || x instanceof JFrame).findFirst().get();
return container instanceof Value2ViewWrapper ? (Value2ViewWrapper) container : null;
}
private MouseTool createReduceMouseTool() {
return new MouseTool() {
private JComponent selection;
private boolean linking;
private JComponent targetValueView;
private Color foreground;
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
linking = true;
targetValueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x ->
x.getParent() == PlaygroundView.this
|| nearestValue2ViewWrapper((JComponent) x.getParent()).getValue().canReduceFrom())
.findFirst().get();
foreground = targetValueView.getForeground();
targetValueView.setForeground(Color.BLUE);
int cursorType = Cursor.HAND_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(linking) {
PlaygroundView.this.setToolTipText("");
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && linking) {
linking = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
targetValueView.setForeground(foreground);
repaint(targetValueView.getBounds());
revalidate();
Point pointInContentPane = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), PlaygroundView.this);
JComponent targetComponent = (JComponent) findComponentAt(pointInContentPane);
//if(targetComponent != targetValueView) {
ReductionValue2 reduction = new ReductionValue2(((Value2ViewWrapper)targetValueView).getValueHolder());
Value2ViewWrapper reductionView = (Value2ViewWrapper) new Value2Holder(reduction).toView(PlaygroundView.this).getComponent();
if(targetComponent == PlaygroundView.this) {
Point pointInTargetComponent = SwingUtilities.convertPoint(PlaygroundView.this, pointInContentPane, targetComponent);
reductionView.setLocation(pointInTargetComponent);
add(reductionView);
} else {
targetComponent = Stream.iterate(targetComponent, c -> (JComponent)c.getParent()).filter(x -> x instanceof Value2ViewWrapper).findFirst().get();
Point pointInTargetComponent = SwingUtilities.convertPoint(PlaygroundView.this, pointInContentPane, targetComponent);
// Find nearest Value2ViewWrapper
Value2ViewWrapper targetComponentParent = (Value2ViewWrapper) Stream.iterate(targetComponent, c -> (JComponent)c.getParent()).filter(x -> x instanceof Value2ViewWrapper).findFirst().get();
// TODO: Should be ValueViewContainer instead of ValueView
targetComponentParent.drop(PlaygroundView.this, reductionView, pointInTargetComponent);
}
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag an object to reduce it as an expression.");
}
};
}
private MouseTool createDeriveMouseTool() {
return new MouseTool() {
private JComponent selection;
private boolean linking;
private JComponent targetValueView;
private Color foreground;
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
linking = true;
targetValueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> x.getParent() == PlaygroundView.this).findFirst().get();
foreground = targetValueView.getForeground();
targetValueView.setForeground(Color.BLUE);
int cursorType = Cursor.HAND_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(linking) {
PlaygroundView.this.setToolTipText("");
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && linking) {
linking = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
targetValueView.setForeground(foreground);
repaint(targetValueView.getBounds());
revalidate();
Point pointInContentPane = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), PlaygroundView.this);
JComponent targetComponent = (JComponent) findComponentAt(pointInContentPane);
Point pointInTargetComponent = SwingUtilities.convertPoint(PlaygroundView.this, pointInContentPane, targetComponent);
if(targetComponent != targetValueView) {
Value2 derivation = ((Value2ViewWrapper)e.getComponent()).getValue().derive();
Value2ViewWrapper reductionView = (Value2ViewWrapper) new Value2Holder(derivation).toView(PlaygroundView.this).getComponent();
if(targetComponent == PlaygroundView.this) {
reductionView.setLocation(pointInTargetComponent);
add(reductionView);
} else {
// Find nearest Value2ViewWrapper
Value2ViewWrapper targetComponentParent = (Value2ViewWrapper) Stream.iterate(targetComponent, c -> (JComponent)c.getParent()).filter(x -> x instanceof Value2ViewWrapper).findFirst().get();
// TODO: Should be ValueViewContainer instead of ValueView
targetComponentParent.drop(PlaygroundView.this, reductionView, pointInTargetComponent);
}
/*if(((Value2ViewWrapper)e.getComponent()).getValue() instanceof ClassValue) {
Value2 instance = ((ClassValue)((Value2ViewWrapper)e.getComponent()).getValue()).instantiate();
Value2ViewWrapper reductionView = (Value2ViewWrapper) new Value2Holder(instance).toView(PlaygroundView.this).getComponent();
if(targetComponent == PlaygroundView.this) {
reductionView.setLocation(pointInTargetComponent);
add(reductionView);
} else {
// Find nearest Value2ViewWrapper
Value2ViewWrapper targetComponentParent = (Value2ViewWrapper) Stream.iterate(targetComponent, c -> (JComponent)c.getParent()).filter(x -> x instanceof Value2ViewWrapper).findFirst().get();
// TODO: Should be ValueViewContainer instead of ValueView
targetComponentParent.drop(PlaygroundView.this, reductionView, pointInTargetComponent);
}
}*/
}
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag an object to reduce it as an expression.");
}
};
}
private MouseTool createDeleteMouseTool() {
return new MouseTool() {
@Override
public void mouseClicked(MouseEvent e) {
PlaygroundView.this.setToolTipText("");
JComponent valueView = (JComponent) e.getComponent();
valueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> x.getParent() == PlaygroundView.this).findFirst().get();
remove(valueView);
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
@Override
public void mouseEntered(MouseEvent e) {
int cursorType = Cursor.CROSSHAIR_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Click on an object to delete it.");
}
};
}
private MouseTool createNameMouseTool() {
return new MouseTool() {
@Override
public void mouseClicked(MouseEvent e) {
PlaygroundView.this.setToolTipText("");
JComponent valueViewTmp = (JComponent) e.getComponent();
ScopeView valueView = (ScopeView) Stream.iterate(valueViewTmp, c -> (JComponent)c.getParent()).filter(x -> x.getParent() == PlaygroundView.this).findFirst().get();
valueView.beginEditName();
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Click on an object to give it a name.");
}
};
}
private MouseTool createApplyMouseTool() {
return new MouseTool() {
private JComponent selection;
private boolean linking;
private JComponent functionView;
private Color foreground;
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
linking = true;
functionView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> x.getParent() == PlaygroundView.this).findFirst().get();
foreground = functionView.getForeground();
functionView.setForeground(Color.BLUE);
int cursorType = Cursor.HAND_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(linking) {
PlaygroundView.this.setToolTipText("");
}
}
@Override
public void mouseReleased(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1 && linking) {
linking = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
functionView.setForeground(foreground);
repaint(functionView.getBounds());
revalidate();
Point pointInContentPane = SwingUtilities.convertPoint(valueView, e.getPoint(), PlaygroundView.this);
JComponent targetComponent = (JComponent) findComponentAt(pointInContentPane);
Point pointInTargetComponent = SwingUtilities.convertPoint(PlaygroundView.this, pointInContentPane, targetComponent);
if(targetComponent != valueView) {
if(!(((Value2ViewWrapper)functionView).getValue() instanceof ClassValue)) {
ApplyValue2 applyValue = new ApplyValue2(((Value2ViewWrapper) functionView).getValueHolder(), () -> new Value2Holder(new AtomValue2("0", "0", new BigDecimal(0))));
((Value2ViewWrapper) functionView).getValueHolder().getParameters().forEach(x ->
applyValue.setArgument(x, new Value2Holder(new AtomValue2("0", "0", new BigDecimal(0)))));
JComponent applyView = new Value2Holder(applyValue).toView(PlaygroundView.this).getComponent();
if (targetComponent == PlaygroundView.this) {
//ScopeView scopeView = new ScopeView(applyView);
applyView.setLocation(pointInTargetComponent);
add(applyView);
} else {
JComponent targetComponentParent = (JComponent) targetComponent.getParent();
((ValueViewContainer) targetComponentParent).drop(PlaygroundView.this, applyView, targetComponent);
}
} else {
ApplyClassValue2 applyValue = new ApplyClassValue2((ClassValue) ((Value2ViewWrapper) functionView).getValueHolder().getValue(), () -> new Value2Holder(new AtomValue2("0", "0", new BigDecimal(0))));
//((Value2ViewWrapper) functionView).getValueHolder().getParameters().forEach(x ->
// applyValue.setArgument(x, new Value2Holder(new AtomValue2("0", "0", new BigDecimal(0)))));
JComponent applyView = new Value2Holder(applyValue).toView(PlaygroundView.this).getComponent();
if (targetComponent == PlaygroundView.this) {
//ScopeView scopeView = new ScopeView(applyView);
applyView.setLocation(pointInTargetComponent);
add(applyView);
} else {
JComponent targetComponentParent = (JComponent) targetComponent.getParent();
((ValueViewContainer) targetComponentParent).drop(PlaygroundView.this, applyView, targetComponent);
}
}
/*ApplyView applyView = new ApplyView(functionView, ((ValueView)functionView).getIdentifiers().stream().map(x -> createDefaultValueView()).collect(Collectors.toList()));
if(targetComponent == PlaygroundView.this) {
ScopeView scopeView = new ScopeView(applyView);
scopeView.setLocation(pointInTargetComponent);
add(scopeView);
} else {
JComponent targetComponentParent = (JComponent) targetComponent.getParent();
((ValueViewContainer) targetComponentParent).drop(PlaygroundView.this, applyView, targetComponent);
}*/
}
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag a function to apply it.");
}
};
}
private MouseTool createReferenceMouseTool() {
return new MouseTool() {
private JComponent selection;
private boolean linking;
private JComponent targetValueView;
private Color foreground;
@Override
public void mousePressed(MouseEvent e) {
JComponent valueView = (JComponent) e.getComponent();
if(e.getButton() == MouseEvent.BUTTON1) {
linking = true;
targetValueView = Stream.iterate(valueView, c -> (JComponent)c.getParent()).filter(x -> x.getParent() == PlaygroundView.this).findFirst().get();
foreground = targetValueView.getForeground();
targetValueView.setForeground(Color.BLUE);
int cursorType = Cursor.HAND_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(linking) {
PlaygroundView.this.setToolTipText("");
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && linking) {
linking = false;
int cursorType = Cursor.DEFAULT_CURSOR;
Component glassPane = ((RootPaneContainer)getTopLevelAncestor()).getGlassPane();
glassPane.setCursor(Cursor.getPredefinedCursor(cursorType));
glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
targetValueView.setForeground(foreground);
repaint(targetValueView.getBounds());
revalidate();
Point pointInContentPane = SwingUtilities.convertPoint(targetValueView, e.getPoint(), PlaygroundView.this);
JComponent targetComponent = (JComponent) findComponentAt(pointInContentPane);
Point pointInTargetComponent = SwingUtilities.convertPoint(PlaygroundView.this, pointInContentPane, targetComponent);
if(targetComponent != targetValueView) {
ReferenceView reduction = new ReferenceView(targetValueView);
if(targetComponent == PlaygroundView.this) {
ScopeView scopeView = new ScopeView(reduction);
scopeView.setLocation(pointInTargetComponent);
add(scopeView);
} else {
JComponent targetComponentParent = (JComponent) targetComponent.getParent();
// TODO: Should be ValueViewContainer instead of ValueView
((ValueViewContainer) targetComponentParent).drop(PlaygroundView.this, reduction, targetComponent);
}
}
}
}
@Override
public void startTool(JComponent component) {
component.setToolTipText("Press and drag an object to reduce it as an expression.");
}
};
}
public JComponent createDefaultValueView() {
return new AtomView("0", new BigDecimal(0));
}
public EditableView createRootEditableView(Supplier<String> textSupplier, Consumer<JComponent> beginEdit, Consumer<JComponent> endEdit, Runnable cancelEdit) {
return createEditableView(new ParsingEditor(this) {
JComponent editorComponent;
@Override
public String getText() {
return textSupplier.get();
}
@Override
public void beginEdit(JComponent editorComponent) {
this.editorComponent = editorComponent;
beginEdit.accept(editorComponent);
add(editorComponent);
repaint();
revalidate();
}
@Override
public void endEdit(JComponent parsedComponent) {
remove(editorComponent);
ScopeView scopeView = new ScopeView((ValueView)parsedComponent);
scopeView.setLocation(editorComponent.getLocation());
add(scopeView);
endEdit.accept(parsedComponent);
repaint();
revalidate();
}
@Override
protected void endEdit(Value2 parsedValue) {
remove(editorComponent);
JComponent valueViewWrapper = new Value2Holder(parsedValue).toView(PlaygroundView.this).getComponent();
valueViewWrapper.setLocation(editorComponent.getLocation());
add(valueViewWrapper);
endEdit.accept(valueViewWrapper);
repaint();
revalidate();
}
@Override
public void cancelEdit() {
remove(editorComponent);
cancelEdit.run();
repaint();
revalidate();
}
});
}
public EditableView createEditableView(Editor editor) {
EditableView[] editableViews = new EditableView[1];
editableViews[0] = new EditableView(new TextParser() {
@Override
public JComponent parse(JComponent editorComponent, String text) {
return ComponentParser.parseComponent(text, PlaygroundView.this);
}
}, new Editor() {
@Override
public String getText() {
return editor.getText();
}
@Override
public void beginEdit(JComponent editorComponent) {
if(currentEditableView != null) {
currentEditableView.commitEdit();
//currentEditableView.cancelEdit();
}
editor.beginEdit(editorComponent);
currentEditableView = editableViews[0];
editorComponent.requestFocusInWindow();
}
@Override
public void endEdit(String text) {
editor.endEdit(text);
currentEditableView = null;
}
/*@Override
public void endEdit(JComponent parsedComponent) {
editor.endEdit(parsedComponent);
currentEditableView = null;
}*/
@Override
public void cancelEdit() {
editor.cancelEdit();
currentEditableView = null;
}
});
return editableViews[0];
}
public void makeEditableByMouse(JComponent valueView) {
//valueView.setComponentPopupMenu(mouseToolSelector);
valueView.addMouseListener(currentMouseToolWrapper);
valueView.addMouseMotionListener(currentMouseToolWrapper);
}
public void unmakeEditableByMouse(JComponent valueView) {
valueView.setComponentPopupMenu(null);
//valueView.removeMouseListener(currentMouseToolWrapper);
valueView.removeMouseMotionListener(currentMouseToolWrapper);
}
private int frameId;
public int nextFrameId() {
return frameId++;
}
} |
package com.thinkbiganalytics.feedmgr.sla;
import com.google.common.collect.Lists;
import com.thinkbiganalytics.metadata.rest.model.sla.Obligation;
import com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup;
import com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement;
import com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreementCheck;
import com.thinkbiganalytics.metadata.sla.api.Metric;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreementActionConfiguration;
import com.thinkbiganalytics.policy.PolicyPropertyTypes;
import com.thinkbiganalytics.policy.PolicyTransformException;
import com.thinkbiganalytics.policy.rest.model.FieldRuleProperty;
import com.thinkbiganalytics.rest.model.LabelValue;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ServiceLevelAgreementMetricTransformerHelper {
public ServiceLevelAgreementMetricTransformerHelper() {
}
/**
* gets all SystemCategory.SystemFeedName values
*/
public List<String> getCategoryFeedNames(ServiceLevelAgreementGroup serviceLevelAgreement) {
List<String> names = new ArrayList<>();
if (serviceLevelAgreement != null) {
List<FieldRuleProperty>
properties =
ServiceLevelAgreementMetricTransformer.instance().findPropertiesForRulesetMatchingRenderTypes(serviceLevelAgreement.getRules(),
new String[]{PolicyPropertyTypes.PROPERTY_TYPE.currentFeed.name(),
PolicyPropertyTypes.PROPERTY_TYPE.feedChips.name(),
PolicyPropertyTypes.PROPERTY_TYPE.feedSelect.name()});
if (properties != null && !properties.isEmpty()) {
//get the Value or List of values.
for (FieldRuleProperty property : properties) {
String value = property.getValue();
if (StringUtils.isNotBlank(value)) {
names.add(value);
} else if (property.getValues() != null && !property.getValues().isEmpty()) {
names.addAll(property.getValues().stream().map(LabelValue::getValue).collect(Collectors.toList()));
}
}
}
}
return names;
}
public void applyFeedNameToCurrentFeedProperties(ServiceLevelAgreementGroup serviceLevelAgreement, String category, String feed) {
if (serviceLevelAgreement != null) {
List<FieldRuleProperty>
properties = new ArrayList<>();
List<FieldRuleProperty>
currentFeedProperties =
ServiceLevelAgreementMetricTransformer.instance().findPropertiesForRulesetMatchingRenderType(serviceLevelAgreement.getRules(), PolicyPropertyTypes.PROPERTY_TYPE.currentFeed.name());
if(currentFeedProperties != null && !currentFeedProperties.isEmpty()) {
properties.addAll(currentFeedProperties);
}
List<FieldRuleProperty>
defaultValueProperties = ServiceLevelAgreementMetricTransformer.instance().findPropertiesForRulesMatchingDefaultValue(serviceLevelAgreement.getRules(),
PolicyPropertyTypes.CURRENT_FEED_VALUE);
if (defaultValueProperties != null && !defaultValueProperties.isEmpty()) {
properties.addAll(defaultValueProperties);
}
if (!properties.isEmpty()) {
for (FieldRuleProperty property : properties) {
if(StringUtils.isBlank(property.getValue())) {
property.setValue(category + "." + feed);
}
}
}
}
}
public ServiceLevelAgreement getServiceLevelAgreement(ServiceLevelAgreementGroup serviceLevelAgreement) {
ServiceLevelAgreement transformedSla = new ServiceLevelAgreement();
transformedSla.setId(serviceLevelAgreement.getId());
transformedSla.setName(serviceLevelAgreement.getName());
transformedSla.setDescription(serviceLevelAgreement.getDescription());
for (ServiceLevelAgreementRule rule : serviceLevelAgreement.getRules()) {
try {
ObligationGroup group = new ObligationGroup();
Metric policy = ServiceLevelAgreementMetricTransformer.instance().fromUiModel(rule);
Obligation obligation = new Obligation(policy.getDescription());
obligation.setMetrics(Lists.newArrayList(policy));
group.addObligation(obligation);
group.setCondition(rule.getCondition().name());
transformedSla.addGroup(group);
} catch (PolicyTransformException e) {
throw new RuntimeException(e);
}
}
return transformedSla;
}
/**
* TODO return the Check object that has the related cron Schedule as well
*/
public List<ServiceLevelAgreementActionConfiguration> getActionConfigurations(ServiceLevelAgreementGroup serviceLevelAgreement) {
List<ServiceLevelAgreementActionConfiguration> actionConfigurations = new ArrayList<>();
if (serviceLevelAgreement.getActionConfigurations() != null) {
for (ServiceLevelAgreementActionUiConfigurationItem agreementActionUiConfigurationItem : serviceLevelAgreement.getActionConfigurations()) {
try {
ServiceLevelAgreementActionConfiguration actionConfiguration = ServiceLevelAgreementActionConfigTransformer.instance().fromUiModel(agreementActionUiConfigurationItem);
actionConfigurations.add(actionConfiguration);
} catch (PolicyTransformException e) {
throw new RuntimeException(e);
}
}
}
return actionConfigurations;
}
/**
* Transform the Rest Model back to the form model
*/
public ServiceLevelAgreementGroup toServiceLevelAgreementGroup(ServiceLevelAgreement sla) {
ServiceLevelAgreementGroup slaGroup = new ServiceLevelAgreementGroup();
slaGroup.setId(sla.getId());
slaGroup.setName(sla.getName());
slaGroup.setDescription(sla.getDescription());
for (ObligationGroup group : sla.getGroups()) {
List<Obligation> obligations = group.getObligations();
for (Obligation obligation : obligations) {
List<Metric> metrics = obligation.getMetrics();
for (Metric metric : metrics) {
ServiceLevelAgreementRule rule = ServiceLevelAgreementMetricTransformer.instance().toUIModel(metric);
slaGroup.addServiceLevelAgreementRule(rule);
}
}
}
//transform the Actions if they exist.
//TODO add in the Schedule prop
if (sla.getSlaChecks() != null) {
List<ServiceLevelAgreementActionUiConfigurationItem> agreementActionUiConfigurationItems = new ArrayList<>();
for(ServiceLevelAgreementCheck check: sla.getSlaChecks()) {
for (ServiceLevelAgreementActionConfiguration actionConfig : check.getActionConfigurations()) {
if(actionConfig != null) {
ServiceLevelAgreementActionUiConfigurationItem uiModel = ServiceLevelAgreementActionConfigTransformer.instance().toUIModel(actionConfig);
agreementActionUiConfigurationItems.add(uiModel);
}
}
}
slaGroup.setActionConfigurations(agreementActionUiConfigurationItems);
}
return slaGroup;
}
} |
package de.fu_berlin.imp.seqan.usability_analyzer.groundedtheory.ui.wizards.pages;
import java.util.concurrent.Callable;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import com.bkahlert.nebula.utils.ExecUtils;
import com.bkahlert.nebula.utils.FontUtils;
public abstract class ORWizardPage extends WizardPage {
private Font font;
private final int numAlternatives;
public ORWizardPage(String pageName, int numAlternatives) {
super(pageName);
this.numAlternatives = numAlternatives;
try {
this.font = ExecUtils.syncExec(new Callable<Font>() {
@Override
public Font call() throws Exception {
return new Font(Display.getCurrent(), FontUtils
.getResizedFontData(Display.getCurrent()
.getSystemFont().getFontData(), 2));
}
});
} catch (Exception e) {
this.font = Display.getDefault().getSystemFont();
}
}
@Override
public final void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
this.setControl(composite);
composite.addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
Font oldFont = e.gc.getFont();
e.gc.setFont(ORWizardPage.this.font);
e.gc.drawText("OR", (int) (e.width / 2 - e.gc.getFontMetrics()
.getAverageCharWidth() * 1.25),
(int) (e.height / 2 - ORWizardPage.this.font
.getFontData()[0].getHeight() / 3.0));
e.gc.setFont(oldFont);
}
});
composite.setLayout(GridLayoutFactory.fillDefaults()
.numColumns(this.numAlternatives).margins(10, 0).spacing(50, 0)
.equalWidth(true).create());
Composite[] contentComposites = new Composite[this.numAlternatives];
for (int i = 0, m = this.numAlternatives; i < m; i++) {
contentComposites[i] = new Composite(composite, SWT.NONE);
contentComposites[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL,
true, true));
}
this.fillContent(contentComposites);
}
public abstract void fillContent(Composite... contentComposites);
@Override
public void dispose() {
this.font.dispose();
super.dispose();
}
} |
package uk.ac.ucl.excites.sapelli.storage.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import uk.ac.ucl.excites.sapelli.storage.util.IntegerRangeMapping;
import uk.ac.ucl.excites.sapelli.storage.visitors.ColumnVisitor;
/**
* A Schema holds a set of ordered {@link Column}s
*
* @author mstevens
*/
@SuppressWarnings("rawtypes")
public class Schema implements Serializable
{
private static final long serialVersionUID = 2L;
static protected final int UNKNOWN_COLUMN_POSITION = -1;
// Identification:
static public final int SCHEMA_ID_SIZE = 36; //bits
static public final IntegerRangeMapping SCHEMA_ID_FIELD = IntegerRangeMapping.ForSize(0, SCHEMA_ID_SIZE); // unsigned(!) 36 bit integer
static public final String ATTRIBUTE_SCHEMA_ID = "schemaID";
static public final String ATTRIBUTE_SCHEMA_NAME = "schemaName";
static public enum ReservedIDs
{
INDEX_SCHEMA,
LOCATION_SCHEMA,
ORIENTATION_SCHEMA
// more later?
}
// v1.x-style identification (for backwards compatibility only):
// Note: schemaID & schemaVersion are no longer stored in a Schema instance, instead a 1.x Project instance holds them (Project#id = schemaID & Project#schemaVersion = schemaVersion)
static public final int V1X_SCHEMA_ID_SIZE = 24; //bits
static public final int V1X_SCHEMA_VERSION_SIZE = 8; //bits
static public final IntegerRangeMapping V1X_SCHEMA_VERSION_FIELD = IntegerRangeMapping.ForSize(0, V1X_SCHEMA_VERSION_SIZE);
static public final int V1X_DEFAULT_SCHEMA_VERSION = 0;
// Note the XML attributes below have inconsistent naming (for everything else we've been using CamelCase instead of dashes), won't fix because no longer used in v2.x
static public final String V1X_ATTRIBUTE_SCHEMA_ID = "schema-id";
static public final String V1X_ATTRIBUTE_SCHEMA_VERSION = "schema-version";
protected final long id;
protected final String name;
private final List<Column> realColumns; // only contains non-virtual columns
private transient List<Column> allColumns; // contains non-virtual and virtual columns
private final Map<String, Integer> columnNameToPosition; // only contains non-virtual columns
private final Map<String, VirtualColumn> virtualColumnsByName;
private final List<Index> indexes;
private Index primaryKey;
private boolean sealed = false;
public Schema(long id, String name)
{
if(SCHEMA_ID_FIELD.fits(id))
this.id = id;
else
throw new IllegalArgumentException("Invalid schema ID value (" + id + "), valid values are " + SCHEMA_ID_FIELD.getLogicalRangeString() + ".");
this.name = (name == null || name.isEmpty() ? "Schema_ID" + id : name);
columnNameToPosition = new LinkedHashMap<String, Integer>();
realColumns = new ArrayList<Column>();
virtualColumnsByName = new HashMap<String, VirtualColumn>();
indexes = new ArrayList<Index>();
}
@SuppressWarnings("unchecked")
public void addColumns(List<Column<?>> columns)
{
for(Column c : columns)
addColumn(c);
}
public <T> void addColumn(Column<T> column)
{
if(sealed)
throw new IllegalStateException("Cannot extend a sealed schema!");
if(containsColumn(column, true))
throw new IllegalArgumentException("The schema already contains a column with name \"" + column.getName() + "\"!");
// Add the column:
columnNameToPosition.put(column.getName(), realColumns.size());
realColumns.add(column);
// Add any virtual versions it may have
for(VirtualColumn<?, T> vCol : column.getVirtualVersions())
{
if(!containsColumn(vCol.getSourceColumn(), false))
throw new IllegalArgumentException("The schema does not contain the source column (" + vCol.getSourceColumn().getName() + ") of the given virtual column.");
virtualColumnsByName.put(vCol.getName(), vCol);
}
}
/**
* Add an {@link Index} to the Schema, which may or may not be used as the primary key.
* In case it is to be used as the primary key the index needs to be unique and should consist only of non-optional (i.e. non-nullable) columns.
*
* Note: adding a primary key index is not allowed after the Schema has been sealed, adding normal indexes is allowed.
*
* @param index
* @param useAsPrimaryKey
*/
public void addIndex(Index index, boolean useAsPrimaryKey)
{
if(sealed && useAsPrimaryKey)
throw new IllegalStateException("Cannot set the primary key of a sealed schema (adding normal indexes is allowed)!");
if(index == null)
throw new IllegalArgumentException("Index cannot be null!");
// Check if the indexed columns are columns of this Schema instance:
for(Column idxCol : index.getColumns(false))
if(!containsColumn(idxCol, false))
throw new IllegalArgumentException("Indexed column '" + idxCol.getName() + "' does not belong to this Schema. Indexed columns need to be added to the Schema before Indexes are added.");
if(useAsPrimaryKey)
{
if(primaryKey != null)
throw new IllegalStateException("This Schema already has a primary key (there can be only 1)!");
if(!index.isUnique())
throw new IllegalArgumentException("An Index needs to be unique to serve as the primary key!");
for(Column idxCol : index.getColumns(false))
if(idxCol.isOptional())
throw new IllegalArgumentException("An primary key index cannot contain optional (i.e. nullable) columns!");
primaryKey = index; // set the index as primary key
}
indexes.add(index); // add to the indexes
}
/**
* @param name
* @param checkVirtual whether or not to look in the schema's virtual columns
* @return the {@link Column} instance with this name, or {@code null} if the Schema contains no such column
*/
public Column getColumn(String name, boolean checkVirtual)
{
Integer pos = columnNameToPosition.get(name);
if(pos == null)
return checkVirtual ? virtualColumnsByName.get(name) : null;
return realColumns.get(pos);
}
public List<Column> getColumns(boolean includeVirtual)
{
if(includeVirtual)
{
if(!sealed || allColumns == null) // (re)initialise the allColumns list if it is null or as long as the schema is not sealed.
{
allColumns = new ArrayList<Column>();
for(Column<?> nonVirtualCol : realColumns)
{
allColumns.add(nonVirtualCol); // "real" column
allColumns.addAll(nonVirtualCol.getVirtualVersions()); // insert virtual versions of real column after it
}
}
return allColumns;
}
return realColumns;
}
/**
* @return an unordered collection of the virtual columns in the schema
*/
public Collection<VirtualColumn> getVirtualColumns()
{
return virtualColumnsByName.values();
}
/**
* Returns the position of a given non-virtual column.
* Null is returned if the schema doesn't contain the column at all, but also if the column is virtual (even if the source is contained by the schema).
*
* @param column a non-virtual column
* @return the position of the given {@link Column} instance within this Schema, or {@link #UNKNOWN_COLUMN_POSITION} if the Schema contains no such column
*/
protected int getColumnPosition(Column column)
{
Integer idx = columnNameToPosition.get(column.getName());
if(idx == null)
return UNKNOWN_COLUMN_POSITION;
return idx.intValue();
}
/**
* @param name the name of a column
* @param checkVirtual whether or not to look in the schema's virtual columns
* @return
*/
public boolean containsColumn(String name, boolean checkVirtual)
{
return columnNameToPosition.containsKey(name) || (checkVirtual && virtualColumnsByName.containsKey(name));
}
/**
*
* @param column
* @param checkVirtual whether or not to look in the schema's virtual columns
* @return whether or not this Schema contains the given Column or an exact equivalent of it
*/
public boolean containsColumn(Column column, boolean checkVirtual)
{
Column myColumn = getColumn(column.getName(), checkVirtual);
return myColumn != null && myColumn.equals(column);
}
/**
* @return the indexes
*/
public List<Index> getIndexes()
{
return indexes;
}
/**
* @return the primaryKey
*/
public Index getPrimaryKey()
{
return primaryKey;
}
/**
* @return whether or not the Schema has a primary key
*/
public boolean hasPrimaryKey()
{
return primaryKey != null;
}
/**
* @return the sealed
*/
public boolean isSealed()
{
return sealed;
}
/**
* seals the schema, after which records can be created based on it, but no more columns can be added
*/
public void seal()
{
this.sealed = true;
}
public Record createRecord()
{
return new Record(this);
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @return the id
*/
public long getID()
{
return id;
}
public int getNumberOfColumns(boolean includeVirtual)
{
return realColumns.size() + (includeVirtual ? virtualColumnsByName.size() : 0);
}
/**
* @return whether or not the size taken up by binary stored records of this schema varies at run-time (i.e. depending on data input)
*/
public boolean isVariableSize()
{
return isVariableSize(false, null);
}
/**
* @return whether or not the size taken up by binary stored records of this schema varies at run-time (i.e. depending on data input)
*
* @param includeVirtual
* @param skipColumns columns to ignore in the total
* @return
*/
public boolean isVariableSize(boolean includeVirtual, Set<Column<?>> skipColumns)
{
for(Column<?> c : getColumns(includeVirtual))
if((skipColumns == null || !skipColumns.contains(c)) && c.isVariableSize())
return true;
return false;
}
/**
* Returns the minimum effective number of bits a record of this schema takes up when written to a binary representation.
* Includes all non-virtual columns in the count.
*
* @return
*/
public int getMinimumSize()
{
return getMinimumSize(false, null);
}
/**
* Returns the minimum effective number of bits a record of this schema takes up when written to a binary representation.
*
* @param includeVirtual
* @param skipColumns columns to ignore in the total
* @return
*/
public int getMinimumSize(boolean includeVirtual, Set<Column<?>> skipColumns)
{
int total = 0;
for(Column<?> c : getColumns(includeVirtual))
if(skipColumns == null || !skipColumns.contains(c))
total += c.getMinimumSize();
return total;
}
/**
* Returns the maximum effective number of bits a record of this schema takes up when written to a binary representation.
* Includes all non-virtual columns in the count.
*
* @return
*/
public int getMaximumSize()
{
return getMaximumSize(false, null);
}
/**
* Returns the maximum effective number of bits a record of this schema takes up when written to a binary representation.
*
* @param includeVirtual
* @param skipColumns columns to ignore the total
* @return
*/
public int getMaximumSize(boolean includeVirtual, Set<Column<?>> skipColumns)
{
int total = 0;
for(Column<?> c : getColumns(includeVirtual))
if(skipColumns == null || !skipColumns.contains(c))
total += c.getMaximumSize();
return total;
}
/**
* Check for equality based on schema ID (nothing else)
*
* @param obj object to compare this one with
* @return whether or not the given Object is a Schema with the same ID & version as this one
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
return equals(obj, false, false, false); // check only schemaID
}
/**
* Check if the provided object is an identical/equivalent Schema. The usageID & usageSubID are always checked, names and columns are optionally checked, descriptions are ignored.
*
* @param obj object to compare this one with
* @param checkNames whether or not to compare the names of the schemas and (if checkColumns is true) those of their columns
* @param checkColumns whether or not to compare columns (types, sizes, etc., and names if checkNames is true)
* @param checkIndexes whether or not to compare indexes
* @return whether or not the given Object is an identical/equivalent Schema (under the given checking conditions)
*/
public boolean equals(Object obj, boolean checkNames, boolean checkColumns, boolean checkIndexes)
{
if(this == obj) // compare pointers first
return true;
if(obj instanceof Schema)
{
Schema other = (Schema) obj;
boolean idMatch = (this.id == other.id);
if(!(checkNames || checkColumns) || !idMatch)
return idMatch;
// Name:
if(checkNames && !this.name.equals(other.name))
return false;
// Columns & indexes:
if(checkColumns)
{
// Check number of (real) columns:
if(realColumns.size() != other.realColumns.size())
return false;
// Compare columns:
Iterator<Column> myCols = realColumns.iterator();
Iterator<Column> otherCols = other.realColumns.iterator();
while(myCols.hasNext() /* && otherCols.hasNext() */)
if(!myCols.next().equals(otherCols.next(), checkNames, true))
return false;
}
if(checkIndexes)
{
// Check number of indexes:
if(indexes.size() != other.indexes.size())
return false;
// Compare indexes:
Iterator<Index> myIndexes = indexes.iterator();
Iterator<Index> otherIndexes = other.indexes.iterator();
while(myIndexes.hasNext() /** otherIndexes.hasNext() */)
if(!myIndexes.next().equals(otherIndexes.next(), checkNames, checkColumns, false))
return false;
}
return true;
}
else
return false;
}
@Override
public int hashCode()
{
int hash = 1;
hash = 31 * hash + (int)(id ^ (id >>> 32));
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + realColumns.hashCode();
hash = 31 * hash + indexes.hashCode();
hash = 31 * hash + (primaryKey == null ? 0 : primaryKey.hashCode());
hash = 31 * hash + (sealed ? 0 : 1);
return hash;
}
@Override
public String toString()
{
return "Schema " + name;
}
public String getSpecification()
{
StringBuffer bff = new StringBuffer();
bff.append(toString() + ":");
for(Column<?> c : getColumns(true))
bff.append("\n\t- " + c.getSpecification());
// TODO add indexes & primary key to schema specs
return bff.toString();
}
public void accept(ColumnVisitor visitor)
{
accept(visitor, null);
}
public void accept(ColumnVisitor visitor, Set<Column<?>> skipColumns)
{
for(Column<?> c : getColumns(visitor.includeVirtualColumns()))
if(skipColumns == null || !skipColumns.contains(c))
c.accept(visitor);
}
} |
package com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes;
import java.util.Iterator;
import java.util.List;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseElement;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.PropertyInterface;
/**
* Default implementation of XObjectDocument. This class manage an XWiki document containing
* provided XWiki class. It add some specifics methods, getters and setters for this type of object
* and fields. It also override {@link Document} (and then {@link XWikiDocument}) isNew concept
* considering as new a document that does not contains an XWiki object of the provided XWiki class.
*
* @version $Id: $
* @see XObjectDocument
* @see XClassManager
* @since Application Manager 1.0RC1
*/
public class DefaultXObjectDocument extends Document implements XObjectDocument
{
/**
* Value in int for {@link Boolean#TRUE}.
*/
private static final int BOOLEANFIELD_TRUE = 1;
/**
* Value in int for {@link Boolean#FALSE}.
*/
private static final int BOOLEANFIELD_FALSE = 0;
/**
* Value in int for {@link Boolean} = null.
*/
private static final int BOOLEANFIELD_MAYBE = 2;
/**
* The class manager for this document.
*/
protected XClassManager sclass;
/**
* The id of the XWiki object included in the document to manage.
*/
protected int objectId;
/**
* true if this is a new document of this class (this document can exist but does not contains
* object of this class).
*/
protected boolean isNew;
/**
* Create instance of DefaultXObjectDocument from provided XWikiDocument.
*
* @param sclass the class manager for this document.
* @param xdoc the XWikiDocument to manage.
* @param objectId the id of the XWiki object included in the document to manage.
* @param context the XWiki context.
* @throws XWikiException error when calling {@link #reload(XWikiContext)}.
*/
public DefaultXObjectDocument(XClassManager sclass, XWikiDocument xdoc, int objectId,
XWikiContext context) throws XWikiException
{
super(xdoc, context);
this.sclass = sclass;
this.objectId = objectId;
reload(context);
}
/**
* @param docFullName modify the full name the the managed XWikiDocument.
*/
public void setFullName(String docFullName)
{
getDoc().setFullName(docFullName, context);
}
/**
* {@inheritDoc}
*
* @see XObjectDocument#reload(com.xpn.xwiki.XWikiContext)
*/
public void reload(XWikiContext context) throws XWikiException
{
if (this.getObjectNumbers(this.sclass.getClassFullName()) == 0) {
if (this.objectId > 0) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC,
XWikiException.ERROR_XWIKI_DOES_NOT_EXIST,
"Object od id " + this.objectId + "does not exist");
}
BaseObject object = getDoc().newObject(this.sclass.getClassFullName(), context);
XWikiDocument docTemplate =
context.getWiki().getDocument(this.sclass.getClassTemplateFullName(), context);
BaseObject templateObject = docTemplate.getObject(this.sclass.getClassFullName());
if (templateObject != null) {
object.merge(templateObject);
}
if (super.isNew()) {
setParent(docTemplate.getParent());
setContent(docTemplate.getContent());
}
this.isNew = true;
}
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.XObjectDocument#getDocumentApi()
*/
public Document getDocumentApi()
{
return this;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.XObjectDocument#getObjectId()
*/
public int getObjectId()
{
return this.objectId;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.XObjectDocument#getObjectApi()
*/
public com.xpn.xwiki.api.Object getObjectApi()
{
BaseObject obj = getBaseObject(false);
return obj == null ? null : obj.newObjectApi(obj, context);
}
/**
* Get the managed {@link BaseObject}.
*
* @param toWrite indicate that the {@link BaseObject} will be modified.
* @return the {@link BaseObject}.
*/
protected BaseObject getBaseObject(boolean toWrite)
{
BaseObject obj;
if (toWrite) {
obj = getDoc().getObject(this.sclass.getClassFullName(), this.objectId);
} else {
obj = this.doc.getObject(this.sclass.getClassFullName(), this.objectId);
}
return obj;
}
/**
* Overwrite current BaseObject fields with provided one. Only provided non null fields are
* copied.
*
* @param sdoc the document to merge.
*/
public void mergeObject(DefaultXObjectDocument sdoc)
{
if (getXClassManager() != sdoc.getXClassManager()) {
return;
}
BaseObject obj1 = getBaseObject(true);
BaseObject obj2 = sdoc.getBaseObject(false);
for (Iterator it = obj2.getPropertyList().iterator(); it.hasNext();) {
String fieldName = (String) it.next();
Object fieldValue2 = obj2.safeget(fieldName);
if (fieldValue2 != null) {
obj1.safeput(fieldName, (PropertyInterface) ((BaseElement) fieldValue2).clone());
}
}
}
/**
* {@inheritDoc}
*
* @see XObjectDocument#getXClassManager()
*/
public XClassManager getXClassManager()
{
return this.sclass;
}
/**
* {@inheritDoc}
*
* @see XObjectDocument#isNew()
*/
public boolean isNew()
{
return super.isNew() || this.isNew;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.api.Document#saveDocument(String)
*/
protected void saveDocument(String comment) throws XWikiException
{
super.saveDocument(comment);
this.isNew = false;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.api.Document#delete()
*/
public void delete() throws XWikiException
{
if (getObjectNumbers(sclass.getClassFullName()) == 1) {
super.delete();
} else {
doc.removeObject(getBaseObject(false));
save();
}
this.isNew = true;
}
/**
* Get the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @return the value in {@link String} of the field <code>fieldName</code> of the managed
* object's class.
* @see com.xpn.xwiki.doc.XWikiDocument#getStringValue(java.lang.String)
*/
public String getStringValue(String fieldName)
{
BaseObject obj = getBaseObject(false);
if (obj == null) {
return null;
}
return obj.getStringValue(fieldName);
}
/**
* Modify the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @param value the new value of the field <code>fieldName</code> of the managed object's
* class.
* @see com.xpn.xwiki.doc.XWikiDocument#setStringValue(java.lang.String,java.lang.String,java.lang.String)
*/
public void setStringValue(String fieldName, String value)
{
BaseObject obj = getBaseObject(true);
if (obj != null) {
obj.setStringValue(fieldName, value);
}
}
/**
* Get the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @return the value in {@link String} of the field <code>fieldName</code> of the managed
* object's class.
* @see com.xpn.xwiki.doc.XWikiDocument#getStringValue(java.lang.String)
*/
public String getLargeStringValue(String fieldName)
{
BaseObject obj = getBaseObject(false);
if (obj == null) {
return null;
}
return obj.getLargeStringValue(fieldName);
}
/**
* Modify the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @param value the new value of the field <code>fieldName</code> of the managed object's
* class.
* @see com.xpn.xwiki.doc.XWikiDocument#setLargeStringValue(java.lang.String,java.lang.String,java.lang.String)
*/
public void setLargeStringValue(String fieldName, String value)
{
BaseObject obj = getBaseObject(true);
if (obj != null) {
obj.setLargeStringValue(fieldName, value);
}
}
/**
* Get the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @return the value in {@link List} of the field <code>fieldName</code> of the managed
* object's class.
* @see com.xpn.xwiki.doc.XWikiDocument#getListValue(java.lang.String)
*/
public List getListValue(String fieldName)
{
BaseObject obj = getBaseObject(false);
if (obj == null) {
return null;
}
return obj.getListValue(fieldName);
}
/**
* Modify the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @param value the new value of the field <code>fieldName</code> of the managed object's
* class.
* @see com.xpn.xwiki.doc.XWikiDocument#setStringListValue(java.lang.String,java.lang.String,java.util.List)
*/
public void setListValue(String fieldName, List value)
{
BaseObject obj = getBaseObject(true);
if (obj != null) {
obj.setStringListValue(fieldName, value);
}
}
/**
* Get the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @return the value in int of the field <code>fieldName</code> of the managed object's class.
* @see com.xpn.xwiki.doc.XWikiDocument#getListValue(java.lang.String)
*/
public int getIntValue(String fieldName)
{
BaseObject obj = getBaseObject(false);
if (obj == null) {
return 0;
}
return obj.getIntValue(fieldName);
}
/**
* Modify the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @param value the new value of the field <code>fieldName</code> of the managed object's
* class.
* @see com.xpn.xwiki.doc.XWikiDocument#setIntValue(String, String, int)
*/
public void setIntValue(String fieldName, int value)
{
BaseObject obj = getBaseObject(true);
if (obj != null) {
obj.setIntValue(fieldName, value);
}
}
/**
* Get the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @return the value in {@link Boolean} of the field <code>fieldName</code> of the managed
* object's class.
* @see com.xpn.xwiki.doc.XWikiDocument#getListValue(java.lang.String)
*/
public Boolean getBooleanValue(String fieldName)
{
int intValue = getIntValue(fieldName);
return intValue == BOOLEANFIELD_TRUE ? Boolean.TRUE : (intValue == BOOLEANFIELD_FALSE
? Boolean.FALSE : null);
}
/**
* Modify the value of the field <code>fieldName</code> of the managed object's class.
*
* @param fieldName the name of the field from the managed object's class where to find the
* value.
* @param value the new value of the field <code>fieldName</code> of the managed object's
* class.
* @see com.xpn.xwiki.doc.XWikiDocument#setIntValue(String, String, int)
*/
public void setBooleanValue(String fieldName, Boolean value)
{
setIntValue(fieldName, value == null ? BOOLEANFIELD_MAYBE : (value.booleanValue()
? BOOLEANFIELD_TRUE : BOOLEANFIELD_FALSE));
}
} |
package org.ovirt.engine.ui.uicommonweb.models.hosts.network;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.common.businessentities.network.Bond;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.common.utils.NetworkCommonUtils;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.ui.uicommonweb.TypeResolver;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.UIMessages;
@RunWith(MockitoJUnitRunner.class)
public class ExecuteNetworkCommandInNetworkOperationTest {
@Mock
private LogicalNetworkModel logicalNetworkModelOfNetworkA;
@Mock
private LogicalNetworkModel logicalNetworkModelOfNetworkC;
@Mock
private BondNetworkInterfaceModel bondNetworkInterfaceModelA;
@Mock
private BondNetworkInterfaceModel bondNetworkInterfaceModelB;
private Network networkA = createNetwork("networkA"); //$NON-NLS-1$
private Network networkC = createNetwork("networkC"); //$NON-NLS-1$
@Mock
private NetworkInterfaceModel networkInterfaceModelOfNicA;
@Mock
private NetworkInterfaceModel networkInterfaceModelOfNicB;
@Mock
private NetworkInterfaceModel networkInterfaceModelOfNicC;
@Mock
private NetworkInterfaceModel networkInterfaceModelOfNicD;
private VdsNetworkInterface nicA = createNic("nicA"); //$NON-NLS-1$
private VdsNetworkInterface nicB = createNic("nicB"); //$NON-NLS-1$
private VdsNetworkInterface nicC = createNic("nicC"); //$NON-NLS-1$
private VdsNetworkInterface nicD = createNic("nicD"); //$NON-NLS-1$
private static final Guid existingBondId = Guid.newGuid();
private static final String existingBondName = "existingBond"; //$NON-NLS-1$
private Bond existingBond = createBond(existingBondId, existingBondName, Arrays.asList(nicA, nicB));
private Bond newlyCreatedBond = createBond(null, "newlyCreatedBond", Collections.<VdsNetworkInterface>emptyList()); //$NON-NLS-1$
private List<VdsNetworkInterface> allNics = new ArrayList<>();
private List<NetworkAttachment> existingNetworkAttachments = new ArrayList<>();
private List<String> networksToSync = new ArrayList<>();
private DataFromHostSetupNetworksModel dataFromHostSetupNetworksModel =
new DataFromHostSetupNetworksModel(allNics, existingNetworkAttachments, networksToSync);
@Before
public void setUp() throws Exception {
when(logicalNetworkModelOfNetworkA.getNetwork()).thenReturn(networkA);
when(logicalNetworkModelOfNetworkC.getNetwork()).thenReturn(networkC);
when(networkInterfaceModelOfNicA.getIface()).thenReturn(nicA);
when(networkInterfaceModelOfNicB.getIface()).thenReturn(nicB);
when(networkInterfaceModelOfNicC.getIface()).thenReturn(nicC);
when(networkInterfaceModelOfNicD.getIface()).thenReturn(nicD);
//mock manager/resolver so it's possible to delegate from one NetworkOperation to another.
ConstantsManager constantsManagerMock = Mockito.mock(ConstantsManager.class);
UIMessages uiMessagesMock = Mockito.mock(UIMessages.class);
when(constantsManagerMock.getMessages()).thenReturn(uiMessagesMock);
when(uiMessagesMock.detachNetwork(anyString())).thenReturn("doh"); //$NON-NLS-1$
ConstantsManager.setInstance(constantsManagerMock);
TypeResolver typeResolverMock = Mockito.mock(TypeResolver.class);
TypeResolver.setInstance(typeResolverMock);
}
/*
* At the beginning there was a void, then NetworkAttachment was created attaching given network and nic.
* */
@Test
public void testCreatingBrandNewNetworkAttachment() throws Exception {
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(false);
NetworkOperation.ATTACH_NETWORK.getTarget().executeNetworkCommand(
logicalNetworkModelOfNetworkA,
networkInterfaceModelOfNicA,
dataFromHostSetupNetworksModel);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(1));
NetworkAttachment networkAttachment = dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.iterator().next();
assertNetworkAttachment(networkAttachment, null, networkA.getId(), nicA.getId());
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.isEmpty(), is(true));
}
/*
* At the beginning there was a NetworkAttachment. Suddenly network was detached from the nic, but in the end,
* network was back attached to the nic unchanged.
* */
@Test
public void testReattachingPreexistingNetworkAfterItsBeingDetached() throws Exception {
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(false);
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
nicA,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
dataFromHostSetupNetworksModel.removedNetworkAttachments.add(networkAttachment);
NetworkOperation.ATTACH_NETWORK.getTarget().executeNetworkCommand(
logicalNetworkModelOfNetworkA,
networkInterfaceModelOfNicA,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(1));
NetworkAttachment updatedNetworkAttachment = dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.iterator().next();
assertNetworkAttachment(updatedNetworkAttachment, networkAttachmentId, networkA.getId(), nicA.getId());
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
}
/*
* At the beginning there was a NetworkAttachment. Suddenly network was detached from the nic, and gets firmly
* attached to another nic.
* */
@Test
public void testReattachingPreexistingNetworkToDifferentNicAfterItsBeingDetached() throws Exception {
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(false);
when(networkInterfaceModelOfNicA.getIface()).thenReturn(nicB);
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment formerAttachment =
NetworkOperation.newNetworkAttachment(networkA,
nicA,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(formerAttachment);
dataFromHostSetupNetworksModel.removedNetworkAttachments.add(formerAttachment);
NetworkOperation.ATTACH_NETWORK.getTarget().executeNetworkCommand(
logicalNetworkModelOfNetworkA,
networkInterfaceModelOfNicA,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(1));
assertNetworkAttachment(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.iterator().next(),
networkAttachmentId,
networkA.getId(),
nicB.getId());
}
/*
* At the beginning there was a NetworkAttachment, and network gets detached from the nic.
* */
@Test
public void testDetachingPreexistingNetworkAttachment() throws Exception {
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
nicA,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
when(logicalNetworkModelOfNetworkA.hasVlan()).thenReturn(false);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(true);
when(logicalNetworkModelOfNetworkA.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicA);
NetworkOperation.DETACH_NETWORK.getTarget().executeNetworkCommand(
logicalNetworkModelOfNetworkA,
null,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(1));
Guid removedNetworkAttachmentId = dataFromHostSetupNetworksModel.removedNetworkAttachments.iterator().next().getId();
assertThat("id mismatch", removedNetworkAttachmentId, is(networkAttachmentId)); //$NON-NLS-1$
}
/*
* At the beginning there was a void, then NetworkAttachment was created attaching given network with nic,
* and then her was immediately detached from him.
* */
@Test
public void testDetachingPreviouslyAddedNetworkAttachment() throws Exception {
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
nicA,
null,
dataFromHostSetupNetworksModel.networksToSync);
dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.add(networkAttachment);
when(logicalNetworkModelOfNetworkA.hasVlan()).thenReturn(false);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(true);
when(logicalNetworkModelOfNetworkA.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicA);
NetworkOperation.DETACH_NETWORK.getTarget().executeNetworkCommand(
logicalNetworkModelOfNetworkA,
null,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
}
/*
* At the beginning there was a bond, which was then broken.
* */
@Test
public void testBreakingExistingBond() throws Exception {
when(bondNetworkInterfaceModelA.getItems()).thenReturn(Collections.<LogicalNetworkModel> emptyList());
when(bondNetworkInterfaceModelA.getIface()).thenReturn(existingBond);
NetworkOperation.BREAK_BOND.getTarget().executeNetworkCommand(
bondNetworkInterfaceModelA,
null,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(1));
Guid removedBondId = dataFromHostSetupNetworksModel.removedBonds.iterator().next().getId();
assertThat("id mismatch", removedBondId, is(existingBond.getId())); //$NON-NLS-1$
}
/*
* At the beginning there was a void, then bond was created and was immediately broken.
* */
@Test
public void testBreakingNewlyCreatedBond() throws Exception {
when(bondNetworkInterfaceModelA.getItems()).thenReturn(Collections.<LogicalNetworkModel> emptyList());
when(bondNetworkInterfaceModelA.getIface()).thenReturn(newlyCreatedBond);
NetworkOperation.BREAK_BOND.getTarget().executeNetworkCommand(
bondNetworkInterfaceModelA,
null,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(0));
}
/*
* At the beginning there was a bond, which was then broken.
* */
@Test
public void testBreakingExistingBondWithNetworkAttached() throws Exception {
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
existingBond,
null,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
when(logicalNetworkModelOfNetworkA.hasVlan()).thenReturn(false);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(true);
when(logicalNetworkModelOfNetworkA.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicA);
when(bondNetworkInterfaceModelA.getItems()).thenReturn(Collections.singletonList(logicalNetworkModelOfNetworkA));
when(bondNetworkInterfaceModelA.getIface()).thenReturn(existingBond);
NetworkOperation.BREAK_BOND.getTarget().executeNetworkCommand(
bondNetworkInterfaceModelA,
null,
dataFromHostSetupNetworksModel
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(1));
Guid removedNetworkAttachmentId = dataFromHostSetupNetworksModel.removedNetworkAttachments.iterator().next().getId();
assertThat("id mismatch", removedNetworkAttachmentId, nullValue()); //$NON-NLS-1$
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(1));
Guid removedBondId = dataFromHostSetupNetworksModel.removedBonds.iterator().next().getId();
assertThat("id mismatch", removedBondId, is(existingBond.getId())); //$NON-NLS-1$
}
/*
* At the beginning there was two nics (one with NetworkAttachment), which, after being introduced to each other,
* formed a firm bond adopting NetworkAttachment as their own.
* */
@Test
public void testBondingTwoNicsWithReattachingNetworkAttachmentOnNewlyCreatedBond() throws Exception {
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
nicA,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(true);
when(logicalNetworkModelOfNetworkA.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicA);
when(networkInterfaceModelOfNicA.getItems()).thenReturn(Collections.singletonList(logicalNetworkModelOfNetworkA));
when(networkInterfaceModelOfNicC.getIface()).thenReturn(newlyCreatedBond);
when(networkInterfaceModelOfNicC.getItems()).thenReturn(Collections.<LogicalNetworkModel> emptyList());
when(networkInterfaceModelOfNicC.getName()).thenReturn(newlyCreatedBond.getName());
NetworkOperation.BOND_WITH.getTarget().executeNetworkCommand(
networkInterfaceModelOfNicA,
networkInterfaceModelOfNicB,
dataFromHostSetupNetworksModel,
newlyCreatedBond
);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(false);
//this is not part of BOND_WITH command, it's simply called after it. BOND_WITH is actually: "detach networks and create bond".
//in production code, probably due to some problems with listeners, this is actually called three times, luckily each time overwriting previous call.
NetworkOperation.attachNetworks(networkInterfaceModelOfNicC,
Collections.singletonList(logicalNetworkModelOfNetworkA),
dataFromHostSetupNetworksModel);
//related network attachment will be updated, not removed and created new one.
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(1));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertNetworkAttachment(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.iterator().next(),
networkAttachmentId,
networkA.getId(),
newlyCreatedBond.getId());
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(1));
assertBond(dataFromHostSetupNetworksModel.newOrModifiedBonds.iterator().next(),
null,
Arrays.asList(nicA, nicB));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(0));
}
/*
* At the beginning there was bond. It was broken into two nics, but they get back together in the end.
* */
@Test
public void testReBondingTwoNicsWithReattachingNetworkAttachmentOnNewlyCreatedBond() throws Exception {
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(false);
dataFromHostSetupNetworksModel.removedBonds.add(existingBond);
NetworkOperation.BOND_WITH.getTarget().executeNetworkCommand(
networkInterfaceModelOfNicA,
networkInterfaceModelOfNicB,
dataFromHostSetupNetworksModel,
createBond(existingBondId, existingBondName, Collections.<VdsNetworkInterface> emptyList())
);
//related network attachment will be updated, not removed and created new one.
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(1));
assertBond(dataFromHostSetupNetworksModel.newOrModifiedBonds.iterator().next(),
existingBondId,
Arrays.asList(nicA, nicB));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(0));
}
/*
* At the beginning there was bond without any network attachment. Then another nic showed up joining the family
* bringing his own network attachment along.
* */
@Test
public void testAddingNewNicWithNetworkAttachmentToExistingBondWithoutAnyAttachment() throws Exception {
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkC,
nicC,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
//this can be confusing. network *is* attached but it gets detached as a part of ADD_TO_BOND, so consulting this method, it will be detached.
when(logicalNetworkModelOfNetworkC.isAttached()).thenReturn(true, false);
when(logicalNetworkModelOfNetworkC.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicC, (NetworkInterfaceModel)null);
when(networkInterfaceModelOfNicC.getItems()).thenReturn(Collections.singletonList(logicalNetworkModelOfNetworkC));
when(bondNetworkInterfaceModelA.getItems()).thenReturn(Collections.<LogicalNetworkModel> emptyList());
when(bondNetworkInterfaceModelA.getIface()).thenReturn(existingBond);
NetworkOperation.ADD_TO_BOND.getTarget().executeNetworkCommand(
networkInterfaceModelOfNicC,
bondNetworkInterfaceModelA,
dataFromHostSetupNetworksModel
);
//related network attachment will be updated, not removed and created new one.
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(1));
assertNetworkAttachment(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.iterator().next(),
networkAttachmentId,
networkC.getId(),
existingBondId);
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(1));
assertBond(dataFromHostSetupNetworksModel.newOrModifiedBonds.iterator().next(),
existingBondId,
Arrays.asList(nicA, nicB, nicC));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(0));
}
/*
* At the beginning there was a bond with three slaves, the one of them left others.
* */
@Test
public void testRemoveSlaveFromBond() throws Exception {
Bond bond = createBond(existingBondId, existingBondName, Arrays.asList(nicA, nicB, nicC));
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment =
NetworkOperation.newNetworkAttachment(networkA,
bond,
null,
networkAttachmentId,
dataFromHostSetupNetworksModel.networksToSync);
existingNetworkAttachments.add(networkAttachment);
when(bondNetworkInterfaceModelA.getIface()).thenReturn(bond);
when(networkInterfaceModelOfNicA.getBond()).thenReturn(bondNetworkInterfaceModelA);
when(bondNetworkInterfaceModelA.getIface()).thenReturn(bond);
NetworkOperation.REMOVE_FROM_BOND.getTarget().executeNetworkCommand(
networkInterfaceModelOfNicA,
null,
dataFromHostSetupNetworksModel
);
//related network attachment will be updated, not removed and created new one.
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(1));
assertBond(dataFromHostSetupNetworksModel.newOrModifiedBonds.iterator().next(),
existingBondId,
Arrays.asList(nicB, nicC));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(0));
}
/*
* At the beginning there was two nics (one with NetworkAttachment), which, after being introduced to each other,
* formed a firm bond adopting NetworkAttachment as their own.
* */
@Test
public void testJoiningBonds() throws Exception {
Guid networkAttachmentId = Guid.newGuid();
NetworkAttachment networkAttachment = NetworkOperation.newNetworkAttachment(networkA,
existingBond,
null,
networkAttachmentId, dataFromHostSetupNetworksModel.networksToSync);
Guid bondBId = Guid.newGuid();
Bond bondB = createBond(bondBId, "bondB", Arrays.asList(nicC, nicD)); //$NON-NLS-1$
existingNetworkAttachments.add(networkAttachment);
when(logicalNetworkModelOfNetworkA.isAttached()).thenReturn(true);
when(logicalNetworkModelOfNetworkA.getAttachedToNic()).thenReturn(networkInterfaceModelOfNicA);
when(bondNetworkInterfaceModelA.getItems()).thenReturn(Collections.singletonList(logicalNetworkModelOfNetworkA));
when(bondNetworkInterfaceModelA.getIface()).thenReturn(existingBond);
when(bondNetworkInterfaceModelA.getBonded()).thenReturn(Arrays.asList(networkInterfaceModelOfNicA,
networkInterfaceModelOfNicB));
when(bondNetworkInterfaceModelB.getItems()).thenReturn(Collections.<LogicalNetworkModel>emptyList());
when(bondNetworkInterfaceModelB.getIface()).thenReturn(bondB);
when(bondNetworkInterfaceModelB.getBonded()).thenReturn(Arrays.asList(networkInterfaceModelOfNicC, networkInterfaceModelOfNicD));
NetworkOperation.JOIN_BONDS.getTarget().executeNetworkCommand(
bondNetworkInterfaceModelA,
bondNetworkInterfaceModelB,
dataFromHostSetupNetworksModel,
newlyCreatedBond
);
assertThat(dataFromHostSetupNetworksModel.newOrModifiedNetworkAttachments.size(), is(0));
assertThat(dataFromHostSetupNetworksModel.removedNetworkAttachments.size(), is(1));
Guid removeNetworkAttachmentId = dataFromHostSetupNetworksModel.removedNetworkAttachments.iterator().next().getId();
assertThat("id mismatch", removeNetworkAttachmentId, is(networkAttachmentId)); //$NON-NLS-1$
assertThat(dataFromHostSetupNetworksModel.newOrModifiedBonds.size(), is(1));
assertBond(dataFromHostSetupNetworksModel.newOrModifiedBonds.iterator().next(),
null,
Arrays.asList(nicA, nicB, nicC, nicD));
assertThat(dataFromHostSetupNetworksModel.removedBonds.size(), is(2));
Iterator<Bond> removedBondsIterator = dataFromHostSetupNetworksModel.removedBonds.iterator();
Guid firstRemovedBondId = removedBondsIterator.next().getId();
assertThat("id mismatch", firstRemovedBondId, is(existingBondId)); //$NON-NLS-1$
Guid secondRemovedBondId = removedBondsIterator.next().getId();
assertThat("id mismatch", secondRemovedBondId, is(bondBId)); //$NON-NLS-1$
}
private void assertBond(Bond bond, Guid bondId, List<VdsNetworkInterface> slaves) {
List<VdsNetworkInterface> existingNics = new ArrayList<>();
existingNics.add(bond);
existingNics.addAll(slaves);
NetworkCommonUtils.fillBondSlaves(existingNics);
Matcher attachmentIdMatcher = bondId == null ? nullValue() : is(bondId);
assertThat("id mismatch", bond.getId(), attachmentIdMatcher); //$NON-NLS-1$
if (slaves != null) {
for (VdsNetworkInterface slave : slaves) {
assertThat("missing slave", bond.getSlaves().contains(slave.getName()), is(true)); //$NON-NLS-1$
}
}
assertThat("invalid slaves count", bond.getSlaves().size(), is(slaves.size())); //$NON-NLS-1$
}
private void assertNetworkAttachment(NetworkAttachment networkAttachment,
Guid attachmentId,
Guid networkId,
Guid nicId) {
Matcher attachmentIdMatcher = attachmentId == null ? nullValue() : is(attachmentId);
assertThat("id mismatch", networkAttachment.getId(), attachmentIdMatcher); //$NON-NLS-1$
assertThat("network id mismatch", networkAttachment.getNetworkId(), equalTo(networkId)); //$NON-NLS-1$
assertThat("nicId mismatch", networkAttachment.getNicId(), equalTo(nicId)); //$NON-NLS-1$
}
private Network createNetwork(String networkA) {
Network result = new Network();
result.setId(Guid.newGuid());
result.setName(networkA);
return result;
}
private VdsNetworkInterface createNic(String nicName) {
VdsNetworkInterface result = new VdsNetworkInterface();
result.setId(Guid.newGuid());
result.setName(nicName);
return result;
}
private Bond createBond(Guid id, String bondName, List<VdsNetworkInterface> slaves) {
Bond result = new Bond();
result.setId(id);
result.setName(bondName);
for (VdsNetworkInterface slave : slaves) {
slave.setBondName(bondName);
}
return result;
}
} |
package fr.javatronic.damapping.intellij.plugin.integration.psiparsing.impl;
import fr.javatronic.damapping.intellij.plugin.integration.psiparsing.PsiContext;
import fr.javatronic.damapping.intellij.plugin.integration.psiparsing.PsiParsingService;
import fr.javatronic.damapping.processor.model.DAAnnotation;
import fr.javatronic.damapping.processor.model.DAEnumValue;
import fr.javatronic.damapping.processor.model.DAInterface;
import fr.javatronic.damapping.processor.model.DAMethod;
import fr.javatronic.damapping.processor.model.DAModifier;
import fr.javatronic.damapping.processor.model.DAName;
import fr.javatronic.damapping.processor.model.DAParameter;
import fr.javatronic.damapping.processor.model.DASourceClass;
import fr.javatronic.damapping.processor.model.DAType;
import fr.javatronic.damapping.processor.model.factory.DANameFactory;
import fr.javatronic.damapping.processor.model.predicate.DAMethodPredicates;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiImportList;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiParameterList;
import com.intellij.psi.PsiReferenceList;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.FluentIterable.from;
public class PsiParsingServiceImpl implements PsiParsingService {
private static final Logger LOGGER = Logger.getInstance(PsiParsingServiceImpl.class.getName());
private final DANameExtractor daNameExtractor;
private final DATypeExtractor daTypeExtractor;
private final DAModifierExtractor daModifierExtractor;
public PsiParsingServiceImpl(DANameExtractor daNameExtractor, DATypeExtractor daTypeExtractor,
DAModifierExtractor daModifierExtractor) {
this.daNameExtractor = daNameExtractor;
this.daTypeExtractor = daTypeExtractor;
this.daModifierExtractor = daModifierExtractor;
}
public PsiParsingServiceImpl() {
this.daNameExtractor = new DANameExtractorImpl();
this.daTypeExtractor = new DATypeExtractorImpl(daNameExtractor);
this.daModifierExtractor = new DAModifierExtractorImpl();
}
@Override
public DASourceClass parse(PsiClass psiClass) {
checkArgument(!psiClass.isAnnotationType(), "Annotation annoted with @Mapper is not supported");
checkArgument(!psiClass.isInterface(), "Interface annoted with @Mapper is not supported");
try {
DASourceClass.Builder builder = daSourceBuilder(psiClass, daTypeExtractor.forClassOrEnum(psiClass));
PsiImportList psiImportList = extractPsiImportList(psiClass);
DAName packageName = daNameExtractor.extractPackageName(psiClass);
PsiContext psiContext = new PsiContext(psiImportList, packageName);
return builder
.withPackageName(psiContext.getPackageName())
.withAnnotations(extractAnnotations(psiClass.getModifierList(), psiContext))
.withModifiers(daModifierExtractor.extractModifiers(psiClass))
.withInterfaces(extractInterfaces(psiClass, psiContext))
.withMethods(extractMethods(psiClass, psiContext))
.build();
}
catch (Throwable r) {
LOGGER.error("An exception occured while parsing Psi tree", r);
throw new RuntimeException(r);
}
}
private static DASourceClass.Builder daSourceBuilder(PsiClass psiClass, DAType daType) {
if (psiClass.isEnum()) {
return DASourceClass.enumBuilder(daType, extractEnumValues(psiClass));
}
else {
return DASourceClass.classbuilder(daType);
}
}
private static List<DAEnumValue> extractEnumValues(PsiClass psiClass) {
return from(Arrays.asList(psiClass.getChildren()))
.filter(PsiEnumConstant.class)
.transform(PsiEnumConstantDAEnumValue.INSTANCE)
.filter(Predicates.notNull())
.toImmutableList();
}
private List<DAAnnotation> extractAnnotations(@Nullable PsiModifierList modifierList,
@Nullable final PsiContext psiContext) {
if (modifierList == null) {
return null;
}
return from(Arrays.asList(modifierList.getChildren()))
.filter(PsiAnnotation.class)
.transform(new Function<PsiAnnotation, DAAnnotation>() {
@Nullable
@Override
public DAAnnotation apply(@Nullable PsiAnnotation psiAnnotation) {
DAAnnotation res = new DAAnnotation(
daTypeExtractor.forAnnotation(psiAnnotation, psiContext)
);
return res;
}
}
)
.toImmutableList();
}
private List<DAInterface> extractInterfaces(final PsiClass psiClass, @Nonnull final PsiContext psiContext) {
PsiReferenceList implementsList = psiClass.getImplementsList();
if (implementsList != null /* null for anonymous classes */
&& implementsList.getRole() == PsiReferenceList.Role.IMPLEMENTS_LIST) {
return from(Arrays.asList(implementsList.getReferenceElements()))
.transform(new Function<PsiJavaCodeReferenceElement, DAInterface>() {
@Override
public DAInterface apply(@Nullable PsiJavaCodeReferenceElement referenceElement) {
return new DAInterface(daTypeExtractor.forInterface(referenceElement, psiContext));
}
}
)
.toImmutableList();
}
return Collections.emptyList();
}
@Nullable
private PsiImportList extractPsiImportList(PsiClass psiClass) {
return from(Arrays.asList(psiClass.getParent().getChildren()))
.filter(PsiImportList.class)
.first()
.orNull();
}
private List<DAMethod> extractMethods(PsiClass psiClass, final PsiContext psiContext) {
List<DAMethod> daMethods = from(Arrays.asList(psiClass.getChildren()))
.filter(PsiMethod.class)
.transform(new Function<PsiMethod, DAMethod>() {
@Nullable
@Override
public DAMethod apply(@Nullable PsiMethod psiMethod) {
if (psiMethod == null) {
return null;
}
return daMethodBuilder(psiMethod)
.withName(DANameFactory.from(psiMethod.getName()))
.withAnnotations(extractAnnotations(psiMethod.getModifierList(), psiContext))
.withModifiers(daModifierExtractor.extractModifiers(psiMethod))
.withParameters(extractParameters(psiMethod, psiContext))
.withReturnType(daTypeExtractor.forMethod(psiMethod, psiContext))
.build();
}
private DAMethod.Builder daMethodBuilder(PsiMethod psiMethod) {
if (psiMethod.isConstructor()) {
return DAMethod.constructorBuilder();
}
return DAMethod.methodBuilder();
}
}
).toImmutableList();
if (!Iterables.any(daMethods, DAMethodPredicates.isConstructor())) {
return ImmutableList.copyOf(
Iterables.concat(Collections.singletonList(instanceDefaultConstructor(psiClass)), daMethods)
);
}
return daMethods;
}
private DAMethod instanceDefaultConstructor(PsiClass psiClass) {
return DAMethod.constructorBuilder()
.withName(DANameFactory.from(psiClass.getName()))
.withModifiers(Collections.singleton(DAModifier.PUBLIC))
.withReturnType(daTypeExtractor.forClassOrEnum(psiClass))
.build();
}
private List<DAParameter> extractParameters(PsiMethod psiMethod, final PsiContext psiContext) {
Optional<PsiParameterList> optional = from(Arrays.asList(psiMethod.getChildren())).filter(PsiParameterList.class)
.first();
if (!optional.isPresent()) {
return Collections.emptyList();
}
return from(Arrays.asList(optional.get().getParameters()))
.transform(new Function<PsiParameter, DAParameter>() {
@Nullable
@Override
public DAParameter apply(@Nullable PsiParameter psiParameter) {
return DAParameter
.builder(
DANameFactory.from(psiParameter.getName()),
daTypeExtractor.forParameter(psiParameter, psiContext)
).withModifiers(daModifierExtractor.extractModifiers(psiParameter))
.build();
}
}
).toImmutableList();
}
private static enum PsiEnumConstantDAEnumValue implements Function<PsiEnumConstant, DAEnumValue> {
INSTANCE;
@Nullable
@Override
public DAEnumValue apply(@Nullable PsiEnumConstant psiEnumConstant) {
if (psiEnumConstant == null) {
return null;
}
return new DAEnumValue(psiEnumConstant.getName());
}
}
} |
package org.innovateuk.ifs.project.grantofferletter.controller;
import org.innovateuk.ifs.commons.error.CommonFailureKeys;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.project.grantofferletter.form.ProjectGrantOfferLetterForm;
import org.innovateuk.ifs.project.grantofferletter.viewmodel.ProjectGrantOfferLetterViewModel;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.resource.ProjectUserResource;
import org.innovateuk.ifs.user.resource.OrganisationResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.FieldError;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource;
import static org.innovateuk.ifs.project.builder.ProjectResourceBuilder.newProjectResource;
import static org.innovateuk.ifs.project.builder.ProjectUserResourceBuilder.newProjectUserResource;
import static org.innovateuk.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
public class ProjectGrantOfferLetterControllerTest extends BaseControllerMockMVCTest<ProjectGrantOfferLetterController> {
@Test
public void testViewGrantOfferLetterPageWithSignedOffer() throws Exception {
long projectId = 123L;
long userId = 1L;
ProjectResource project = newProjectResource().withId(projectId).build();
FileEntryResource grantOfferLetter = newFileEntryResource().build();
FileEntryResource signedGrantOfferLetter = newFileEntryResource().build();
FileEntryResource additionalContractFile = newFileEntryResource().build();
when(projectService.getById(projectId)).thenReturn(project);
when(projectService.isUserLeadPartner(projectId, userId)).thenReturn(true);
when(projectService.getSignedGrantOfferLetterFileDetails(projectId)).thenReturn(Optional.of(signedGrantOfferLetter));
when(projectService.getGeneratedGrantOfferFileDetails(projectId)).thenReturn(Optional.of(grantOfferLetter));
when(projectService.getAdditionalContractFileDetails(projectId)).thenReturn(Optional.of(additionalContractFile));
when(projectService.getProjectUsersForProject(projectId)).thenReturn(newProjectUserResource()
.withRoleName(UserRoleType.PROJECT_MANAGER)
.withUser(userId)
.build(1));
when(projectService.isSignedGrantOfferLetterApproved(projectId)).thenReturn(serviceSuccess(Boolean.FALSE));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer", project.getId())).
andExpect(status().isOk()).
andExpect(view().name("project/grant-offer-letter")).
andReturn();
ProjectGrantOfferLetterViewModel model = (ProjectGrantOfferLetterViewModel) result.getModelAndView().getModel().get("model");
// test the view model
assertEquals(project.getId(), model.getProjectId());
assertEquals(project.getName(), model.getProjectName());
assertTrue(model.isOfferSigned());
assertNull(model.getSubmitDate());
assertTrue(model.isShowSubmitButton());
assertNull(model.getSubmitDate());
assertFalse(model.isSubmitted());
assertFalse(model.isOfferApproved());
}
@Test
public void testDownloadUnsignedGrantOfferLetter() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(projectService.getGeneratedGrantOfferFile(123L)).
thenReturn(Optional.of(fileContents));
when(projectService.getGeneratedGrantOfferFileDetails(123L)).
thenReturn(Optional.of(fileDetails));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/grant-offer-letter", 123L)).
andExpect(status().isOk()).
andReturn();
assertEquals("My content!", result.getResponse().getContentAsString());
assertEquals("inline; filename=\"" + fileDetails.getName() + "\"",
result.getResponse().getHeader("Content-Disposition"));
}
@Test
public void testDownloadSignedGrantOfferLetter() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(projectService.getSignedGrantOfferLetterFile(123L)).
thenReturn(Optional.of(fileContents));
when(projectService.getSignedGrantOfferLetterFileDetails(123L)).
thenReturn(Optional.of(fileDetails));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/signed-grant-offer-letter", 123L)).
andExpect(status().isOk()).
andReturn();
assertEquals("My content!", result.getResponse().getContentAsString());
assertEquals("inline; filename=\"" + fileDetails.getName() + "\"",
result.getResponse().getHeader("Content-Disposition"));
}
@Test
public void testDownloadAdditionalContract() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(projectService.getAdditionalContractFile(123L)).
thenReturn(Optional.of(fileContents));
when(projectService.getAdditionalContractFileDetails(123L)).
thenReturn(Optional.of(fileDetails));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/additional-contract", 123L)).
andExpect(status().isOk()).
andReturn();
assertEquals("My content!", result.getResponse().getContentAsString());
assertEquals("inline; filename=\"" + fileDetails.getName() + "\"",
result.getResponse().getHeader("Content-Disposition"));
}
@Test
public void testUploadSignedGrantOfferLetter() throws Exception {
FileEntryResource createdFileDetails = newFileEntryResource().withName("A name").build();
MockMultipartFile uploadedFile = new MockMultipartFile("signedGrantOfferLetter", "filename.txt", "text/plain", "My content!".getBytes());
ProjectResource project = newProjectResource().withId(123L).build();
ProjectUserResource pmUser = newProjectUserResource().withRoleName(UserRoleType.PROJECT_MANAGER).withUser(loggedInUser.getId()).build();
List<ProjectUserResource> puRes = new ArrayList<ProjectUserResource>(Arrays.asList(pmUser));
when(projectService.getById(123L)).thenReturn(project);
when(projectService.getProjectUsersForProject(123L)).thenReturn(puRes);
when(projectService.getGeneratedGrantOfferFileDetails(123L)).thenReturn(Optional.of(createdFileDetails));
when(projectService.addSignedGrantOfferLetter(123L, "text/plain", 11, "filename.txt", "My content!".getBytes())).
thenReturn(serviceSuccess(createdFileDetails));
mockMvc.perform(
fileUpload("/project/123/offer").
file(uploadedFile).
param("uploadSignedGrantOfferLetterClicked", "")).
andExpect(status().is3xxRedirection()).
andExpect(view().name("redirect:/project/123/offer"));
}
@Test
public void testUploadSignedGrantOfferLetterGolNotSent() throws Exception {
FileEntryResource createdFileDetails = newFileEntryResource().withName("A name").build();
MockMultipartFile uploadedFile = new MockMultipartFile("signedGrantOfferLetter", "filename.txt", "text/plain", "My content!".getBytes());
ProjectResource project = newProjectResource().withId(123L).build();
ProjectUserResource pmUser = newProjectUserResource().withRoleName(UserRoleType.PROJECT_MANAGER).withUser(loggedInUser.getId()).build();
List<ProjectUserResource> puRes = new ArrayList<ProjectUserResource>(Arrays.asList(pmUser));
when(projectService.getById(123L)).thenReturn(project);
when(projectService.getProjectUsersForProject(123L)).thenReturn(puRes);
when(projectService.getSignedGrantOfferLetterFileDetails(123L)).thenReturn(Optional.empty());
when(projectService.getGeneratedGrantOfferFileDetails(123L)).thenReturn(Optional.of(createdFileDetails));
when(projectService.getAdditionalContractFileDetails(123L)).thenReturn(Optional.empty());
when(projectService.addSignedGrantOfferLetter(123L, "text/plain", 11, "filename.txt", "My content!".getBytes())).
thenReturn(serviceFailure(CommonFailureKeys.GRANT_OFFER_LETTER_MUST_BE_SENT_BEFORE_UPLOADING_SIGNED_COPY));
when(projectService.isSignedGrantOfferLetterApproved(project.getId())).thenReturn(serviceSuccess(Boolean.FALSE));
MvcResult mvcResult = mockMvc.perform(
fileUpload("/project/123/offer").
file(uploadedFile).
param("uploadSignedGrantOfferLetterClicked", "")).
andExpect(status().isOk()).
andExpect(view().name("project/grant-offer-letter")).andReturn();
ProjectGrantOfferLetterForm form = (ProjectGrantOfferLetterForm)mvcResult.getModelAndView().getModel().get("form");
assertEquals(1, form.getObjectErrors().size());
assertEquals(form.getObjectErrors(), form.getBindingResult().getFieldErrors("signedGrantOfferLetter"));
assertTrue(form.getObjectErrors().get(0) instanceof FieldError);
}
@Test
public void testConfirmationView() throws Exception {
mockMvc.perform(get("/project/123/offer/confirmation")).
andExpect(status().isOk()).
andExpect(view().name("project/grant-offer-letter-confirmation"));
}
@Test
public void testSubmitOfferLetter() throws Exception {
long projectId = 123L;
when(projectService.submitGrantOfferLetter(projectId)).thenReturn(serviceSuccess());
mockMvc.perform(post("/project/" + projectId + "/offer").
param("confirmSubmit", "")).
andExpect(status().is3xxRedirection());
verify(projectService).submitGrantOfferLetter(projectId);
}
@Override
protected ProjectGrantOfferLetterController supplyControllerUnderTest() {
return new ProjectGrantOfferLetterController();
}
} |
package io.subutai.core.environment.impl.adapter;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Sets;
import io.subutai.common.command.CommandException;
import io.subutai.common.command.CommandResult;
import io.subutai.common.command.Request;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.host.ContainerHostInfoModel;
import io.subutai.common.host.ContainerHostState;
import io.subutai.common.host.HostArchitecture;
import io.subutai.common.host.HostInterfaceModel;
import io.subutai.common.host.HostInterfaces;
import io.subutai.common.peer.ContainerSize;
import io.subutai.common.peer.Host;
import io.subutai.core.environment.impl.EnvironmentManagerImpl;
import io.subutai.core.environment.impl.entity.EnvironmentContainerImpl;
class ProxyEnvironmentContainer extends EnvironmentContainerImpl
{
private static final Logger LOG = LoggerFactory.getLogger( ProxyEnvironmentContainer.class );
private static final RequestBuilder WHOAMI = new RequestBuilder( "whoami" );
private Host proxyContainer;
private final boolean local;
ProxyEnvironmentContainer( JsonNode json, EnvironmentManagerImpl environmentManager, Set<String> localContainerIds )
{
super( "hub", json.get( "peerId" ).asText(),
new ContainerHostInfoModel( json.get( "id" ).asText(), json.get( "hostName" ).asText(),
json.get( "name" ).asText(), initHostInterfaces( json ), HostArchitecture.AMD64,
ContainerHostState.RUNNING ), json.get( "templateName" ).asText(), HostArchitecture.AMD64, 0, 0,
json.get( "domainName" ).asText(), parseSize( json ), json.get( "hostId" ).asText(),
json.get( "name" ).asText() );
local = localContainerIds.contains( getId() );
setEnvironmentManager( environmentManager );
}
@Override
public boolean isLocal()
{
return local;
}
@Override
public boolean isConnected()
{
return isLocal() ? super.isConnected() : isRemoteContainerConnected();
}
private boolean isRemoteContainerConnected()
{
try
{
CommandResult result = execute( WHOAMI );
return result.getExitCode() == 0
&& StringUtils.isNotBlank( result.getStdOut() )
&& result.getStdOut().contains( "root" );
}
catch ( CommandException e )
{
LOG.error( "Error to check if remote container is connected: ", e );
return false;
}
}
private static ContainerSize parseSize( JsonNode json )
{
String size = json.get( "type" ).asText();
return ContainerSize.valueOf( size );
}
private static HostInterfaces initHostInterfaces( JsonNode json )
{
String ip = json.get( "ipAddress" ).asText();
String id = json.get( "id" ).asText();
HostInterfaceModel him = new HostInterfaceModel( "eth0", ip );
Set<HostInterfaceModel> set = Sets.newHashSet();
set.add( him );
return new HostInterfaces( id, set );
}
void setProxyContainer( Host proxyContainer )
{
this.proxyContainer = proxyContainer;
LOG.debug( "Set proxy: container={}, proxy={}", getId(), proxyContainer.getId() );
}
@Override
public CommandResult execute( RequestBuilder requestBuilder ) throws CommandException
{
Host host = this;
// If this is a remote host then the command is sent via a proxyContainer
// b/c the remote host is not directly accessible from the current peer.
if ( proxyContainer != null )
{
requestBuilder = wrapForProxy( requestBuilder );
host = proxyContainer;
}
return host.getPeer().execute( requestBuilder, host );
}
private RequestBuilder wrapForProxy( RequestBuilder requestBuilder )
{
String proxyIp = proxyContainer.getHostInterfaces().getAll().iterator().next().getIp();
String targetHostIp = getHostInterfaces().getAll().iterator().next().getIp();
if ( targetHostIp.contains( "/" ) )
{
targetHostIp = StringUtils.substringBefore( targetHostIp, "/" );
}
Request req = requestBuilder.build( "id" );
String command = String.format( "ssh root@%s %s", targetHostIp, req.getCommand() );
LOG.debug( "Command wrapped '{}' to send via {}", command, proxyIp );
return new RequestBuilder( command )
.withTimeout( requestBuilder.getTimeout() );
}
} |
package cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.impl;
import com.google.common.collect.Table;
import cz.cuni.mff.odcleanstore.conflictresolution.*;
import cz.cuni.mff.odcleanstore.conflictresolution.exceptions.ConflictResolutionException;
import cz.cuni.mff.odcleanstore.conflictresolution.exceptions.ResolutionFunctionNotRegisteredException;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.CRContextImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.ConflictResolutionPolicyImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.ResolutionStrategyImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.ResolvedStatementFactoryImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.util.CRUtils;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.util.EmptyMetadataModel;
import cz.cuni.mff.odcleanstore.conflictresolution.resolution.AllResolution;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.ResourceDescription;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.ResourceDescriptionConflictResolver;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.UriMapping;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.AlternativeUriNavigator;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.EmptyUriMapping;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterable;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterableImpl;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.util.ClusterIterator;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.util.ODCSFusionToolCRUtils;
import cz.cuni.mff.odcleanstore.vocabulary.ODCS;
import org.openrdf.model.*;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* TODO
*/
public class ResourceDescriptionConflictResolverImpl implements ResourceDescriptionConflictResolver {
private static final Logger LOG = LoggerFactory.getLogger(ResourceDescriptionConflictResolverImpl.class);
/** Default conflict resolution strategy. */
public static final ResolutionStrategy DEFAULT_RESOLUTION_STRATEGY = new ResolutionStrategyImpl(
AllResolution.getName(),
EnumCardinality.MANYVALUED,
EnumAggregationErrorStrategy.RETURN_ALL);
/** Default prefix of graph names where resolved quads are placed. */
public static final String DEFAULT_RESOLVED_GRAPHS_URI_PREFIX = ODCS.NAMESPACE + "cr/";
private static final ValueFactory VF = ValueFactoryImpl.getInstance();
private static final SortedListModelFactory SORTED_LIST_MODEL_FACTORY = new SortedListModelFactory();
private final Model metadataModel;
private final UriMapping uriMapping;
private final ConflictResolutionPolicy conflictResolutionPolicy;
private final ResolutionFunctionRegistry resolutionFunctionRegistry;
private final ResolvedStatementFactoryImpl resolvedStatementFactory;
/**
* Creates a new instance with the given settings.
* @param resolutionFunctionRegistry registry for obtaining conflict resolution function implementations
* @param conflictResolutionPolicy conflict resolution parameters
* @param uriMapping mapping of URIs to their canonical URI (based on owl:sameAs links)
* @param metadata additional metadata for use by resolution functions (e.g. source quality etc.)
* @param resolvedGraphsURIPrefix prefix of graph names where resolved quads are placed
*/
public ResourceDescriptionConflictResolverImpl(
ResolutionFunctionRegistry resolutionFunctionRegistry,
ConflictResolutionPolicy conflictResolutionPolicy,
UriMapping uriMapping,
Model metadata,
String resolvedGraphsURIPrefix) {
this.resolutionFunctionRegistry = resolutionFunctionRegistry;
this.conflictResolutionPolicy = conflictResolutionPolicy;
this.uriMapping = uriMapping != null
? uriMapping
: EmptyUriMapping.getInstance();
this.metadataModel = metadata != null
? metadata
: new EmptyMetadataModel();
this.resolvedStatementFactory = resolvedGraphsURIPrefix != null
? new ResolvedStatementFactoryImpl(resolvedGraphsURIPrefix)
: new ResolvedStatementFactoryImpl(DEFAULT_RESOLVED_GRAPHS_URI_PREFIX);
}
/**
* Apply conflict resolution process to the given resource description and return result.
* @param resourceDescription container of quads that make up the description of the respective statement
* (i.e. quads that are relevant for the conflict resolution process)
* @return collection of quads derived from the input with resolved
* conflicts, (F-)quality estimate and provenance information.
* @throws ConflictResolutionException error during the conflict resolution process
* @see ResolvedStatement
*/
@Override
public Collection<ResolvedStatement> resolveConflicts(ResourceDescription resourceDescription) throws ConflictResolutionException {
long startTime = logStarted(resourceDescription.getDescribingStatements().size());
ConflictResolutionPolicy effectiveResolutionPolicy = getEffectiveResolutionPolicy();
ConflictClustersMap conflictClustersMap = ConflictClustersMap.fromCollection(resourceDescription.getDescribingStatements(), uriMapping);
Collection<ResolvedStatement> result = createResultCollection(resourceDescription.getDescribingStatements().size());
AlternativeUriNavigator dependentProperties = new AlternativeUriNavigator(getDependentPropertyMapping(effectiveResolutionPolicy));
Resource canonicalResource = uriMapping.mapResource(resourceDescription.getResource());
resolveResource(canonicalResource, conflictClustersMap, dependentProperties, effectiveResolutionPolicy, result);
logFinished(startTime, result);
return result;
}
/**
* Resolve conflicts in statements contained in {@code conflictClustersMap} for the given {@code canonicalResource}.
* @param canonicalResource canonical version of resource to be resolved
* @param conflictClustersMap conflictClustersMap statements grouped by canonical subject and property
* @param dependentPropertyMapping property dependencies
* @param effectiveResolutionPolicy conflict resolution policy to be used
* @param result collection where the resolved result is added to
*/
private void resolveResource(
Resource canonicalResource,
ConflictClustersMap conflictClustersMap,
AlternativeUriNavigator dependentPropertyMapping,
ConflictResolutionPolicy effectiveResolutionPolicy,
Collection<ResolvedStatement> result) throws ConflictResolutionException {
Iterator<URI> propertyIt = conflictClustersMap.listProperties(canonicalResource);
Set<URI> resolvedProperties = new HashSet<>();
while (propertyIt.hasNext()) {
URI property = propertyIt.next();
if (resolvedProperties.contains(property)) {
continue;
}
if (dependentPropertyMapping.hasAlternativeUris(property)) {
List<URI> dependentProperties = dependentPropertyMapping.listAlternativeUris(property);
resolveResourceDependentProperties(
conflictClustersMap.getResourceStatementsMap(canonicalResource), canonicalResource,
dependentProperties,
effectiveResolutionPolicy,
result);
resolvedProperties.addAll(dependentProperties);
} else {
resolveResourceProperty(
conflictClustersMap.getConflictClusterStatements(canonicalResource, property), canonicalResource,
property,
effectiveResolutionPolicy,
result);
resolvedProperties.add(property);
}
}
}
// TODO: refactor + move ?
// FIXME: !!!! DO NOT SELECT BEST SUBJECT, BUT COMBINATION OF SUBJECT AND GRAPH
// (triples from the same graph should go together even if the same resource URI is used in multiple graphs)
/**
* Resolves conflicts in {@code statementsToResolveByProperty} for a set of mutually dependent properties.
* This method <b>doesn't expect statements to be resolved to share the same subject</b> but it assumes that
* all the subjects map to the same canonical resource and therefore belong to the same conflict clusters.
* @param statementsToResolveByProperty statements to be resolved as a map canonical property -> (unmapped) statements with the property
* @param subject canonical subject for the statements to resolve
* @param dependentProperties list of mutually dependent properties to be resolved
* @param effectiveResolutionPolicy resolution policy
* @param result collection where resolved result is added to
* @throws ConflictResolutionException CR error
*/
private void resolveResourceDependentProperties(
Map<URI, List<Statement>> statementsToResolveByProperty,
Resource subject,
List<URI> dependentProperties,
ConflictResolutionPolicy effectiveResolutionPolicy,
Collection<ResolvedStatement> result) throws ConflictResolutionException {
// Step 1: resolve conflicts for each (non-canonical) subject and property
Table<Resource, URI, Collection<ResolvedStatement>> conflictClustersTable = ODCSFusionToolCRUtils.newHashTable();
for (URI property : dependentProperties) {
List<Statement> conflictingStatements = statementsToResolveByProperty.get(property);
if (conflictingStatements == null) {
continue;
}
ClusterIterator<Statement> subjectClusterIterator = new ClusterIterator<>(conflictingStatements, StatementBySubjectComparator.getInstance());
while (subjectClusterIterator.hasNext()) {
List<Statement> statements = subjectClusterIterator.next();
Resource notMappedSubject = statements.get(0).getSubject();
StatementMappingIterator mappingIterator = new StatementMappingIterator(statements.iterator(), uriMapping, VF);
Model conflictClusterModel = SORTED_LIST_MODEL_FACTORY.fromUnorderedIterator(mappingIterator);
Collection<ResolvedStatement> resolvedConflictCluster = resolveConflictCluster(
conflictClusterModel, notMappedSubject, property, effectiveResolutionPolicy, conflictingStatements);
conflictClustersTable.put(notMappedSubject, property, resolvedConflictCluster);
}
}
// Step 2: Choose the best subject by aggregate quality
Resource bestSubject = null;
double bestSubjectQuality = -1;
for (Resource notMappedSubject : conflictClustersTable.rowKeySet()) {
double aggregateQualitySum = 0;
for (URI property : dependentProperties) {
aggregateQualitySum += aggregateConflictClusterQuality(conflictClustersTable.get(notMappedSubject, property));
}
double notMappedSubjectQuality = aggregateQualitySum / dependentProperties.size();
if (notMappedSubjectQuality > bestSubjectQuality) {
bestSubject = notMappedSubject;
bestSubjectQuality = notMappedSubjectQuality;
}
}
// Step 3: Add statements for the best subject to the result
if (bestSubject != null) {
Map<URI, Collection<ResolvedStatement>> selectedStatements = conflictClustersTable.row(bestSubject);
for (Collection<ResolvedStatement> resolvedStatements : selectedStatements.values()) {
result.addAll(resolvedStatements);
}
}
}
/**
* Resolves conflicts in {@code conflictClusterToResolve} for a single given property.
* This method doesn't expect statements to be resolved to share the same subject but it <b>assumes that
* all the subjects and properties map to the same canonical resource and property</b> and therefore
* belong to the same conflict clusters.
* @param conflictClusterToResolve conflicting statements to be resolved;
* subjects and predicates of these statements should map to the given canonical subject and property
* @param subject canonical subject for the conflict cluster
* @param property canonical property for the conflict cluster
* @param effectiveResolutionPolicy resolution policy
* @param result collection where resolved result is added to
* @throws ConflictResolutionException
*/
private void resolveResourceProperty(
List<Statement> conflictClusterToResolve,
Resource subject,
URI property,
ConflictResolutionPolicy effectiveResolutionPolicy,
Collection<ResolvedStatement> result) throws ConflictResolutionException {
StatementMappingIterator mappingIterator = new StatementMappingIterator(conflictClusterToResolve.iterator(), uriMapping, VF);
Model conflictClusterModel = SORTED_LIST_MODEL_FACTORY.fromUnorderedIterator(mappingIterator);
Collection<ResolvedStatement> resolvedStatements = resolveConflictCluster(conflictClusterModel, subject, property, effectiveResolutionPolicy, conflictClusterModel);
result.addAll(resolvedStatements);
}
// this method assumes that all statements in conflictClusterModel share the same subject and property
/**
* Resolve conflicts in {@code conflictClusterToResolve}. This methods expects that <b>all statements in
* {@code conflictClusterToResolve} share the same subject and property</b> (no further mapping is performed).
* @param conflictClusterToResolve statements to be resolved;
* subjects and predicate in these triples must be the same for all triples
* @param subject canonical subject for the conflict cluster
* @param property canonical property for the conflict cluster
* @param effectiveResolutionPolicy resolution policy
* @param conflictingStatements conflicting statements to be considered during quality calculation.
* @return resolved statements produced by conflict resolution function
* @throws ConflictResolutionException CR error
*/
@SuppressWarnings("UnusedParameters")
private Collection<ResolvedStatement> resolveConflictCluster(
Model conflictClusterToResolve,
Resource subject,
URI property,
ConflictResolutionPolicy effectiveResolutionPolicy,
Collection<Statement> conflictingStatements) throws ConflictResolutionException {
if (conflictClusterToResolve.isEmpty()) {
return Collections.emptyList();
}
// Get resolution strategy
ResolutionStrategy resolutionStrategy = effectiveResolutionPolicy.getPropertyResolutionStrategies().get(property);
if (resolutionStrategy == null) {
resolutionStrategy = effectiveResolutionPolicy.getDefaultResolutionStrategy();
}
// Prepare resolution functions & context
ResolutionFunction resolutionFunction = getResolutionFunction(resolutionStrategy);
CRContext context = new CRContextImpl(conflictingStatements, metadataModel, resolutionStrategy, resolvedStatementFactory);
// Resolve conflicts & append to result
// FIXME: resolution functions generally assume that the model is spog-sorted; while this works now, it can be easily broken in future
return resolutionFunction.resolve(conflictClusterToResolve, context);
}
private ConflictResolutionPolicy getEffectiveResolutionPolicy() {
ResolutionStrategy effectiveDefaultStrategy = DEFAULT_RESOLUTION_STRATEGY;
Map<URI, ResolutionStrategy> effectivePropertyStrategies = new HashMap<>();
if (conflictResolutionPolicy != null && conflictResolutionPolicy.getDefaultResolutionStrategy() != null) {
effectiveDefaultStrategy = CRUtils.fillResolutionStrategyDefaults(
conflictResolutionPolicy.getDefaultResolutionStrategy(),
DEFAULT_RESOLUTION_STRATEGY);
}
if (conflictResolutionPolicy != null && conflictResolutionPolicy.getPropertyResolutionStrategies() != null) {
for (Map.Entry<URI, ResolutionStrategy> entry : conflictResolutionPolicy.getPropertyResolutionStrategies().entrySet()) {
URI mappedURI = (URI) uriMapping.mapResource(entry.getKey());
ResolutionStrategy strategy = CRUtils.fillResolutionStrategyDefaults(entry.getValue(), effectiveDefaultStrategy);
effectivePropertyStrategies.put(mappedURI, strategy);
}
}
ConflictResolutionPolicyImpl result = new ConflictResolutionPolicyImpl();
result.setDefaultResolutionStrategy(effectiveDefaultStrategy);
result.setPropertyResolutionStrategy(effectivePropertyStrategies);
return result;
}
private UriMappingIterable getDependentPropertyMapping(ConflictResolutionPolicy effectiveResolutionPolicy) {
UriMappingIterableImpl dependentPropertyMapping = new UriMappingIterableImpl();
for (URI uri : effectiveResolutionPolicy.getPropertyResolutionStrategies().keySet()) {
ResolutionStrategy resolutionStrategy = effectiveResolutionPolicy.getPropertyResolutionStrategies().get(uri);
if (resolutionStrategy.getDependsOn() != null) {
dependentPropertyMapping.addLink(
(URI) uriMapping.mapResource(uri),
(URI) uriMapping.mapResource(resolutionStrategy.getDependsOn()));
}
}
return dependentPropertyMapping;
}
protected ResolutionFunction getResolutionFunction(ResolutionStrategy resolutionStrategy) throws ResolutionFunctionNotRegisteredException {
return resolutionFunctionRegistry.get(resolutionStrategy.getResolutionFunctionName());
}
protected Collection<ResolvedStatement> createResultCollection(int inputSize) {
return new ArrayList<>(inputSize / 2);
}
private double aggregateConflictClusterQuality(Collection<ResolvedStatement> resolvedStatements) {
if (resolvedStatements == null || resolvedStatements.isEmpty()) {
return 0d;
}
double sum = 0d;
for (ResolvedStatement resolvedStatement : resolvedStatements) {
sum += resolvedStatement.getQuality();
}
return sum / resolvedStatements.size();
}
private long logStarted(int inputStatementCount) {
if (LOG.isDebugEnabled()) {
LOG.debug("Resolving conflicts among {} quads.", inputStatementCount);
return System.currentTimeMillis();
} else {
return 0;
}
}
private void logFinished(long startTime, Collection<ResolvedStatement> result) {
if (LOG.isDebugEnabled()) {
LOG.debug("Conflict resolution executed in {} ms, resolved to {} quads",
System.currentTimeMillis() - startTime, result.size());
}
}
private static class StatementBySubjectComparator implements Comparator<Statement> {
private static final Comparator<Statement> INSTANCE = new StatementBySubjectComparator();
public static Comparator<Statement> getInstance() {
return INSTANCE;
}
@Override
public int compare(Statement o1, Statement o2) {
return CRUtils.compareValues(o1.getSubject(), o2.getSubject());
}
}
} |
package org.xwiki.extension.repository.internal.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.environment.Environment;
import org.xwiki.extension.repository.internal.ExtensionSerializer;
/**
* Store resolve core extension to not have to resolve it again at next restart.
*
* @version $Id$
* @since 6.4M1
*/
@Component(roles = CoreExtensionCache.class)
@Singleton
public class CoreExtensionCache implements Initializable
{
/**
* The String to search in a descriptor URL to know if it's inside a jar or another packaged file.
*/
private static final String PACKAGE_MARKER = "!/";
@Inject
private Environment environment;
@Inject
private ExtensionSerializer serializer;
@Inject
private Logger logger;
private File folder;
@Override
public void initialize() throws InitializationException
{
File permanentDirectory = this.environment.getPermanentDirectory();
if (permanentDirectory != null) {
this.folder = new File(permanentDirectory, "cache/extension/core/");
}
}
/**
* @param extension the extension to store
* @throws Exception when failing to store the extension
*/
public void store(DefaultCoreExtension extension) throws Exception
{
if (this.folder == null) {
return;
}
URL descriptorURL = extension.getDescriptorURL();
if (!descriptorURL.getPath().contains(PACKAGE_MARKER)) {
// Usually mean jars are not kept, don't cache that or it's going to be a nightmare when upgrading
return;
}
File file = getFile(descriptorURL);
// Make sure the file parents exist
if (!file.exists()) {
file.getParentFile().mkdirs();
}
try (FileOutputStream stream = new FileOutputStream(file)) {
this.serializer.saveExtensionDescriptor(extension, stream);
}
}
/**
* @param repository the repository to set in the new extension instance
* @param descriptorURL the extension descriptor URL
* @return the extension corresponding to the passed descriptor URL, null if none could be found
*/
public DefaultCoreExtension getExtension(DefaultCoreExtensionRepository repository, URL descriptorURL)
{
if (this.folder == null) {
return null;
}
if (!descriptorURL.getPath().contains(PACKAGE_MARKER)) {
// Usually mean jars are not kept, make sure to not take into account such a wrongly cached descriptor
return null;
}
File file = getFile(descriptorURL);
if (file.exists()) {
try (FileInputStream stream = new FileInputStream(file)) {
DefaultCoreExtension coreExtension =
this.serializer.loadCoreExtensionDescriptor(repository, descriptorURL, stream);
coreExtension.setCached(true);
return coreExtension;
} catch (Exception e) {
this.logger.warn("Failed to parse cached core extension", e);
}
}
return null;
}
private File getFile(URL url)
{
// FIXME: make it more unique
String fileName = String.valueOf(url.toExternalForm().hashCode());
return new File(this.folder, fileName + ".xed");
}
} |
package xal.app.tripviewer;
import xal.extension.application.*;
/**
* Main is the ApplicationAdaptor for the trip viewer.
* @author t6p
*/
public class Main extends ApplicationAdaptor {
/**
* Returns the text file suffixes of files this application can open.
* @return Suffixes of readable files
*/
public String[] readableDocumentTypes() {
return new String[0];
}
/**
* Returns the text file suffixes of files this application can write.
* @return Suffixes of writable files
*/
public String[] writableDocumentTypes() {
return new String[0];
}
/**
* Implement this method to return an instance of my custom document.
* @return An instance of my custom document.
*/
public XalDocument newEmptyDocument() {
return new TripDocument();
}
/**
* Implement this method to return an instance of my custom document
* corresponding to the specified URL.
* @param url The URL of the file to open.
* @return An instance of my custom document.
*/
public XalDocument newDocument( final java.net.URL url ) {
return newEmptyDocument();
}
/**
* Specifies the name of my application.
* @return Name of my application.
*/
public String applicationName() {
return "Trip Viewer";
}
/**
* Constructor
*/
public Main() {
}
/** The main method of the application. */
static public void main( final String[] args ) {
try {
System.out.println( "Starting Trip Viewer..." );
Application.launch( new Main() );
}
catch(Exception exception) {
System.err.println( exception.getMessage() );
exception.printStackTrace();
Application.displayApplicationError( "Launch Exception", "Launch Exception", exception );
System.exit( -1 );
}
}
} |
package yaplstack.ast;
import yaplstack.Instruction;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Generator implements AST.Visitor<Void> {
interface TwoStageGenerator {
Runnable generate(List<Instruction> instructions, Map<Object, Integer> labelToIndex);
}
private boolean asExpression;
private boolean functionScope;
private List<TwoStageGenerator> stagedInstructions = new ArrayList<>();
private MetaFrame context;
public Generator(boolean asExpression) {
this(asExpression, false, new ArrayList<>(), createContext());
}
private static MetaFrame createContext() {
MetaFrame context = new MetaFrame();
context.locals.add("self");
return context;
}
public void emitLoadSelf() {
emit(Instruction.Factory.loadVar("self", 0));
}
public Generator(boolean asExpression, boolean functionScope, List<TwoStageGenerator> stagedInstructions, MetaFrame context) {
this.stagedInstructions = stagedInstructions;
this.asExpression = asExpression;
this.functionScope = functionScope;
this.context = context;
}
private void mark(Object label) {
emit((instructions, labelToIndex) -> {
int index = instructions.size();
labelToIndex.put(label, index);
return () -> {
};
});
}
private void emitJump(Object label, Function<Integer, Instruction> instructionFunction) {
emit((instructions, labelToIndex) -> {
int instructionIndex = instructions.size();
instructions.add(null);
return () -> {
int jumpIndex = labelToIndex.get(label);
Instruction instruction = instructionFunction.apply(jumpIndex);
instructions.set(instructionIndex, instruction);
};
});
}
private void emitJumpIfTrue(Object label) {
emitJump(label, index -> Instruction.Factory.jumpIfTrue(index));
}
private void emitJump(Object label) {
emit(Instruction.Factory.loadConst(true));
emitJumpIfTrue(label);
}
@Override
public Void visitProgram(AST code) {
code.accept(this);
emit(Instruction.Factory.finish);
return null;
}
@Override
public Void visitBlock(List<AST> code) {
if(asExpression) {
code.subList(0, code.size() - 1).forEach(x -> visitAsStatement(x));
visitAsExpression(code.get(code.size() - 1));
} else {
code.forEach(x -> visitAsStatement(x));
}
return null;
}
@Override
public Void visitFN(List<String> params, AST code) {
if(asExpression) {
emit(Instruction.Factory.newEnvironment);
emit(Instruction.Factory.dup);
Generator bodyGenerator = new Generator(true);
bodyGenerator.context.context = context;
bodyGenerator.functionScope = true;
bodyGenerator.context.locals.addAll(params);
code.accept(bodyGenerator);
int variableCount = bodyGenerator.context.locals.size() - params.size();
Generator generator = new Generator(true);
generator.context.locals.addAll(params);
// Allocate variables
for(int i = 0; i < variableCount; i++)
generator.emit(Instruction.Factory.loadConst(null));
generator.emit(bodyGenerator);
generator.emit(Instruction.Factory.popCallFrame(1));
Instruction[] instructionArray = generator.generate();
emit(Instruction.Factory.loadConst(instructionArray));
emit(Instruction.Factory.store(Selector.get("call", params.size())));
}
return null;
}
private Instruction[] generate() {
ArrayList<Instruction> instructions = new ArrayList<>();
Hashtable<Object, Integer> labelToIndex = new Hashtable<>();
stagedInstructions.stream()
.map(x -> x.generate(instructions, labelToIndex))
.collect(Collectors.toList())
.forEach(x -> x.run());
return instructions.stream().toArray(s -> new Instruction[s]);
}
@Override
public Void visitApply(AST target, List<AST> args) {
emitLoadSelf();
args.forEach(x -> visitAsExpression(x));
visitAsExpression(target);
// Forward arguments
emit(Instruction.Factory.pushCallFrame(1 + args.size()));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitSend(AST target, String name, List<AST> arguments) {
visitAsExpression(target);
if(arguments.size() > 0) {
arguments.forEach(x -> visitAsExpression(x));
emit(Instruction.Factory.dupx(arguments.size()));
} else {
emit(Instruction.Factory.dup);
}
emit(Instruction.Factory.load(Selector.get(name, arguments.size())));
emit(Instruction.Factory.pushCallFrame(1 + arguments.size()));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitObject(List<Slot> slots) {
emit(Instruction.Factory.newEnvironment);
HashSet<MetaFrame> dependentContexts = new HashSet<>();
slots.forEach(x -> {
x.accept(new Slot.Visitor() {
@Override
public void visitField(String name, AST value) {
emit(Instruction.Factory.dup);
visitAsExpression(value);
emit(Instruction.Factory.store(name));
}
@Override
public void visitMethod(String name, List<String> parameters, AST body) {
emit(Instruction.Factory.dup);
visitMethodContent(parameters, body);
emit(Instruction.Factory.store(Selector.get(name, parameters.size())));
}
private void visitMethodContent(List<String> params, AST code) {
Generator bodyGenerator = new Generator(true);
bodyGenerator.functionScope = true;
bodyGenerator.context.locals.addAll(params);
//bodyGenerator.context.closedContexts = closedContexts;
bodyGenerator.context.context = context;
code.accept(bodyGenerator);
int variableCount = bodyGenerator.context.locals.size() - params.size();
Generator generator = new Generator(true);
generator.context.locals.addAll(params);
// Allocate variables
for(int i = 0; i < variableCount; i++)
generator.emit(Instruction.Factory.loadConst(null));
generator.emit(bodyGenerator);
generator.emit(Instruction.Factory.popCallFrame(1));
Instruction[] instructionArray = generator.generate();
emit(Instruction.Factory.loadConst(instructionArray));
if(bodyGenerator.context.isDepedent)
dependentContexts.add(bodyGenerator.context);
}
});
});
if(dependentContexts.size() > 0) {
emit(Instruction.Factory.dup);
emit(Instruction.Factory.loadCallFrame);
emit(Instruction.Factory.store("__frame__"));
}
return null;
}
@Override
public Void visitFrameLoad(AST target, int ordinal) {
visitAsExpression(target);
emit(Instruction.Factory.frameLoadVar(ordinal));
return null;
}
@Override
public Void visitFrameStore(AST target, int ordinal, AST value) {
visitAsExpression(target);
visitAsExpression(value);
emit(Instruction.Factory.frameStoreVar(ordinal));
return null;
}
@Override
public Void visitTest(AST condition, AST ifTrue, AST ifFalse) {
visitAsExpression(condition);
Object labelIfTrue = new Object();
Object labelEnd = new Object();
emitJumpIfTrue(labelIfTrue);
ifFalse.accept(this);
emitJump(labelEnd);
mark(labelIfTrue);
ifTrue.accept(this);
mark(labelEnd);
return null;
}
@Override
public Void visitLoop(AST condition, AST body) {
Object labelStart = new Object();
Object labelBody = new Object();
Object labelEnd = new Object();
mark(labelStart);
visitAsExpression(condition);
emitJumpIfTrue(labelBody);
emitJump(labelEnd);
mark(labelBody);
body.accept(this);
emitJump(labelStart);
mark(labelEnd);
if(asExpression)
emit(Instruction.Factory.loadConst(null));
return null;
}
@Override
public Void visitEnv() {
if(asExpression)
emitLoadSelf();
return null;
}
@Override
public Void visitItoc(AST i) {
visitAsExpression(i);
emit(Instruction.Factory.itoc);
return null;
}
@Override
public Void visitApplyCC(AST target) {
return null;
}
@Override
public Void visitResume(AST target, AST value) {
visitAsExpression(value);
visitAsExpression(target);
emit(Instruction.Factory.resume(1));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitFrame() {
if(asExpression)
emit(Instruction.Factory.loadCallFrame);
return null;
}
@Override
public Void visitRet(AST expression) {
visitAsExpression(expression);
emit(Instruction.Factory.popCallFrame(1));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitNot(AST expression) {
visitAsExpression(expression);
if(asExpression)
emit(Instruction.Factory.not);
else
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitBP() {
emit(Instruction.Factory.bp);
if(asExpression)
emit(Instruction.Factory.loadConst(false));
return null;
}
@Override
public Void visitLiteral(Object obj) {
if(asExpression)
emit(Instruction.Factory.loadConst(obj));
return null;
}
@Override
public Void visitAddi(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.addi);
}
return null;
}
@Override
public Void visitSubi(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.subi);
}
return null;
}
@Override
public Void visitMuli(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.muli);
}
return null;
}
@Override
public Void visitDivi(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.divi);
}
return null;
}
@Override
public Void visitLti(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.lti);
}
return null;
}
@Override
public Void visitGti(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.gti);
}
return null;
}
@Override
public Void visitEqi(AST lhs, AST rhs) {
if(asExpression) {
visitAsExpression(lhs);
visitAsExpression(rhs);
emit(Instruction.Factory.eqi);
}
return null;
}
@Override
public Void visitNewInstance(Constructor constructor, List<AST> args) {
args.forEach(x -> visitAsExpression(x));
emit(Instruction.Factory.newInstance(constructor));
return null;
}
@Override
public Void visitInvoke(Method method, List<AST> args) {
args.forEach(x -> visitAsExpression(x));
emit(Instruction.Factory.invoke(method));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitInvoke(AST target, Method method, List<AST> args) {
visitAsExpression(target);
args.forEach(x -> visitAsExpression(x));
emit(Instruction.Factory.invoke(method));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitFieldGet(Field field) {
if(asExpression)
emit(Instruction.Factory.fieldGet(field));
return null;
}
@Override
public Void visitFieldGet(AST target, Field field) {
visitAsExpression(target);
emit(Instruction.Factory.fieldGet(field));
if(!asExpression)
emit(Instruction.Factory.pop);
return null;
}
@Override
public Void visitFieldSet(Field field, AST value) {
visitAsExpression(value);
if(asExpression)
emit(Instruction.Factory.dup);
emit(Instruction.Factory.fieldSet(field));
return null;
}
@Override
public Void visitFieldSet(AST target, Field field, AST value) {
visitAsExpression(target);
visitAsExpression(value);
if(asExpression)
emit(Instruction.Factory.dupx1down);
emit(Instruction.Factory.fieldSet(field));
return null;
}
@Override
public Void visitLocal(AST target, String name, AST value) {
visitAsExpression(target);
visitAsExpression(value);
if(asExpression)
emit(Instruction.Factory.dupx1down);
emit(Instruction.Factory.store(name));
return null;
}
@Override
public Void visitLocal(String name, AST value) {
if(functionScope) {
int localOrdinal = context.locals.size();
context.locals.add(name);
visitAsExpression(value);
if (asExpression)
emit(Instruction.Factory.dup);
emit(Instruction.Factory.storeVar(localOrdinal));
} else {
emitLoadSelf();
visitAsExpression(value);
if (asExpression)
emit(Instruction.Factory.dupx1down);
emit(Instruction.Factory.store(name));
}
return null;
}
@Override
public Void visitStore(AST target, String name, AST value) {
visitAsExpression(target);
visitAsExpression(value);
if(asExpression)
emit(Instruction.Factory.dupx1down);
emit(Instruction.Factory.store(name));
return null;
}
@Override
public Void visitStore(String name, AST value) {
int localOrdinal = context.locals.indexOf(name);
if(localOrdinal != -1) {
visitAsExpression(value);
if (asExpression)
emit(Instruction.Factory.dup);
emit(Instruction.Factory.storeVar(localOrdinal));
} else {
emitLoadSelf();
visitAsExpression(value);
if (asExpression)
emit(Instruction.Factory.dupx1down);
emit(Instruction.Factory.store(name));
}
return null;
}
@Override
public Void visitLoad(AST target, String name) {
if(asExpression) {
visitAsExpression(target);
emit(Instruction.Factory.load(name));
}
return null;
}
@Override
public Void visitLoad(String name) {
if(asExpression)
context.emitLoad(this, name);
return null;
}
private void visitAsNonFunction(AST code) {
Generator generator = new Generator(asExpression, false, stagedInstructions, null);
code.accept(generator);
}
private void visitAsObject(AST code) {
Generator generator = new Generator(false, false, stagedInstructions, null);
code.accept(generator);
}
private void visitAsExpression(AST expression) {
Generator generator = new Generator(true, functionScope, stagedInstructions, context);
expression.accept(generator);
}
private void visitAsStatement(AST statement) {
Generator generator = new Generator(false, functionScope, stagedInstructions, context);
statement.accept(generator);
}
public void emit(Instruction instruction) {
emit((instructions, indexToLabel) -> {
instructions.add(instruction);
return () -> {
};
});
}
private void emit(Generator generator) {
emit(((instructions, labelToIndex) -> {
List<Runnable> postProcessors = generator.stagedInstructions.stream()
.map(x -> x.generate(instructions, labelToIndex))
.collect(Collectors.toList());
return () -> postProcessors.forEach(x -> x.run());
}));
}
private void emit(TwoStageGenerator generator) {
stagedInstructions.add(generator);
}
public static Instruction[] toInstructions(AST code) {
return toInstructions(code, g -> { }, g -> { });
}
private static Instruction[] toInstructions(AST code, Consumer<Generator> pre, Consumer<Generator> post) {
Generator generator = new Generator(true);
pre.accept(generator);
code.accept(generator);
post.accept(generator);
return generator.generate();
}
} |
package owltools.graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.obolibrary.obo2owl.Obo2OWLConstants.Obo2OWLVocabulary;
import org.obolibrary.obo2owl.Obo2Owl;
import org.obolibrary.obo2owl.Owl2Obo;
import org.obolibrary.oboformat.model.OBODoc;
import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.AddImport;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAnnotationSubject;
import org.semanticweb.owlapi.model.OWLAnnotationValue;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDeclarationAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom;
import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLInverseObjectPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectAllValuesFrom;
import org.semanticweb.owlapi.model.OWLObjectComplementOf;
import org.semanticweb.owlapi.model.OWLObjectHasValue;
import org.semanticweb.owlapi.model.OWLObjectIntersectionOf;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLObjectPropertyExpression;
import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLObjectUnionOf;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLPropertyExpression;
import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLRestriction;
import org.semanticweb.owlapi.model.OWLSubClassOfAxiom;
import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom;
import org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom;
import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.RemoveImport;
import org.semanticweb.owlapi.model.UnknownOWLOntologyException;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
import owltools.graph.OWLGraphWrapper.ISynonym;
import owltools.graph.OWLQuantifiedProperty.Quantifier;
import owltools.graph.shunt.OWLShuntEdge;
import owltools.graph.shunt.OWLShuntGraph;
import owltools.graph.shunt.OWLShuntNode;
import owltools.profile.Profiler;
/**
* Wraps one or more OWLOntology objects providing convenient OBO-like operations
*
* <h3>Capabilities</h3>
* <ul>
* <li>convenience methods for OBO-like properties such as synonyms, textual definitions, obsoletion, replaced_by
* <li>simple graph-like operations over ontologies, including reachability/closure queries that respect the OWL semantics
* </ul>
*
* <h3>Data model</h3>
*
* An instance of an OWLGraphWrapper wraps one or more {@link org.semanticweb.owlapi.model.OWLOntology} objects. One of these is designated
* the <i>sourceOntology</i>, the others are designated <i>support ontologies</i>
* (see {@link #getSourceOntology()} and {@link #getSupportOntologySet()}).
* The source ontology may import the support
* ontologies, but this is optional. Most OWLGraphWrapper methods operate over the union of the source ontology
* and support ontologies. This is particularly useful for working with OBO Library ontologies, where axioms
* connecting ontologies may be available as separate ontologies.
*
* <h3>Graph operations</h3>
*
* See {@link owltools.graph}
*
* <h3>Fetching objects</h3>
*
* This wrapper provides convenience methods for fetching objects by OBO-Style IDs, IRIs or by labels.
* Note that unlike the get* calls on {@link OWLDataFactory} objects, these only return an object if it
* has been declared in either the source ontology or a support ontology.
*
* See for example
*
* <ul>
* <li>{@link #getOWLClass(String id)}
* <li>{@link #getOWLClassByIdentifier(String id)}
* <li>{@link #getOWLObjectByLabel(String label)}
* </ul>
* <h3>OBO Metadata</h3>
*
* <h4>OBO-style identifiers</h4>
*
* This class accepts the use of OBO-Format style identifiers in some contexts, e.g. GO:0008150
*
* See methods such as
* <ul>
* <li>{@link #getOWLClassByIdentifier(String id)}
* </ul>
*
* <h4>Textual metadata</h4>
*
* Documentation to follow....
*
* @see OWLGraphUtil
* @author cjm
*
*/
public class OWLGraphWrapper {
private static Logger LOG = Logger.getLogger(OWLGraphWrapper.class);
public static final String DEFAULT_IRI_PREFIX = "http://purl.obolibrary.org/obo/";
@Deprecated
OWLOntology ontology; // this is the ontology used for querying. may be the merge of sourceOntology+closure
OWLOntology sourceOntology; // graph is seeded from this ontology.
Set<OWLOntology> supportOntologySet = new HashSet<OWLOntology>();
OWLReasoner reasoner = null;
Config config = new Config();
private Map<OWLObject,Set<OWLGraphEdge>> edgeBySource;
private Map<OWLObject,Set<OWLGraphEdge>> edgeByTarget;
public Map<OWLObject,Set<OWLGraphEdge>> inferredEdgeBySource = null; // public to serialize
private Map<OWLObject,Set<OWLGraphEdge>> inferredEdgeByTarget = null;
// used to store mappings child->parent, where
// parent = UnionOf( ..., child, ...)
private Map<OWLObject,Set<OWLObject>> extraSubClassOfEdges = null;
private Profiler profiler = new Profiler();
/**
* Configuration options. These are typically specific to a
* OWLGraphWrapper instance.
*
*/
public class Config {
// by default the graph closure includes only named entities
public boolean isIncludeClassExpressionsInClosure = true;
// by default we do not follow complement of - TODO
public boolean isFollowComplementOfInClosure = false;
public boolean isCacheClosure = true;
public boolean isMonitorMemory = false;
// if set to non-null, this constrains graph traversal. TODO
public Set<OWLQuantifiedProperty> graphEdgeIncludeSet = null;
public Set<OWLQuantifiedProperty> graphEdgeExcludeSet = null;
public OWLClass excludeMetaClass = null;
/**
* @param p
* @param q
*/
public void excludeProperty(OWLObjectProperty p, Quantifier q) {
if (graphEdgeExcludeSet == null)
graphEdgeExcludeSet = new HashSet<OWLQuantifiedProperty>();
graphEdgeExcludeSet.add(new OWLQuantifiedProperty(p, q));
}
/**
* @see #excludeProperty(OWLObjectProperty, Quantifier) - the default quantifier is some
* @param p
*/
public void excludeProperty(OWLObjectProperty p) {
excludeProperty(p, Quantifier.SOME);
}
public void includeProperty(OWLObjectProperty p) {
includeProperty(p, Quantifier.SOME);
}
public void includeProperty(OWLObjectProperty p, Quantifier q) {
if (graphEdgeIncludeSet == null)
graphEdgeIncludeSet = new HashSet<OWLQuantifiedProperty>();
graphEdgeIncludeSet.add(new OWLQuantifiedProperty(p, q));
}
public void excludeAllWith(OWLAnnotationProperty ap, OWLOntology o) {
for (OWLObjectProperty p : o.getObjectPropertiesInSignature(true)) {
Set<OWLAnnotation> anns = p.getAnnotations(o, ap);
for (OWLAnnotation ann : anns) {
if (ann.getValue() instanceof OWLLiteral) {
OWLLiteral v = (OWLLiteral) ann.getValue();
if (v.parseBoolean()) {
excludeProperty(p);
}
}
}
}
}
public void includeAllWith(OWLAnnotationProperty ap, OWLOntology o) {
for (OWLObjectProperty p : o.getObjectPropertiesInSignature(true)) {
Set<OWLAnnotation> anns = p.getAnnotations(o, ap);
for (OWLAnnotation ann : anns) {
if (ann.getValue() instanceof OWLLiteral) {
OWLLiteral v = (OWLLiteral) ann.getValue();
if (v.parseBoolean()) {
includeProperty(p);
}
}
}
}
}
}
/**
* Create a new wrapper for an OWLOntology
*
* @param ontology
*
* @throws OWLOntologyCreationException
* @throws UnknownOWLOntologyException
*/
public OWLGraphWrapper(OWLOntology ontology) throws UnknownOWLOntologyException, OWLOntologyCreationException {
super();
sourceOntology = ontology;
getManager().getOntologyFormat(ontology);
}
/**
* Create a new wrapper for an OWLOntology
*
* @param ontology
* @param isMergeImportClosure
* @throws UnknownOWLOntologyException
* @throws OWLOntologyCreationException
* @deprecated
*/
@Deprecated
public OWLGraphWrapper(OWLOntology ontology, boolean isMergeImportClosure) throws UnknownOWLOntologyException, OWLOntologyCreationException {
super();
if (isMergeImportClosure) {
System.out.println("setting source ontology:"+ontology);
this.sourceOntology = ontology;
// the query ontology is the source ontology plus the imports closure
useImportClosureForQueries();
}
else {
this.sourceOntology = ontology;
}
getManager().getOntologyFormat(ontology);
}
/**
* creates a new {@link OWLOntology} as the source ontology
*
* @param iri
* @throws OWLOntologyCreationException
*/
public OWLGraphWrapper(String iri) throws OWLOntologyCreationException {
super();
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
sourceOntology = manager.createOntology(IRI.create(iri));
}
/**
* adds an imports declaration between the source ontology and extOnt
*
* @param extOnt
*/
public void addImport(OWLOntology extOnt) {
AddImport ai = new AddImport(getSourceOntology(), getDataFactory().getOWLImportsDeclaration(extOnt.getOntologyID().getOntologyIRI()));
getManager().applyChange(ai);
}
/**
* if called, copies all axioms from import closure into query ontology.
*
* @throws UnknownOWLOntologyException
* @throws OWLOntologyCreationException
*/
@Deprecated
public void useImportClosureForQueries() throws UnknownOWLOntologyException, OWLOntologyCreationException {
this.ontology =
OWLManager.createOWLOntologyManager().createOntology(sourceOntology.getOntologyID().getOntologyIRI(), sourceOntology.getImportsClosure());
}
@Deprecated
public void addQueryOntology(OWLOntology extOnt) throws OWLOntologyCreationException {
Set<OWLAxiom> axioms = ontology.getAxioms();
axioms.addAll(extOnt.getAxioms());
this.ontology =
OWLManager.createOWLOntologyManager().createOntology(axioms, sourceOntology.getOntologyID().getOntologyIRI());
}
/**
* Adds all axioms from extOnt into source ontology
*
* @param extOnt
* @throws OWLOntologyCreationException
*/
public void mergeOntology(OWLOntology extOnt) throws OWLOntologyCreationException {
OWLOntologyManager manager = getManager();
for (OWLAxiom axiom : extOnt.getAxioms()) {
manager.applyChange(new AddAxiom(sourceOntology, axiom));
}
for (OWLImportsDeclaration oid: extOnt.getImportsDeclarations()) {
manager.applyChange(new AddImport(sourceOntology, oid));
}
}
public void mergeOntology(OWLOntology extOnt, boolean isRemoveFromSupportList) throws OWLOntologyCreationException {
mergeOntology(extOnt);
if (isRemoveFromSupportList) {
this.supportOntologySet.remove(extOnt);
}
}
public void mergeSupportOntology(String ontologyIRI, boolean isRemoveFromSupportList) throws OWLOntologyCreationException {
OWLOntology extOnt = null;
for (OWLOntology ont : this.supportOntologySet) {
if (ont.getOntologyID().getOntologyIRI().toString().equals(ontologyIRI)) {
extOnt = ont;
break;
}
}
mergeOntology(extOnt);
if (isRemoveFromSupportList) {
this.supportOntologySet.remove(extOnt);
}
}
public void mergeSupportOntology(String ontologyIRI) throws OWLOntologyCreationException {
mergeSupportOntology(ontologyIRI, true);
}
@Deprecated
public OWLOntology getOntology() {
return getSourceOntology();
}
@Deprecated
public void setOntology(OWLOntology ontology) {
setSourceOntology(ontology);
}
/**
* Every OWLGraphWrapper objects wraps zero or one source ontologies.
*
* @return ontology
*/
public OWLOntology getSourceOntology() {
return sourceOntology;
}
public void setSourceOntology(OWLOntology sourceOntology) {
this.sourceOntology = sourceOntology;
}
public Profiler getProfiler() {
return profiler;
}
public void setProfiler(Profiler profiler) {
this.profiler = profiler;
}
public OWLReasoner getReasoner() {
return reasoner;
}
/**
* @param reasoner
*/
public void setReasoner(OWLReasoner reasoner) {
this.reasoner = reasoner;
}
/**
* all operations are over a set of ontologies - the source ontology plus
* any number of supporting ontologies. The supporting ontologies may be drawn
* from the imports closure of the source ontology, although this need not be the case.
*
* @return set of support ontologies
*/
public Set<OWLOntology> getSupportOntologySet() {
return supportOntologySet;
}
public void setSupportOntologySet(Set<OWLOntology> supportOntologySet) {
this.supportOntologySet = supportOntologySet;
}
public void addSupportOntology(OWLOntology o) {
this.supportOntologySet.add(o);
}
public void removeSupportOntology(OWLOntology o) {
this.supportOntologySet.remove(o);
}
/**
* Each ontology in the import closure of the source ontology is added to
* the list of support ontologies
*
*/
public void addSupportOntologiesFromImportsClosure() {
addSupportOntologiesFromImportsClosure(false);
}
/**
* Each ontology in the import closure of the source ontology
* (and the import closure of each existing support ontology, if
* doForAllSupportOntologies is true) is added to
* the list of support ontologies
*
* @param doForAllSupportOntologies
*/
public void addSupportOntologiesFromImportsClosure(boolean doForAllSupportOntologies) {
Set<OWLOntology> ios = new HashSet<OWLOntology>();
ios.add(sourceOntology);
if (doForAllSupportOntologies) {
ios.addAll(getSupportOntologySet());
}
for (OWLOntology so : ios) {
for (OWLOntology o : so.getImportsClosure()) {
if (o.equals(sourceOntology))
continue;
addSupportOntology(o);
}
}
}
public void addImportsFromSupportOntologies() {
OWLOntology sourceOntology = getSourceOntology();
OWLOntologyManager manager = getManager();
OWLDataFactory factory = getDataFactory();
for (OWLOntology o : getSupportOntologySet()) {
OWLImportsDeclaration importsDeclaration = factory.getOWLImportsDeclaration(o.getOntologyID().getOntologyIRI());
AddImport ai = new AddImport(sourceOntology, importsDeclaration);
LOG.info("Applying: "+ai);
manager.applyChange(ai);
}
this.setSupportOntologySet(new HashSet<OWLOntology>());
}
public void remakeOntologiesFromImportsClosure() throws OWLOntologyCreationException {
remakeOntologiesFromImportsClosure((new OWLOntologyID()).getOntologyIRI());
}
public void remakeOntologiesFromImportsClosure(IRI ontologyIRI) throws OWLOntologyCreationException {
addSupportOntologiesFromImportsClosure();
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
sourceOntology = manager.createOntology(sourceOntology.getAxioms(), ontologyIRI);
}
/**
* note: may move to mooncat
* @throws OWLOntologyCreationException
*/
public void mergeImportClosure() throws OWLOntologyCreationException {
mergeImportClosure(false);
}
public void mergeImportClosure(boolean isRemovedImportsDeclarations) throws OWLOntologyCreationException {
OWLOntologyManager manager = getManager();
//OWLOntologyID oid = sourceOntology.getOntologyID();
Set<OWLOntology> imports = sourceOntology.getImportsClosure();
//manager.removeOntology(sourceOntology);
//sourceOntology = manager.createOntology(oid);
for (OWLOntology o : imports) {
if (o.equals(sourceOntology))
continue;
manager.addAxioms(sourceOntology, o.getAxioms());
}
Set<OWLImportsDeclaration> oids = sourceOntology.getImportsDeclarations();
for (OWLImportsDeclaration oid : oids) {
RemoveImport ri = new RemoveImport(sourceOntology, oid);
getManager().applyChange(ri);
}
}
/**
* in general application code need not call this - it is mostly used internally
*
* @return union of source ontology plus all supporting ontologies
*/
public Set<OWLOntology> getAllOntologies() {
Set<OWLOntology> all = new HashSet<OWLOntology>(getSupportOntologySet());
for (OWLOntology o : getSupportOntologySet()) {
all.addAll(o.getImportsClosure());
}
all.add(getSourceOntology());
all.addAll(getSourceOntology().getImportsClosure());
return all;
}
public OWLDataFactory getDataFactory() {
return getManager().getOWLDataFactory();
}
public OWLOntologyManager getManager() {
return sourceOntology.getOWLOntologyManager();
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
// BASIC GRAPH EDGE TRAVERSAL
/**
* retrieves direct edges from a source
* to the direct **named** target
*
* e.g. if (A SubClassOf B) then outgoing(A) = { <A,sub,B>}
* e.g. if (A SubClassOf R some B) then outgoing(A) = { <A, R-some, B> }
* e.g. if (A SubClassOf R some (R2 some B)) then outgoing(A) = { <A, [R-some,R2-same], B> }
*
* @param cls source
* @return all edges that originate from source to nearest named object target
*/
public Set<OWLGraphEdge> getOutgoingEdges(OWLObject cls) {
Set<OWLGraphEdge> pEdges = getPrimitiveOutgoingEdges(cls);
LOG.debug("primitive edges:"+cls+" --> "+pEdges);
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : pEdges) {
edges.addAll(primitiveEdgeToFullEdges(e));
}
LOG.debug(" all:"+cls+" --> "+edges);
return edges;
}
public Set<OWLGraphEdge> getOutgoingEdges(OWLObject obj, boolean isClosure,boolean isReflexive) {
if (isClosure) {
if (isReflexive)
return getOutgoingEdgesClosureReflexive(obj);
else
return getOutgoingEdgesClosure(obj);
}
else
return getOutgoingEdgesClosure(obj);
}
private Set<OWLObject> getOutgoingEdgesViaReverseUnion(OWLObject child) {
if (extraSubClassOfEdges == null)
cacheReverseUnionMap();
if (extraSubClassOfEdges.containsKey(child))
return new HashSet<OWLObject>(extraSubClassOfEdges.get(child));
else
return new HashSet<OWLObject>();
}
private void cacheReverseUnionMap() {
extraSubClassOfEdges = new HashMap<OWLObject, Set<OWLObject>>();
for (OWLOntology o : getAllOntologies()) {
for (OWLClass cls : o.getClassesInSignature()) {
for (OWLEquivalentClassesAxiom eca : o.getEquivalentClassesAxioms(cls)) {
for (OWLClassExpression ce : eca.getClassExpressions()) {
if (ce instanceof OWLObjectUnionOf) {
for (OWLObject child : ((OWLObjectUnionOf)ce).getOperands()) {
if (extraSubClassOfEdges.containsKey(child)) {
extraSubClassOfEdges.get(child).add(cls);
}
else {
extraSubClassOfEdges.put(child, new HashSet<OWLObject>());
extraSubClassOfEdges.get(child).add(cls);
}
}
}
}
}
}
}
}
/**
* primitive edges connect any combination of named objects and expressions
*
* e.g. (A SubClassOf R some B) => <A,sub,R-some-B>, <R-some-B,R-some,B>
* @param s source
* @return set of {@link OWLGraphEdge}
*/
public Set<OWLGraphEdge> getPrimitiveOutgoingEdges(OWLObject s) {
profiler.startTaskNotify("getPrimitiveOutgoingEdges");
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLOntology o : getAllOntologies()) {
if (s instanceof OWLClass) {
for (OWLSubClassOfAxiom sca : o.getSubClassAxiomsForSubClass((OWLClass) s)) {
edges.add(createSubClassOfEdge(sca.getSubClass(), sca.getSuperClass()));
}
for (OWLEquivalentClassesAxiom eqa : o.getEquivalentClassesAxioms((OWLClass) s)) {
for (OWLClassExpression ce : eqa.getClassExpressions()) {
if (!ce.equals(s))
edges.add(createSubClassOfEdge(s, ce));
}
}
for (OWLObject pbu : getOutgoingEdgesViaReverseUnion(s)) {
if (pbu instanceof OWLClass)
edges.add(createSubClassOfEdge(s,(OWLClass)pbu));
}
}
else if (s instanceof OWLIndividual) {
// TODO - do we care about punning?
// need to define semantics here
//System.err.println("getting individual axioms");
for (OWLClassAssertionAxiom a : o.getClassAssertionAxioms((OWLIndividual) s)) {
edges.add(new OWLGraphEdge(s,a.getClassExpression(),null,Quantifier.INSTANCE_OF,getSourceOntology()));
}
for (OWLObjectPropertyAssertionAxiom a : o.getObjectPropertyAssertionAxioms((OWLIndividual) s)) {
edges.add(new OWLGraphEdge(s,a.getObject(),a.getProperty(),Quantifier.PROPERTY_ASSERTION,getSourceOntology()));
}
}
else if (s instanceof OWLRestriction<?, ?, ?>) {
edges.add(restrictionToPrimitiveEdge((OWLRestriction<?, ?, ?>) s));
}
else if (s instanceof OWLObjectIntersectionOf) {
for (OWLClassExpression ce : ((OWLObjectIntersectionOf)s).getOperands()) {
edges.add(createSubClassOfEdge(s,ce));
}
}
else if (s instanceof OWLObjectUnionOf) {
// do nothing in this direction
}
}
if (reasoner != null) {
// if (s instanceof OWLClassExpression) {
// JCel can't do class expressions. TODO: make this more flexible
if (s instanceof OWLClass) {
for (Node<OWLClass> pn : reasoner.getSuperClasses( (OWLClassExpression)s, true)) {
for (OWLClass p : pn.getEntities()) {
OWLGraphEdge e = createSubClassOfEdge(s,p);
e.getSingleQuantifiedProperty().setInferred(true);
edges.add(e);
}
}
}
}
filterEdges(edges);
profiler.endTaskNotify("getPrimitiveOutgoingEdges");
return edges;
}
// TODO - DRY
private boolean isExcluded(OWLQuantifiedProperty qp) {
if (config.graphEdgeIncludeSet != null) {
LOG.debug("includes:"+config.graphEdgeIncludeSet);
if (qp.getProperty() == null)
return false;
for (OWLQuantifiedProperty qtp : config.graphEdgeIncludeSet) {
LOG.debug(" testing:"+qtp);
if (qp.subsumes(qtp))
return false;
}
LOG.debug(" not in inclusions list:"+qp);
return true;
}
if (config.graphEdgeExcludeSet != null) {
LOG.debug("excludes:"+config.graphEdgeExcludeSet);
for (OWLQuantifiedProperty qtp : config.graphEdgeExcludeSet) {
if (qtp.subsumes(qp))
return true;
}
return false;
}
return false;
}
/**
* only include those edges that match user constraints.
*
* default is to include
*
* If the includeSet is specified, then the candidate property MUST be in this set.
* If the excludeSet is specified, then the candidate property MUST NOT be in this set.
*
* Note there is generally little point in specifying both, but sometimes this may
* be useful; e.g. to configure a generic includeSet
*
* @param edges
*/
private void filterEdges(Set<OWLGraphEdge> edges) {
Set<OWLGraphEdge> rmEdges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : edges) {
if (isExcludeEdge(e)) {
rmEdges.add(e);
}
}
edges.removeAll(rmEdges);
}
public boolean isExcludeEdge(OWLGraphEdge edge) {
if (config.graphEdgeExcludeSet != null ||
config.graphEdgeIncludeSet != null) {
for (OWLQuantifiedProperty qp : edge.getQuantifiedPropertyList()) {
if (isExcluded(qp)) {
LOG.debug("excluded:"+edge+" based on: "+qp);
return true;
}
}
}
OWLObject t = edge.getTarget();
if (t != null) {
if (t instanceof OWLNamedObject) {
OWLNamedObject nt = (OWLNamedObject) t;
// TODO
if (nt.getIRI().toString().startsWith("http:
return true;
if (t instanceof OWLClass && t.equals(getDataFactory().getOWLThing())) {
return true;
}
}
}
return false;
}
// e.g. R-some-B ==> <R-some-B,R,B>
private OWLGraphEdge restrictionToPrimitiveEdge(OWLRestriction s) {
OWLObjectPropertyExpression p = null;
OWLObject t = null;
OWLQuantifiedProperty.Quantifier q = null;
if (s instanceof OWLObjectSomeValuesFrom) {
t = ((OWLObjectSomeValuesFrom)s).getFiller();
p = (OWLObjectPropertyExpression) s.getProperty();
q = OWLQuantifiedProperty.Quantifier.SOME;
}
else if (s instanceof OWLObjectAllValuesFrom) {
t = ((OWLObjectAllValuesFrom)s).getFiller();
p = (OWLObjectPropertyExpression) s.getProperty();
q = OWLQuantifiedProperty.Quantifier.ONLY;
}
else if (s instanceof OWLObjectHasValue) {
t = ((OWLObjectHasValue)s).getValue();
p = (OWLObjectPropertyExpression) s.getProperty();
q = OWLQuantifiedProperty.Quantifier.VALUE;
}
else {
System.err.println("cannot handle:"+s);
}
return new OWLGraphEdge(s,t,p,q,getSourceOntology());
}
private OWLGraphEdge createSubClassOfEdge(OWLObject s, OWLClassExpression t) {
return new OWLGraphEdge(s,t,null,Quantifier.SUBCLASS_OF,getSourceOntology());
}
// extend an edge target until we hit a named object.
// this could involve multiple extensions and "forks", e.g.
// <A sub B^C> ==> <A sub B>, <A sub C>
private Set<OWLGraphEdge> primitiveEdgeToFullEdges(OWLGraphEdge e) {
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
if (e.isTargetNamedObject()) {
edges.add(e); // do nothing
}
else {
// extend
OWLObject s = e.getSource();
Set<OWLGraphEdge> nextEdges = getOutgoingEdges(e.getTarget());
for (OWLGraphEdge e2 : nextEdges) {
OWLGraphEdge nu = this.combineEdgePair(s, e, e2, 1);
if (nu != null)
edges.add(nu);
}
}
filterEdges(edges);
return edges;
}
/**
* caches full outgoing and incoming edges
*
* in general you should not need to call this directly;
* used internally by this class.
*/
public void cacheEdges() {
edgeBySource = new HashMap<OWLObject,Set<OWLGraphEdge>>();
edgeByTarget = new HashMap<OWLObject,Set<OWLGraphEdge>>();
// initialize with all named objects in ontology
Stack<OWLObject> allObjs = new Stack<OWLObject>();
allObjs.addAll(getAllOWLObjects());
Set<OWLObject> visisted = new HashSet<OWLObject>();
while (allObjs.size() > 0) {
OWLObject s = allObjs.pop();
if (visisted.contains(s))
continue;
visisted.add(s);
if (!edgeBySource.containsKey(s))
edgeBySource.put(s, new HashSet<OWLGraphEdge>());
for (OWLGraphEdge edge : getPrimitiveOutgoingEdges(s)) {
edgeBySource.get(s).add(edge);
OWLObject t = edge.getTarget();
if (!edgeByTarget.containsKey(t))
edgeByTarget.put(t, new HashSet<OWLGraphEdge>());
edgeByTarget.get(t).add(edge);
// we also want to get all edges from class expressions;
// class expressions aren't in the initial signature, but
// we add them here when we encounter them
if (t instanceof OWLClassExpression) {
allObjs.add(t);
}
}
}
}
/**
* @param t
* @return all edges that have t as a direct target
*/
public Set<OWLGraphEdge> getIncomingEdges(OWLObject t) {
ensureEdgesCached();
if (edgeByTarget.containsKey(t)) {
return new HashSet<OWLGraphEdge>(edgeByTarget.get(t));
}
return new HashSet<OWLGraphEdge>();
}
private void ensureEdgesCached() {
if (edgeByTarget == null)
cacheEdges();
}
/**
* pack/translate an edge (either asserted or a graph closure edge) into
* an OWL class expression according to the OWLGraph to OWLOntology
* translation rules.
*
* (this is the reverse translation of the one from an OWLOntology to an
* OWLGraph)
*
* e.g. after calling for the graph closure of an OWLClass a,
* we may get back an edge <a [part_of-some, adjacent_to-some, has_part-some] b>.
* after feeding this edge into this method we obtain the expression
* part_of some (adjacent_to some (has_part some b))
*
* @param e edge
* @return class expression equivalent to edge
*/
public OWLObject edgeToTargetExpression(OWLGraphEdge e) {
return edgeToTargetExpression(e.getQuantifiedPropertyList().iterator(),e.getTarget());
}
private OWLObject edgeToTargetExpression(
Iterator<OWLQuantifiedProperty> qpi, OWLObject t) {
OWLDataFactory dataFactory = getDataFactory();
if (qpi.hasNext()) {
OWLQuantifiedProperty qp = qpi.next();
OWLObject x = edgeToTargetExpression(qpi,t);
OWLClassExpression t2;
if (!(x instanceof OWLClassExpression)) {
//System.err.println("Not a CE: "+x);
HashSet<OWLNamedIndividual> ins = new HashSet<OWLNamedIndividual>();
ins.add((OWLNamedIndividual) x);
t2 = dataFactory.getOWLObjectOneOf(ins);
}
else {
t2 = (OWLClassExpression) x;
}
if (qp.isSubClassOf()) {
return t2;
}
else if (qp.isInstanceOf()) {
return t2;
}
else if (qp.isIdentity()) {
return t2;
}
else if (qp.isPropertyAssertion()) {
return dataFactory.getOWLObjectSomeValuesFrom(qp.getProperty(),
(OWLClassExpression) t2);
}
else if (qp.isSomeValuesFrom()) {
return dataFactory.getOWLObjectSomeValuesFrom(qp.getProperty(),
(OWLClassExpression) t2);
}
else if (qp.isAllValuesFrom()) {
return dataFactory.getOWLObjectAllValuesFrom(qp.getProperty(),
(OWLClassExpression) t2);
}
else if (qp.isHasValue()) {
if (x instanceof OWLNamedObject)
return dataFactory.getOWLObjectHasValue(qp.getProperty(),
dataFactory.getOWLNamedIndividual(((OWLNamedObject) x).getIRI()));
else {
System.err.println("warning: treating "+x+" as allvaluesfrom");
return dataFactory.getOWLObjectAllValuesFrom(qp.getProperty(),
(OWLClassExpression) x);
}
}
else {
System.err.println("cannot handle:"+qp);
// TODO
return null;
}
}
else {
return t;
}
}
// GRAPH CLOSURE METHODS
/**
* Retrieves the graph closure originating from source.
* E.g. if A SubClassOf R some B & B SubClassOf S some C, then
* closure(A) = { <A R-some B>, <A [R-some,S-some] C>.
*
* Composition rules are used to compact the list of connecting edge labels
* (e.g. transitivity).
*
* The resulting edges can be translated into class expressions using
* method edgeToTargetExpression(e). E.g. in the above the expression would be
* R some (S some C)
*
* @param s source
* @return closure of edges originating from source
*/
public Set<OWLGraphEdge> getOutgoingEdgesClosure(OWLObject s) {
if (config.isCacheClosure) {
if (inferredEdgeBySource == null)
inferredEdgeBySource = new HashMap<OWLObject,Set<OWLGraphEdge>>();
if (inferredEdgeBySource.containsKey(s)) {
return new HashSet<OWLGraphEdge>(inferredEdgeBySource.get(s));
}
}
profiler.startTaskNotify("getOutgoingEdgesClosure");
Stack<OWLGraphEdge> edgeStack = new Stack<OWLGraphEdge>();
Set<OWLGraphEdge> closureSet = new HashSet<OWLGraphEdge>();
//Set<OWLGraphEdge> visitedSet = new HashSet<OWLGraphEdge>();
Set<OWLObject> visitedObjs = new HashSet<OWLObject>();
Map<OWLObject,Set<OWLGraphEdge>> visitedMap = new HashMap<OWLObject,Set<OWLGraphEdge>>();
visitedObjs.add(s);
visitedMap.put(s, new HashSet<OWLGraphEdge>());
// initialize. we seed the search with a reflexive identity edge DEPR
//edgeStack.add(new OWLGraphEdge(s,s,null,Quantifier.IDENTITY,ontology));
// seed stack
edgeStack.addAll(getPrimitiveOutgoingEdges(s));
closureSet.addAll(edgeStack);
while (!edgeStack.isEmpty()) {
OWLGraphEdge ne = edgeStack.pop();
//System.out.println("NEXT: "+ne+" //stack: "+edgeStack);
int nextDist = ne.getDistance() + 1;
Set<OWLGraphEdge> extSet = getPrimitiveOutgoingEdges(ne.getTarget());
for (OWLGraphEdge extEdge : extSet) {
//System.out.println(" EXT:"+extEdge);
OWLGraphEdge nu = combineEdgePair(s, ne, extEdge, nextDist);
if (nu == null)
continue;
//if (!isKeepEdge(nu))
// continue;
OWLObject nuTarget = nu.getTarget();
//System.out.println(" COMBINED:"+nu);
// check for cycles. this is not as simple as
// checking if we have visited the node, as we are interested
// in different paths to the same node.
// todo - check if there is an existing path to this node
// that is shorter
//if (!visitedSet.contains(nu)) {
boolean isEdgeVisited = false;
if (visitedObjs.contains(nuTarget)) {
// we have potentially visited this edge before
// TODO - this is temporary. need to check edge not node
//isEdgeVisited = true;
//System.out.println("checking to see if visisted "+nu);
//System.out.println(nu.getFinalQuantifiedProperty());
for (OWLGraphEdge ve : visitedMap.get(nuTarget)) {
//System.out.println(" ve:"+ve.getFinalQuantifiedProperty());
if (ve.getFinalQuantifiedProperty().equals(nu.getFinalQuantifiedProperty())) {
//System.out.println("already visited: "+nu);
isEdgeVisited = true;
}
}
if (!isEdgeVisited) {
visitedMap.get(nuTarget).add(nu);
}
}
else {
visitedObjs.add(nuTarget);
visitedMap.put(nuTarget, new HashSet<OWLGraphEdge>());
visitedMap.get(nuTarget).add(nu);
}
if (!isEdgeVisited) {
//System.out.println(" *NOT VISITED:"+nu+" visistedSize:"+visitedSet.size());
if (nu.getTarget() instanceof OWLNamedObject ||
config.isIncludeClassExpressionsInClosure) {
closureSet.add(nu);
}
edgeStack.add(nu);
//visitedSet.add(nu);
}
}
}
if (config.isCacheClosure) {
inferredEdgeBySource.put(s, new HashSet<OWLGraphEdge>(closureSet));
}
profiler.endTaskNotify("getOutgoingEdgesClosure");
return closureSet;
}
/**
* as getOutgoingEdgesClosure(s), but also includes an identity edge
* @param s
* @return set of {@link OWLGraphEdge}
*/
public Set<OWLGraphEdge> getOutgoingEdgesClosureReflexive(OWLObject s) {
Set<OWLGraphEdge> edges = getOutgoingEdgesClosure(s);
edges.add(new OWLGraphEdge(s,s,null,Quantifier.IDENTITY,getSourceOntology()));
return edges;
}
/**
* find the set of classes or class expressions subsuming source, using the graph closure.
*
* this is just the composition of getOutgoingEdgesClosure and edgeToTargetExpression -- the
* latter method "packs" a chain of edges into a class expression
*
* only "linear" expressions are found, corresponding to a path in the graph.
* e.g. [sub,part_of-some,develops_from-some] ==> part_of some (develops_from some t)
*
* if the edge consists entirely of subclass links, the the subsumers will be all
* named classes.
*
* @param s source
* @return set of {@link OWLObject}
*/
public Set<OWLObject> getSubsumersFromClosure(OWLObject s) {
Set<OWLObject> ts = new HashSet<OWLObject>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(s)) {
for (OWLGraphEdge se : getOWLGraphEdgeSubsumers(e)) {
ts.add(edgeToTargetExpression(se));
}
ts.add(edgeToTargetExpression(e));
}
return ts;
}
/**
* See {@link #getIncomingEdgesClosure(OWLObject s, boolean isComplete)}
*
* @param s
* @param isComplete
* @return set of edges
*/
public Set<OWLGraphEdge> getOutgoingEdgesClosure(OWLObject s, boolean isComplete) {
if (isComplete) {
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(s)) {
edges.addAll(getOWLGraphEdgeSubsumers(e));
}
return edges;
}
else {
return getOutgoingEdgesClosure(s);
}
}
/**
* See {@link #getIncomingEdgesClosure(OWLObject s, boolean isComplete)}
*
* @param s
* @return set of edges, never null
*/
public Set<OWLGraphEdge> getCompleteOutgoingEdgesClosure(OWLObject s) {
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(s)) {
edges.addAll(getOWLGraphEdgeSubsumers(e));
}
return edges;
}
/**
* Treats an edge as a path and performs a query.
*
* E.g <x [R SOME] [S SOME] y> will be treated as the class expression
* R SOME (S SOME y)
* @param e
* @return set of {@link OWLObject}, never null
*/
public Set<OWLObject> queryDescendants(OWLGraphEdge e) {
profiler.startTaskNotify("queryDescendants");
Set<OWLObject> results = new HashSet<OWLObject>();
// reflexivity
results.add(this.edgeToTargetExpression(e));
List<OWLQuantifiedProperty> eqpl = e.getQuantifiedPropertyList();
// first find all subclasses of target (todo - optimize)
for (OWLObject d1 : queryDescendants((OWLClassExpression)e.getTarget())) {
//LOG.info(" Q="+d1);
Set<OWLGraphEdge> dEdges = this.getIncomingEdgesClosure(d1, true);
for (OWLGraphEdge dEdge : dEdges) {
List<OWLQuantifiedProperty> dqpl = new Vector<OWLQuantifiedProperty>(dEdge.getQuantifiedPropertyList());
if (dqpl.get(0).isInstanceOf()) {
// the graph path from an individual will start with either
// an instance-of QP, or a property assertion.
// we ignore the instance-of here, as the query is implicitly for individuals
// and classes
dqpl.remove(dqpl.get(0));
}
if (dqpl.equals(eqpl)) {
results.add(dEdge.getSource());
}
}
}
profiler.endTaskNotify("queryDescendants");
return results;
}
/**
* Performs a closed-world query using a DL expression as a set of boolean database-style constraints.
*
* No attempt is made to optimize the query. The engine is incomplete and currently ontology implements
* queries for constructs that use AND, OR, SOME
*
* @param t classExpression
* @return set of descendants
*/
public Set<OWLObject> queryDescendants(OWLClassExpression t) {
return queryDescendants(t, true, true);
}
public Set<OWLObject> queryDescendants(OWLClassExpression t, boolean isInstances, boolean isClasses) {
Set<OWLObject> results = new HashSet<OWLObject>();
results.add(t);
// transitivity and link composition
Set<OWLGraphEdge> dEdges = this.getIncomingEdgesClosure(t, true);
for (OWLGraphEdge dEdge : dEdges) {
if (dEdge.getQuantifiedPropertyList().size() > 1)
continue;
OWLQuantifiedProperty qp = dEdge.getSingleQuantifiedProperty();
if ((isInstances && qp.isInstanceOf()) ||
(isClasses && qp.isSubClassOf()))
results.add(dEdge.getSource());
}
if (t instanceof OWLObjectIntersectionOf) {
Set<OWLObject> iresults = null;
for (OWLClassExpression y : ((OWLObjectIntersectionOf)t).getOperands()) {
if (iresults == null) {
iresults = queryDescendants(y, isInstances, isClasses);
}
else {
if (y instanceof OWLObjectComplementOf) {
// mini-optimization:
// for "A and not B and ...", perform B and remove results from A.
// assumes the NOT precedes the initial operand, and is preferably
// as far to the end as possible.
// this could be easily improved upon, but this functionality
// will eventually be subsumed by reasoners in any case...
OWLClassExpression z = ((OWLObjectComplementOf) y).getOperand();
iresults.removeAll(queryDescendants(z, isInstances, isClasses));
}
else {
iresults.retainAll(queryDescendants(y, isInstances, isClasses));
}
}
}
results.addAll(iresults);
}
else if (t instanceof OWLObjectUnionOf) {
for (OWLClassExpression y : ((OWLObjectUnionOf)t).getOperands()) {
results.addAll(queryDescendants(y, isInstances, isClasses));
}
}
else if (t instanceof OWLRestriction) {
results.addAll(queryDescendants(restrictionToPrimitiveEdge((OWLRestriction) t)));
}
else if (t instanceof OWLObjectComplementOf) {
// NOTE: this is closed-world negation
// TODO: optimize by re-ordering clauses
for (OWLOntology o : getAllOntologies()) {
results.addAll(o.getClassesInSignature(true));
}
results.removeAll(queryDescendants( ((OWLObjectComplementOf) t).getOperand()));
}
// equivalent classes - substitute a named class in the query for an expression
else if (t instanceof OWLClass) {
for (OWLOntology ont : this.getAllOntologies()) {
for (OWLEquivalentClassesAxiom ax : ont.getEquivalentClassesAxioms((OWLClass)t)) {
for (OWLClassExpression y : ax.getClassExpressions()) {
if (y instanceof OWLClass)
continue;
results.addAll(queryDescendants(y, isInstances, isClasses));
}
}
}
}
else {
LOG.error("Cannot handle:"+t);
}
return results;
}
/**
* @param s source
* @param t target
* @return all edges connecting source and target in the graph closure
*/
public Set<OWLGraphEdge> getEdgesBetween(OWLObject s, OWLObject t) {
Set<OWLGraphEdge> allEdges = getOutgoingEdgesClosureReflexive(s);
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : allEdges) {
if (e.getTarget().equals(t))
edges.add(e);
}
return edges;
}
public Set<OWLGraphEdge> getCompleteEdgesBetween(OWLObject s, OWLObject t) {
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : getEdgesBetween(s,t)) {
edges.add(e);
for (OWLGraphEdge se : this.getOWLGraphEdgeSubsumers(e))
edges.add(se);
}
return edges;
}
/**
* returns all ancestors of an object. Here, ancestors is defined as any
* named object that can be reached from x over some path of asserted edges.
* relations are ignored.
*
* @param x source
* @return all reachable target nodes, regardless of edges
*/
public Set<OWLObject> getAncestors(OWLObject x) {
Set<OWLObject> ancs = new HashSet<OWLObject>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(x)) {
ancs.add(e.getTarget());
}
return ancs;
}
/**
* returns all ancestors that can be reached over subclass or
* the specified set of relations
*
* @param x the sourceObject
* @param overProps
* @return set of ancestors
*/
public Set<OWLObject> getAncestors(OWLObject x, Set<OWLPropertyExpression> overProps) {
Set<OWLObject> ancs = new HashSet<OWLObject>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(x)) {
boolean isAddMe = false;
if (overProps != null) {
List<OWLQuantifiedProperty> qps = e.getQuantifiedPropertyList();
if (qps.size() == 0) {
isAddMe = true;
}
else if (qps.size() == 1) {
OWLQuantifiedProperty qp = qps.get(0);
if (qp.isIdentity()) {
isAddMe = true;
}
else if (qp.isSubClassOf()) {
isAddMe = true;
}
else if (qp.isSomeValuesFrom() && overProps.contains(qp.getProperty())) {
isAddMe = true;
}
}
else {
// no add
}
}
else {
isAddMe = true;
}
if (isAddMe)
ancs.add(e.getTarget());
}
return ancs;
}
public Set<OWLObject> getAncestorsReflexive(OWLObject x) {
Set<OWLObject> ancs = getAncestors(x);
ancs.add(x);
return ancs;
}
public Set<OWLObject> getAncestorsReflexive(OWLObject x, Set<OWLPropertyExpression> overProps) {
Set<OWLObject> ancs = getAncestors(x, overProps);
ancs.add(x);
return ancs;
}
/**
* Gets all ancestors that are OWLNamedObjects
*
* i.e. excludes anonymous class expressions
*
* @param x
* @return set of named ancestors
*/
public Set<OWLObject> getNamedAncestors(OWLObject x) {
Set<OWLObject> ancs = new HashSet<OWLObject>();
for (OWLGraphEdge e : getOutgoingEdgesClosure(x)) {
if (e.getTarget() instanceof OWLNamedObject)
ancs.add(e.getTarget());
}
return ancs;
}
public Set<OWLObject> getNamedAncestorsReflexive(OWLObject x) {
Set<OWLObject> ancs = getNamedAncestors(x);
ancs.add(x);
return ancs;
}
/**
* Gets all ancestors and direct descendents (distance == 1) that are OWLNamedObjects.
* i.e. excludes anonymous class expressions
*
* TODO: we're current just doing distance == 1 both up and down
* TODO: a work in progress
* TODO: no distinction in relation types here--we lie to is_a
*
* @param x
* @return set of named ancestors and direct descendents
*/
public OWLShuntGraph getSegmentShuntGraph(OWLObject x) {
// Collection depot.
OWLShuntGraph graphSegment = new OWLShuntGraph();
// Add this node.
String topicID = getIdentifier(x);
String topicLabel = getLabel(x);
OWLShuntNode tn = new OWLShuntNode(topicID, topicLabel);
graphSegment.addNode(tn);
// Next, get all of the named ancestors and add them to our shunt graph.
// TODO: we're currently just doing distance == 1.
// We need some traversal code going up!
for (OWLGraphEdge e : getOutgoingEdges(x)) {
//if( e.getDistance() == 1 ){
OWLObject t = e.getTarget();
if (t instanceof OWLNamedObject){
String objectID = getIdentifier(t);
String objectLabel = getLabel(t);
// Add node.
OWLShuntNode sn = new OWLShuntNode(objectID, objectLabel);
graphSegment.addNode(sn);
//Add edge.
OWLShuntEdge se = new OWLShuntEdge(topicID, objectID);
graphSegment.addEdge(se);
}
}
// Next, get all of the immediate descendents.
// Yes, this could be done more efficiently by reworking
// getIncomingEdgesClosure for our case, but I'm heading towards
// proof on concept right now; optimization later.
// Basically, toss anything that is not of distance 1--we already got
// reflexive above.
for (OWLGraphEdge e : getIncomingEdges(x)) {
//if( e.getDistance() == 1 ){
OWLObject t = e.getSource();
if( t instanceof OWLNamedObject ){
String subjectID = getIdentifier(t);
String subjectLabel = getLabel(t);
// Add node.
OWLShuntNode sn = new OWLShuntNode(subjectID, subjectLabel);
graphSegment.addNode(sn);
//Add edge.
OWLShuntEdge se = new OWLShuntEdge(subjectID, topicID);
graphSegment.addEdge(se);
}
}
return graphSegment;
}
/**
* Return a JSONized version of the output of getSegmentShuntGraph
*
* @param x
* @return String representing part of the OWL graph
*/
public String getSegmentShuntGraphJSON(OWLObject x) {
// Collection depot.
OWLShuntGraph graphSegment = getSegmentShuntGraph(x);
return graphSegment.toJSON();
}
/**
* gets all descendants d of x, where d is reachable by any path. Excludes self
*
* @see #getAncestors
* @see owltools.graph
* @param x
* @return descendant objects
*/
public Set<OWLObject> getDescendants(OWLObject x) {
Set<OWLObject> descs = new HashSet<OWLObject>();
for (OWLGraphEdge e : getIncomingEdgesClosure(x)) {
descs.add(e.getSource());
}
return descs;
}
/**
* gets all reflexive descendants d of x, where d is reachable by any path. Includes self
*
* @see #getAncestors
* @see owltools.graph
* @param x
* @return descendant objects plus x
*/
public Set<OWLObject> getDescendantsReflexive(OWLObject x) {
Set<OWLObject> getDescendants = getDescendants(x);
getDescendants.add(x);
return getDescendants;
}
/**
* return all individuals i where x is reachable from i
* @param x
* @return set of individual {@link OWLObject}s
*/
public Set<OWLObject> getIndividualDescendants(OWLObject x) {
Set<OWLObject> descs = new HashSet<OWLObject>();
for (OWLGraphEdge e : getIncomingEdgesClosure(x)) {
OWLObject s = e.getSource();
if (s instanceof OWLIndividual)
descs.add(s);
}
return descs;
}
/**
* As {@link #getIncomingEdgesClosure(OWLObject t)}, but allows the option of including
* 'complete' edge list. A complete edge list also includes redundant subsuming paths. E.g
*
* if there is a path <x [R some] [S some] y>
* and R' and S' are super-properties of R and S, then there will also be a path
* <x [R' some] [S' some] y>
*
* The default is false, i.e. if the more specific path exists, only it will be returned
*
*
* @param t
* @param isComplete
* @return set of edges
*/
public Set<OWLGraphEdge> getIncomingEdgesClosure(OWLObject t, boolean isComplete) {
if (isComplete) {
Set<OWLGraphEdge> ccs = new HashSet<OWLGraphEdge>();
for (OWLGraphEdge e : getIncomingEdgesClosure(t)) {
ccs.addAll(getOWLGraphEdgeSubsumers(e));
}
return ccs;
}
else {
return getIncomingEdgesClosure(t);
}
}
/**
* gets all inferred edges coming in to the target edge
*
* for every s, if t is reachable from s, then include the inferred edge between s and t.
*
* @see #getOutgoingEdgesClosure
* @param t target
* @return all edges connecting all descendants of target to target
*/
public Set<OWLGraphEdge> getIncomingEdgesClosure(OWLObject t) {
if (config.isCacheClosure) {
if (inferredEdgeByTarget == null)
inferredEdgeByTarget = new HashMap<OWLObject,Set<OWLGraphEdge>>();
if (inferredEdgeByTarget.containsKey(t)) {
return new HashSet<OWLGraphEdge>(inferredEdgeByTarget.get(t));
}
}
profiler.startTaskNotify("getIncomingEdgesClosure");
Stack<OWLGraphEdge> edgeStack = new Stack<OWLGraphEdge>();
Set<OWLGraphEdge> closureSet = new HashSet<OWLGraphEdge>();
//Set<OWLGraphEdge> visitedSet = new HashSet<OWLGraphEdge>();
Set<OWLObject> visitedObjs = new HashSet<OWLObject>();
Map<OWLObject,Set<OWLGraphEdge>> visitedMap = new HashMap<OWLObject,Set<OWLGraphEdge>>();
visitedObjs.add(t);
visitedMap.put(t, new HashSet<OWLGraphEdge>());
// initialize -
// note that edges are always from src to tgt. here we are extending down from tgt to src
//edgeStack.add(new OWLGraphEdge(t,t,ontology,new OWLQuantifiedProperty()));
edgeStack.addAll(getIncomingEdges(t));
closureSet.addAll(edgeStack);
while (!edgeStack.isEmpty()) {
OWLGraphEdge ne = edgeStack.pop();
int nextDist = ne.getDistance() + 1;
// extend down from this edge; e.g. [s, extEdge + ne, tgt]
Set<OWLGraphEdge> extSet = getIncomingEdges(ne.getSource());
for (OWLGraphEdge extEdge : extSet) {
// extEdge o ne --> nu
//OWLGraphEdge nu = combineEdgePairDown(ne, extEdge, nextDist);
OWLGraphEdge nu = combineEdgePair(extEdge.getSource(), extEdge, ne, nextDist);
if (nu == null)
continue;
// TODO - no longer required?
//if (!isKeepEdge(nu))
// continue;
OWLObject nusource = nu.getSource();
boolean isEdgeVisited = false;
if (visitedObjs.contains(nusource)) {
//isEdgeVisited = true;
for (OWLGraphEdge ve : visitedMap.get(nusource)) {
//System.out.println(" ve:"+ve.getFinalQuantifiedProperty());
if (ve.getFirstQuantifiedProperty().equals(nu.getFirstQuantifiedProperty())) {
//System.out.println("already visited: "+nu);
// always favor the shorter path
if (ve.getQuantifiedPropertyList().size() <= nu.getQuantifiedPropertyList().size()) {
isEdgeVisited = true;
}
}
}
if (!isEdgeVisited) {
visitedMap.get(nusource).add(nu);
}
}
else {
visitedObjs.add(nusource);
visitedMap.put(nusource, new HashSet<OWLGraphEdge>());
visitedMap.get(nusource).add(nu);
}
if (!isEdgeVisited) {
if (nu.getSource() instanceof OWLNamedObject ||
config.isIncludeClassExpressionsInClosure) {
closureSet.add(nu);
}
edgeStack.add(nu);
//visitedSet.add(nu);
}
}
}
if (config.isCacheClosure) {
inferredEdgeByTarget.put(t, new HashSet<OWLGraphEdge>(closureSet));
}
profiler.endTaskNotify("getIncomingEdgesClosure");
return closureSet;
}
/**
* Composes two graph edges into a new edge, using axioms in the ontology to determine the correct composition
*
* For example, Edge(x,SUBCLASS_OF,y) * Edge(y,SUBCLASS_OF,z) yields Edge(x,SUBCLASS_OF,z)
*
* Note that property chains of length>2 are currently ignored
*
* @param s - source node
* @param ne - edge 1
* @param extEdge - edge 2
* @param nextDist - new distance
* @return edge
*/
public OWLGraphEdge combineEdgePair(OWLObject s, OWLGraphEdge ne, OWLGraphEdge extEdge, int nextDist) {
//System.out.println("combing edges: "+s+" // "+ne+ " * "+extEdge);
// Create an edge with no edge labels; we will fill the label in later
OWLGraphEdge nu = new OWLGraphEdge(s, extEdge.getTarget());
List<OWLQuantifiedProperty> qpl1 = new Vector<OWLQuantifiedProperty>(ne.getQuantifiedPropertyList());
List<OWLQuantifiedProperty> qpl2 = new Vector<OWLQuantifiedProperty>(extEdge.getQuantifiedPropertyList());
while (qpl1.size() > 0 && qpl2.size() > 0) {
OWLQuantifiedProperty combinedQP = combinedQuantifiedPropertyPair(qpl1.get(qpl1.size()-1),qpl2.get(0));
if (combinedQP == null)
break;
if (isExcluded(combinedQP)) {
return null;
}
qpl1.set(qpl1.size()-1, combinedQP);
if (combinedQP.isIdentity())
qpl1.subList(qpl1.size()-1,qpl1.size()).clear();
qpl2.subList(0, 1).clear();
}
qpl1.addAll(qpl2);
nu.setQuantifiedPropertyList(qpl1);
nu.setDistance(nextDist);
return nu;
}
/**
* combine [srcEdge + tgtEdge]
*
* srcEdge o tgtEdge --> returned edge
*
* @see #combineEdgePair(OWLObject s, OWLGraphEdge ne, OWLGraphEdge extEdge, int nextDist)
* @param tgtEdge
* @param srcEdge
* @param nextDist
* @return edge
*/
private OWLGraphEdge combineEdgePairDown(OWLGraphEdge tgtEdge, OWLGraphEdge srcEdge, int nextDist) {
// fill in edge label later
// todo
OWLGraphEdge nu = new OWLGraphEdge(srcEdge.getSource(), tgtEdge.getTarget());
nu.setDistance(nextDist);
Vector<OWLQuantifiedProperty> qps = new Vector<OWLQuantifiedProperty>();
// put all but the final one in a new list
int n = 0;
int size = tgtEdge.getQuantifiedPropertyList().size();
OWLQuantifiedProperty finalQP = null;
for (OWLQuantifiedProperty qp : tgtEdge.getQuantifiedPropertyList()) {
n++;
if (n > 1)
qps.add(qp);
else
finalQP = qp;
}
// TODO
// join src+tgt edge
OWLQuantifiedProperty combinedQP =
combinedQuantifiedPropertyPair(srcEdge.getFinalQuantifiedProperty(), tgtEdge.getSingleQuantifiedProperty());
//combinedQuantifiedPropertyPair(tgtEdge.getFinalQuantifiedProperty(), srcEdge.getSingleQuantifiedProperty());
if (combinedQP == null) {
qps.add(finalQP);
qps.add(srcEdge.getSingleQuantifiedProperty());
}
else {
qps.add(combinedQP);
}
nu.setQuantifiedPropertyList(qps);
return nu;
}
/**
* Edge composition rules
*
* TODO - property chains of length > 2
* @param x
* @param y
* @return property or null
*/
private OWLQuantifiedProperty combinedQuantifiedPropertyPair(OWLQuantifiedProperty x, OWLQuantifiedProperty y) {
if (x.isSubClassOf() && y.isSubClassOf()) { // TRANSITIVITY OF SUBCLASS
return new OWLQuantifiedProperty(Quantifier.SUBCLASS_OF);
}
else if (x.isInstanceOf() && y.isSubClassOf()) { // INSTANCE OF CLASS IS INSTANCE OF SUPERCLASS
return new OWLQuantifiedProperty(Quantifier.INSTANCE_OF);
}
else if (x.isSubClassOf() && y.isSomeValuesFrom()) { // TRANSITIVITY OF SUBCLASS: existentials
return new OWLQuantifiedProperty(y.getProperty(),Quantifier.SOME);
}
else if (x.isSomeValuesFrom() && y.isSubClassOf()) { // TRANSITIVITY OF SUBCLASS: existentials
return new OWLQuantifiedProperty(x.getProperty(),Quantifier.SOME);
}
else if (x.isSubClassOf() && y.isAllValuesFrom()) {
return new OWLQuantifiedProperty(y.getProperty(),Quantifier.ONLY);
}
else if (x.isAllValuesFrom() && y.isSubClassOf()) {
return new OWLQuantifiedProperty(x.getProperty(),Quantifier.ONLY);
}
else if (x.isSomeValuesFrom() &&
y.isSomeValuesFrom() &&
x.getProperty() != null &&
x.getProperty().equals(y.getProperty()) &&
x.getProperty().isTransitive(sourceOntology)) { // todo
return new OWLQuantifiedProperty(x.getProperty(),Quantifier.SOME);
}
else if (x.isSomeValuesFrom() &&
y.isSomeValuesFrom() &&
chain(x.getProperty(), y.getProperty()) != null) { // TODO: length>2
return new OWLQuantifiedProperty(chain(x.getProperty(), y.getProperty()),Quantifier.SOME);
}
else if (x.isPropertyAssertion() &&
y.isPropertyAssertion() &&
x.getProperty() != null &&
x.getProperty().equals(y.getProperty()) &&
x.getProperty().isTransitive(sourceOntology)) { // todo
return new OWLQuantifiedProperty(x.getProperty(),Quantifier.PROPERTY_ASSERTION);
}
else if (x.isPropertyAssertion() &&
y.isPropertyAssertion() &&
x.getProperty() != null &&
isInverseOfPair(x.getProperty(),y.getProperty())) {
return new OWLQuantifiedProperty(Quantifier.IDENTITY); // TODO - doesn't imply identity for classes
}
else {
// cannot combine - caller will add QP to sequence
return null;
}
}
// true if there is a property chain such that p1 o p2 --> p3, where p3 is returned
private OWLObjectProperty chain(OWLObjectProperty p1, OWLObjectProperty p2) {
if (p1 == null || p2 == null)
return null;
if (getPropertyChainMap().containsKey(p1)) {
for (List<OWLObjectProperty> list : getPropertyChainMap().get(p1)) {
if (p2.equals(list.get(0))) {
return list.get(1);
}
}
}
return null;
}
// TODO - currently hardcoded for simple property chains
Map<OWLObjectProperty,Set<List<OWLObjectProperty>>> pcMap = null;
private Map<OWLObjectProperty,Set<List<OWLObjectProperty>>> getPropertyChainMap() {
if (pcMap == null) {
pcMap = new HashMap<OWLObjectProperty,Set<List<OWLObjectProperty>>>();
for (OWLSubPropertyChainOfAxiom a : sourceOntology.getAxioms(AxiomType.SUB_PROPERTY_CHAIN_OF)) {
//LOG.info("CHAIN:"+a+" // "+a.getPropertyChain().size());
if (a.getPropertyChain().size() == 2) {
OWLObjectPropertyExpression p1 = a.getPropertyChain().get(0);
OWLObjectPropertyExpression p2 = a.getPropertyChain().get(1);
//LOG.info(" xxCHAIN:"+p1+" o "+p2);
if (p1 instanceof OWLObjectProperty && p2 instanceof OWLObjectProperty) {
List<OWLObjectProperty> list = new Vector<OWLObjectProperty>();
list.add((OWLObjectProperty) p2);
list.add((OWLObjectProperty) a.getSuperProperty());
if (!pcMap.containsKey(p1))
pcMap.put((OWLObjectProperty) p1, new HashSet<List<OWLObjectProperty>>());
pcMap.get((OWLObjectProperty) p1).add(list);
//LOG.info(" xxxCHAIN:"+p1+" ... "+list);
}
}
else {
// TODO
}
}
}
return pcMap;
}
private boolean isInverseOfPair(OWLObjectProperty p1, OWLObjectProperty p2) {
for (OWLOntology ont : getAllOntologies()) {
for (OWLInverseObjectPropertiesAxiom a : ont.getInverseObjectPropertyAxioms(p1)) {
if (a.getFirstProperty().equals(p2) ||
a.getSecondProperty().equals(p2)) {
return true;
}
}
}
return false;
}
/**
* Find all edges of the form [i INST c] in the graph closure.
* (this includes both direct assertions, plus assertions to objects
* that link to c via a chain of SubClassOf assertions)
*
* the semantics are the same as inferred ClassAssertion axioms
*
* @param c owlClass
* @return all individuals classified here via basic graph traversal
*/
public Set<OWLIndividual> getInstancesFromClosure(OWLClass c) {
Set<OWLIndividual> ins = new HashSet<OWLIndividual>();
for (OWLOntology o : getAllOntologies()) {
// iterate through all individuals; sequential scan may be slow for
// large knowledge bases
for (OWLIndividual in : o.getIndividualsInSignature()) {
for (OWLGraphEdge e : getEdgesBetween(in, c)) {
List<OWLQuantifiedProperty> qps = e.getQuantifiedPropertyList();
// check for edges of the form < i INSTANCE_OF c >
// we exclude relation chaims, e.g. <i [INSTANCE_OF PART_OF-some] c>
if (qps.size() == 1 && qps.get(0).isInstanceOf()) {
ins.add(in);
break;
}
}
}
}
return ins;
}
/**
* Finds all edges between an instance i and he given class c.
*
* this includes inferred class assertions, as well as chains such as
*
* i has_part j, j inst_of k, k part_of some c
*
* @param c owlClass
* @return all edges in closure between an instance and owlClass
*/
public Set<OWLGraphEdge> getInstanceChainsFromClosure(OWLClass c) {
Set<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>();
for (OWLOntology o : getAllOntologies()) {
// iterate through all individuals; sequential scan may be slow for
// large knowledge bases
for (OWLIndividual in : o.getIndividualsInSignature()) {
edges.addAll(getEdgesBetween(in, c));
}
}
return edges;
}
// BASIC WRAPPER UTILITIES
/**
* fetches all classes, individuals and object properties in all ontologies
*
* @return all named objects
*/
public Set<OWLObject> getAllOWLObjects() {
Set<OWLObject> obs = new HashSet<OWLObject>();
for (OWLOntology o : getAllOntologies()) {
obs.addAll(o.getClassesInSignature());
obs.addAll(o.getIndividualsInSignature());
obs.addAll(o.getObjectPropertiesInSignature());
}
return obs;
}
/**
* fetches the rdfs:label for an OWLObject
*
* assumes zero or one rdfs:label
*
* @param c
* @return label
*/
public String getLabel(OWLObject c) {
return getAnnotationValue(c, getDataFactory().getRDFSLabel());
}
public String getLabelOrDisplayId(OWLObject c) {
String label = getLabel(c);
if (label == null) {
if (c instanceof OWLNamedObject) {
OWLNamedObject nc = (OWLNamedObject)c;
label = nc.getIRI().getFragment();
}
else {
label = c.toString();
}
}
return label;
}
/**
* tests if an OWLObject has been declared obsolete in the source ontology
*
* @param c
* @return boolean
*/
public boolean isObsolete(OWLObject c) {
for (OWLAnnotation ann : ((OWLEntity)c).getAnnotations(getSourceOntology())) {
if (ann.isDeprecatedIRIAnnotation()) {
return true;
}
}
return false;
}
/**
* gets the value of rdfs:comment for an OWLObject
*
* @param c
* @return comment of null
*/
public String getComment(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_COMMENT.getIRI());
return getAnnotationValue(c, lap);
}
/**
* fetches the value of a single-valued annotation property for an OWLObject
*
* TODO: provide a flag that determines behavior in the case of >1 value
*
* @param c
* @param lap
* @return value
*/
public String getAnnotationValue(OWLObject c, OWLAnnotationProperty lap) {
Set<OWLAnnotation>anns = new HashSet<OWLAnnotation>();
if (c instanceof OWLEntity) {
for (OWLOntology ont : getAllOntologies()) {
// TODO : import closure
anns.addAll(((OWLEntity) c).getAnnotations(ont,lap));
}
}
else {
return null;
}
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
return val.getLiteral(); // return first - TODO - check zero or one
}
}
return null;
}
/**
* gets the values of all annotation assertions to an OWLObject for a particular annotation property
*
* @param c
* @param lap
* @return list of values or null
*/
public List<String> getAnnotationValues(OWLObject c, OWLAnnotationProperty lap) {
Set<OWLAnnotation>anns = new HashSet<OWLAnnotation>();
if (c instanceof OWLEntity) {
for (OWLOntology ont : getAllOntologies()) {
anns.addAll(((OWLEntity) c).getAnnotations(ont,lap));
}
}
else {
return null;
}
ArrayList<String> list = new ArrayList<String>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
list.add( val.getLiteral());
}
else if (a.getValue() instanceof IRI) {
IRI val = (IRI)a.getValue();
list.add( getIdentifier(val) );
}
}
return list;
}
/**
* Gets the textual definition of an OWLObject
*
* assumes zero or one def
*
*
* It returns the definition text (encoded as def in obo format and IAO_0000115 annotation property in OWL format) of a class
* @param c
* @return definition
*/
public String getDef(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000115.getIRI());
return getAnnotationValue(c, lap);
}
/**
* It returns the value of the is_metadata_tag tag.
* @param c could OWLClass or OWLObjectProperty
* @return boolean
*/
public boolean getIsMetaTag(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_METADATA_TAG.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the subset tag.
* @param c could OWLClass or OWLObjectProperty
* @return values
*/
// TODO - return set
public List<String> getSubsets(OWLObject c) {
//OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_SUBSET.getTag());
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_OIO_inSubset.getIRI());
return getAnnotationValues(c, lap);
}
/**
* fetches all subset names that are used
*
* @return all subsets used in source ontology
*/
public Set<String> getAllUsedSubsets() {
Set<String> subsets = new HashSet<String>();
for (OWLObject x : getAllOWLObjects()) {
subsets.addAll(getSubsets(x));
}
return subsets;
}
/**
* given a subset name, find all OWLObjects (typically OWLClasses) assigned to that subset
*
* @param subset
* @return set of {@link OWLObject}
*/
public Set<OWLObject> getOWLObjectsInSubset(String subset) {
Set<OWLObject> objs = new HashSet<OWLObject>();
for (OWLObject x : getAllOWLObjects()) {
if (getSubsets(x).contains(subset))
objs.add(x);
}
return objs;
}
/**
* given a subset name, find all OWLClasses assigned to that subset
* @param subset
* @return set of {@link OWLClass}
*/
public Set<OWLClass> getOWLClassesInSubset(String subset) {
Set<OWLClass> objs = new HashSet<OWLClass>();
for (OWLObject x : getAllOWLObjects()) {
if (getSubsets(x).contains(subset) && x instanceof OWLClass)
objs.add((OWLClass) x);
}
return objs;
}
/**
* It returns the value of the domain tag
* @param prop
* @return domain string or null
*/
public String getDomain(OWLObjectProperty prop){
Set<OWLClassExpression> domains = prop.getDomains(ontology);
for(OWLClassExpression ce: domains){
return getIdentifier(ce);
}
return null;
}
/**
* It returns the value of the range tag
* @param prop
* @return range or null
*/
public String getRange(OWLObjectProperty prop){
Set<OWLClassExpression> domains = prop.getRanges(ontology);
for(OWLClassExpression ce: domains){
return getIdentifier(ce);
}
return null;
}
/**
* It returns the values of the replaced_by tag or IAO_0100001 annotation.
* @param c could OWLClass or OWLObjectProperty
* @return list of values
*/
public List<String> getReplacedBy(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0100001.getIRI());
return getAnnotationValues(c, lap);
}
/**
* It returns the values of the consider tag.
*
* @param c could OWLClass or OWLObjectProperty
* @return list of values
*/
public List<String> getConsider(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_CONSIDER.getTag());
return getAnnotationValues(c, lap);
}
/**
* It returns the value of the is-obsolete tag.
* @param c could OWLClass or OWLObjectProperty
* @return boolean
*/
public boolean getIsObsolete(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_OBSELETE.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is-obsolete tag.
* @param c could OWLClass or OWLObjectProperty
* @return String
*/
public String getIsObsoleteBinaryString(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_OBSELETE.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? "false": "true";
//return val;
}
/**
* It returns the values of the alt_id tag
* @param c
* @return list of identifiers
*/
public List<String> getAltIds(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_ALT_ID.getTag());
return getAnnotationValues(c, lap);
}
/**
* It returns the value of the builtin tag
* @param c
* @return boolean
*/
@Deprecated
public boolean getBuiltin(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_BUILTIN.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is_anonymous tag
* @param c
* @return boolean
*/
@Deprecated
public boolean getIsAnonymous(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_ANONYMOUS.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It translates a oboformat tag into an OWL annotation property
* @param tag
* @return {@link OWLAnnotationProperty}
*/
public OWLAnnotationProperty getAnnotationProperty(String tag){
return getDataFactory().getOWLAnnotationProperty(Obo2Owl.trTagToIRI(tag));
}
/**
* It returns the value of the OBO-namespace tag
*
* Example: if the OWLObject is the GO class GO:0008150, this would return "biological_process"
*
* @param c
* @return namespace
*/
public String getNamespace(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_NAMESPACE.getTag());
return getAnnotationValue(c, lap);
}
/**
* It returns the value of the created_by tag
* @param c
* @return value or null
*/
public String getCreatedBy(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_CREATED_BY.getTag());
return getAnnotationValue(c, lap);
}
/**
* It returns the value of the is_anti_symmetric tag or IAO_0000427 annotation
* @param c
* @return boolean
*/
public boolean getIsAntiSymmetric(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000427.getIRI());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
/**
* It returns the value of the is_cyclic tag
* @param c
* @return boolean
*/
public boolean getIsCyclic(OWLObject c) {
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_IS_CYCLIC.getTag());
String val = getAnnotationValue(c, lap);
return val == null ? false: Boolean.valueOf(val);
}
// TODO - fix for multiple ontologies
/**
* true if c is transitive in the source ontology
*
* @param c
* @return boolean
*/
public boolean getIsTransitive(OWLObjectProperty c) {
Set<OWLTransitiveObjectPropertyAxiom> ax = sourceOntology.getTransitiveObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
/**
* true if c is functional in the source ontology
* @param c
* @return boolean
*/
public boolean getIsFunctional(OWLObjectProperty c) {
Set<OWLFunctionalObjectPropertyAxiom> ax = sourceOntology.getFunctionalObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsInverseFunctional(OWLObjectProperty c) {
Set<OWLInverseFunctionalObjectPropertyAxiom> ax = sourceOntology.getInverseFunctionalObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsReflexive(OWLObjectProperty c) {
Set<OWLReflexiveObjectPropertyAxiom> ax = sourceOntology.getReflexiveObjectPropertyAxioms(c);
return ax.size()>0;
}
// TODO - fix for multiple ontologies
public boolean getIsSymmetric(OWLObjectProperty c) {
Set<OWLSymmetricObjectPropertyAxiom> ax = sourceOntology.getSymmetricObjectPropertyAxioms(c);
return ax.size()>0;
}
/**
* returns parent properties of p in all ontologies
* @param p
* @return set of properties
*/
public Set<OWLObjectPropertyExpression> getSuperPropertiesOf(OWLObjectPropertyExpression p) {
Set<OWLObjectPropertyExpression> ps = new HashSet<OWLObjectPropertyExpression>();
for (OWLOntology ont : getAllOntologies()) {
for (OWLSubObjectPropertyOfAxiom a : ont.getObjectSubPropertyAxiomsForSubProperty(p)) {
ps.add(a.getSuperProperty());
}
}
return ps;
}
public Set<OWLObjectPropertyExpression> getSuperPropertyClosureOf(OWLObjectPropertyExpression p) {
Set<OWLObjectPropertyExpression> superProps = new HashSet<OWLObjectPropertyExpression>();
Stack<OWLObjectPropertyExpression> stack = new Stack<OWLObjectPropertyExpression>();
stack.add(p);
while (!stack.isEmpty()) {
OWLObjectPropertyExpression nextProp = stack.pop();
Set<OWLObjectPropertyExpression> directSupers = getSuperPropertiesOf(nextProp);
directSupers.removeAll(superProps);
stack.addAll(directSupers);
superProps.addAll(directSupers);
}
return superProps;
}
public Set<OWLObjectPropertyExpression> getSuperPropertyReflexiveClosureOf(OWLObjectPropertyExpression p) {
Set<OWLObjectPropertyExpression> superProps = getSuperPropertyClosureOf(p);
superProps.add(p);
return superProps;
}
/**
* generalizes over quantified properties
*
* @param e
* @return set of edges
*/
public Set<OWLGraphEdge> getOWLGraphEdgeSubsumers(OWLGraphEdge e) {
return getOWLGraphEdgeSubsumers(e, 0);
}
public Set<OWLGraphEdge> getOWLGraphEdgeSubsumers(OWLGraphEdge e, int i) {
Set<OWLGraphEdge> subsumers = new HashSet<OWLGraphEdge>();
if (i >= e.getQuantifiedPropertyList().size()) {
subsumers.add(new OWLGraphEdge(e.getSource(), e.getTarget(), new Vector<OWLQuantifiedProperty>(), null));
return subsumers;
}
OWLQuantifiedProperty qp = e.getQuantifiedPropertyList().get(i);
Set<OWLQuantifiedProperty> superQps = new HashSet<OWLQuantifiedProperty>();
superQps.add(qp);
OWLObjectProperty p = qp.getProperty();
if (p != null) {
for (OWLObjectPropertyExpression pe : getSuperPropertyClosureOf(p)) {
if (pe.equals(this.getDataFactory().getOWLTopObjectProperty()))
continue;
if (pe instanceof OWLObjectProperty) {
OWLQuantifiedProperty newQp = new OWLQuantifiedProperty(pe, qp.getQuantifier());
if (!isExcluded(newQp)) {
superQps.add(newQp);
}
}
}
}
for (OWLQuantifiedProperty sqp : superQps) {
for (OWLGraphEdge se : getOWLGraphEdgeSubsumers(e, i+1)) {
List<OWLQuantifiedProperty> qpl = new Vector<OWLQuantifiedProperty>();
qpl.add(sqp);
qpl.addAll(se.getQuantifiedPropertyList());
subsumers.add(new OWLGraphEdge(e.getSource(),e.getTarget(),
qpl, e.getOntology()));
}
}
return subsumers;
}
/**
* get the values of of the obo xref tag
*
* @param c
* @return It returns null if no xref annotation is found.
*/
public List<String> getXref(OWLObject c){
OWLAnnotationProperty lap = getAnnotationProperty(OboFormatTag.TAG_XREF.getTag());
Set<OWLAnnotation>anns = null;
if (c instanceof OWLEntity) {
anns = ((OWLEntity) c).getAnnotations(sourceOntology,lap);
}
else {
return null;
}
List<String> list = new ArrayList<String>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
list.add( val.getLiteral()) ;
}
}
return list;
}
/**
* Get the definition xrefs (IAO_0000115)
*
* @param c
* @return list of definition xrefs
*/
public List<String> getDefXref(OWLObject c){
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(Obo2OWLVocabulary.IRI_IAO_0000115.getIRI());
OWLAnnotationProperty xap = getAnnotationProperty(OboFormatTag.TAG_XREF.getTag());
List<String> list = new ArrayList<String>();
if(c instanceof OWLEntity){
for (OWLAnnotationAssertionAxiom oaax :((OWLEntity) c).getAnnotationAssertionAxioms(sourceOntology)){
if(lap.equals(oaax.getProperty())){
for(OWLAnnotation a: oaax.getAnnotations(xap)){
if(a.getValue() instanceof OWLLiteral){
list.add( ((OWLLiteral)a.getValue()).getLiteral() );
}
}
}
}
}
return list;
}
/**
* Return a overlaps with getIsaPartofLabelClosure and stuff in GafSolrDocumentLoader.
* Intended for GOlr loading.
*
* @param c
* @return list of is_partof_closure ids
*/
public Map<String,String> getIsaPartofClosureMap(OWLObject c){
Map<String,String> isa_partof_map = new HashMap<String,String>(); // capture labels/ids
OWLObjectProperty p = getOWLObjectPropertyByIdentifier("BFO:0000050");
Set<OWLPropertyExpression> ps = Collections.singleton((OWLPropertyExpression)p);
Set<OWLObject> ancs = getAncestors(c, ps);
for (OWLObject t : ancs) {
if (! (t instanceof OWLClass)){
continue;
}
String tid = getIdentifier(t);
String tlabel = null;
if (t != null){
tlabel = getLabel(t);
}
if (tlabel != null) {
isa_partof_map.put(tid, tlabel);
}else{
isa_partof_map.put(tid, tid);
}
}
return isa_partof_map;
}
/**
* Return a overlaps with getIsaPartofLabelClosure and stuff in GafSolrDocumentLoader.
* Intended for GOlr loading.
*
* @param c
* @return list of is_partof_closure ids
*/
public List<String> getIsaPartofIDClosure(OWLObject c){
Map<String, String> foo = getIsaPartofClosureMap(c);
List<String> bar = new ArrayList<String>(foo.keySet());
return bar;
}
/**
* Return a overlaps with getIsaPartofIDClosure and stuff in GafSolrDocumentLoader.
* Intended for GOlr loading.
*
* @param c
* @return list of is_partof_closure labels
*/
public List<String> getIsaPartofLabelClosure(OWLObject c){
Map<String, String> foo = getIsaPartofClosureMap(c);
List<String> bar = new ArrayList<String>(foo.values());
return bar;
}
/**
* Return the names of the asserted subClasses of the cls (Class)
* passed in the argument
*
*
* @param cls
* @return array of of strings
*/
@Deprecated
public String[] getSubClassesNames(OWLClass cls){
Set<OWLClassExpression> st = cls.getSubClasses(sourceOntology);
ArrayList<String> ar = new ArrayList<String>();
for(OWLClassExpression ce: st){
if(ce instanceof OWLNamedObject)
ar.add(getLabel(ce));
}
return ar.toArray(new String[ar.size()]);
}
/**
* It returns array of synonyms (is encoded as synonym in obo format and IAO_0000118 annotation property in OWL format) of a class
* @param c
* @return array of strings or null
*/
@Deprecated
public String[] getSynonymStrings(OWLObject c) {
OWLAnnotationProperty lap = getDataFactory().getOWLAnnotationProperty(IRI.create(DEFAULT_IRI_PREFIX + "IAO_0000118"));
Set<OWLAnnotation>anns = null;
if (c instanceof OWLEntity) {
anns = ((OWLEntity) c).getAnnotations(sourceOntology,lap);
}
else {
return null;
}
ArrayList<String> list = new ArrayList<String>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
list.add(val.getLiteral()); // return first - todo - check zero or one
}
}
return list.toArray(new String[list.size()]);
}
/**
* It returns list of synonyms as encoded by OBO2OWL.
*
* @param c
* @return list of synonyms or null
*/
public List<ISynonym> getOBOSynonyms(OWLObject c) {
OWLEntity e;
if (c instanceof OWLEntity) {
e = (OWLEntity) c;
}
else {
return null;
}
List<ISynonym> synonyms = null;
synonyms = merge(synonyms, getOBOSynonyms(e, Obo2OWLVocabulary.IRI_OIO_hasExactSynonym));
synonyms = merge(synonyms, getOBOSynonyms(e, Obo2OWLVocabulary.IRI_OIO_hasRelatedSynonym));
synonyms = merge(synonyms, getOBOSynonyms(e, Obo2OWLVocabulary.IRI_OIO_hasNarrowSynonym));
synonyms = merge(synonyms, getOBOSynonyms(e, Obo2OWLVocabulary.IRI_OIO_hasBroadSynonym));
return synonyms;
}
private <T> List<T> merge(List<T> list1, List<T> list2) {
if (list1 == null || list1.isEmpty()) {
return list2;
}
if (list2 == null || list2.isEmpty()) {
return list1;
}
List<T> synonyms = new ArrayList<T>(list1.size() + list2.size());
synonyms.addAll(list1);
synonyms.addAll(list2);
return synonyms;
}
/**
* It returns String Listof synonyms.
*
* @param c
* @return string list of synonyms
*/
public List<String> getOBOSynonymStrings(OWLObject c) {
List<String> synStrings = new ArrayList<String>();
// Term synonym gathering rather more irritating.
List<ISynonym> syns = getOBOSynonyms(c);
if( syns != null && ! syns.isEmpty() ){
for( ISynonym s : syns ){
String synLabel = s.getLabel();
// Standard neutral synonym.
synStrings.add(synLabel);
// EXPERIMENTAL: scoped synonym label.
//String synScope = s.getScope();
//String synScopeName = "synonym_label_with_scope_" + synScope.toLowerCase();
//cls_doc.addField(synScopeName, synLabel);
}
}
return synStrings;
}
private List<ISynonym> getOBOSynonyms(OWLEntity e, Obo2OWLVocabulary vocabulary) {
// get all synonyms defined in the source ontology
Set<ISynonym> synonymSet = getOBOSynonyms(e, vocabulary, sourceOntology);
// iterate over import closure, as the OWL-API currently doesn't have a
// method get annotations and its axioms from imported ontologies
for(OWLOntology ont : sourceOntology.getImportsClosure()) {
synonymSet = merge(synonymSet, getOBOSynonyms(e, vocabulary, ont));
}
// repeat for support ontologies
for(OWLOntology support : getSupportOntologySet()) {
synonymSet = merge(synonymSet, getOBOSynonyms(e, vocabulary, support));
for(OWLOntology ont : support.getImportsClosure()) {
synonymSet = merge(synonymSet, getOBOSynonyms(e, vocabulary, ont));
}
}
if (synonymSet == null || synonymSet.isEmpty()) {
return null;
}
// sort the result alphabetical
List<ISynonym> synonyms = new ArrayList<ISynonym>(synonymSet);
Collections.sort(synonyms, new Comparator<ISynonym>() {
@Override
public int compare(ISynonym o1, ISynonym o2) {
int cmp = compareStrings(o1.getLabel(), o2.getLabel());
if (cmp == 0) {
cmp = compareStrings(o1.getScope(), o2.getScope());
}
if (cmp == 0) {
cmp = compareStrings(o1.getCategory(), o2.getCategory());
}
return cmp;
}
private int compareStrings(String s1, String s2) {
int cmp = 0;
if (s1 != null) {
if (s2 == null) {
cmp = -1;
}
else {
cmp = s1.compareTo(s2);
}
}
else if (s2 != null) {
cmp = 1;
}
return cmp ;
}
});
return synonyms ;
}
private <T> Set<T> merge(Set<T> set1, Set<T> set2) {
if (set1 == null || set1.isEmpty()) {
return set2;
}
if (set2 == null || set2.isEmpty()) {
return set1;
}
Set<T> synonyms = new HashSet<T>(set1);
synonyms.addAll(set2);
return synonyms;
}
private Set<ISynonym> getOBOSynonyms(OWLEntity e, Obo2OWLVocabulary vocabulary, OWLOntology ont) {
OWLAnnotationProperty property = getDataFactory().getOWLAnnotationProperty(vocabulary.getIRI());
Set<OWLAnnotation> anns = e.getAnnotations(ont, property);
Set<OWLAnnotationAssertionAxiom> annotationAssertionAxioms = e.getAnnotationAssertionAxioms(ont);
if (anns != null && !anns.isEmpty()) {
Set<ISynonym> set = new HashSet<ISynonym>();
for (OWLAnnotation a : anns) {
if (a.getValue() instanceof OWLLiteral) {
OWLLiteral val = (OWLLiteral) a.getValue();
String label = val.getLiteral();
if (label != null && label.length() > 0) {
Set<String> xrefs = getOBOSynonymXrefs(annotationAssertionAxioms, val, property);
Synonym s = new Synonym(label, vocabulary.getMappedTag(), null, xrefs);
set.add(s);
}
}
}
if (!set.isEmpty()) {
return set;
}
}
return null;
}
private Set<String> getOBOSynonymXrefs(Set<OWLAnnotationAssertionAxiom> annotationAssertionAxioms, OWLLiteral val, OWLAnnotationProperty property) {
if (annotationAssertionAxioms == null || annotationAssertionAxioms.isEmpty()) {
return null;
}
Set<String> xrefs = new HashSet<String>();
for (OWLAnnotationAssertionAxiom annotationAssertionAxiom : annotationAssertionAxioms) {
// check if it is the correct property
if (!property.equals(annotationAssertionAxiom.getProperty())) {
continue;
}
// check if its is the corresponding value
if (!val.equals(annotationAssertionAxiom.getValue())) {
continue;
}
Set<OWLAnnotation> annotations = annotationAssertionAxiom.getAnnotations();
for (OWLAnnotation owlAnnotation : annotations) {
if (owlAnnotation.getValue() instanceof OWLLiteral) {
OWLLiteral xrefLiteral = (OWLLiteral) owlAnnotation.getValue();
String xref = xrefLiteral.getLiteral();
xrefs.add(xref);
}
}
}
if (!xrefs.isEmpty()) {
return xrefs;
}
return null;
}
public static interface ISynonym {
/**
* @return the label
*/
public String getLabel();
/**
* @return the scope
*/
public String getScope();
/**
* @return the category
*/
public String getCategory();
/**
* @return the xrefs
*/
public Set<String> getXrefs();
}
public static class Synonym implements ISynonym {
private String label;
private String scope;
private String category;
private Set<String> xrefs;
/**
* @param label
* @param scope
* @param category
* @param xrefs
*/
public Synonym(String label, String scope, String category, Set<String> xrefs) {
super();
this.label = label;
this.scope = scope;
this.category = category;
this.xrefs = xrefs;
}
@Override
public String getLabel() {
return label;
}
@Override
public String getScope() {
return scope;
}
@Override
public String getCategory() {
return category;
}
@Override
public Set<String> getXrefs() {
return xrefs;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Synonym [");
builder.append("label=");
builder.append(label);
if (scope != null) {
builder.append(", scope=");
builder.append(scope);
}
if (category != null) {
builder.append(", category=");
builder.append(category);
}
if (xrefs != null) {
builder.append(", xrefs=");
builder.append(xrefs);
}
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
result = prime * result + ((scope == null) ? 0 : scope.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof ISynonym == false) {
return false;
}
ISynonym other = (ISynonym) obj;
if (label == null) {
if (other.getLabel() != null) {
return false;
}
}
else if (!label.equals(other.getLabel())) {
return false;
}
if (scope == null) {
if (other.getScope() != null) {
return false;
}
}
else if (!scope.equals(other.getScope())) {
return false;
}
if (category == null) {
if (other.getCategory() != null) {
return false;
}
}
else if (!category.equals(other.getCategory())) {
return false;
}
return true;
}
}
/**
* gets the OBO-style ID of the source ontology IRI. E.g. "go"
*
* @return id of source ontology
*/
public String getOntologyId(){
return Owl2Obo.getOntologyId(this.getSourceOntology());
}
/**
* gets the OBO-style ID of the specified object. E.g. "GO:0008150"
*
* @param owlObject
* @return OBO-style identifier, using obo2owl mapping
*/
public String getIdentifier(OWLObject owlObject) {
return Owl2Obo.getIdentifierFromObject(owlObject, this.sourceOntology, null);
}
/**
* gets the OBO-style ID of the specified object. E.g. "GO:0008150"
*
* @param iriId
* @return OBO-style identifier, using obo2owl mapping
*/
public String getIdentifier(IRI iriId) {
return Owl2Obo.getIdentifier(iriId);
}
// TODO - use Obo2Owl.oboIdToIRI()
public IRI getIRIByIdentifier(String id) {
// TODO - provide a static method for doing this
Obo2Owl b = new Obo2Owl();
b.setObodoc(new OBODoc());
return b.oboIdToIRI(id);
}
/**
* Given an OBO-style ID, return the corresponding OWLObject, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return object with id or null
*/
public OWLObject getOWLObjectByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (getOWLClass(iri) != null) {
return getOWLClass(iri);
}
else if (getOWLIndividual(iri) != null) {
return getOWLIndividual(iri);
}
else if (getOWLObjectProperty(iri) != null) {
return getOWLObjectProperty(iri);
}
return null;
}
/**
* Given an OBO-style ID, return the corresponding OWLObjectProperty, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLObjectProperty with id or null
*/
public OWLObjectProperty getOWLObjectPropertyByIdentifier(String id) {
return getDataFactory().getOWLObjectProperty(getIRIByIdentifier(id));
}
/**
* Given an OBO-style ID, return the corresponding OWLNamedIndividual, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLNamedIndividual with id or null
*/
public OWLNamedIndividual getOWLIndividualByIdentifier(String id) {
return getDataFactory().getOWLNamedIndividual(getIRIByIdentifier(id));
}
/**
* Given an OBO-style ID, return the corresponding OWLClass, if it is declared - otherwise null
*
* @param id - e.g. GO:0008150
* @return OWLClass with id or null
*/
public OWLClass getOWLClassByIdentifier(String id) {
IRI iri = getIRIByIdentifier(id);
if (iri != null)
return getOWLClass(iri);
return null;
}
/**
* fetches an OWL Object by rdfs:label
*
* if there is >1 match, return the first one encountered
*
* @param label
* @return object or null
*/
public OWLObject getOWLObjectByLabel(String label) {
IRI iri = getIRIByLabel(label);
if (iri != null)
return getOWLObject(iri);
return null;
}
/**
* fetches an OWL IRI by rdfs:label
*
* @param label
* @return IRI or null
*/
public IRI getIRIByLabel(String label) {
try {
return getIRIByLabel(label, false);
} catch (SharedLabelException e) {
// note that it should be impossible to reach this point
// if getIRIByLabel is called with isEnforceUnivocal = false
e.printStackTrace();
return null;
}
}
/**
* fetches an OWL IRI by rdfs:label, optionally testing for uniqueness
*
* TODO: index labels. This currently scans all labels in the ontology, which is expensive
*
* @param label
* @param isEnforceUnivocal
* @return IRI or null
* @throws SharedLabelException if >1 IRI shares input label
*/
public IRI getIRIByLabel(String label, boolean isEnforceUnivocal) throws SharedLabelException {
IRI iri = null;
for (OWLOntology o : getAllOntologies()) {
Set<OWLAnnotationAssertionAxiom> aas = o.getAxioms(AxiomType.ANNOTATION_ASSERTION);
for (OWLAnnotationAssertionAxiom aa : aas) {
OWLAnnotationValue v = aa.getValue();
OWLAnnotationProperty property = aa.getProperty();
if (property.isLabel() && v instanceof OWLLiteral) {
if (label.equals( ((OWLLiteral)v).getLiteral())) {
OWLAnnotationSubject subject = aa.getSubject();
if (subject instanceof IRI) {
if (isEnforceUnivocal) {
if (iri != null && !iri.equals((IRI)subject)) {
throw new SharedLabelException(label,iri,(IRI)subject);
}
iri = (IRI)subject;
}
else {
return (IRI)subject;
}
}
else {
//return null;
}
}
}
}
}
return iri;
}
/**
* Returns an OWLClass given an IRI string
*
* the class must be declared in either the source ontology, or in a support ontology,
* otherwise null is returned
*
* @param s IRI string
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(String s) {
IRI iri = IRI.create(s);
return getOWLClass(iri);
}
/**
* Returns an OWLClass given an IRI
*
* the class must be declared in either the source ontology, or in a support ontology,
* otherwise null is returned
*
* @param iri
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(IRI iri) {
OWLClass c = getDataFactory().getOWLClass(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(c).size() > 0) {
return c;
}
}
return null;
}
/**
* @param x
* @return {@link OWLClass}
*/
public OWLClass getOWLClass(OWLObject x) {
return getDataFactory().getOWLClass(((OWLNamedObject)x).getIRI());
}
/**
* Returns an OWLNamedIndividual with this IRI <b>if it has been declared</b>
* in the source or support ontologies. Returns null otherwise.
* @param iri
* @return {@link OWLNamedIndividual}
*/
public OWLNamedIndividual getOWLIndividual(IRI iri) {
OWLNamedIndividual c = getDataFactory().getOWLNamedIndividual(iri);
for (OWLOntology o : getAllOntologies()) {
for (OWLDeclarationAxiom da : o.getDeclarationAxioms(c)) {
if (da.getEntity() instanceof OWLNamedIndividual) {
return (OWLNamedIndividual) da.getEntity();
}
}
}
return null;
}
/**
* @see #getOWLIndividual(IRI)
* @param s
* @return {@link OWLNamedIndividual}
*/
public OWLNamedIndividual getOWLIndividual(String s) {
IRI iri = IRI.create(s);
return getOWLIndividual(iri);
}
/**
* Returns the OWLObjectProperty with this IRI
*
* Must have been declared in one of the ontologies
*
* @param iri
* @return {@link OWLObjectProperty}
*/
public OWLObjectProperty getOWLObjectProperty(String iri) {
return getOWLObjectProperty(IRI.create(iri));
}
public OWLObjectProperty getOWLObjectProperty(IRI iri) {
OWLObjectProperty p = getDataFactory().getOWLObjectProperty(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(p).size() > 0) {
return p;
}
}
return null;
}
public OWLAnnotationProperty getOWLAnnotationProperty(IRI iri) {
OWLAnnotationProperty p = getDataFactory().getOWLAnnotationProperty(iri);
for (OWLOntology o : getAllOntologies()) {
if (o.getDeclarationAxioms(p).size() > 0) {
return p;
}
}
return null;
}
public OWLObject getOWLObject(String s) {
return getOWLObject(IRI.create(s));
}
/**
* Returns the OWLObject with this IRI
*
* Must have been declared in one of the ontologies
*
* Currently OWLObject must be one of OWLClass, OWLObjectProperty or OWLNamedIndividual
*
* If the ontology employs punning and there different entities with the same IRI, then
* the order of precedence is OWLClass then OWLObjectProperty then OWLNamedIndividual
*
* @param s entity IRI
* @return {@link OWLObject}
*/
public OWLObject getOWLObject(IRI s) {
OWLObject o;
o = getOWLClass(s);
if (o == null) {
o = getOWLIndividual(s);
}
if (o == null) {
o = getOWLObjectProperty(s);
}
if (o == null) {
o = getOWLAnnotationProperty(s);
}
return o;
}
} |
package travelplanner;
import java.awt.EventQueue;
import javax.swing.JFrame;
import com.toedter.calendar.JCalendar;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.event.ActionEvent;
import com.toedter.calendar.JDateChooser;
public class main {
private JTable table;
private JPanel contentPane;
private JFrame frame;
private JTextField txtCardNr;
private JTextField txtOrigin;
private JTextField txtDestination;
private JTextField usernameField;
private JTextField passwordField;
private JTextField nameField;
private JTextField lastNameField;
private JTextField emailField;
private JTextField passwordConfirmField;
private JTextField txtPrice;
private JTextField txtDate;
private JTextField txtTime;
private JTextField txtDate_2;
private JTextField txtTime_2;
private JTextField txtDepartureTime;
private JTextField txtArrivalTime;
private JTextField txtPricePerSeat;
private SystemController sc = new SystemController();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
main window = new main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public main() {
frame = new JFrame();
initialize(frame);
}
private void initialize(JFrame frame) {
frame.setBounds(100, 100, 723, 540);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
login_register(frame);
txtOrigin = new JTextField();
txtOrigin.setBounds(94, 107, 144, 20);
frame.getContentPane().add(txtOrigin);
txtOrigin.setColumns(10);
txtDestination = new JTextField();
txtDestination.setColumns(10);
txtDestination.setBounds(376, 107, 144, 20);
frame.getContentPane().add(txtDestination);
JLabel lblOrigin = new JLabel("Origin");
lblOrigin.setBounds(94, 82, 46, 14);
frame.getContentPane().add(lblOrigin);
JLabel lblDestination = new JLabel("Destination");
lblDestination.setBounds(376, 82, 138, 14);
frame.getContentPane().add(lblDestination);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//searchGUI test = new searchGUI();
//test.main();
frame.getContentPane().removeAll();
login_register(frame);
search(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
//frame.repaint();
}
});
btnSearch.setBounds(253, 304, 89, 23);
frame.getContentPane().add(btnSearch);
JCheckBox chckbxReturnFlight = new JCheckBox("Return Flight");
chckbxReturnFlight.setBounds(376, 304, 97, 23);
frame.getContentPane().add(chckbxReturnFlight);
JDateChooser dateOrigin = new JDateChooser();
dateOrigin.setBounds(94, 159, 95, 20);
frame.getContentPane().add(dateOrigin);
JDateChooser dateReturn = new JDateChooser();
dateReturn.setEnabled(false);
dateReturn.setBounds(376, 159, 95, 20);
frame.getContentPane().add(dateReturn);
JButton btnAdminTest = new JButton("Admin test");
btnAdminTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
adminMain(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
});
btnAdminTest.setBounds(10, 10, 111, 23);
frame.getContentPane().add(btnAdminTest);
}
public void login_register(JFrame frame){
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
login(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
});
btnLogin.setBounds(391, 11, 89, 21);
frame.getContentPane().add(btnLogin);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
register(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
});
btnRegister.setBounds(489, 11, 89, 21);
frame.getContentPane().add(btnRegister);
}
public void user_logout(JFrame frame){
JLabel lblUser = new JLabel("Welcome User: xxx");
lblUser.setBounds(345, 11, 150, 21);
frame.getContentPane().add(lblUser);
JButton btnRegister = new JButton("Logout");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
initialize(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
});
btnRegister.setBounds(489, 11, 89, 21);
frame.getContentPane().add(btnRegister);
}
public void login(JFrame frame){
contentPane = new JPanel();
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
usernameField = new JTextField();
usernameField.setBounds(127, 107, 196, 20);
frame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(127, 177, 196, 20);
frame.getContentPane().add(passwordField);
passwordField.setColumns(10);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(127, 150, 46, 14);
frame.getContentPane().add(lblPassword);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(127, 74, 78, 14);
frame.getContentPane().add(lblUsername);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
boolean res = sc.login(usernameField.getText(), passwordField.getText());
if (res) {
System.out.println("res true, successfully logged in");
frame.getContentPane().removeAll();
initialize(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
} else {
System.out.println("res false");
frame.getContentPane().removeAll();
initialize(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(loginGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
btnLogin.setBounds(182, 250, 89, 23);
frame.getContentPane().add(btnLogin);
}
public void register(JFrame frame){
contentPane = new JPanel();
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
nameField = new JTextField();
nameField.setBounds(173, 71, 156, 20);
frame.getContentPane().add(nameField);
nameField.setColumns(10);
lastNameField = new JTextField();
lastNameField.setColumns(10);
lastNameField.setBounds(173, 121, 156, 20);
frame.getContentPane().add(lastNameField);
emailField = new JTextField();
emailField.setColumns(10);
emailField.setBounds(173, 175, 156, 20);
frame.getContentPane().add(emailField);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.setBounds(173, 229, 156, 20);
frame.getContentPane().add(passwordField);
passwordConfirmField = new JPasswordField();
passwordConfirmField.setColumns(10);
passwordConfirmField.setBounds(173, 281, 156, 20);
frame.getContentPane().add(passwordConfirmField);
JLabel lblName = new JLabel("Name");
lblName.setBounds(173, 48, 46, 14);
frame.getContentPane().add(lblName);
JLabel lblLastName = new JLabel("Last Name");
lblLastName.setBounds(173, 102, 70, 14);
frame.getContentPane().add(lblLastName);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(173, 150, 46, 14);
frame.getContentPane().add(lblEmail);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(173, 206, 70, 14);
frame.getContentPane().add(lblPassword);
JLabel lblConfirmPassword = new JLabel("Confirm Password");
lblConfirmPassword.setBounds(173, 260, 116, 14);
frame.getContentPane().add(lblConfirmPassword);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (passwordField.getText().equals(passwordConfirmField.getText())) {
try {
sc.register(emailField.getText(), passwordField.getText(), nameField.getText(), lastNameField.getText());
frame.getContentPane().removeAll();
frame.getContentPane().repaint();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(registerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("passwords doesn't match");
}
}
});
btnRegister.setBounds(208, 334, 89, 23);
frame.getContentPane().add(btnRegister);
}
public void search(JFrame frame){
contentPane = new JPanel();
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
JButton btnSearch = new JButton("Search");
btnSearch.setBounds(527, 48, 89, 23);
frame.getContentPane().add(btnSearch);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(66, 82, 550, 321);
frame.getContentPane().add(scrollPane);
DefaultTableModel model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Origin");
model.addColumn("Destination");
model.addColumn("Date");
for(int i = 0; i < 10; i++){
model.insertRow(i,new Object[] {"test","test","test"});
}
scrollPane.setViewportView(table);
txtOrigin = new JTextField();
txtOrigin.setBounds(66, 49, 161, 20);
frame.getContentPane().add(txtOrigin);
txtOrigin.setColumns(10);
txtDestination = new JTextField();
txtDestination.setColumns(10);
txtDestination.setBounds(237, 49, 164, 20);
frame.getContentPane().add(txtDestination);
JDateChooser dateOrigin = new JDateChooser();
dateOrigin.setBounds(411, 49, 95, 20);
frame.getContentPane().add(dateOrigin);
JLabel lblOrigin = new JLabel("Origin");
lblOrigin.setBounds(66, 24, 46, 14);
frame.getContentPane().add(lblOrigin);
JLabel lblDestination = new JLabel("Destination");
lblDestination.setBounds(237, 24, 100, 14);
frame.getContentPane().add(lblDestination);
JButton btnBook = new JButton("Book");
btnBook.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
book(frame);
frame.getContentPane().repaint();
}
});
btnBook.setBounds(280, 424, 89, 23);
frame.getContentPane().add(btnBook);
}
public void book(JFrame frame){
contentPane = new JPanel();
user_logout(frame);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
txtOrigin = new JTextField();
txtOrigin.setBounds(81, 87, 176, 20);
frame.getContentPane().add(txtOrigin);
txtOrigin.setColumns(10);
JTextField txtDestination = new JTextField();
txtDestination.setColumns(10);
txtDestination.setBounds(81, 144, 176, 20);
frame.getContentPane().add(txtDestination);
txtPrice = new JTextField();
txtPrice.setColumns(10);
txtPrice.setBounds(81, 261, 58, 20);
frame.getContentPane().add(txtPrice);
txtDate = new JTextField();
txtDate.setBounds(399, 87, 86, 20);
frame.getContentPane().add(txtDate);
txtDate.setColumns(10);
txtTime = new JTextField();
txtTime.setColumns(10);
txtTime.setBounds(559, 87, 86, 20);
frame.getContentPane().add(txtTime);
txtDate_2 = new JTextField();
txtDate_2.setColumns(10);
txtDate_2.setBounds(399, 144, 86, 20);
frame.getContentPane().add(txtDate_2);
txtTime_2 = new JTextField();
txtTime_2.setColumns(10);
txtTime_2.setBounds(559, 144, 86, 20);
frame.getContentPane().add(txtTime_2);
JLabel lblOrigin = new JLabel("Origin");
lblOrigin.setBounds(81, 62, 46, 14);
frame.getContentPane().add(lblOrigin);
JLabel lblDestination = new JLabel("Destination");
lblDestination.setBounds(81, 118, 136, 14);
frame.getContentPane().add(lblDestination);
JLabel lblEnterPassengers = new JLabel("Enter Nr Of Passengers");
lblEnterPassengers.setBounds(81, 179, 136, 14);
frame.getContentPane().add(lblEnterPassengers);
JLabel lblPrice = new JLabel("Price");
lblPrice.setBounds(81, 235, 46, 14);
frame.getContentPane().add(lblPrice);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(399, 62, 46, 14);
frame.getContentPane().add(lblDate);
JLabel lblDate_2 = new JLabel("Date");
lblDate_2.setBounds(399, 118, 46, 14);
frame.getContentPane().add(lblDate_2);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(559, 62, 46, 14);
frame.getContentPane().add(lblTime);
JLabel lblTime_2 = new JLabel("Time");
lblTime_2.setBounds(559, 119, 46, 14);
frame.getContentPane().add(lblTime_2);
JSpinner spPassengers = new JSpinner();
spPassengers.setEnabled(true);
spPassengers.setBounds(81, 204, 29, 20);
frame.getContentPane().add(spPassengers);
JButton btnBook = new JButton("Book");
btnBook.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
pay(frame);
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
}
});
btnBook.setBounds(278, 362, 89, 23);
frame.getContentPane().add(btnBook);
}
public void pay(JFrame frame){
contentPane = new JPanel();
user_logout(frame);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
JLabel lblPrice = new JLabel("Price:");
lblPrice.setBounds(77, 126, 46, 14);
frame.getContentPane().add(lblPrice);
JLabel lblDisplayPrice = new JLabel("Displaying Price");
lblDisplayPrice.setBounds(161, 126, 162, 14);
frame.getContentPane().add(lblDisplayPrice);
JLabel lblCardNr = new JLabel("Card Nr:");
lblCardNr.setBounds(77, 172, 46, 14);
frame.getContentPane().add(lblCardNr);
txtCardNr = new JTextField();
txtCardNr.setBounds(161, 169, 342, 20);
frame.getContentPane().add(txtCardNr);
txtCardNr.setColumns(10);
JLabel lblReceipt = new JLabel("Receipt sent to:");
lblReceipt.setBounds(77, 222, 150, 14);
frame.getContentPane().add(lblReceipt);
JLabel lblUserEmail = new JLabel("User Email");
lblUserEmail.setBounds(161, 270, 226, 14);
frame.getContentPane().add(lblUserEmail);
JButton btnPay = new JButton("Pay");
btnPay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
initialize(frame);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
btnPay.setBounds(77, 328, 89, 23);
frame.getContentPane().add(btnPay);
}
public void adminMain(JFrame frame){
contentPane = new JPanel();
user_logout(frame);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
txtOrigin = new JTextField();
txtOrigin.setColumns(10);
txtOrigin.setBounds(35, 60, 161, 20);
frame.getContentPane().add(txtOrigin);
JLabel lblOrigin = new JLabel("Origin");
lblOrigin.setBounds(35, 35, 46, 14);
frame.getContentPane().add(lblOrigin);
JLabel lblDestination = new JLabel("Destination");
lblDestination.setBounds(206, 35, 100, 14);
frame.getContentPane().add(lblDestination);
txtDestination = new JTextField();
txtDestination.setColumns(10);
txtDestination.setBounds(206, 60, 164, 20);
frame.getContentPane().add(txtDestination);
JDateChooser dateOrigin = new JDateChooser();
dateOrigin.setBounds(380, 60, 95, 20);
frame.getContentPane().add(dateOrigin);
JButton button = new JButton("Search");
button.setBounds(496, 59, 89, 23);
frame.getContentPane().add(button);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(35, 96, 550, 321);
frame.getContentPane().add(scrollPane);
DefaultTableModel model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Origin");
model.addColumn("Destination");
model.addColumn("Date");
for(int i = 0; i < 10; i++){
model.insertRow(i,new Object[] {"test","test","test"});
}
scrollPane.setViewportView(table);
JButton btnAddFlight = new JButton("Add Flight");
btnAddFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
adminEditAdd(frame);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
btnAddFlight.setBounds(606, 93, 89, 23);
frame.getContentPane().add(btnAddFlight);
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
adminEditAdd(frame);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
btnEdit.setBounds(606, 142, 89, 23);
frame.getContentPane().add(btnEdit);
JButton btnRemove = new JButton("Remove");
btnRemove.setBounds(606, 190, 89, 23);
frame.getContentPane().add(btnRemove);
}
public void adminEditAdd(JFrame frame){
contentPane = new JPanel();
user_logout(frame);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(contentPane);
txtOrigin = new JTextField();
txtOrigin.setBounds(119, 83, 178, 20);
frame.getContentPane().add(txtOrigin);
txtOrigin.setColumns(10);
txtDestination = new JTextField();
txtDestination.setColumns(10);
txtDestination.setBounds(409, 83, 178, 20);
frame.getContentPane().add(txtDestination);
txtDepartureTime = new JTextField();
txtDepartureTime.setColumns(10);
txtDepartureTime.setBounds(119, 191, 178, 20);
frame.getContentPane().add(txtDepartureTime);
txtArrivalTime = new JTextField();
txtArrivalTime.setColumns(10);
txtArrivalTime.setBounds(409, 191, 178, 20);
frame.getContentPane().add(txtArrivalTime);
txtPricePerSeat = new JTextField();
txtPricePerSeat.setColumns(10);
txtPricePerSeat.setBounds(409, 245, 178, 20);
frame.getContentPane().add(txtPricePerSeat);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
adminMain(frame);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
btnSubmit.setBounds(304, 336, 89, 23);
frame.getContentPane().add(btnSubmit);
JDateChooser dateDeparture = new JDateChooser();
dateDeparture.setBounds(119, 135, 178, 20);
frame.getContentPane().add(dateDeparture);
JDateChooser dateArrival = new JDateChooser();
dateArrival.setBounds(409, 135, 178, 20);
frame.getContentPane().add(dateArrival);
JSpinner spNrOfSeats = new JSpinner();
spNrOfSeats.setBounds(119, 245, 89, 20);
frame.getContentPane().add(spNrOfSeats);
JLabel lblOrigin = new JLabel("Origin");
lblOrigin.setBounds(119, 61, 46, 14);
frame.getContentPane().add(lblOrigin);
JLabel lblDestination = new JLabel("Destination");
lblDestination.setBounds(408, 61, 89, 14);
frame.getContentPane().add(lblDestination);
JLabel lblDepartureDate = new JLabel("Departure date");
lblDepartureDate.setBounds(119, 114, 89, 14);
frame.getContentPane().add(lblDepartureDate);
JLabel lblArrivalDate = new JLabel("Arrival Date");
lblArrivalDate.setBounds(409, 110, 151, 14);
frame.getContentPane().add(lblArrivalDate);
JLabel lblDepartureTime = new JLabel("Departure Time");
lblDepartureTime.setBounds(119, 166, 124, 14);
frame.getContentPane().add(lblDepartureTime);
JLabel lblArrivalTime = new JLabel("Arrival Time");
lblArrivalTime.setBounds(409, 166, 124, 14);
frame.getContentPane().add(lblArrivalTime);
JLabel lblSeats = new JLabel("Seats");
lblSeats.setBounds(119, 222, 46, 14);
frame.getContentPane().add(lblSeats);
JLabel lblPricePerSeat = new JLabel("Price per seat");
lblPricePerSeat.setBounds(409, 220, 96, 14);
frame.getContentPane().add(lblPricePerSeat);
}
} |
package org.opendaylight.controller.cluster.databroker.actors.dds;
import akka.actor.ActorRef;
import akka.actor.Status;
import com.google.common.base.Throwables;
import com.google.common.base.Verify;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.StampedLock;
import org.opendaylight.controller.cluster.access.client.BackendInfoResolver;
import org.opendaylight.controller.cluster.access.client.ClientActorBehavior;
import org.opendaylight.controller.cluster.access.client.ClientActorContext;
import org.opendaylight.controller.cluster.access.client.ConnectedClientConnection;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link ClientActorBehavior} acting as an intermediary between the backend actors and the DistributedDataStore
* frontend.
*
* <p>
* This class is not visible outside of this package because it breaks the actor containment. Services provided to
* Java world outside of actor containment are captured in {@link DataStoreClient}.
*
* <p>
* IMPORTANT: this class breaks actor containment via methods implementing {@link DataStoreClient} contract.
* When touching internal state, be mindful of the execution context from which execution context, Actor
* or POJO, is the state being accessed or modified.
*
* <p>
* THREAD SAFETY: this class must always be kept thread-safe, so that both the Actor System thread and the application
* threads can run concurrently. All state transitions must be made in a thread-safe manner. When in
* doubt, feel free to synchronize on this object.
*
* <p>
* PERFORMANCE: this class lies in a performance-critical fast path. All code needs to be concise and efficient, but
* performance must not come at the price of correctness. Any optimizations need to be carefully analyzed
* for correctness and performance impact.
*
* <p>
* TRADE-OFFS: part of the functionality runs in application threads without switching contexts, which makes it ideal
* for performing work and charging applications for it. That has two positive effects:
* - CPU usage is distributed across applications, minimizing work done in the actor thread
* - CPU usage provides back-pressure towards the application.
*
* @author Robert Varga
*/
abstract class AbstractDataStoreClientBehavior extends ClientActorBehavior<ShardBackendInfo>
implements DataStoreClient {
private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStoreClientBehavior.class);
private final Map<LocalHistoryIdentifier, ClientLocalHistory> histories = new ConcurrentHashMap<>();
private final AtomicLong nextHistoryId = new AtomicLong(1);
private final StampedLock lock = new StampedLock();
private final SingleClientHistory singleHistory;
private volatile Throwable aborted;
AbstractDataStoreClientBehavior(final ClientActorContext context,
final BackendInfoResolver<ShardBackendInfo> resolver) {
super(context, resolver);
singleHistory = new SingleClientHistory(this, new LocalHistoryIdentifier(getIdentifier(), 0));
}
// Methods below are invoked from the client actor thread
@Override
protected final void haltClient(final Throwable cause) {
// If we have encountered a previous problem there is no cleanup necessary, as we have already cleaned up
// Thread safely is not an issue, as both this method and any failures are executed from the same (client actor)
// thread.
if (aborted != null) {
abortOperations(cause);
}
}
private void abortOperations(final Throwable cause) {
final long stamp = lock.writeLock();
try {
// This acts as a barrier, application threads check this after they have added an entry in the maps,
// and if they observe aborted being non-null, they will perform their cleanup and not return the handle.
aborted = cause;
for (ClientLocalHistory h : histories.values()) {
h.localAbort(cause);
}
histories.clear();
} finally {
lock.unlockWrite(stamp);
}
}
private AbstractDataStoreClientBehavior shutdown(final ClientActorBehavior<ShardBackendInfo> currentBehavior) {
abortOperations(new IllegalStateException("Client " + getIdentifier() + " has been shut down"));
return null;
}
@Override
protected final AbstractDataStoreClientBehavior onCommand(final Object command) {
if (command instanceof GetClientRequest) {
((GetClientRequest) command).getReplyTo().tell(new Status.Success(this), ActorRef.noSender());
} else {
LOG.warn("{}: ignoring unhandled command {}", persistenceId(), command);
}
return this;
}
/*
* The connection has resolved, which means we have to potentially perform message adaptation. This is a bit more
* involved, as the messages need to be replayed to the individual proxies.
*/
@Override
protected final ConnectionConnectCohort connectionUp(final ConnectedClientConnection<ShardBackendInfo> newConn) {
final long stamp = lock.writeLock();
// Step 1: Freeze all AbstractProxyHistory instances pointing to that shard. This indirectly means that no
// further TransactionProxies can be created and we can safely traverse maps without risking
// missing an entry
final Collection<HistoryReconnectCohort> cohorts = new ArrayList<>();
startReconnect(singleHistory, newConn, cohorts);
for (ClientLocalHistory h : histories.values()) {
startReconnect(h, newConn, cohorts);
}
return previousEntries -> {
try {
// Step 2: Collect previous successful requests from the cohorts. We do not want to expose
// the non-throttling interface to the connection, hence we use a wrapper consumer
for (HistoryReconnectCohort c : cohorts) {
c.replaySuccessfulRequests(previousEntries);
}
// Step 3: Install a forwarder, which will forward requests back to affected cohorts. Any outstanding
// requests will be immediately sent to it and requests being sent concurrently will get
// forwarded once they hit the new connection.
return BouncingReconnectForwarder.forCohorts(newConn, cohorts);
} finally {
try {
// Step 4: Complete switchover of the connection. The cohorts can resume normal operations.
for (HistoryReconnectCohort c : cohorts) {
c.close();
}
} finally {
lock.unlockWrite(stamp);
}
}
};
}
private static void startReconnect(final AbstractClientHistory history,
final ConnectedClientConnection<ShardBackendInfo> newConn,
final Collection<HistoryReconnectCohort> cohorts) {
final HistoryReconnectCohort cohort = history.startReconnect(newConn);
if (cohort != null) {
cohorts.add(cohort);
}
}
// Methods below are invoked from application threads
@Override
public final ClientLocalHistory createLocalHistory() {
final LocalHistoryIdentifier historyId = new LocalHistoryIdentifier(getIdentifier(),
nextHistoryId.getAndIncrement());
final long stamp = lock.readLock();
try {
if (aborted != null) {
throw Throwables.propagate(aborted);
}
final ClientLocalHistory history = new ClientLocalHistory(this, historyId);
LOG.debug("{}: creating a new local history {}", persistenceId(), history);
Verify.verify(histories.put(historyId, history) == null);
return history;
} finally {
lock.unlockRead(stamp);
}
}
@Override
public final ClientTransaction createTransaction() {
return singleHistory.createTransaction();
}
@Override
public final ClientSnapshot createSnapshot() {
return singleHistory.takeSnapshot();
}
@Override
public final void close() {
context().executeInActor(this::shutdown);
}
abstract Long resolveShardForPath(YangInstanceIdentifier path);
} |
package fr.openwide.core.wicket.more.markup.html.basic;
import java.util.Collection;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.model.IModel;
public abstract class AbstractHideableContainer<T extends AbstractHideableContainer<T>> extends WebMarkupContainer {
private static final long serialVersionUID = -4570949966472824133L;
@SuppressWarnings("rawtypes")
private final AbstractHideableBehavior hideableBehavior;
@SuppressWarnings("rawtypes")
protected AbstractHideableContainer(String id, AbstractHideableBehavior hideableBehavior) {
super(id);
this.hideableBehavior = hideableBehavior;
add(hideableBehavior);
}
/**
* @return this as an object of type T
* @see PlaceholderContainer
* @see EnclosureContainer
*/
protected abstract T thisAsT();
@SuppressWarnings("unchecked")
public T collectionModel(IModel<? extends Collection<?>> model) {
hideableBehavior.collectionModel(model);
return thisAsT();
}
/**
* @deprecated Use {@link #collectionModel(IModel)}
*/
@SuppressWarnings("unchecked")
@Deprecated
public T listModel(IModel<? extends List<?>> model) {
hideableBehavior.collectionModel(model);
return thisAsT();
}
@SuppressWarnings("unchecked")
public T model(IModel<?> model) {
hideableBehavior.model(model);
return thisAsT();
}
@SuppressWarnings("unchecked")
public T models(IModel<?>... model) {
hideableBehavior.models(model);
return thisAsT();
}
public T component(Component component) {
hideableBehavior.component(component);
return thisAsT();
}
public T components(Component... component) {
hideableBehavior.components(component);
return thisAsT();
}
} |
package com.camnter.hook.ams.f.service.plugin.host;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.Log;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("DanglingJavadoc")
public final class ProxyServiceManager {
private static final String TAG = ProxyServiceManager.class.getSimpleName();
private static volatile ProxyServiceManager INSTANCE;
// Service
private Map<String, Service> serviceMap = new HashMap<>();
// apk file ServiceInfo
private Map<ComponentName, ServiceInfo> serviceInfoMap = new HashMap<>();
public synchronized static ProxyServiceManager getInstance() {
if (INSTANCE == null) {
INSTANCE = new ProxyServiceManager();
}
return INSTANCE;
}
/**
* Service
* Service new Service
*
* @param rawIntent proxyIntent
* @param startId startId
*/
void onStart(@NonNull final Intent rawIntent,
final int startId) {
// intent ServiceInfo
final ServiceInfo serviceInfo = this.selectPluginService(rawIntent);
if (serviceInfo == null) {
Log.w(TAG, "[ProxyServiceManager] [onStart] can not found service : " +
rawIntent.getComponent());
return;
}
try {
if (!serviceMap.containsKey(serviceInfo.name)) {
// service
this.proxyCreateService(serviceInfo);
}
final Service service = this.serviceMap.get(serviceInfo.name);
service.onStart(rawIntent, startId);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Service
* Service , ProxyService
*
* @param rawIntent rawIntent
* @return int
*/
@SuppressWarnings("UnusedReturnValue")
int onStop(@NonNull final Intent rawIntent) {
// Intent ServiceInfo
final ServiceInfo serviceInfo = selectPluginService(rawIntent);
if (serviceInfo == null) {
Log.w(TAG, "[ProxyServiceManager] [stopService] can not found service: " +
rawIntent.getComponent());
return 0;
}
// ServiceInfo Service
final Service service = this.serviceMap.get(serviceInfo.name);
if (service == null) {
Log.w(TAG,
"[ProxyServiceManager] [stopService] can not running, are you stopped it multi-times?");
return 0;
}
service.onDestroy();
// Service
this.serviceMap.remove(serviceInfo.name);
if (this.serviceMap.isEmpty()) {
Log.d(TAG, "[ProxyServiceManager] [stopService] service all stopped, stop proxy");
final Context appContext = SmartApplication.getContext();
appContext.stopService(new Intent().setComponent(
new ComponentName(appContext.getPackageName(), ProxyService.class.getName())));
}
return 1;
}
/**
* ServiceInfo
*
* @param pluginIntent Intent
* @return intent ServiceInfo
*/
private ServiceInfo selectPluginService(Intent pluginIntent) {
for (ComponentName componentName : this.serviceInfoMap.keySet()) {
if (componentName.equals(pluginIntent.getComponent())) {
return this.serviceInfoMap.get(componentName);
}
}
return null;
}
/**
* ActivityThread # handleCreateService Service
*
* @param serviceInfo service
* @throws Exception exception
*/
@SuppressLint("PrivateApi")
private void proxyCreateService(@NonNull final ServiceInfo serviceInfo) throws Exception {
IBinder token = new Binder();
/**
* ActivityThread # CreateServiceData
*
* CreateServiceData
*
* static final class CreateServiceData {
* IBinder token;
* ServiceInfo info;
* CompatibilityInfo compatInfo;
* Intent intent;
* public String toString() {
* return "CreateServiceData{token=" + token + " className=" + info.name + " packageName=" + info.packageName + " intent=" + intent + "}";
* }
* }
*/
final Class<?> createServiceDataClass = Class.forName(
"android.app.ActivityThread$CreateServiceData");
final Constructor<?> constructor = createServiceDataClass.getDeclaredConstructor();
constructor.setAccessible(true);
final Object createServiceData = constructor.newInstance();
/**
* Hook CreateServiceData # IBinder token
*/
final Field tokenField = createServiceDataClass.getDeclaredField("token");
tokenField.setAccessible(true);
tokenField.set(createServiceData, token);
/**
* Hook CreateServiceData # ServiceInfo info
*
* loadClass
* LoadedApk ClassLoader
* Hook BaseDexClassLoader
*/
serviceInfo.applicationInfo.packageName = SmartApplication.getContext().getPackageName();
final Field infoField = createServiceDataClass.getDeclaredField("info");
infoField.setAccessible(true);
infoField.set(createServiceData, serviceInfo);
final Class<?> compatibilityClass = Class.forName("android.content.res.CompatibilityInfo");
final Field defaultCompatibilityField = compatibilityClass.getDeclaredField(
"DEFAULT_COMPATIBILITY_INFO");
final Object defaultCompatibility = defaultCompatibilityField.get(null);
final Field compatInfoField = createServiceDataClass.getDeclaredField("compatInfo");
compatInfoField.setAccessible(true);
compatInfoField.set(createServiceData, defaultCompatibility);
/**
* ActivityThread
*/
final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
final Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(
"currentActivityThread");
final Object currentActivityThread = currentActivityThreadMethod.invoke(null);
/**
* ActivityThread # handleCreateService(CreateServiceData data)
*/
final Method handleCreateServiceMethod = activityThreadClass.getDeclaredMethod(
"handleCreateService", createServiceDataClass);
handleCreateServiceMethod.setAccessible(true);
handleCreateServiceMethod.invoke(currentActivityThread, createServiceData);
/**
* ActivityThread # handleCreateService(CreateServiceData data) Service
* ActivityThread # mServices
*
* CreateServiceData # IBinder token Service
*/
final Field mServicesField = activityThreadClass.getDeclaredField("mServices");
mServicesField.setAccessible(true);
final Map mServices = (Map) mServicesField.get(currentActivityThread);
final Service service = (Service) mServices.get(token);
/**
* , Service
*
* Service AMS
* Service
*
*
*/
mServices.remove(token);
/**
* Service
*/
serviceMap.put(serviceInfo.name, service);
}
/**
* Apk <service>
*
*
* PackageParser generateServiceInfo
*
* @param apkFile apkFile
* @throws Exception exception
*/
@SuppressLint("PrivateApi")
public void preLoadServices(@NonNull final File apkFile, final Context context)
throws Exception {
/**
* PackageParser # parsePackage(File packageFile, int flags)
*/
final Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser");
final int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
throw new RuntimeException(
"[BaseDexClassLoaderHooker] the sdk version must >= 14 (4.0.0)");
}
final Object packageParser;
final Object packageObject;
final Method parsePackageMethod;
if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
// >= 5.0.0
// parsePackage(File packageFile, int flags)
/**
* PackageParser
*
* PackageParser # parsePackage(File packageFile, int flags)
* apk Package
*/
packageParser = packageParserClass.newInstance();
parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage",
File.class, int.class);
packageObject = parsePackageMethod.invoke(
packageParser,
apkFile,
PackageManager.GET_SERVICES
);
} else {
// >= 4.0.0
// parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)
/**
* PackageParser PackageParser(String archiveSourcePath)
*
* PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)
* apk Package
*/
final String apkFileAbsolutePath = apkFile.getAbsolutePath();
packageParser = packageParserClass.getConstructor(String.class)
.newInstance(apkFileAbsolutePath);
parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage",
File.class, String.class, DisplayMetrics.class, int.class);
packageObject = parsePackageMethod.invoke(
packageParser,
apkFile,
apkFile.getAbsolutePath(),
context.getResources().getDisplayMetrics(),
PackageManager.GET_SERVICES
);
}
if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// >= 4.2.0
// generateServiceInfo(Service s, int flags, PackageUserState state, int userId)
/**
* Package # ArrayList<Service> services
* ArrayList<Service> services Service ServiceInfo
*/
final Field servicesField = packageObject.getClass().getDeclaredField("services");
final List services = (List) servicesField.get(packageObject);
/**
* UserHandle # static @UserIdInt int getCallingUserId()
* userId
*
* PackageUserState
*/
final Class<?> packageParser$ServiceClass = Class.forName(
"android.content.pm.PackageParser$Service");
final Class<?> packageUserStateClass = Class.forName(
"android.content.pm.PackageUserState");
final Class<?> userHandler = Class.forName("android.os.UserHandle");
final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId");
final int userId = (Integer) getCallingUserIdMethod.invoke(null);
final Object defaultUserState = packageUserStateClass.newInstance();
// android.content.pm.PackageParser#generateServiceInfo(Service s, int flags, PackageUserState state, int userId)
Method generateReceiverInfo = packageParserClass.getDeclaredMethod(
"generateServiceInfo",
packageParser$ServiceClass, int.class, packageUserStateClass, int.class);
/**
* PackageParser # generateServiceInfo(Service s, int flags, PackageUserState state, int userId)
* Service ServiceInfo
*
*
*/
for (Object service : services) {
final ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser,
service, 0,
defaultUserState, userId);
this.serviceInfoMap.put(new ComponentName(info.packageName, info.name), info);
}
} else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
// >= 4.1.0
// generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId)
/**
* Package # ArrayList<Service> services
* ArrayList<Service> services Service ServiceInfo
*/
final Field servicesField = packageObject.getClass().getDeclaredField("services");
final List services = (List) servicesField.get(packageObject);
// android.content.pm.PackageParser#generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId)
final Class<?> packageParser$ServiceClass = Class.forName(
"android.content.pm.PackageParser$Service");
final Class<?> userHandler = Class.forName("android.os.UserId");
final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId");
final int userId = (Integer) getCallingUserIdMethod.invoke(null);
Method generateReceiverInfo = packageParserClass.getDeclaredMethod(
"generateServiceInfo",
packageParser$ServiceClass, int.class, boolean.class, int.class, int.class);
/**
* PackageParser # generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId)
* Service ServiceInfo
*
* 4.0.0
* public class PackageParser {
* public final static class Package {
* // User set enabled state.
* public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
*
* // Whether the package has been stopped.
* public boolean mSetStopped = false;
* }
* }
*
*
*/
for (Object service : services) {
final ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser,
service, 0, false, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, userId);
this.serviceInfoMap.put(new ComponentName(info.packageName, info.name), info);
}
} else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// >= 4.0.0
// generateServiceInfo(Service s, int flags)
/**
* Package # ArrayList<Service> services
* ArrayList<Service> services Service ServiceInfo
*/
final Field servicesField = packageObject.getClass().getDeclaredField("services");
final List services = (List) servicesField.get(packageObject);
// android.content.pm.PackageParser#generateServiceInfo(Service s, int flags)
final Class<?> packageParser$ServiceClass = Class.forName(
"android.content.pm.PackageParser$Service");
Method generateReceiverInfo = packageParserClass.getDeclaredMethod(
"generateServiceInfo",
packageParser$ServiceClass, int.class);
/**
* PackageParser # generateServiceInfo(Activity a, int flags)
* Service ServiceInfo
*
*
*/
for (Object service : services) {
final ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser,
service, 0);
this.serviceInfoMap.put(new ComponentName(info.packageName, info.name), info);
}
}
}
} |
package org.epics.pvmanager.util;
import java.util.Date;
import org.epics.util.time.Timestamp;
/**
* Represent a time stamp at nanosecond accuracy. The time is internally stored
* as two values: the UNIX timestamp (number of seconds since
* 1/1/1970) and the nanoseconds past that timestamp. The UNIX timestamp is
* stored as a signed long, which has the range of 292 billion years before
* and another 292 past the epoch.
* <p>
* Note that while TimeStamp are usually created according to system clocks which
* takes into account leap seconds, all the math operations on TimeStamps do
* not take leap seconds into account.
*
* @deprecated this class is being retired in favor of {@link Timestamp}
* @author carcassi
*/
@Deprecated
public class TimeStamp implements Comparable<TimeStamp> {
/*
* When the class is initialized, get the current timestamp and nanotime,
* so that future instances can be calculated from this reference.
*/
private static final TimeStamp base = TimeStamp.timestampOf(new Date());
private static final long baseNano = System.nanoTime();
/**
* Unix timestamp
*/
private final long unixSec;
/**
* Nanoseconds past the timestamp. Must be 0 < nanoSec < 999,999,999
*/
private final int nanoSec;
private TimeStamp(long unixSec, int nanoSec) {
if (nanoSec < 0 || nanoSec > 999999999)
throw new IllegalArgumentException("Nanoseconds cannot be between 0 and 999,999,999");
this.unixSec = unixSec;
this.nanoSec = nanoSec;
}
/**
* Unix time; seconds from midnight 1/1/1970.
* @return unix time
*/
public long getSec() {
return unixSec;
}
/**
* Nanoseconds within the given second.
* @return nanoseconds (0 < nanoSec < 999,999,999)
*/
public long getNanoSec() {
return nanoSec;
}
/**
* Returns a new timestamp from UNIX time.
*
* @param unixSec number of seconds in the UNIX epoch.
* @param nanoSec nanoseconds past the given seconds (must be 0 < nanoSec < 999,999,999)
* @return a new timestamp
*/
public static TimeStamp time(long unixSec, int nanoSec) {
return new TimeStamp(unixSec, nanoSec);
}
/**
* Converts a {@link java.util.Date} to a timestamp. Date is accurate to
* milliseconds, so the last 6 digits are always going to be zeros.
*
* @param date the date to convert
* @return a new timestamp
*/
public static TimeStamp timestampOf(Date date) {
long time = date.getTime();
int nanoSec = (int) (time % 1000) * 1000000;
long epicsSec = (time / 1000);
return time(epicsSec, nanoSec);
}
public static TimeStamp timestampOf(Timestamp timestamp) {
return time(timestamp.getSec(), timestamp.getNanoSec());
}
/**
* Returns a new timestamp for the current instant. The timestamp is calculated
* using {@link java.lang.System#nanoTime()}, so it has the accuracy given
* by that function.
*
* @return a new timestamp
*/
public static TimeStamp now() {
return base.plus(TimeDuration.nanos(System.nanoTime() - baseNano));
}
/**
* Converts the time stamp to a standard Date. The conversion is done once,
* and it trims all precision below milliSec.
*
* @return a date
*/
public Date asDate() {
return new Date((unixSec)*1000+nanoSec/1000000);
}
/**
* Converts to the epics common definition of time.
*/
public Timestamp asTimestamp() {
return Timestamp.of(unixSec, nanoSec);
}
/**
* Null safe way of converting to the epics common definition of time.
*
* @param timeStamp the timeStamp to convert
* @return a new timestamp
*/
public static Timestamp asTimestamp(TimeStamp timeStamp) {
if (timeStamp == null)
return null;
return timeStamp.asTimestamp();
}
@Override
public int hashCode() {
return Long.valueOf(nanoSec).hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TimeStamp) {
TimeStamp other = (TimeStamp) obj;
return other.nanoSec == nanoSec && other.unixSec == unixSec;
}
return false;
}
/**
* Defines the natural ordering for timestamp as forward in time.
*
* @param o another object
* @return comparison result
*/
@Override
public int compareTo(TimeStamp other) {
if (unixSec < other.unixSec) {
return -1;
} else if (unixSec == other.unixSec) {
if (nanoSec < other.nanoSec) {
return -1;
} else if (nanoSec == other.nanoSec) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
/**
* Adds the given duration to this timestamp and returns the result.
* @param duration a time duration
* @return a new timestamp
*/
public TimeStamp plus(TimeDuration duration) {
return createWithCarry(unixSec, nanoSec + duration.getNanoSec());
}
/**
* Creates a new time stamp by carrying nanosecs into seconds if necessary.
*
* @param seconds new seconds
* @param nanos new nanoseconds (can be the whole long range)
* @return the new timestamp
*/
private static TimeStamp createWithCarry(long seconds, long nanos) {
if (nanos > 999999999) {
seconds = seconds + nanos / 1000000000;
nanos = nanos % 1000000000;
}
if (nanos < 0) {
long pastSec = nanos / 1000000000;
pastSec
seconds += pastSec;
nanos -= pastSec * 1000000000;
}
return new TimeStamp(seconds, (int) nanos);
}
/**
* Subtracts the given duration to this timestamp and returns the result.
* @param duration a time duration
* @return a new timestamp
*/
public TimeStamp minus(TimeDuration duration) {
return createWithCarry(unixSec, nanoSec - duration.getNanoSec());
}
@Override
public String toString() {
return unixSec + "." + nanoSec;
}
/**
* Calculates the time passed from the reference to this timeStamp.
* The resulting duration is the absolute value, so it does not matter
* on which object the function is called.
*
* @param reference another time stamp
* @return the duration between the two timeStamps
*/
public TimeDuration durationFrom(TimeStamp reference) {
long nanoSecDiff = reference.nanoSec - nanoSec;
nanoSecDiff += (reference.unixSec - unixSec) * 1000000000;
nanoSecDiff = Math.abs(nanoSecDiff);
return TimeDuration.nanos(nanoSecDiff);
}
} |
package de.cooperate.modeling.graphical.papyrus.extensions.outline;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;
/**
* Provides the content of the Papyrus outline.
*/
public class PapyrusContentProvider implements ITreeContentProvider {
private static class ElementComparator implements Comparator<Element> {
@Override
public int compare(Element o1, Element o2) {
int typeComparison = o1.eClass().getName().compareTo(o2.eClass().getName());
if (typeComparison != 0) {
return typeComparison;
}
String name1 = determineName(o1);
String name2 = determineName(o2);
return name1.compareTo(name2);
}
private static String determineName(Element o1) {
return Optional.of(o1).filter(NamedElement.class::isInstance).map(NamedElement.class::cast)
.map(NamedElement::getName).orElse("");
}
}
private static final Comparator<Element> COMPARATOR = new ElementComparator();
private Collection<EObject> relevantUMLElements = Collections.emptySet();
@Override
public Object[] getElements(Object input) {
Optional<Diagram> diagram = Optional.ofNullable(input).filter(Diagram.class::isInstance)
.map(Diagram.class::cast);
relevantUMLElements = diagram.map(PapyrusContentProvider::getTransitiveViews)
.map(c -> c.stream().map(View::getElement).collect(Collectors.toSet())).orElse(Collections.emptySet());
Optional<Element> diagramRoot = diagram.map(Diagram::getElement).filter(Element.class::isInstance)
.map(Element.class::cast);
if (!diagramRoot.isPresent()) {
return new Object[0];
}
return diagramRoot.get().getOwnedElements().stream().filter(relevantUMLElements::contains).sorted(COMPARATOR)
.collect(Collectors.toList()).toArray();
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof Element) {
return ((Element) parentElement).getOwnedElements().stream().filter(relevantUMLElements::contains)
.sorted(COMPARATOR).toArray();
}
return new Object[0];
}
@Override
public Object getParent(Object element) {
if (element instanceof Element) {
return ((Element) element).getOwner();
}
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof EObject) {
return ((EObject) element).eContents().stream().filter(relevantUMLElements::contains).findAny().isPresent();
}
return false;
}
private static Collection<View> getTransitiveViews(Diagram diagram) {
Collection<View> views = new HashSet<>();
views.add(diagram);
for (TreeIterator<EObject> it = diagram.eAllContents(); it.hasNext();) {
Optional.of(it.next()).filter(View.class::isInstance).map(View.class::cast).ifPresent(views::add);
}
return views;
}
} |
package xyz.hotchpotch.util.stream;
import java.io.Serializable;
import java.util.Objects;
/**
* 2<br>
*
* @param <T> 1
* @param <U> 2
* @author nmby
*/
public class Pair<T, U> implements Serializable {
// ++++++++++++++++ static members ++++++++++++++++
private static final long serialVersionUID = 1L;
/**
* {@code Pair} <br>
*
* @param m1 1{@code null}
* @param m2 2{@code null}
* @return {@code (m1, m2)} {@code Pair}
*/
public static <T, U> Pair<T, U> of(T m1, U m2) {
return new Pair<>(m1, m2);
}
// ++++++++++++++++ instance members ++++++++++++++++
private final T m1;
private final U m2;
private Pair(T m1, U m2) {
this.m1 = m1;
this.m2 = m2;
}
/**
* 1<br>
*
* @return 1
*/
public T m1() {
return m1;
}
/**
* 2<br>
*
* @return 2
*/
public U m2() {
return m2;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Pair) {
Pair<?, ?> p = (Pair<?, ?>) obj;
return Objects.equals(m1, p.m1) && Objects.equals(m2, p.m2);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(m1, m2);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("(%s, %s)", m1, m2);
}
} |
package com.parse.starter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.AlertDialog;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.parse.FunctionCallback;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseUser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
public class ACTMsg extends AppCompatActivity {
private String[] header;
private BroadcastReceiver msgReceiver;
private ParseUser me;
//message file global
private File common_dir;
//display global
private ChatAdapter adapter;
private ListView messagesContainer;
private String msg_filename;
private File msg_file;
static private String conversation_list_filename = "conversation_list.json";
static private File conversation_file;
static Activity activity;
/*Variables for pinch zoom*/
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
private int mode = NONE;
private PointF start, mid;
private float oldDist = 1f;
private Matrix matrix, savedMatrix;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actmsg);
activity = this;
me = ParseUser.getCurrentUser();
Bundle b = this.getIntent().getExtras();
if (b != null)
header = b.getStringArray("ThreadHeader");
TextView headerView = (TextView) findViewById(R.id.msg_thread_header);
headerView.setText( formatHeader() );
//manage files
common_dir = getApplicationContext().getFilesDir();
msg_filename = "MSG_"+header[0]+".json";//todo change this later
msg_file = new File(common_dir, msg_filename);
conversation_file = new File(common_dir, conversation_list_filename);
//read back for testing
//fileRead(conversation_file);
msgReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//... update ui here
String action = intent.getAction();
JSONObject jsonObject;
String content = intent.getExtras().getString("CONTENT");
try {
jsonObject = new JSONObject(content);
} catch (JSONException e) {
e.printStackTrace();
return;
}
if(action.equals("com.parse.favourama.HANDLE_FAVOURAMA_REQUESTS")){
//Hao: do nothing here
}
else if (action.equals("com.parse.favourama.HANDLE_FAVOURAMA_MESSAGES")){
/* HAO
* */
Log.d("MCONTENT", jsonObject.toString());
String chat_content = new String();
String txt_type = new String();
try{
chat_content = jsonObject.getString("content");
txt_type = jsonObject.getString("ctype");
if (txt_type.equals(ChatMessage.PICTURE_TYPE)){
ImageChannel.saveImageToFile(chat_content, getApplicationContext(), activity);
}else{
ChatMessage chatmsg = new ChatMessage();
chatmsg.setId(0);//todo do I need an id?
chatmsg.setMe(false);
chatmsg.setMessage(chat_content);
chatmsg.setMessageType(txt_type);
chatmsg.setDate(DateFormat.getDateTimeInstance().format(new Date()));
displayMessage(chatmsg);
}
}catch(org.json.JSONException e){
e.printStackTrace();
}
//updateDisplay(jsonObject);
}
else if(action.equals("com.parse.favourama.HANDLE_FAVOURAMA_RATINGS")){
/*The action is rating*/
//processRating(jsonObject);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.parse.favourama.HANDLE_FAVOURAMA_REQUESTS");
filter.addAction("com.parse.favourama.HANDLE_FAVOURAMA_MESSAGES");
filter.addAction("com.parse.favourama.HANDLE_FAVOURAMA_RATINGS");
registerReceiver(msgReceiver, filter);
//init
messagesContainer = (ListView) findViewById(R.id.messagesContainer);
adapter = new ChatAdapter(ACTMsg.this, new ArrayList<ChatMessage>());
messagesContainer.setAdapter(adapter);
//reconstruct old messages, checking to prevent filenotfound error
if(msg_file.length()!=0){
msg_reconstruct();
}
matrix = new Matrix();
savedMatrix = new Matrix();
start = new PointF();
mid = new PointF();
}
@Override
public void onPause() {
StarterApplication.activityPaused();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
StarterApplication.activityResumed();
StarterApplication.setInMessage();
StarterApplication.setToWhom(header[0]);
}
public void onClickSend(View view) {
EditText editText = (EditText) findViewById(R.id.typing_box);
String content = editText.getText().toString();
if( content == null || content.isEmpty() ){
return;
}
JSONObject msg = new JSONObject();
try {
msg.put("TYPE", "MESSAGE");
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("ctype", ChatMessage.TEXT_TYPE);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("content", content);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("time", DateFormat.getDateTimeInstance().format(new Date()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("username", me.getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("destination", header[0]);
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("TYPE", "MESSAGE");
params.put("ctype", ChatMessage.TEXT_TYPE);
params.put("content", content);
params.put("time", DateFormat.getDateTimeInstance().format(new Date()));
params.put("destination", header[0]);
params.put("username", me.getUsername());
params.put("rating", me.get("Rating"));
Log.d("RATING", " " + me.get("Rating"));
ParseCloud.callFunctionInBackground("sendMessageToUser", params, new FunctionCallback<String>() {
public void done(String success, ParseException e) {
if (e == null) {
Log.d("push", "Message Sent!");
} else {
Log.d("push", "Message failure >_< \n" + "Plese check your internet connection!\n"
+ e.getMessage() + " <><><><><><> Code: " + e.getCode());
}
}
});
editText.getText().clear();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//update screen
ChatMessage chatmsg = new ChatMessage();
chatmsg.setId(0);//todo do I need an id?
chatmsg.setMe(true);
chatmsg.setMessage(content);
chatmsg.setMessageType(ChatMessage.TEXT_TYPE);
chatmsg.setDate(DateFormat.getDateTimeInstance().format(new Date()));
displayMessage(chatmsg);
updateDisplay(msg);
}
public void backToMain(View view) {
unregisterReceiver(msgReceiver);
Intent result = new Intent();
setResult(Activity.RESULT_OK, result);
finish();
}
// public String formatHeader(){
// String res = "In Regards to:\n" + header[0] + ": " + header[2];
// return res;
public String formatHeader(){
String res = header[0];
return res;
}
public void updateDisplay(JSONObject jsonObject){
/*HAO to Jeremy:
* This function is where you implement updating the display and/or
* writing to files which store conversation threads,
* Check if the incoming message is for the current chat thread or other threads and act differently*/
//make sure not to change the original value
String[] namesToWrite = {"TYPE","content","ctype","time","username"};
JSONObject jsonObjectToWrite = null;
try {
jsonObjectToWrite = new JSONObject(jsonObject, namesToWrite);
}catch(JSONException e){
e.printStackTrace();
}
//write to file
MyThreads.fileWrite(jsonObjectToWrite, msg_filename, this);
//read back for testing
//fileRead(msg_file);
}
private void msg_reconstruct(){
/*Hao: use linkedlist for better performance*/
LinkedList<JSONObject> jsonObjectArrayList = new LinkedList<>();
LinkedList<ChatMessage> chatMessageArrayList = new LinkedList<>();
/*Hao: Code has been refactored to be more extensive, and has better structure*/
MyThreads.readLine(msg_file, jsonObjectArrayList, this);
for(int i=0; i<jsonObjectArrayList.size(); i++){
JSONObject jObject = jsonObjectArrayList.get(i);
ChatMessage msg = new ChatMessage();
msg.setId(i);
String theOtherPersonUsername = header[0];
String username_read = null;
try {
username_read = jObject.get("username").toString();
}catch(JSONException e){
e.printStackTrace();
}
if( username_read.equals(theOtherPersonUsername) ){
msg.setMe(false);
}else{
msg.setMe(true);
}
try {
msg.setMessage(jObject.get("content").toString());
}catch(JSONException e){
e.printStackTrace();
}
try {
msg.setMessageType(jObject.get("ctype").toString());
}catch(JSONException e){
e.printStackTrace();
}
try {
msg.setDate(jObject.get("time").toString());
}catch(JSONException e){
e.printStackTrace();
}
chatMessageArrayList.add(msg);
}
for (ChatMessage msgToDisplay:chatMessageArrayList){
displayMessage(msgToDisplay);
}
}
private void displayMessage(ChatMessage message) {
adapter.add(message);
adapter.notifyDataSetChanged();
/*scroll();*/
}
//TO HAO: My read function for reading entire file, testing purposes
public void rateFavour(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if( !MyThreads.isRatable(common_dir, header[0]) ){
builder.setMessage("Sorry, you have already rated this user for this request, you cannot rate again.");
AlertDialog error = builder.create();
error.show();
return;
}
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.rating_dialog, null))
// Add action buttons
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Remove ratable indicator, cannot rate again
MyThreads.removeRatable(common_dir, header[0]);
RatingBar ratingBar = (RatingBar) ((AlertDialog)dialog).findViewById(R.id.rate_user);
float rating = ratingBar.getRating();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("TYPE", "RATING");
params.put("Rating", rating);
params.put("username", header[0]);
ParseCloud.callFunctionInBackground("RateUser", params, new FunctionCallback<String>() {
public void done(String success, ParseException e) {
if (e == null) {
Log.d("push", "Rating Sent!");
} else {
Log.d("push", "Rating failure >_< \n" + "Plese check your internet connection!\n"
+ e.getMessage() + " <><><><><><> Code: " + e.getCode());
}
}
});
/*dialog.dismiss();*/
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*dialog.dismiss();*/
}
});
final AlertDialog rdialog = builder.create();
rdialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button pb = rdialog.getButton(DialogInterface.BUTTON_POSITIVE);
pb.setTextColor(0xffcaaaaa);
Button nb = rdialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nb.setTextColor(0xff000000);
nb.setTextColor(0xff000000);
}
});
rdialog.show();
}
public void send_picture(View view) {
CropImage.startPickImageActivity(this);
}
public void confirmSendPic(final Bitmap bitmap){
LayoutInflater inflater = this.getLayoutInflater();
View fullView = inflater.inflate(R.layout.image_popup, null, false);
ImageView dView = ((ImageView) fullView.findViewById(R.id.image_full_screen));
dView.setImageBitmap(bitmap);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(fullView)
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ImageChannel.makeImageBox(bitmap, activity);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*Do nothing*/
}
});
AlertDialog fullImage = builder.create();
fullImage.show();
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentUri.getPath();
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == AppCompatActivity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
String imgPath = getRealPathFromURI(this, imageUri);
Log.d("RPATH", imgPath);
Bitmap bitmap = ImageChannel.decodeScaledDownBitmap(imgPath);
confirmSendPic(bitmap);
}
}
public void SendPictureHelper(String imageID) {
/*String url was previous paramter*/
JSONObject msg = new JSONObject();
try {
msg.put("TYPE", "MESSAGE");
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("ctype", ChatMessage.PICTURE_TYPE);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("content", imageID);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("time", DateFormat.getDateTimeInstance().format(new Date()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("username", me.getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg.put("destination", header[0]);
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("TYPE", "MESSAGE");
params.put("ctype", ChatMessage.PICTURE_TYPE);
params.put("content", imageID);
params.put("time", DateFormat.getDateTimeInstance().format(new Date()));
params.put("username", me.getUsername());
params.put("destination", header[0]);
params.put("rating", me.get("Rating"));
ParseCloud.callFunctionInBackground("sendMessageToUser", params, new FunctionCallback<String>() {
public void done(String success, ParseException e) {
if (e == null) {
Log.d("push", "Message Sent!");
} else {
Log.d("push", "Message failure >_< \n" + "Plese check your internet connection!\n"
+ e.getMessage() + " <><><><><><> Code: " + e.getCode());
}
}
});
//For testing purposes currently
ChatMessage chatmsg = new ChatMessage();
chatmsg.setId(0);//todo do I need an id?
chatmsg.setMe(true);
chatmsg.setMessage(imageID);
chatmsg.setMessageType(ChatMessage.PICTURE_TYPE);
chatmsg.setDate(DateFormat.getDateTimeInstance().format(new Date()));
displayMessage(chatmsg);
updateDisplay(msg);
}
public void chat_show_image(String chat_content, String txt_type){
ChatMessage chatmsg = new ChatMessage();
chatmsg.setId(0);//todo do I need an id?
chatmsg.setMe(false);
chatmsg.setMessage(chat_content);
chatmsg.setMessageType(txt_type);
chatmsg.setDate(DateFormat.getDateTimeInstance().format(new Date()));
displayMessage(chatmsg);
}
public void fullScreenDisplay(View view) {
//Get screen size
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Drawable image = ((ImageView) view).getDrawable();
double sw = (double) view.getWidth();
double sh = (double) view.getHeight();
double scale = (width/sw > height/sh)? height/sh : width/sw;
Log.d("IMGSize", "Ori: " + sw + " " + sh + ", " + "Scale: " + scale);
double fw = sw*scale;
double fh = sh*scale;
LayoutInflater inflater = this.getLayoutInflater();
View fullView = inflater.inflate(R.layout.image_popup, null, false);
ImageView dView = ((ImageView) fullView.findViewById(R.id.image_full_screen));
dView.setImageDrawable(image);
dView.getLayoutParams().width = (int) fw;
dView.getLayoutParams().height = (int) fh;
/*Initial scaling*/
matrix.reset();
matrix.postScale((float) scale, (float) scale);
dView.setImageMatrix(matrix);
dView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() != R.id.image_full_screen){
return false;
}
ImageView view = (ImageView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
Log.d("ONTOUCH", "Entering onTouch...");
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
// Leaves a red canvas behind, need to fix this
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y);
} else if (mode == ZOOM) {
float newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
view.setImageMatrix(matrix);
return true;
}
});
Log.d("IMGSize", "Final: " + fw + " " + fh + ", " + "Window width: " + width);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(fullView);
AlertDialog fullImage = builder.create();
fullImage.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = fullImage.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lp.copyFrom(window.getAttributes());
lp.width = (int) fw;
lp.height = (int) fh;
window.setAttributes(lp);
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
} |
package io.subutai.core.hubmanager.impl.environment.state.build;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Maps;
import io.subutai.common.environment.Environment;
import io.subutai.common.environment.EnvironmentNotFoundException;
import io.subutai.common.environment.HostAddresses;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.EnvironmentId;
import io.subutai.common.peer.HostNotFoundException;
import io.subutai.common.peer.Peer;
import io.subutai.common.security.SshKey;
import io.subutai.common.security.SshKeys;
import io.subutai.common.settings.Common;
import io.subutai.core.hubmanager.api.RestResult;
import io.subutai.core.hubmanager.api.exception.HubManagerException;
import io.subutai.core.hubmanager.impl.environment.state.Context;
import io.subutai.core.hubmanager.impl.environment.state.StateHandler;
import io.subutai.hub.share.dto.environment.EnvironmentDto;
import io.subutai.hub.share.dto.environment.EnvironmentNodeDto;
import io.subutai.hub.share.dto.environment.EnvironmentNodesDto;
import io.subutai.hub.share.dto.environment.EnvironmentPeerDto;
import io.subutai.hub.share.dto.environment.SSHKeyDto;
public class ConfigureContainerStateHandler extends StateHandler
{
public ConfigureContainerStateHandler( Context ctx )
{
super( ctx, "Containers configuration" );
}
@Override
protected Object doHandle( EnvironmentPeerDto peerDto ) throws HubManagerException
{
try
{
logStart();
EnvironmentDto envDto =
ctx.restClient.getStrict( path( "/rest/v1/environments/%s", peerDto ), EnvironmentDto.class );
peerDto = configureSsh( peerDto, envDto );
configureHosts( envDto );
changeHostNames( envDto );
setQuotas( envDto );
logEnd();
return peerDto;
}
catch ( Exception e )
{
throw new HubManagerException( e );
}
}
@Override
protected RestResult<Object> post( EnvironmentPeerDto peerDto, Object body )
{
return ctx.restClient.post( path( "/rest/v1/environments/%s/container", peerDto ), body );
}
private EnvironmentPeerDto configureSsh( EnvironmentPeerDto peerDto, EnvironmentDto envDto )
throws HubManagerException
{
try
{
EnvironmentId envId = new EnvironmentId( envDto.getId() );
Environment environment = null;
try
{
environment = ctx.envManager.loadEnvironment( envDto.getId() );
}
catch ( EnvironmentNotFoundException e )
{
log.info( e.getMessage() );
}
boolean isSsEnv = environment != null && !Common.HUB_ID.equals( environment.getPeerId() );
Set<String> peerSshKeys = getCurrentSshKeys( envId, isSsEnv );
Set<String> hubSshKeys = new HashSet<>();
for ( EnvironmentNodesDto nodesDto : envDto.getNodes() )
{
for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() )
{
if ( nodeDto.getSshKeys() != null )
{
hubSshKeys.addAll( trim( nodeDto.getSshKeys() ) );
}
}
}
//remove obsolete keys
Set<String> obsoleteKeys = new HashSet<>();
obsoleteKeys.addAll( peerSshKeys );
obsoleteKeys.removeAll( hubSshKeys );
removeKeys( envId, obsoleteKeys, isSsEnv );
//add new keys
Set<String> newKeys = new HashSet<>();
if ( isSsEnv )
{
//for SS env no need to duplicate keys, it will add to Environment entity
hubSshKeys.removeAll( peerSshKeys );
}
newKeys.addAll( hubSshKeys );
if ( newKeys.isEmpty() )
{
return peerDto;
}
final SshKeys sshKeys = new SshKeys();
sshKeys.addStringKeys( newKeys );
if ( isSsEnv )
{
Set<Peer> peers = environment.getPeers();
for ( final Peer peer : peers )
{
if ( peer.isOnline() )
{
peer.configureSshInEnvironment( environment.getEnvironmentId(), sshKeys );
//add peer to dto
for ( SSHKeyDto sshKeyDto : peerDto.getEnvironmentInfo().getSshKeys() )
{
sshKeyDto.addConfiguredPeer( peer.getId() );
}
}
}
for ( SshKey sshKey : sshKeys.getKeys() )
{
ctx.envManager.addSshKeyToEnvironmentEntity( environment.getId(), sshKey.getPublicKey() );
}
}
else
{
ctx.localPeer.configureSshInEnvironment( envId, sshKeys );
//add peer to dto
for ( SSHKeyDto sshKeyDto : peerDto.getEnvironmentInfo().getSshKeys() )
{
sshKeyDto.addConfiguredPeer( ctx.localPeer.getId() );
}
}
return peerDto;
}
catch ( Exception e )
{
throw new HubManagerException( e );
}
}
private Set<String> trim( final Set<String> sshKeys )
{
Set<String> trimmed = new HashSet<>();
if ( sshKeys != null && !sshKeys.isEmpty() )
{
for ( String sshKey : sshKeys )
{
trimmed.add( sshKey.trim() );
}
}
return trimmed;
}
private void removeKeys( EnvironmentId envId, Set<String> obsoleteKeys, boolean isSsEnv )
{
try
{
for ( String obsoleteKey : obsoleteKeys )
{
if ( isSsEnv )
{
ctx.envManager.removeSshKey( envId.getId(), obsoleteKey, false );
}
else
{
ctx.localPeer.removeFromAuthorizedKeys( envId, obsoleteKey );
}
}
}
catch ( Exception e )
{
log.error( "Error removing ssh key: {}", e.getMessage() );
}
}
private Set<String> getCurrentSshKeys( EnvironmentId envId, boolean isSsEnv )
{
Set<String> currentKeys = new HashSet<>();
try
{
Set<ContainerHost> containers = new HashSet<>();
if ( isSsEnv )
{
Environment environment = ctx.envManager.loadEnvironment( envId.getId() );
containers.addAll( environment.getContainerHosts() );
}
else
{
containers.addAll( ctx.localPeer.findContainersByEnvironmentId( envId.getId() ) );
}
for ( ContainerHost containerHost : containers )
{
SshKeys sshKeys = containerHost.getPeer().getContainerAuthorizedKeys( containerHost.getContainerId() );
for ( SshKey sshKey : sshKeys.getKeys() )
{
currentKeys.add( sshKey.getPublicKey() );
}
}
}
catch ( Exception e )
{
log.error( "Error getting env ssh keys: {}", e.getMessage() );
}
return currentKeys;
}
private void configureHosts( EnvironmentDto envDto )
{
log.info( "Configuring hosts:" );
// <hostname, IPs>
final Map<String, String> hostAddresses = Maps.newHashMap();
for ( EnvironmentNodesDto nodesDto : envDto.getNodes() )
{
for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() )
{
log.info( "- noteDto: containerId={}, containerName={}, hostname={}, state={}",
nodeDto.getContainerId(), nodeDto.getContainerName(), nodeDto.getHostName(),
nodeDto.getState() );
// Remove network mask "/24" in IP
String ip = StringUtils.substringBefore( nodeDto.getIp(), "/" );
hostAddresses.put( nodeDto.getHostName(), ip );
}
}
try
{
ctx.localPeer.configureHostsInEnvironment( new EnvironmentId( envDto.getId() ),
new HostAddresses( hostAddresses ) );
}
catch ( Exception e )
{
log.error( "Error configuring hosts: {}", e.getMessage() );
}
}
private void changeHostNames( EnvironmentDto envDto )
{
for ( EnvironmentNodesDto nodesDto : envDto.getNodes() )
{
for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() )
{
try
{
ContainerHost ch = ctx.localPeer.getContainerHostById( nodeDto.getContainerId() );
if ( !ch.getHostname().equals( nodeDto.getHostName() ) )
{
ctx.localPeer.setContainerHostname( ch.getContainerId(), nodeDto.getHostName() );
}
}
catch ( HostNotFoundException ignore )
{
//this is a remote container
//no-op
}
catch ( Exception e )
{
log.error( "Error configuring hostnames: {}", e.getMessage() );
}
}
}
}
private void setQuotas( EnvironmentDto envDto )
{
for ( EnvironmentNodesDto nodesDto : envDto.getNodes() )
{
for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() )
{
try
{
ContainerHost ch = ctx.localPeer.getContainerHostById( nodeDto.getContainerId() );
ctx.localPeer.setQuota( ch.getContainerId(), nodeDto.getContainerQuota() );
}
catch ( HostNotFoundException ignore )
{
//this is a remote container
//no-op
}
catch ( Exception e )
{
log.error( "Error setting quotas: {}", e.getMessage() );
}
}
}
}
} |
package fr.openwide.core.jpa.more.business.link.service;
import io.mola.galimatias.GalimatiasParseException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkErrorType;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkStatus;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkWrapper;
import fr.openwide.core.spring.config.CoreConfigurer;
@Service("externalLinkCheckerService")
public class ExternalLinkCheckerServiceImpl implements IExternalLinkCheckerService {
private static final Logger LOGGER = LoggerFactory.getLogger(ExternalLinkCheckerServiceImpl.class);
@Autowired
private IExternalLinkWrapperService externalLinkWrapperService;
@Autowired
private ConfigurableApplicationContext applicationContext;
@Autowired
private CoreConfigurer configurer;
private CloseableHttpClient httpClient = null;
/**
* we can put here some URLs known to fail. Otherwise, it's better to do it directly in the application.
*/
private List<Pattern> ignorePatterns = Lists.newArrayList(
);
@PostConstruct
private void initialize() {
RequestConfig requestConfig = RequestConfig.custom()
.setMaxRedirects(configurer.getExternalLinkCheckerMaxRedirects())
.setSocketTimeout(configurer.getExternalLinkCheckerTimeout())
.setConnectionRequestTimeout(configurer.getExternalLinkCheckerTimeout())
.setConnectTimeout(configurer.getExternalLinkCheckerTimeout())
.setStaleConnectionCheckEnabled(true)
.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
.build();
httpClient = HttpClientBuilder.create()
.setUserAgent(configurer.getExternalLinkCheckerUserAgent())
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(Lists.newArrayList(
new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE),
new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"),
new BasicHeader("Accept-Language", "fr,en;q=0.8,fr-fr;q=0.6,en-us;q=0.4,en-gb;q=0.2")
))
.build();
}
@PreDestroy
private void destroy() {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("Unable to close the HTTP client", e);
}
}
}
// Public methods
@Override
public void checkBatch() throws ServiceException, SecurityServiceException {
List<ExternalLinkWrapper> links = externalLinkWrapperService.listNextCheckingBatch(configurer.getExternalLinkCheckerBatchSize());
runTasksInParallel(createTasksByDomain(links), 10, TimeUnit.HOURS);
}
@Override
public void checkLink(final ExternalLinkWrapper link) throws ServiceException, SecurityServiceException {
try {
io.mola.galimatias.URL url = io.mola.galimatias.URL.parse(link.getUrl());
checkLinksWithSameUrl(url, ImmutableList.of(link));
} catch (GalimatiasParseException e) {
markAsInvalid(link);
}
}
@Override
public void checkLinksWithSameUrl(io.mola.galimatias.URL url, Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException {
StatusLine httpStatus = null;
ExternalLinkErrorType errorType = null;
// Special casing the ignore patterns
for (Pattern pattern : ignorePatterns) {
if (pattern.matcher(url.toHumanString()).matches()) {
markAsIgnored(links);
return;
}
}
URI uri;
try {
uri = url.toJavaURI();
} catch (URISyntaxException e) {
// java.net.URI is buggy and doesn't support domain names with underscores. As galimatias already check
// the URL format, if we are here, it's probably because java.net.URI doesn't handle this case very well
// so we simply ignore the link instead of marking it as dead.
markAsIgnored(links);
return;
}
// Check the URL and update the links
try {
// We try a HEAD request
httpStatus = sendRequest(new HttpHead(uri));
if (httpStatus != null && httpStatus.getStatusCode() != HttpStatus.SC_OK) {
// If the result of the HEAD request is not OK, we try a GET request
// Using HttpStatus.SC_METHOD_NOT_ALLOWED looked like a clever trick but a lot of sites return
// 400 or 500 errors for HEAD requests
httpStatus = sendRequest(new HttpGet(uri));
}
if (httpStatus == null) {
errorType = ExternalLinkErrorType.UNKNOWN_HTTPCLIENT_ERROR;
} else if (httpStatus.getStatusCode() != HttpStatus.SC_OK) {
errorType = ExternalLinkErrorType.HTTP;
}
} catch (IllegalArgumentException e) {
errorType = ExternalLinkErrorType.INVALID_IDN;
} catch (SocketTimeoutException e) {
errorType = ExternalLinkErrorType.TIMEOUT;
} catch (IOException e) {
errorType = ExternalLinkErrorType.IO;
}
if (errorType == null) {
markAsOnline(links);
} else {
markAsOfflineOrDead(links, errorType, httpStatus);
}
}
// Private methods
private Collection<Callable<Void>> createTasksByDomain(List<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException {
Collection<Callable<Void>> tasks = Lists.newArrayList();
Map<String, Multimap<io.mola.galimatias.URL, Long>> domainToUrlToIds = Maps.newLinkedHashMap();
for (ExternalLinkWrapper link : links) {
try {
// there's no need to normalize the URL further as galimatias already normalizes the host and it's the
// only part we can normalize.
io.mola.galimatias.URL url = io.mola.galimatias.URL.parse(link.getUrl());
String domain = url.host().toHumanString();
Multimap<io.mola.galimatias.URL, Long> urlToIds = domainToUrlToIds.get(domain);
if (urlToIds == null) {
urlToIds = LinkedListMultimap.create();
domainToUrlToIds.put(domain, urlToIds);
}
urlToIds.put(url, link.getId());
} catch (Exception e) {
// if we cannot parse the URI, there's no need to go further, we mark it as invalid and we ignore it
markAsInvalid(link);
}
}
for (Multimap<io.mola.galimatias.URL, Long> urlToIds : domainToUrlToIds.values()) {
tasks.add(new ExternalLinkCheckByDomainTask(applicationContext, urlToIds.asMap()));
}
return tasks;
}
private void markAsInvalid(ExternalLinkWrapper link) throws ServiceException, SecurityServiceException {
link.setLastCheckDate(new Date());
link.setStatus(ExternalLinkStatus.DEAD_LINK);
link.setLastErrorType(ExternalLinkErrorType.URI_SYNTAX);
externalLinkWrapperService.update(link);
}
private void markAsIgnored(Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException {
Date checkDate = new Date();
for (ExternalLinkWrapper link : links) {
link.setLastCheckDate(checkDate);
link.setConsecutiveFailures(0);
link.setStatus(ExternalLinkStatus.IGNORED);
externalLinkWrapperService.update(link);
}
}
private void markAsOnline(Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException {
Date checkDate = new Date();
for (ExternalLinkWrapper link : links) {
link.setLastCheckDate(checkDate);
link.setConsecutiveFailures(0);
link.setStatus(ExternalLinkStatus.ONLINE);
link.setLastStatusCode(HttpStatus.SC_OK);
externalLinkWrapperService.update(link);
}
}
private void markAsOfflineOrDead(Collection<ExternalLinkWrapper> links, final ExternalLinkErrorType errorType, final StatusLine status) throws ServiceException, SecurityServiceException {
Date checkDate = new Date();
for (ExternalLinkWrapper link : links) {
link.setLastCheckDate(checkDate);
link.setLastErrorType(errorType);
link.setConsecutiveFailures(link.getConsecutiveFailures() + 1);
if (status != null) {
link.setLastStatusCode(status.getStatusCode());
} else {
link.setLastStatusCode(null);
}
if (link.getConsecutiveFailures() >= configurer.getExternalLinkCheckerRetryAttemptsLimit()) {
link.setStatus(ExternalLinkStatus.DEAD_LINK);
} else {
link.setStatus(ExternalLinkStatus.OFFLINE);
}
externalLinkWrapperService.update(link);
}
}
private StatusLine sendRequest(HttpRequestBase request) throws IOException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
return response.getStatusLine();
} finally {
if (request != null) {
request.reset();
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOGGER.error("Unable to close the HTTP response", e);
}
}
}
}
private void runTasksInParallel(Collection<? extends Callable<Void>> tasks, long timeout, TimeUnit timeoutUnit) throws ServiceException {
final int threadPoolSize = configurer.getExternalLinkCheckerThreadPoolSize();
final ThreadPoolExecutor executor = new ThreadPoolExecutor(
threadPoolSize, threadPoolSize,
100, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
executor.prestartAllCoreThreads();
try {
List<Future<Void>> futures = executor.invokeAll(tasks, timeout, timeoutUnit);
for (Future<Void> future : futures) {
future.get(); // Check that no error has occurred
}
} catch (Exception e) {
throw new ServiceException("Interrupted request", e);
} finally {
try {
executor.shutdown();
} catch (Exception e) {
LOGGER.warn("An error occurred while shutting down threads", e);
}
}
}
public void addIgnorePattern(Pattern ignorePattern) {
this.ignorePatterns.add(ignorePattern);
}
} |
package org.modmine.web;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.apache.tools.ant.filters.StringInputStream;
import org.intermine.bio.constants.ModMineCacheKeys;
import org.intermine.model.bio.Chromosome;
import org.intermine.model.bio.DatabaseRecord;
import org.intermine.model.bio.Experiment;
import org.intermine.model.bio.ExpressionLevel;
import org.intermine.model.bio.Location;
import org.intermine.model.bio.Project;
import org.intermine.model.bio.ResultFile;
import org.intermine.model.bio.SequenceFeature;
import org.intermine.model.bio.Submission;
import org.intermine.modelproduction.MetadataManager;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryFunction;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.sql.Database;
import org.intermine.util.PropertiesUtil;
import org.intermine.util.TypeUtil;
import org.modmine.web.GBrowseParser.GBrowseTrack;
/**
* Read modENCODE metadata into objects that simplify display code, cache results.
*
* @author Richard Smith
*/
public final class MetadataCache
{
private static final Logger LOG = Logger.getLogger(MetadataCache.class);
private static Map<String, DisplayExperiment> experimentCache = null;
private static Map<Integer, Map<String, Long>> submissionFeatureCounts = null;
private static Map<Integer, Map<String, Long>> submissionFeatureExpressionLevelCounts = null;
private static Map<String, Map<String, Long>> experimentFeatureExpressionLevelCounts = null;
private static Map<Integer, Integer> submissionExpressionLevelCounts = null;
private static Map<Integer, Integer> submissionIdCache = null;
private static Map<Integer, List<GBrowseTrack>> submissionTracksCache = null;
private static Map<Integer, Set<ResultFile>> submissionFilesCache = null;
private static Map<Integer, Integer> filesPerSubmissionCache = null;
private static Map<Integer, List<String>> submissionLocatedFeatureTypes = null;
private static Map<Integer, List<String>> submissionUnlocatedFeatureTypes = null;
private static Map<Integer, List<String[]>> submissionRepositedCache = null;
private static Map<String, String> featDescriptionCache = null;
private static Map<String, List<DisplayExperiment>> projectExperiments = null;
private static Properties metadataProperties = null;
private static long lastTrackCacheRefresh = 0;
private static final long TWO_HOUR = 7200000;
private MetadataCache() {
}
// TODO SEPARATE PUBLIC AND PRIVATE METHODS, ALL PUBLIC METHODS SHOULD COME FIRST
/**
* Fetch experiment details for display.
* @param os the production objectStore
* @return a list of experiments
*/
public static synchronized List<DisplayExperiment> getExperiments(ObjectStore os) {
if (experimentCache == null) {
readExperiments(os);
}
return new ArrayList<DisplayExperiment>(experimentCache.values());
}
/**
* Fetch experiment details for display.
* @param os the production objectStore
* @return a list of experiments
*/
public static synchronized Map<String, List<DisplayExperiment>>
getProjectExperiments(ObjectStore os) {
if (projectExperiments == null) {
readProjectExperiments(os);
}
return projectExperiments;
}
/**
* Fetch the metadata properties from database.
* @param os the production objectStore
* @return the metadata properties
*/
public static synchronized Properties getProperties(ObjectStore os)
throws SQLException, IOException {
if (metadataProperties == null) {
readProperties(os);
}
return metadataProperties;
}
/**
* Fetch GBrowse tracks per submission for display. This updates automatically from the GBrowse
* server and refreshes periodically (according to threshold). When refreshing another process
* is spawned which will update tracks when finished, if GBrowse can't be accessed the current
* list of tracks of tracks are preserved.
* @return map from submission id to list of GBrowse tracks
*/
public static synchronized Map<Integer, List<GBrowseTrack>> getGBrowseTracks() {
fetchGBrowseTracks();
while (submissionTracksCache == null) {
try {
MetadataCache.class.wait();
} catch (InterruptedException e) {
}
}
return submissionTracksCache;
}
/**
* Fetch unlocated feature types per submission.
* @param os the production objectStore
* @return map of unlocated feature types
*/
public static synchronized Map<Integer, List<String>> getLocatedFeatureTypes(ObjectStore os) {
if (submissionLocatedFeatureTypes == null) {
readSubmissionLocatedFeature(os);
}
return submissionLocatedFeatureTypes;
}
/**
* Fetch unlocated feature types per submission.
* @param os the production objectStore
* @return map of unlocated feature types
*/
public static synchronized Map<Integer, List<String>> getUnlocatedFeatureTypes(ObjectStore os) {
if (submissionUnlocatedFeatureTypes == null) {
readUnlocatedFeatureTypes(os);
}
return submissionUnlocatedFeatureTypes;
}
/**
* Fetch unlocated feature types per submission.
* @param os the production objectStore
* @param dccId ID from DCC
* @return map of unlocated feature types
*/
public static synchronized
Set<String> getUnlocatedFeatureTypesBySubId(ObjectStore os, Integer dccId) {
if (submissionUnlocatedFeatureTypes == null) {
readUnlocatedFeatureTypes(os);
}
Set<String> uf = new HashSet<String>(submissionUnlocatedFeatureTypes.get(dccId));
return uf;
}
/**
* Fetch the collection of ResultFiles per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<Integer, Set<ResultFile>> getSubmissionFiles(ObjectStore os) {
if (submissionFilesCache == null) {
readSubmissionFiles(os);
}
return submissionFilesCache;
}
/**
* Fetch the collection of Expression Level Counts per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<Integer, Integer>
getSubmissionExpressionLevelCounts(ObjectStore os) {
if (submissionExpressionLevelCounts == null) {
readSubmissionExpressionLevelCounts(os);
}
return submissionExpressionLevelCounts;
}
/**
* Fetch the collection of Expression Level Counts per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<Integer, Map<String, Long>>
getSubmissionFeatureExpressionLevelCounts(ObjectStore os) {
if (submissionFeatureExpressionLevelCounts == null) {
readSubmissionFeatureExpressionLevelCounts(os);
}
return submissionFeatureExpressionLevelCounts;
}
/**
* Fetch the collection of Expression Level Counts per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<String, Map<String, Long>>
getExperimentFeatureExpressionLevelCounts(ObjectStore os) {
if (experimentFeatureExpressionLevelCounts == null) {
readExperimentFeatureExpressionLevelCounts(os);
}
return experimentFeatureExpressionLevelCounts;
}
/**
* Fetch number of input/output file per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<Integer, Integer> getFilesPerSubmission(ObjectStore os) {
if (submissionFilesCache == null) {
readSubmissionFiles(os);
}
filesPerSubmissionCache = new HashMap<Integer, Integer>();
Iterator<Integer> dccId = submissionFilesCache.keySet().iterator();
while (dccId.hasNext()) {
Integer thisSub = dccId.next();
Integer nrFiles = submissionFilesCache.get(thisSub).size();
filesPerSubmissionCache.put(thisSub, nrFiles);
}
return filesPerSubmissionCache;
}
/**
* Fetch a list of file names for a given submission.
* @param os the objectStore
* @param dccId the modENCODE submission id
* @return a list of file names
*/
public static synchronized List<ResultFile> getFilesByDccId(ObjectStore os,
Integer dccId) {
if (submissionFilesCache == null) {
readSubmissionFiles(os);
}
return new ArrayList<ResultFile>(submissionFilesCache.get(dccId));
}
/**
* Fetch a list of GBrowse tracks for a given submission.
* @param dccId the modENCODE submission id
* @return a list of file names
*/
public static synchronized List<GBrowseTrack> getTracksByDccId(Integer dccId) {
Map<Integer, List<GBrowseTrack>> tracks = getGBrowseTracks();
if (tracks.get(dccId) != null) {
return new ArrayList<GBrowseTrack>(tracks.get(dccId));
} else {
return new ArrayList<GBrowseTrack>();
}
}
/**
* Fetch a list of file names for a given submission.
* @param servletContext servletContext
* @return a list of file names
*/
public static synchronized
Map<String, String> getFeatTypeDescription(ServletContext servletContext) {
if (featDescriptionCache == null) {
readFeatTypeDescription(servletContext);
}
return featDescriptionCache;
}
/**
* Fetch a map from feature type to count for a given submission.
* @param os the objectStore
* @param dccId the modENCODE submission id
* @return a map from feature type to count
*/
public static synchronized Map<String, Long> getSubmissionFeatureCounts(ObjectStore os,
Integer dccId) {
if (submissionFeatureCounts == null) {
readSubmissionFeatureCounts(os);
}
return submissionFeatureCounts.get(dccId);
}
// TODO ADD A NEW METHOD TO RUN A QUERY FOR ALL SUBMISSIONS AND POPULATE submissionIdCache, CALL
// THAT METHOD HERE INSTEAD OF readSubmissionFeatureCounts
/**
* Fetch a submission by the modENCODE submission ids
* @param os the objectStore
* @param dccId the modENCODE submission id
* @return the requested submission
* @throws ObjectStoreException if error reading database
*/
public static synchronized Submission getSubmissionByDccId(ObjectStore os, Integer dccId)
throws ObjectStoreException {
if (submissionIdCache == null) {
readSubmissionFeatureCounts(os);
}
return (Submission) os.getObjectById(submissionIdCache.get(dccId));
}
/**
* Get experiment information by name
* @param os the objectStore
* @param name of the experiment to fetch
* @return details of the experiment
* @throws ObjectStoreException if error reading database
*/
public static synchronized DisplayExperiment getExperimentByName(ObjectStore os, String name)
throws ObjectStoreException {
if (experimentCache == null) {
readExperiments(os);
}
return experimentCache.get(name);
}
private static void fetchGBrowseTracks() {
long timeSinceLastRefresh = System.currentTimeMillis() - lastTrackCacheRefresh;
if (timeSinceLastRefresh > TWO_HOUR) {
readGBrowseTracks();
lastTrackCacheRefresh = System.currentTimeMillis();
}
}
/**
* Set the map of GBrowse tracks.
*
* @param tracks map of dccId:GBrowse tracks
*/
public static synchronized void setGBrowseTracks(Map<Integer, List<GBrowseTrack>> tracks) {
MetadataCache.class.notifyAll();
submissionTracksCache = tracks;
}
/**
* Method to obtain the map of unlocated feature types by submission id
*
* @param os the objectStore
* @return submissionUnlocatedFeatureTypes
*/
private static Map<Integer, List<String>> readUnlocatedFeatureTypes(ObjectStore os) {
long startTime = System.currentTimeMillis();
try {
if (submissionUnlocatedFeatureTypes != null) {
return submissionUnlocatedFeatureTypes;
}
submissionUnlocatedFeatureTypes = new HashMap<Integer, List<String>>();
if (submissionLocatedFeatureTypes == null) {
readSubmissionLocatedFeature(os);
}
if (submissionFeatureCounts == null) {
readSubmissionFeatureCounts(os);
}
for (Integer subId : submissionFeatureCounts.keySet()) {
Set<String> allFeatures = submissionFeatureCounts.get(subId).keySet();
Set<String> difference = new HashSet<String>(allFeatures);
if (submissionLocatedFeatureTypes.get(subId) != null) {
difference.removeAll(submissionLocatedFeatureTypes.get(subId));
}
if (!difference.isEmpty()) {
List<String> thisUnlocated = new ArrayList<String>();
for (String fType : difference) {
thisUnlocated.add(fType);
}
submissionUnlocatedFeatureTypes.put(subId, thisUnlocated);
}
}
} catch (Exception err) {
err.printStackTrace();
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed unlocated feature cache, took: " + timeTaken + "ms size = "
+ submissionUnlocatedFeatureTypes.size());
return submissionUnlocatedFeatureTypes;
}
/**
*
* @param os objectStore
* @return map exp-tracks
*/
public static Map<String, List<GBrowseTrack>> getExperimentGBrowseTracks(ObjectStore os) {
Map<String, List<GBrowseTrack>> tracks = new HashMap<String, List<GBrowseTrack>>();
Map<Integer, List<GBrowseTrack>> subTracksMap = getGBrowseTracks();
for (DisplayExperiment exp : getExperiments(os)) {
List<GBrowseTrack> expTracks = new ArrayList<GBrowseTrack>();
tracks.put(exp.getName(), expTracks);
for (Submission sub : exp.getSubmissions()) {
if (subTracksMap.get(sub.getdCCid()) != null) {
List<GBrowseTrack> subTracks = subTracksMap.get(sub.getdCCid());
if (subTracks != null) {
// check so it is unique
// expTracks.addAll(subTracks);
addToList(expTracks, subTracks);
} else {
continue;
}
}
}
}
return tracks;
}
/**
* adds the elements of a list i to a list l only if they are not yet
* there
* @param l the receiving list
* @param i the donating list
*/
private static void addToList(List<GBrowseTrack> l, List<GBrowseTrack> i) {
Iterator<GBrowseTrack> it = i.iterator();
while (it.hasNext()) {
GBrowseTrack thisId = it.next();
if (!l.contains(thisId)) {
l.add(thisId);
}
}
}
/**
*
* @param os objectStore
* @return map exp-repository entries
*/
public static Map<String, Set<String[]>> getExperimentRepositoryEntries(ObjectStore os) {
Map<String, Set<String[]>> reposited = new HashMap<String, Set<String[]>>();
Map<Integer, List<String[]>> subRepositedMap = getRepositoryEntries(os);
for (DisplayExperiment exp : getExperiments(os)) {
Set<String[]> expReps = new HashSet<String[]>();
for (Submission sub : exp.getSubmissions()) {
List<String[]> subReps = subRepositedMap.get(sub.getdCCid());
if (subReps != null) {
expReps.addAll(subReps);
}
}
// for each experiment, we don't to count twice the same repository
// entry produced by 2 different submissions.
Set<String[]> expRepsCleaned = removeDuplications(expReps);
reposited.put(exp.getName(), expRepsCleaned);
}
return reposited;
}
private static Set<String[]> removeDuplications(Set<String[]> expReps) {
// removing the same repository entry coming from different submissions
// in the given experiment
Set<String> db = new HashSet<String>();
Set<String> acc = new HashSet<String>();
Set<String[]> dup = new HashSet<String[]>();
for (String[] s : expReps) {
if (db.contains(s[0]) && acc.contains(s[1])) {
// we don't remove place holders
if (!s[1].startsWith("To be")) {
dup.add(s);
}
}
db.add(s[0]);
acc.add(s[1]);
}
// do the difference between sets and return it
Set<String[]> uniques = new HashSet<String[]>(expReps);
uniques.removeAll(dup);
return uniques;
}
/**
*
* @param os objectStore
* @return map experiment expression levels
*/
public static Map<String, Integer> getExperimentExpressionLevels(ObjectStore os) {
Map<String, Integer> experimentELevel = new HashMap<String, Integer>();
Map<Integer, Integer> subELevelMap = getSubmissionExpressionLevelCounts(os);
for (DisplayExperiment exp : getExperiments(os)) {
Integer expCount = 0;
for (Submission sub : exp.getSubmissions()) {
Integer subCount = subELevelMap.get(sub.getdCCid());
if (subCount != null) {
expCount = expCount + subCount;
}
}
// if (expCount > 0) {
experimentELevel.put(exp.getName(), expCount);
}
return experimentELevel;
}
// TODO DELETE THIS, WAS ALREADY COMMENTED OUT
// /**
// *
// * @param os objectStore
// * @return map exp-repository entries
// */
// public static Map<String, Map<String, Long>>
// readExperimentFeatureExpressionLevels(ObjectStore os) {
// Map<String, Map<String, Long>> expELevels = new HashMap<String, Map<String, Long>>();
// Map<Integer, Map<String, Long>> subELevels = getSubmissionFeatureExpressionLevelCounts(os);
// for (DisplayExperiment exp : getExperiments(os)) {
// for (Submission sub : exp.getSubmissions()) {
// Map<String, Long> subFeat = subELevels.get(sub.getdCCid());
// if (subFeat != null) {
// // get the experiment feature map
// Map<String, Long> expFeat =
// expELevels.get(exp.getName());
// if (expFeat == null) {
// expELevels.put(exp.getName(), subFeat);
// } else {
// for (String feat : subFeat.keySet()) {
// Long subCount = subFeat.get(feat);
// Long expCount = subCount;
// if (expFeat.get(feat) != null) {
// expCount = expCount + expFeat.get(feat);
// expFeat.put(feat, expCount);
// expCount = Long.valueOf(0);
// expELevels.put(exp.getName(), expFeat);
// return expELevels;
/**
* Fetch a map from project name to experiment.
* @param os the production ObjectStore
* @return a map from project name to experiment
*/
public static Map<String, List<DisplayExperiment>>
readProjectExperiments(ObjectStore os) {
long startTime = System.currentTimeMillis();
projectExperiments = new TreeMap<String, List<DisplayExperiment>>();
for (DisplayExperiment exp : getExperiments(os)) {
List<DisplayExperiment> exps = projectExperiments.get(exp.getProjectName());
if (exps == null) {
exps = new ArrayList<DisplayExperiment>();
projectExperiments.put(exp.getProjectName(), exps);
}
exps.add(exp);
}
long totalTime = System.currentTimeMillis() - startTime;
LOG.info("Made project map: " + projectExperiments.size()
+ " took: " + totalTime + " ms.");
return projectExperiments;
}
private static void readExperiments(ObjectStore os) {
long startTime = System.currentTimeMillis();
Map<String, Map<String, Long>> featureCounts = getExperimentFeatureCounts(os);
Map<String, Map<String, Long>> uniqueFeatureCounts = getUniqueExperimentFeatureCounts(os);
try {
Query q = new Query();
QueryClass qcProject = new QueryClass(Project.class);
QueryField qcName = new QueryField(qcProject, "name");
q.addFrom(qcProject);
q.addToSelect(qcProject);
QueryClass qcExperiment = new QueryClass(Experiment.class);
q.addFrom(qcExperiment);
q.addToSelect(qcExperiment);
QueryCollectionReference projExperiments = new QueryCollectionReference(qcProject,
"experiments");
ContainsConstraint cc = new ContainsConstraint(projExperiments, ConstraintOp.CONTAINS,
qcExperiment);
q.setConstraint(cc);
q.addToOrderBy(qcName);
Results results = os.execute(q);
experimentCache = new HashMap<String, DisplayExperiment>();
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = (ResultsRow<?>) iter.next();
Project project = (Project) row.get(0);
Experiment experiment = (Experiment) row.get(1);
// expFeatureUniqueCounts is a subset of expFeatureCounts
Map<String, Long> expFeatureCounts = featureCounts.get(experiment.getName());
Map<String, Long> expFeatureUniqueCounts = uniqueFeatureCounts
.get(experiment.getName());
Set<FeatureCountsRecord> featureCountsRecords =
new LinkedHashSet<FeatureCountsRecord>();
if (expFeatureCounts != null) {
for (Map.Entry<String, Long> entry : expFeatureCounts.entrySet()) {
String ft = entry.getKey();
Long fc = entry.getValue();
Long ufc = null;
if (expFeatureUniqueCounts.get(ft) != null) {
ufc = expFeatureUniqueCounts.get(ft);
}
FeatureCountsRecord fcr = new FeatureCountsRecord(ft, fc, ufc);
featureCountsRecords.add(fcr);
}
} else { featureCountsRecords = null; }
DisplayExperiment displayExp = new DisplayExperiment(experiment, project,
featureCountsRecords, os);
experimentCache.put(displayExp.getName(), displayExp);
}
} catch (Exception err) {
err.printStackTrace();
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed experiment cache, took: " + timeTaken + "ms size = "
+ experimentCache.size());
}
// TODO REPLACE THIS, READ FROM PROPS WITH KEY ModMineCacheKeys.EXP_FEATURE_COUNT
/**
* The counts are duplicated in the method, see getUniqueExperimentFeatureCounts
*/
private static Map<String, Map<String, Long>> getExperimentFeatureCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
// NB: example of query (with group by) enwrapping a subquery that gets rids of
// duplications
Query q = new Query();
QueryClass qcExp = new QueryClass(Experiment.class);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryField qfName = new QueryField(qcExp, "name");
QueryField qfClass = new QueryField(qcLsf, "class");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcExp);
q.addToSelect(qcExp);
q.addToSelect(qcLsf);
q.addToSelect(qfName);
q.addToSelect(qfClass);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference submissions = new QueryCollectionReference(qcExp, "submissions");
ContainsConstraint ccSubs = new ContainsConstraint(submissions, ConstraintOp.CONTAINS,
qcSub);
cs.addConstraint(ccSubs);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
q.setConstraint(cs);
q.setDistinct(true);
Query superQ = new Query();
superQ.addFrom(q);
QueryField superQfName = new QueryField(q, qfName);
QueryField superQfClass = new QueryField(q, qfClass);
superQ.addToSelect(superQfName);
superQ.addToSelect(superQfClass);
superQ.addToOrderBy(superQfName);
superQ.addToOrderBy(superQfClass);
superQ.addToGroupBy(superQfName);
superQ.addToGroupBy(superQfClass);
superQ.addToSelect(new QueryFunction());
superQ.setDistinct(false);
Results results = os.execute(superQ);
Map<String, Map<String, Long>> featureCounts =
new LinkedHashMap<String, Map<String, Long>>();
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
String expName = (String) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
Long count = (Long) row.get(2);
Map<String, Long> expFeatureCounts = featureCounts.get(expName);
if (expFeatureCounts == null) {
expFeatureCounts = new HashMap<String, Long>();
featureCounts.put(expName, expFeatureCounts);
}
expFeatureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Read experiment feature counts, took: " + timeTaken + "ms");
return featureCounts;
}
// TODO REPLACE THIS METHOD, READ FROM PROPERTIES WITH ModMineCacheKeys.UNIQUE_EXP_FEATURE_COUNT
/**
* Method equivalent to getExperimentFeatureCounts but return Unique counts
*
* @param os
* @return Map<String: expName, Map<String: feature type, Long: count>>
*/
private static Map<String, Map<String, Long>> getUniqueExperimentFeatureCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
Query q = new Query();
QueryClass qcExp = new QueryClass(Experiment.class);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryClass qcChr = new QueryClass(Chromosome.class);
QueryClass qcLoc = new QueryClass(Location.class);
QueryField qfExpName = new QueryField(qcExp, "name");
QueryField qfFT = new QueryField(qcLsf, "class");
QueryField qfChrID = new QueryField(qcChr, "primaryIdentifier");
QueryField qfStart = new QueryField(qcLoc, "start");
QueryField qfEnd = new QueryField(qcLoc, "end");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcExp);
q.addFrom(qcChr);
q.addFrom(qcLoc);
q.addToSelect(qfExpName);
q.addToSelect(qfFT);
q.addToSelect(qfChrID);
q.addToSelect(qfStart);
q.addToSelect(qfEnd);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference submissions = new QueryCollectionReference(qcExp, "submissions");
ContainsConstraint ccSubs = new ContainsConstraint(submissions, ConstraintOp.CONTAINS,
qcSub);
cs.addConstraint(ccSubs);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
QueryObjectReference chromosome = new QueryObjectReference(qcLsf, "chromosome");
ContainsConstraint ccChr = new ContainsConstraint(chromosome,
ConstraintOp.CONTAINS, qcChr);
cs.addConstraint(ccChr);
QueryObjectReference chromosomeLocation = new QueryObjectReference(qcLsf,
"chromosomeLocation");
ContainsConstraint ccChrLoc = new ContainsConstraint(chromosomeLocation,
ConstraintOp.CONTAINS, qcLoc);
cs.addConstraint(ccChrLoc);
q.setConstraint(cs);
q.setDistinct(true);
Query superQ = new Query();
superQ.addFrom(q);
QueryField superQfName = new QueryField(q, qfExpName);
QueryField superQfFT = new QueryField(q, qfFT);
superQ.addToSelect(superQfName);
superQ.addToSelect(superQfFT);
superQ.addToOrderBy(superQfName);
superQ.addToOrderBy(superQfFT);
superQ.addToGroupBy(superQfName);
superQ.addToGroupBy(superQfFT);
superQ.addToSelect(new QueryFunction());
superQ.setDistinct(false);
Results results = os.execute(superQ);
Map<String, Map<String, Long>> featureCounts =
new LinkedHashMap<String, Map<String, Long>>();
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter = (Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
String expName = (String) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
Long count = (Long) row.get(2);
Map<String, Long> expFeatureCounts = featureCounts.get(expName);
if (expFeatureCounts == null) {
expFeatureCounts = new HashMap<String, Long>();
featureCounts.put(expName, expFeatureCounts);
}
expFeatureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Read experiment feature counts, took: " + timeTaken + "ms");
return featureCounts;
}
// TODO DELETE THIS, IT ISN'T USED
/**
* Method equivalent to getUniqueExperimentFeatureCountsByExpNameSlow but much faster
*
* @param expName name of an experiment
* @param os
* @return featureCounts Map<String: feature type, Long: feature count>
*/
private static Map<String, Long> getUniqueExperimentFeatureCountsByExpNameFast(
String expName, ObjectStore os) {
long startTime = System.currentTimeMillis();
Query q = new Query();
QueryClass qcExp = new QueryClass(Experiment.class);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryClass qcChr = new QueryClass(Chromosome.class);
QueryClass qcLoc = new QueryClass(Location.class);
QueryField qfExpName = new QueryField(qcExp, "name");
QueryField qfFT = new QueryField(qcLsf, "class");
QueryField qfChrID = new QueryField(qcChr, "primaryIdentifier");
QueryField qfStart = new QueryField(qcLoc, "start");
QueryField qfEnd = new QueryField(qcLoc, "end");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcExp);
q.addFrom(qcChr);
q.addFrom(qcLoc);
q.addToSelect(qfFT);
q.addToSelect(qfChrID);
q.addToSelect(qfStart);
q.addToSelect(qfEnd);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
SimpleConstraint scExpName = new SimpleConstraint(qfExpName,
ConstraintOp.EQUALS, new QueryValue(expName));
cs.addConstraint(scExpName);
QueryCollectionReference submissions = new QueryCollectionReference(qcExp, "submissions");
ContainsConstraint ccSubs = new ContainsConstraint(submissions, ConstraintOp.CONTAINS,
qcSub);
cs.addConstraint(ccSubs);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
QueryObjectReference chromosome = new QueryObjectReference(qcLsf, "chromosome");
ContainsConstraint ccChr = new ContainsConstraint(chromosome,
ConstraintOp.CONTAINS, qcChr);
cs.addConstraint(ccChr);
QueryObjectReference chromosomeLocation = new QueryObjectReference(qcLsf,
"chromosomeLocation");
ContainsConstraint ccChrLoc = new ContainsConstraint(chromosomeLocation,
ConstraintOp.CONTAINS, qcLoc);
cs.addConstraint(ccChrLoc);
q.setConstraint(cs);
q.setDistinct(true);
Query superQ = new Query();
superQ.addFrom(q);
QueryField superQfFT = new QueryField(q, qfFT);
superQ.addToSelect(superQfFT);
superQ.addToOrderBy(superQfFT);
superQ.addToGroupBy(superQfFT);
superQ.addToSelect(new QueryFunction());
superQ.setDistinct(false);
Results results = os.execute(superQ);
Map<String, Long> featureCounts = new LinkedHashMap<String, Long>();
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Class<?> feat = (Class<?>) row.get(0);
Long count = (Long) row.get(1);
featureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Read experiment feature counts, took: " + timeTaken + "ms");
return featureCounts;
}
// TODO DELETE THIS, IT ISN'T USED
private static void readSubmissionFeatureCountsO(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionFeatureCounts = new LinkedHashMap<Integer, Map<String, Long>>();
submissionIdCache = new HashMap<Integer, Integer>();
Query q = new Query();
q.setDistinct(false);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryField qfClass = new QueryField(qcLsf, "class");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addToSelect(qcSub);
q.addToSelect(qfClass);
q.addToSelect(new QueryFunction());
q.addToGroupBy(qcSub);
q.addToGroupBy(qfClass);
q.addToOrderBy(qcSub);
q.addToOrderBy(qfClass);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
q.setConstraint(cs);
Results results = os.execute(q);
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Submission sub = (Submission) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
Long count = (Long) row.get(2);
submissionIdCache.put(sub.getdCCid(), sub.getId());
Map<String, Long> featureCounts = submissionFeatureCounts.get(sub.getdCCid());
if (featureCounts == null) {
featureCounts = new HashMap<String, Long>();
submissionFeatureCounts.put(sub.getdCCid(), featureCounts);
}
featureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submissionFeatureCounts cache, took: " + timeTaken + "ms size = "
+ submissionFeatureCounts.size());
}
private static Properties readProperties(ObjectStore os) throws SQLException, IOException {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
String objectSummaryString =
MetadataManager.retrieve(db, MetadataManager.MODMINE_METADATA_CACHE);
metadataProperties = new Properties();
InputStream objectStoreSummaryPropertiesStream = new StringInputStream(objectSummaryString);
metadataProperties.load(objectStoreSummaryPropertiesStream);
return metadataProperties;
}
// TODO submissionIdCache CAN'T BE POPULATED FROM THIS METHOD, ADD A NEW METHOD TO QUERY FOR
// SUBMISSIONS AND CACHE THEIR IDS
private static void readSubmissionFeatureCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionFeatureCounts = new LinkedHashMap<Integer, Map<String, Long>>();
submissionIdCache = new HashMap<Integer, Integer>();
Properties props = new Properties();
try {
props =
PropertiesUtil.stripStart(ModMineCacheKeys.SUB_FEATURE_COUNT, getProperties(os));
} catch (SQLException e) {
throw new RuntimeException("Some SQL error happened. ", e);
} catch (IOException e) {
throw new RuntimeException("Some IO error happened. ", e);
}
for (Object key : props.keySet()) {
String keyString = (String) key;
String[] token = keyString.split("\\.");
Integer dccId = Integer.parseInt(token[0]);
String feature = token[1];
Long count = Long.parseLong((String) props.get(key));
Map<String, Long> featureCounts = submissionFeatureCounts.get(dccId);
if (featureCounts == null) {
featureCounts = new HashMap<String, Long>();
submissionFeatureCounts.put(dccId, featureCounts);
}
featureCounts.put(feature, count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submissionFeatureCounts cache, took: " + timeTaken + "ms size = "
+ submissionFeatureCounts.size());
}
// TODO REPLACE THIS, READ FROM PROPS WITH ModMineCacheKeys.SUB_FEATURE_EXPRESSION_LEVEL_COUNT
private static void readSubmissionFeatureExpressionLevelCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionFeatureExpressionLevelCounts = new LinkedHashMap<Integer, Map<String, Long>>();
//submissionIdCache = new HashMap<Integer, Integer>();
Query q = new Query();
q.setDistinct(false);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryClass qcEL = new QueryClass(ExpressionLevel.class);
QueryField qfClass = new QueryField(qcLsf, "class");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcEL);
q.addToSelect(qcSub);
q.addToSelect(qfClass);
q.addToSelect(new QueryFunction());
q.addToGroupBy(qcSub);
q.addToGroupBy(qfClass);
q.addToOrderBy(qcSub);
q.addToOrderBy(qfClass);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
QueryCollectionReference el = new QueryCollectionReference(qcLsf, "expressionLevels");
ContainsConstraint ccEl = new ContainsConstraint(el, ConstraintOp.CONTAINS, qcEL);
cs.addConstraint(ccEl);
q.setConstraint(cs);
Results results = os.execute(q);
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Submission sub = (Submission) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
Long count = (Long) row.get(2);
//submissionIdCache.put(sub.getdCCid(), sub.getId());
Map<String, Long> featureCounts =
submissionFeatureExpressionLevelCounts.get(sub.getdCCid());
if (featureCounts == null) {
featureCounts = new HashMap<String, Long>();
submissionFeatureExpressionLevelCounts.put(sub.getdCCid(), featureCounts);
}
featureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submissionFeatureExpressionLevelCounts cache, took: " + timeTaken
+ "ms size = " + submissionFeatureExpressionLevelCounts.size()
+ "<->" + submissionFeatureCounts.size());
LOG.info("submissionFeatureELCounts " + submissionFeatureExpressionLevelCounts);
}
// TODO REMOVE THIS METHOD, ADD NEW METHOD THAT ITERATES THROUGH SUBMISSIONS PER EXPERIMENT AND
// SUMS EXPRESSION LEVEL COUNTS PER FEATURE TYPE FROM getSubmissionFeatureExpressionLevelCounts
private static void readExperimentFeatureExpressionLevelCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
experimentFeatureExpressionLevelCounts = new LinkedHashMap<String, Map<String, Long>>();
//submissionIdCache = new HashMap<Integer, Integer>();
Query q = new Query();
q.setDistinct(false);
QueryClass qcExp = new QueryClass(Experiment.class);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryClass qcEL = new QueryClass(ExpressionLevel.class);
QueryField qfClass = new QueryField(qcLsf, "class");
q.addFrom(qcExp);
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcEL);
q.addToSelect(qcExp);
q.addToSelect(qfClass);
q.addToSelect(new QueryFunction());
q.addToGroupBy(qcExp);
q.addToGroupBy(qfClass);
q.addToOrderBy(qcExp);
q.addToOrderBy(qfClass);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference submissions = new QueryCollectionReference(qcExp, "submissions");
ContainsConstraint ccSubs =
new ContainsConstraint(submissions, ConstraintOp.CONTAINS, qcSub);
cs.addConstraint(ccSubs);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
QueryCollectionReference el = new QueryCollectionReference(qcLsf, "expressionLevels");
ContainsConstraint ccEl = new ContainsConstraint(el, ConstraintOp.CONTAINS, qcEL);
cs.addConstraint(ccEl);
q.setConstraint(cs);
Results results = os.execute(q);
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Experiment exp = (Experiment) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
Long count = (Long) row.get(2);
//submissionIdCache.put(sub.getdCCid(), sub.getId());
Map<String, Long> featureCounts =
experimentFeatureExpressionLevelCounts.get(exp.getName());
if (featureCounts == null) {
featureCounts = new HashMap<String, Long>();
experimentFeatureExpressionLevelCounts.put(exp.getName(), featureCounts);
}
featureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed experimentFeatureExpressionLevelCounts cache, took: " + timeTaken
+ "ms size = " + experimentFeatureExpressionLevelCounts.size());
LOG.info("experimentFeatureELCounts " + experimentFeatureExpressionLevelCounts);
}
// TODO REPLACE THIS METHOD WITH ONE THAT ITERATES getSubmissionFeatureExpressionLevelCounts
// AND SUMS EXPRESSION LEVEL COUNTS FOR THE WHOLE SUBMISSION
private static void readSubmissionExpressionLevelCounts(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionExpressionLevelCounts = new HashMap<Integer, Integer>();
Query q = new Query();
q.setDistinct(false);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcEL = new QueryClass(ExpressionLevel.class);
QueryField qfDccid = new QueryField(qcSub, "DCCid");
q.addFrom(qcSub);
q.addFrom(qcEL);
q.addToSelect(qfDccid);
q.addToSelect(new QueryFunction());
q.addToGroupBy(qcSub);
q.addToOrderBy(qfDccid);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference el = new QueryCollectionReference(qcSub, "expressionLevels");
ContainsConstraint ccEl = new ContainsConstraint(el, ConstraintOp.CONTAINS, qcEL);
cs.addConstraint(ccEl);
q.setConstraint(cs);
Results results = os.execute(q);
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Integer dccId = (Integer) row.get(0);
Long count = (Long) row.get(1);
submissionExpressionLevelCounts.put(dccId, count.intValue());
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submissionExpressionLevelCounts cache, took: " + timeTaken
+ "ms size = " + submissionExpressionLevelCounts.size());
LOG.info("submissionELCounts " + submissionExpressionLevelCounts);
}
// TODO DELETE THIS, IT'S NEVER CALLED
private static void readSubmissionExpressionLevelCounts2(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionExpressionLevelCounts = new HashMap<Integer, Integer>();
if (submissionIdCache == null) {
readSubmissionFeatureCounts(os);
}
if (submissionFeatureExpressionLevelCounts == null) {
readSubmissionFeatureExpressionLevelCounts(os);
}
for (Integer dccId : submissionIdCache.keySet()) {
Integer count = 0;
Map<String, Long> featureCounts =
submissionFeatureExpressionLevelCounts.get(dccId);
if (featureCounts == null) {
continue;
}
if (!featureCounts.isEmpty()) {
for (String feat : featureCounts.keySet()) {
count = count + featureCounts.get(feat).intValue();
}
}
submissionExpressionLevelCounts.put(dccId, count);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submissionExpressionLevelCounts cache, took: " + timeTaken
+ "ms size = " + submissionExpressionLevelCounts.size());
LOG.debug("submissionELCounts " + submissionExpressionLevelCounts);
}
// TODO GIVE THIS METHOD A BETTER NAME
private static void readSubmissionFiles(ObjectStore os) {
long startTime = System.currentTimeMillis();
try {
Query q = new Query();
QueryClass qcSubmission = new QueryClass(Submission.class);
QueryField qfDCCid = new QueryField(qcSubmission, "DCCid");
q.addFrom(qcSubmission);
q.addToSelect(qfDCCid);
QueryClass qcFile = new QueryClass(ResultFile.class);
q.addFrom(qcFile);
q.addToSelect(qcFile);
QueryCollectionReference subFiles = new QueryCollectionReference(qcSubmission,
"resultFiles");
ContainsConstraint cc = new ContainsConstraint(subFiles, ConstraintOp.CONTAINS,
qcFile);
q.setConstraint(cc);
q.addToOrderBy(qfDCCid);
Results results = os.execute(q);
submissionFilesCache = new HashMap<Integer, Set<ResultFile>>();
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = (ResultsRow<?>) iter.next();
Integer dccId = (Integer) row.get(0);
ResultFile file = (ResultFile) row.get(1);
addToMap(submissionFilesCache, dccId, file);
}
} catch (Exception err) {
err.printStackTrace();
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed submission collections caches, took: " + timeTaken + "ms size: files = "
+ submissionFilesCache.size());
}
// TODO DELETE THIS, WAS ALREADY COMMENTED OUT
// private static void readSubmissionExpressionLevels(ObjectStore os) {
// long startTime = System.currentTimeMillis();
// try {
// Query q = new Query();
// QueryClass qcSubmission = new QueryClass(Submission.class);
// QueryField qfDCCid = new QueryField(qcSubmission, "DCCid");
// q.addFrom(qcSubmission);
// q.addToSelect(qfDCCid);
// QueryClass qcEL = new QueryClass(ExpressionLevel.class);
// q.addFrom(qcEL);
// q.addToSelect(qcEL);
// QueryCollectionReference subFiles = new QueryCollectionReference(qcSubmission,
// "expressionLevels");
// ContainsConstraint cc = new ContainsConstraint(subFiles, ConstraintOp.CONTAINS,
// qcEL);
// q.setConstraint(cc);
// q.addToOrderBy(qfDCCid);
// Results results = os.execute(q);
// submissionExpressionLevelCounts = new HashMap<Integer, Integer>();
// @SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
// (Iterator) results.iterator();
// while (iter.hasNext()) {
// ResultsRow<?> row = (ResultsRow<?>) iter.next();
// Integer dccId = (Integer) row.get(0);
// ResultFile file = (ResultFile) row.get(1);
// addToMap(submissionExpressionLevelCounts, dccId, file.);
// } catch (Exception err) {
// err.printStackTrace();
// long timeTaken = System.currentTimeMillis() - startTime;
// LOG.info("Primed submission collections caches, took: " + timeTaken + "ms size: files = "
// + submissionFilesCache.size() + ", expression levels = "
// + submissionExpressionLevelCounts.size());
//// LOG.info("Primed submission collections caches, XXXX: " + submissionFilesCache);
// TODO MOVE THIS QUERY TO CreateModMineMetaDataCache and add value to ModMineCacheKeys
private static void readSubmissionLocatedFeature(ObjectStore os) {
long startTime = System.currentTimeMillis();
submissionLocatedFeatureTypes = new LinkedHashMap<Integer, List<String>>();
Query q = new Query();
q.setDistinct(true);
QueryClass qcSub = new QueryClass(Submission.class);
QueryClass qcLsf = new QueryClass(SequenceFeature.class);
QueryClass qcLoc = new QueryClass(Location.class);
QueryField qfClass = new QueryField(qcLsf, "class");
q.addFrom(qcSub);
q.addFrom(qcLsf);
q.addFrom(qcLoc);
q.addToSelect(qcSub);
q.addToSelect(qfClass);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference features = new QueryCollectionReference(qcSub, "features");
ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf);
cs.addConstraint(ccFeats);
QueryObjectReference location = new QueryObjectReference(qcLsf, "chromosomeLocation");
ContainsConstraint ccLocs = new ContainsConstraint(location, ConstraintOp.CONTAINS, qcLoc);
cs.addConstraint(ccLocs);
q.setConstraint(cs);
Results results = os.execute(q);
// for each classes set the values for jsp
@SuppressWarnings("unchecked") Iterator<ResultsRow> iter =
(Iterator) results.iterator();
while (iter.hasNext()) {
ResultsRow<?> row = iter.next();
Submission sub = (Submission) row.get(0);
Class<?> feat = (Class<?>) row.get(1);
addToMap(submissionLocatedFeatureTypes, sub.getdCCid(),
TypeUtil.unqualifiedName(feat.getName()));
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed located features cache, took: " + timeTaken + "ms size = "
+ submissionLocatedFeatureTypes.size());
}
/**
* Fetch reposited (GEO/SRA/AE..) entries per submission.
* @param os the production objectStore
* @return map
*/
public static synchronized Map<Integer, List<String[]>> getRepositoryEntries(ObjectStore os) {
if (submissionRepositedCache == null) {
readSubmissionRepositoryEntries(os);
}
return submissionRepositedCache;
}
private static void readSubmissionRepositoryEntries(ObjectStore os) {
long startTime = System.currentTimeMillis();
try {
Query q = new Query();
QueryClass qcSubmission = new QueryClass(Submission.class);
QueryField qfDCCid = new QueryField(qcSubmission, "DCCid");
q.addFrom(qcSubmission);
q.addToSelect(qfDCCid);
QueryClass qcRepositoryEntry = new QueryClass(DatabaseRecord.class);
QueryField qfDatabase = new QueryField(qcRepositoryEntry, "database");
QueryField qfAccession = new QueryField(qcRepositoryEntry, "accession");
QueryField qfUrl = new QueryField(qcRepositoryEntry, "url");
q.addFrom(qcRepositoryEntry);
q.addToSelect(qfDatabase);
q.addToSelect(qfAccession);
q.addToSelect(qfUrl);
// join the tables
QueryCollectionReference ref1 =
new QueryCollectionReference(qcSubmission, "databaseRecords");
ContainsConstraint cc = new ContainsConstraint(ref1, ConstraintOp.CONTAINS,
qcRepositoryEntry);
q.setConstraint(cc);
q.addToOrderBy(qfDCCid);
q.addToOrderBy(qfDatabase);
Results results = os.execute(q);
submissionRepositedCache = new HashMap<Integer, List<String[]>>();
Integer counter = 0;
Integer prevSub = new Integer(-1);
List<String[]> subRep = new ArrayList<String[]>();
Iterator<?> i = results.iterator();
while (i.hasNext()) {
ResultsRow<?> row = (ResultsRow<?>) i.next();
counter++;
Integer dccId = (Integer) row.get(0);
String db = (String) row.get(1);
String acc = (String) row.get(2);
String url = (String) row.get(3);
String[] thisRecord = {db, acc, url};
if (!dccId.equals(prevSub) || counter.equals(results.size())) {
if (prevSub > 0) {
if (counter.equals(results.size())) {
prevSub = dccId;
subRep.add(thisRecord);
}
List<String[]> subRepIn = new ArrayList<String[]>();
subRepIn.addAll(subRep);
submissionRepositedCache.put(prevSub, subRepIn);
subRep.clear();
}
prevSub = dccId;
}
subRep.add(thisRecord);
}
} catch (Exception err) {
err.printStackTrace();
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed Repository entries cache, took: " + timeTaken + "ms size = "
+ submissionRepositedCache.size());
}
/**
* adds an element to a list which is the value of a map
* @param m the map (<Integer, List<String>>)
* @param key the key for the map
* @param value the list
*/
private static void addToMap(Map<Integer, List<String>> m, Integer key, String value) {
List<String> ids = new ArrayList<String>();
if (m.containsKey(key)) {
ids = m.get(key);
}
if (!ids.contains(value)) {
ids.add(value);
m.put(key, ids);
}
}
/**
* adds an element to a set of ResultFile which is the value of a map
* @param m the map (<Integer, Set<ResultFile>>)
* @param key the key for the map
* @param value the list
*/
private static void addToMap(Map<Integer, Set<ResultFile>> m, Integer key, ResultFile value) {
Set<ResultFile> files = new HashSet<ResultFile>();
if (m.containsKey(key)) {
files = m.get(key);
}
if (!files.contains(value)) {
// check if same name
for (ResultFile file : files) {
if (file.getName().equals(value.getName())) {
LOG.info("DUPLICATED FILE " + value.getName() + " - ids: in " + value.getId()
+ " dup " + file.getId());
return;
}
}
files.add(value);
m.put(key, files);
}
}
/**
* Method to fill the cached map of submissions (ddcId) to list of
* GBrowse tracks
*
*/
private static void readGBrowseTracks() {
Runnable r = new Runnable() {
public void run() {
threadedReadGBrowseTracks();
}
};
Thread t = new Thread(r);
t.start();
}
private static void threadedReadGBrowseTracks() {
long startTime = System.currentTimeMillis();
Map<Integer, List<GBrowseTrack>> tracks = new HashMap<Integer, List<GBrowseTrack>>();
Map<Integer, List<GBrowseTrack>> flyTracks = null;
Map<Integer, List<GBrowseTrack>> wormTracks = null;
try {
flyTracks = GBrowseParser.readTracks("fly");
wormTracks = GBrowseParser.readTracks("worm");
} catch (Exception e) {
LOG.error(e);
}
if (flyTracks != null && wormTracks != null) {
tracks.putAll(flyTracks);
tracks.putAll(wormTracks);
setGBrowseTracks(tracks);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed GBrowse tracks cache, took: " + timeTaken + "ms size = "
+ tracks.size());
}
/**
* This method get the feature descriptions from a property file.
*
* @return the map feature/description
*/
private static Map<String, String> readFeatTypeDescription(ServletContext servletContext) {
long startTime = System.currentTimeMillis();
featDescriptionCache = new HashMap<String, String>();
Properties props = new Properties();
InputStream is
= servletContext.getResourceAsStream("/WEB-INF/featureTypeDescr.properties");
if (is == null) {
LOG.info("Unable to find /WEB-INF/featureTypeDescr.properties, "
+ "there will be no feature type descriptions");
} else {
try {
props.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Enumeration<?> en = props.keys();
while (en.hasMoreElements()) {
String expFeat = (String) en.nextElement();
String descr = props.getProperty(expFeat);
featDescriptionCache.put(expFeat, descr);
}
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Primed feature description cache, took: " + timeTaken + "ms size = "
+ featDescriptionCache.size());
return featDescriptionCache;
}
} |
package j2048.jgamegui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import jgame.GContainer;
import jgame.GMessage;
/**
* The main view for a game of 2048.
*
* @author William Chargin
*
*/
public class GamePanel extends GContainer {
/**
* A score display component with a label and a mutable value.
*
* @author William Chargin
*
*/
private static class ScoreDisplay extends GContainer {
/**
* Creates a message to be used as a label for the score.
*
* @param text
* the text of the label
* @return the label message
*/
private static GMessage createLabelMessage(String text) {
final GMessage label = new GMessage();
label.setColor(J2048.LIGHT_TEXT);
label.setText(text.toUpperCase());
label.setSize(90, 30);
label.setFontSize(16);
label.setFontStyle(Font.BOLD);
label.setAlignmentX(1);
label.setAlignmentY(0.5);
label.setAnchorTopLeft();
return label;
}
/**
* Creates a message representing a score.
*
* @param value
* the initial value for the score message
* @return the score message
*/
private static GMessage createScoreMessage(int value) {
final GMessage score = new GMessage();
score.setColor(Color.WHITE);
score.setText(Integer.toString(value));
score.setSize(100, 30);
score.setFontSize(22);
score.setFontStyle(Font.BOLD);
score.setAlignmentX(0);
score.setAlignmentY(0.5);
score.setAnchorTopLeft();
return score;
}
/**
* The actual integer value of the score.
*/
private int scoreValue;
/**
* The message displaying the score value.
*/
private final GMessage scoreMessage;
/**
* Creates a {@code ScoreDisplay} initialized to the given title and a
* score of {@code 0}.
*
* @param title
* the title of this display
*/
public ScoreDisplay(String title) {
setAnchorTopLeft();
setSize(200, 30);
GMessage label = createLabelMessage(title);
addAt(label, 0, 0);
scoreMessage = createScoreMessage(0);
addAt(scoreMessage, 100, 0);
}
/**
* Gets the current score.
*
* @return the current score
*/
public int getScore() {
return scoreValue;
}
@Override
public void paint(Graphics2D g) {
g.setColor(J2048.MAIN_COLOR);
g.fillRoundRect(0, 0, getIntWidth(), getIntHeight(), 3, 3);
super.paint(g);
}
/**
* Sets the score displayed in this {@code ScoreDisplay}.
*
* @param newScore
* the new displayed score
*/
public void setScore(int newScore) {
scoreValue = newScore;
scoreMessage.setText(Integer.toString(scoreValue));
}
}
/**
* The message representing the user's current score.
*/
private final ScoreDisplay scoreValue;
/**
* The message representing the user's best score.
*/
private final ScoreDisplay bestValue;
/**
* The grid used in this game.
*/
private final GridPanel grid;
public GamePanel() {
setSize(500, 600);
final GMessage title = new GMessage("2048");
title.setColor(J2048.TEXT_COLOR);
title.setSize(250, 100);
title.setAnchorTopLeft();
title.setAlignmentX(0.5);
title.setAlignmentY(0.5);
title.setFontSize(72);
title.setFontStyle(Font.BOLD);
add(title);
addAt(scoreValue = new ScoreDisplay("Score"), 275, 10);
addAt(bestValue = new ScoreDisplay("Best"), 275, 55);
grid = new GridPanel();
grid.setAnchorTopLeft();
addAt(grid, 0, 100);
}
/**
* Updates the "best score" display to reflect the new best score.
*
* @param newBestScore
* the new best score
*/
public void setBestScore(int newBestScore) {
bestValue.setScore(newBestScore);
}
/**
* Updates the "score" display to reflect the new score.
*
* @param newScore
* the new score
*/
public void setScore(int newScore) {
scoreValue.setScore(newScore);
if (newScore > bestValue.getScore()) {
setBestScore(newScore);
}
}
} |
package cz.cuni.lf1.lge.ThunderSTORM;
import static cz.cuni.lf1.lge.ThunderSTORM.util.ImageMath.subtract;
import static cz.cuni.lf1.lge.ThunderSTORM.util.ImageMath.add;
import cz.cuni.lf1.lge.ThunderSTORM.UI.AnalysisOptionsDialog;
import cz.cuni.lf1.lge.ThunderSTORM.UI.GUI;
import cz.cuni.lf1.lge.ThunderSTORM.UI.MacroParser;
import cz.cuni.lf1.lge.ThunderSTORM.UI.RenderingOverlay;
import cz.cuni.lf1.lge.ThunderSTORM.UI.StoppedByUserException;
import cz.cuni.lf1.lge.ThunderSTORM.detectors.IDetector;
import cz.cuni.lf1.lge.ThunderSTORM.detectors.ui.IDetectorUI;
import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.Molecule;
import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.MoleculeDescriptor;
import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.PSFModel;
import cz.cuni.lf1.lge.ThunderSTORM.estimators.ui.IEstimatorUI;
import cz.cuni.lf1.lge.ThunderSTORM.filters.ui.IFilterUI;
import cz.cuni.lf1.lge.ThunderSTORM.rendering.IncrementalRenderingMethod;
import cz.cuni.lf1.lge.ThunderSTORM.rendering.RenderingQueue;
import cz.cuni.lf1.lge.ThunderSTORM.rendering.ui.IRendererUI;
import cz.cuni.lf1.lge.ThunderSTORM.results.IJResultsTable;
import cz.cuni.lf1.lge.ThunderSTORM.results.MeasurementProtocol;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder;
import cz.cuni.lf1.lge.ThunderSTORM.util.Point;
import cz.cuni.lf1.lge.ThunderSTORM.util.VectorMath;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.Roi;
import ij.plugin.filter.ExtendedPlugInFilter;
import static ij.plugin.filter.PlugInFilter.DOES_16;
import static ij.plugin.filter.PlugInFilter.DOES_32;
import static ij.plugin.filter.PlugInFilter.DOES_8G;
import static ij.plugin.filter.PlugInFilter.DOES_STACKS;
import static ij.plugin.filter.PlugInFilter.DONE;
import static ij.plugin.filter.PlugInFilter.FINAL_PROCESSING;
import static ij.plugin.filter.PlugInFilter.NO_CHANGES;
import static ij.plugin.filter.PlugInFilter.NO_UNDO;
import static ij.plugin.filter.PlugInFilter.PARALLELIZE_STACKS;
import static ij.plugin.filter.PlugInFilter.SUPPORTS_MASKING;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.Recorder;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.SwingUtilities;
/**
* ThunderSTORM Analysis plugin.
*
* Open the options dialog, process an image stack to recieve a list of
* localized molecules which will get displayed in the {@code ResultsTable} and
* previed in a new {@code ImageStack} with detections marked as crosses in
* {@code Overlay} of each slice of the stack.
*/
public final class AnalysisPlugIn implements ExtendedPlugInFilter {
private int stackSize;
private final AtomicInteger nProcessed = new AtomicInteger(0);
private final int pluginFlags = DOES_8G | DOES_16 | DOES_32 | NO_CHANGES
| NO_UNDO | DOES_STACKS | PARALLELIZE_STACKS | FINAL_PROCESSING | SUPPORTS_MASKING;
private List<IFilterUI> allFilters;
private List<IDetectorUI> allDetectors;
private List<IEstimatorUI> allEstimators;
private List<IRendererUI> allRenderers;
private int selectedFilter;
private int selectedEstimator;
private int selectedDetector;
private int selectedRenderer;
private ImagePlus processedImage;
private RenderingQueue renderingQueue;
private ImagePlus renderedImage;
private Roi roi;
private MeasurementProtocol measurementProtocol;
private AnalysisOptionsDialog dialog;
/**
* Returns flags specifying capabilities of the plugin.
*
* This method is called before an actual analysis and returns flags
* supported by the plugin. The method is also called after the processing
* is finished to fill the {@code ResultsTable} and to visualize the
* detections directly in image stack (a new copy of image stack is
* created).
*
* <strong>The {@code ResultsTable} is always guaranteed to contain columns
* <i>frame, x, y</i>!</strong> The other parameters are optional and can
* change for different PSFs.
*
* @param command command
* @param imp ImagePlus instance holding the active image (not required)
* @return flags specifying capabilities of the plugin
*/
@Override
public int setup(String command, ImagePlus imp) {
GUI.setLookAndFeel();
if(command.equals("final")) {
IJ.showStatus("ThunderSTORM is generating the results...");
// Show results (table and overlay)
showResults();
// Finished
IJ.showProgress(1.0);
IJ.showStatus("ThunderSTORM finished.");
return DONE;
} else if("showResultsTable".equals(command)) {
IJResultsTable.getResultsTable().show();
return DONE;
} else {
processedImage = imp;
return pluginFlags; // Grayscale only, no changes to the image and therefore no undo
}
}
/**
* Show the options dialog for a particular command and block the current
* processing thread until user confirms his settings or cancels the
* operation.
*
* @param command command (not required)
* @param imp ImagePlus instance holding the active image (not required)
* @param pfr instance that initiated this plugin (not required)
* @return
*/
@Override
public int showDialog(final ImagePlus imp, final String command, PlugInFilterRunner pfr) {
try {
// load modules
allFilters = ModuleLoader.getUIModules(IFilterUI.class);
allDetectors = ModuleLoader.getUIModules(IDetectorUI.class);
allEstimators = ModuleLoader.getUIModules(IEstimatorUI.class);
allRenderers = ModuleLoader.getUIModules(IRendererUI.class);
if(MacroParser.isRanFromMacro()) {
//parse the macro options
MacroParser parser = new MacroParser(allFilters, allEstimators, allDetectors, allRenderers);
selectedFilter = parser.getFilterIndex();
selectedDetector = parser.getDetectorIndex();
selectedEstimator = parser.getEstimatorIndex();
roi = imp.getRoi() != null ? imp.getRoi() : new Roi(0, 0, imp.getWidth(), imp.getHeight());
IRendererUI rendererPanel = parser.getRendererUI();
rendererPanel.setSize(roi.getBounds().width, roi.getBounds().height);
IncrementalRenderingMethod method = rendererPanel.getImplementation();
renderedImage = (method != null) ? method.getRenderedImage() : null;
renderingQueue = new RenderingQueue(method, new RenderingQueue.DefaultRepaintTask(renderedImage), rendererPanel.getRepaintFrequency());
measurementProtocol = new MeasurementProtocol(imp, allFilters.get(selectedFilter), allDetectors.get(selectedDetector), allEstimators.get(selectedEstimator));
} else {
// Create and show the dialog
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
dialog = new AnalysisOptionsDialog(imp, command, allFilters, allDetectors, allEstimators, allRenderers);
dialog.setVisible(true);
}
});
} catch(InvocationTargetException e) {
throw e.getCause();
}
if(dialog.wasCanceled()) { // This is a blocking call!!
return DONE; // cancel
}
selectedFilter = dialog.getFilterIndex();
selectedDetector = dialog.getDetectorIndex();
selectedEstimator = dialog.getEstimatorIndex();
selectedRenderer = dialog.getRendererIndex();
roi = imp.getRoi() != null ? imp.getRoi() : new Roi(0, 0, imp.getWidth(), imp.getHeight());
IRendererUI renderer = allRenderers.get(selectedRenderer);
renderer.setSize(roi.getBounds().width, roi.getBounds().height);
IncrementalRenderingMethod method = renderer.getImplementation();
renderedImage = (method != null) ? method.getRenderedImage() : null;
renderingQueue = new RenderingQueue(method, new RenderingQueue.DefaultRepaintTask(renderedImage), renderer.getRepaintFrequency());
//if recording window is open, record parameters of all modules
if(Recorder.record) {
MacroParser.recordFilterUI(dialog.getFilter());
MacroParser.recordDetectorUI(dialog.getDetector());
MacroParser.recordEstimatorUI(dialog.getEstimator());
MacroParser.recordRendererUI(dialog.getRenderer());
}
measurementProtocol = new MeasurementProtocol(imp, dialog.getFilter(), dialog.getDetector(), dialog.getEstimator());
}
} catch(Throwable ex) {
IJ.handleException(ex);
return DONE;
}
try {
Thresholder.loadFilters(allFilters);
Thresholder.setActiveFilter(selectedFilter); // !! must be called before any threshold is evaluated !!
Thresholder.parseThreshold(allDetectors.get(selectedDetector).getThreadLocalImplementation().getThresholdFormula());
} catch(Exception ex) {
IJ.error("Error parsing threshold formula! " + ex.toString());
return DONE;
}
IJResultsTable rt = IJResultsTable.getResultsTable();
rt.reset();
rt.setOriginalState();
rt.forceHide();
return pluginFlags;
}
/**
* Gives the plugin information about the number of passes through the image
* stack we want to process.
*
* Allocation of resources to store the results is done here.
*
* @param nPasses number of passes through the image stack we want to
* process
*/
@Override
public void setNPasses(int nPasses) {
stackSize = nPasses;
nProcessed.set(0);
}
/**
* Run the plugin.
*
* This method is ran in parallel, thus counting the results must be done
* atomicaly.
*
* @param ip input image
*/
@Override
public void run(ImageProcessor ip) {
assert (selectedFilter >= 0 && selectedFilter < allFilters.size()) : "Index out of bounds: selectedFilter!";
assert (selectedDetector >= 0 && selectedDetector < allDetectors.size()) : "Index out of bounds: selectedDetector!";
assert (selectedEstimator >= 0 && selectedEstimator < allEstimators.size()) : "Index out of bounds: selectedEstimator!";
assert (selectedRenderer >= 0 && selectedRenderer < allRenderers.size()) : "Index out of bounds: selectedRenderer!";
assert (renderingQueue != null) : "Renderer was not selected!";
ip.setRoi(roi);
FloatProcessor fp = subtract((FloatProcessor) ip.crop().convertToFloat(), (float) CameraSetupPlugIn.getOffset());
float minVal = VectorMath.min((float[]) fp.getPixels());
if(minVal < 0) {
IJ.log("Camera base level is set higher than values in the image!");
fp = add(-minVal, fp);
}
if(roi != null) {
fp.setMask(roi.getMask());
}
try {
Thresholder.setCurrentImage(fp);
FloatProcessor filtered = allFilters.get(selectedFilter).getThreadLocalImplementation().filterImage(fp);
IDetector detector = allDetectors.get(selectedDetector).getThreadLocalImplementation();
Vector<Point> detections = detector.detectMoleculeCandidates(filtered);
Vector<Molecule> fits = allEstimators.get(selectedEstimator).getThreadLocalImplementation().estimateParameters(fp, Point.applyRoiMask(roi, detections));
storeFits(fits, ip.getSliceNumber());
nProcessed.incrementAndGet();
if(fits.size() > 0) {
renderingQueue.renderLater(fits);
}
IJ.showProgress((double) nProcessed.intValue() / (double) stackSize);
IJ.showStatus("ThunderSTORM processing frame " + nProcessed + " of " + stackSize + "...");
GUI.checkIJEscapePressed();
} catch (StoppedByUserException ie){
IJResultsTable rt = IJResultsTable.getResultsTable();
synchronized(rt) {
if(rt.isForceHidden()) {
showResults();
}
}
}
}
synchronized public void storeFits(Vector<Molecule> fits, int frame) {
IJResultsTable rt = IJResultsTable.getResultsTable();
for(Molecule psf : fits) {
psf.insertParamAt(0, MoleculeDescriptor.LABEL_FRAME, MoleculeDescriptor.Units.UNITLESS, (double)frame);
rt.addRow(psf);
}
}
public static void setDefaultColumnsWidth(IJResultsTable rt) {
rt.setColumnPreferredWidth(MoleculeDescriptor.LABEL_ID, 40);
rt.setColumnPreferredWidth(MoleculeDescriptor.LABEL_FRAME, 40);
rt.setColumnPreferredWidth(PSFModel.Params.LABEL_X, 60);
rt.setColumnPreferredWidth(PSFModel.Params.LABEL_Y, 60);
rt.setColumnPreferredWidth(PSFModel.Params.LABEL_SIGMA, 40);
rt.setColumnPreferredWidth(PSFModel.Params.LABEL_SIGMA1, 40);
rt.setColumnPreferredWidth(PSFModel.Params.LABEL_SIGMA2, 40);
}
synchronized public void showResults() {
// Show table with results
IJResultsTable rt = IJResultsTable.getResultsTable();
rt.sortTableByFrame();
rt.insertIdColumn();
rt.copyOriginalToActual();
rt.setActualState();
rt.convertAllColumnsToAnalogUnits();
rt.setPreviewRenderer(renderingQueue);
setDefaultColumnsWidth(rt);
if(processedImage != null) {
rt.setAnalyzedImage(processedImage);
}
rt.setMeasurementProtocol(measurementProtocol);
rt.forceShow();
// Show detections in the image
if(processedImage != null) {
processedImage.setOverlay(null);
RenderingOverlay.showPointsInImage(rt, processedImage, roi.getBounds(), Color.red, RenderingOverlay.MARKER_CROSS);
renderingQueue.repaintLater();
}
}
} |
package de.osramos.ss13.proj1.services;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import de.osramos.ss13.proj1.model.Route;
import de.osramos.ss13.proj1.model.Taskdb;
import de.osramos.ss13.proj1.model.Userdb;
public class FirstRun implements ApplicationListener<ContextRefreshedEvent> {
static boolean first = true;
public synchronized void onApplicationEvent(ContextRefreshedEvent context) {
if (first) {
first = false;
PopulateDatabase();
}
}
public void PopulateDatabase() {
// populate with default usernames and passwords
CreateUsers();
// create sample routes
createRoutes();
// create example tasks
createTasks();
}
private void CreateUsers() {
Userdb user = null;
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("all").getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = new Userdb();
user.setFirstname("Developer");
user.setLastname("DEVELOPER");
user.setUsername("all");
user.setUserrole("all");
user.setPassword("all");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("admin")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = new Userdb();
user.setFirstname("admin");
user.setLastname("ADMIN");
user.setUsername("admin");
user.setUserrole("admin");
user.setPassword("admin");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("senior")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = new Userdb();
user.setFirstname("senior");
user.setLastname("SENIOR");
user.setUsername("senior");
user.setUserrole("senior");
user.setPassword("senior");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("testsenior")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = new Userdb();
user.setFirstname("testsenior");
user.setLastname("TESTSENIOR");
user.setUsername("testsenior");
user.setUserrole("senior");
user.setPassword("testsenior");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("trainee")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = null;
user = new Userdb();
user.setFirstname("trainee");
user.setLastname("TRAINEE");
user.setUsername("trainee");
user.setUserrole("trainee");
user.setPassword("trainee");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("maxmus")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = null;
user = new Userdb();
user.setFirstname("Max");
user.setLastname("MUSTERMANN");
user.setUsername("maxmus");
user.setUserrole("trainee");
user.setPassword("maxmus");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("tobsch")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = null;
user = new Userdb();
user.setFirstname("Tobias");
user.setLastname("SCHULZ");
user.setUsername("tobsch");
user.setUserrole("senior");
user.setPassword("tobsch");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("manmei")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = null;
user = new Userdb();
user.setFirstname("Manuel");
user.setLastname("MEIER");
user.setUsername("manmei");
user.setUserrole("admin");
user.setPassword("manmei");
user.persist();
}
} catch (Exception e) {
}
}
try {
user = null;
user = Userdb.findUserdbsByUsernameEquals("axesch")
.getSingleResult();
} catch (Exception e) {
} finally {
try {
if (null == user) {
user = null;
user = new Userdb();
user.setFirstname("Axel");
user.setLastname("SCHULZ");
user.setUsername("axesch");
user.setUserrole("trainee");
user.setPassword("axesch");
user.persist();
}
} catch (Exception e) {
}
}
}
private void createTasks() {
Userdb all = Userdb.findUserdbsByUsernameEquals("all")
.getSingleResult();
Userdb trainee = Userdb.findUserdbsByUsernameEquals("trainee")
.getSingleResult();
Userdb senior = Userdb.findUserdbsByUsernameEquals("senior")
.getSingleResult();
Userdb testsenior = Userdb.findUserdbsByUsernameEquals("testsenior")
.getSingleResult();
Userdb maxmus = Userdb.findUserdbsByUsernameEquals("maxmus")
.getSingleResult();
Userdb tobsch = Userdb.findUserdbsByUsernameEquals("tobsch")
.getSingleResult();
Route route = Route.findAllRoutes().get(0);
Route route1 = Route.findAllRoutes().get(1);
System.out.println("route" + route.getStartpointName());
Taskdb t = null;
t = new Taskdb();
t.setDescription("description A");
t.setPerson("Mr. Bond");
t.setBuilding("Building ??");
t.setPersonfunction("Function 007");
t.setRoomno("007");
t.setTaskname("Your first mission");
t.setTrainee(all);
t.setSenior(all);
t.setMap(route);
t.persist();
t = new Taskdb();
t.setDescription("description B");
t.setPerson("Mr. Powers");
t.setBuilding("Club X");
t.setPersonfunction("Function uncertain");
t.setRoomno("no number");
t.setTaskname("Your punishment");
t.setTrainee(all);
t.setSenior(all);
t.setMap(route1);
t.persist();
t = new Taskdb();
t.setDescription("description C");
t.setPerson("Mr. C");
t.setBuilding("Building C");
t.setPersonfunction("Function C");
t.setRoomno("Room C");
t.setTaskname("Task C");
t.setTrainee(trainee);
t.setSenior(testsenior);
t.persist();
t = new Taskdb();
t.setDescription("Find the Cafeteria");
t.setPerson("-");
t.setBuilding("Building D1");
t.setPersonfunction("-");
t.setRoomno("-");
t.setTaskname("What is the main dish of today?");
t.setTrainee(maxmus);
t.setSenior(senior);
t.persist();
t = new Taskdb();
t.setDescription("Get to know the HR department");
t.setPerson("Manuel Meier");
t.setBuilding("Building C2");
t.setPersonfunction("Recruiter");
t.setRoomno("01.231");
t.setTaskname("Ask Manuel Meier for his favorite color");
t.setTrainee(maxmus);
t.setSenior(tobsch);
t.persist();
t = new Taskdb();
t.setDescription("Use the bus shuttle");
t.setPerson("-");
t.setBuilding("-");
t.setPersonfunction("-");
t.setRoomno("-");
t
.setTaskname("Take the bus shuttle from A to B. Ask the driver for his name when you get out.");
t.setTrainee(maxmus);
t.setSenior(tobsch);
t.persist();
}
private void createRoutes() {
Route r = null;
r = new Route();
r.setStartpointName("Building A1");
r.setEndpointName("Building B2");
r.persist();
r = new Route();
r.setStartpointName("Building X");
r.setEndpointName("Building Z");
r.persist();
}
} |
package de.fhpotsdam.unfolding.marker;
import java.util.ArrayList;
import java.util.List;
import de.fhpotsdam.unfolding.UnfoldingMap;
/**
* Manages markers of different types. Is always connected to one map (for location to screen coordinate conversion).
*/
public class MarkerManager<E extends Marker> {
protected UnfoldingMap map;
protected List<E> markers;
protected boolean bEnableDrawing;
/**
* Creates a MarkerManager with an empty markers list.
*/
public MarkerManager() {
markers = new ArrayList<E>();
bEnableDrawing = true;
}
/**
* Creates a MarkerManager with given markers.
*
* @param markers
* The markers to add.
*/
public MarkerManager(List<E> markers) {
this();
addMarkers(markers);
}
/**
* Set the map to use for conversion of geo-locations to screen positions for the markers.
*
* @param map
* The map.
*/
public void setMap(UnfoldingMap map) {
this.map = map;
}
/**
* Sets the markers to manage.
*
* @param markers
* A list of markers. If null all existing markers will be removed.
*/
public void setMarkers(List<E> markers) {
if (markers != null) {
this.markers = markers;
}
else {
// Convenient method. Users should use clearMarkers() directly.
clearMarkers();
}
}
/**
* Removes a marker from the managed markers.
*
* @param marker
* The marker to remove.
* @return Whether the list contained the given marker.
*/
public boolean removeMarker(E marker) {
return markers.remove(marker);
}
/**
* Removes all markers.
*/
public void clearMarkers() {
markers.clear();
}
public boolean isDrawingEnabled() {
return bEnableDrawing;
}
public void enableDrawing() {
bEnableDrawing = true;
}
public void disableDrawing() {
bEnableDrawing = false;
}
/**
* Toggles whether this marker manager draws all markers or none.
*/
public void toggleDrawing() {
bEnableDrawing = !bEnableDrawing;
}
/**
* Adds a marker to the manager marker list.
*
* @param marker
* The marker to add.
* @return Whether the marker was added or not.
*/
public boolean addMarker(E marker) {
if (markers == null) {
this.markers = new ArrayList<E>();
}
if (markers.contains(marker))
return false;
markers.add(marker);
return true;
}
/**
* Adds a list of markers to the managed markers.
*
* @param markers
* A list of markers.
*/
public void addMarkers(List<E> markers) {
if (this.markers == null) {
this.markers = new ArrayList<E>();
}
this.markers.addAll(markers);
}
/**
* Returns all markers managed by this MarkerManager.
*
* @return A list of markers.
*/
public List<E> getMarkers() {
return markers;
}
/**
* @deprecated Replaced by {@link #getFirstHitMarker(float, float)}
*/
@Deprecated
public Marker isInside(float checkX, float checkY) {
return getFirstHitMarker(checkX, checkY);
}
/**
* Returns the nearest marker to the given screen coordinates.
*
* @param checkX
* The x position to check.
* @param checkY
* The y position to check.
* @return The nearest marker, or null if no marker was hit.
*/
public E getNearestMarker(float checkX, float checkY) {
E foundMarker = null;
double minDist = Double.MAX_VALUE;
for (E marker : markers) {
// Distance between marker geo-location and check position in geo-location
double dist = marker.getDistanceTo(map.getLocation(checkX, checkY));
if (minDist == dist) {
if (marker.isInside(map, checkX, checkY)) {
foundMarker = marker;
}
} else if (minDist > dist) {
minDist = dist;
foundMarker = marker;
}
}
return foundMarker;
}
/**
* Returns the first marker which the given screen coordinates hit.
*
* @param checkX
* The x position to check.
* @param checkY
* The y position to check.
* @return The hit marker, or null if no marker was hit.
*/
public E getFirstHitMarker(float checkX, float checkY) {
E foundMarker = null;
// NB: Markers should be ordered, e.g. by size ascending, i.e. big, medium, small
for (E marker : markers) {
// NB: If markers are order by size descending, i.e. small, medium, big
// for (int i = markers.size() - 1; i >= 0; i--) {
// Marker marker = markers.get(i);
if (marker.isInside(map, checkX, checkY)) {
foundMarker = marker;
break;
}
}
return foundMarker;
}
/**
* Returns all hit markers.
*
* @param checkX
* The x position to check.
* @param checkY
* The y position to check.
* @return All hit markers, or an empty list if no marker was hit.
*/
public List<E> getHitMarkers(float checkX, float checkY) {
List<E> hitMarkers = new ArrayList<E>();
for (E marker : markers) {
if (marker.isInside(map, checkX, checkY)) {
hitMarkers.add(marker);
}
}
return hitMarkers;
}
/**
* Internal method to draw all managed markers.
*/
public void draw() {
if (!bEnableDrawing)
return;
for (Marker marker : markers) {
marker.draw(map);
}
}
} |
package de.wak_sh.client.backend;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public abstract class ProgressDialogTask<Params, Result> extends
AsyncTask<Params, Void, Result> {
private ProgressDialog progressDialog;
private Context context;
private String text;
public ProgressDialogTask(Context context, String text) {
this.context = context;
this.text = text;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(text);
progressDialog.show();
}
@Override
protected void onPostExecute(Result result) {
dismissProgressDialog();
}
@Override
protected void onCancelled() {
dismissProgressDialog();
}
private void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
} |
package org.opennms.features.topology.plugins.browsers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.opennms.core.criteria.Criteria;
import org.opennms.core.criteria.Order;
import org.opennms.core.criteria.restrictions.Restriction;
import org.opennms.features.topology.api.VerticesUpdateManager;
import org.opennms.features.topology.api.topo.GroupRef;
import org.opennms.features.topology.api.topo.Vertex;
import org.opennms.features.topology.api.topo.VertexRef;
import org.opennms.netmgt.dao.api.OnmsDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.thirdparty.guava.common.base.Function;
import com.google.gwt.thirdparty.guava.common.collect.Collections2;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.BeanItem;
/**
*
* @param <T> The type of the elements in the container.
* @param <K> the key of the elements in the container.
*/
public abstract class OnmsDaoContainer<T,K extends Serializable> implements Container, Container.Sortable, Container.Ordered, Container.Indexed, Container.ItemSetChangeNotifier, VerticesUpdateManager.VerticesUpdateListener {
private static final long serialVersionUID = -9131723065433979979L;
protected static final int DEFAULT_PAGE_SIZE = 200; // items per page/cache
protected static final int DEFAULT_SIZE_RELOAD_TIME = 10000;
private static final Logger LOG = LoggerFactory.getLogger(OnmsDaoContainer.class);
protected static class Page {
protected int length;
// we initially set it to -1 to force an update on index=0
protected int offset = -1;
protected final Size size;
public Page (int length, Size size) {
this.length = length;
this.size = size;
}
/**
* Updates the offset of the current page and returns weather the offset was changed or not.
* @param index
* @return true when the offset has changed, false otherwise.
*/
public boolean updateOffset(int index) {
int oldOffset = offset;
if (index < 0) index = 0;
offset = index / length * length;
return oldOffset != offset; // an update has been made
}
public int getStart() {
return offset;
}
}
protected static class Size {
private Date lastUpdate = null;
private int value;
private int reloadTimer; // in ms
private final SizeReloadStrategy reloadStrategy;
protected Size(int reloadTimer, SizeReloadStrategy reloadStrategy) {
this.reloadTimer = reloadTimer == 0 ? DEFAULT_SIZE_RELOAD_TIME : reloadTimer;
this.reloadStrategy = reloadStrategy;
}
public synchronized int getValue() {
if (isOutdated()) reloadSize();
return value;
}
private boolean isOutdated() {
return lastUpdate == null || lastUpdate.getTime() + reloadTimer < new Date().getTime();
}
private synchronized void reloadSize() {
value = reloadStrategy.reload();
lastUpdate = new Date();
}
private void setOutdated() {
lastUpdate = null;
}
}
protected static interface SizeReloadStrategy {
int reload();
}
protected static class SortEntry implements Comparable<SortEntry> {
private final String propertyId;
private final boolean ascending;
private SortEntry(String propertyId, boolean ascending) {
this.propertyId = propertyId;
this.ascending = ascending;
}
@Override
public int compareTo(SortEntry o) {
return propertyId.compareTo(o.propertyId);
}
}
protected class Cache {
// Maps each itemId to a item.
private Map<K, BeanItem<T>> cacheContent = new HashMap<K, BeanItem<T>>();
// Maps each row to an itemId
private Map<Integer, K> rowMap = new HashMap<Integer, K>();
private Cache() {
}
public boolean containsItemId(K itemId) {
if (itemId == null) return false;
return cacheContent.containsKey(itemId);
}
public boolean containsIndex(int index) {
return rowMap.containsKey(Integer.valueOf(index));
}
public BeanItem<T> getItem(K itemId) {
if (containsItemId(itemId)) return cacheContent.get(itemId);
return null;
}
public void addItem(int rowNumber, K itemId, T bean) {
if (containsItemId(itemId)) return; //already added
cacheContent.put(itemId, new BeanItem<T>(bean));
rowMap.put(rowNumber, itemId);
}
public int getIndex(K itemId) {
for (Map.Entry<Integer, K> eachRow : rowMap.entrySet()) {
if (eachRow.getValue().equals(itemId))
return eachRow.getKey();
}
return -1; // not found
}
public void reset() {
cacheContent.clear();
rowMap.clear();
}
public K getItemId(int rowIndex) {
return rowMap.get(Integer.valueOf(rowIndex));
}
public void reload(Page page) {
size.setOutdated(); // force to be outdated
reset();
List<T> beans = getItemsForCache(m_dao, page);
if (beans == null) return;
int rowNumber = page.getStart();
for (T eachBean : beans) {
addItem(rowNumber, getId(eachBean), eachBean);
doItemAddedCallBack(rowNumber, getId(eachBean), eachBean);
rowNumber++;
}
}
}
private final OnmsDao<T,K> m_dao;
// ORDER/SORTING
private final List<Order> m_orders = new ArrayList<Order>();
// FILTERING
private final List<Restriction> m_restrictions = new ArrayList<Restriction>();
private final List< SortEntry> m_sortEntries = new ArrayList<SortEntry>();
/**
* TODO: Fix concurrent access to this field
*/
private final Collection<ItemSetChangeListener> m_itemSetChangeListeners = new HashSet<ItemSetChangeListener>();
private final Map<String,String> m_beanToHibernatePropertyMapping = new HashMap<String,String>();
private final Size size;
private final Page page;
private final Cache cache;
private final Class<T> m_itemClass;
private Map<Object,Class<?>> m_properties;
public OnmsDaoContainer(Class<T> itemClass, OnmsDao<T,K> dao) {
m_itemClass = itemClass;
m_dao = dao;
size = new Size(DEFAULT_SIZE_RELOAD_TIME, new SizeReloadStrategy() {
@Override
public int reload() {
return m_dao.countMatching(getCriteria(null, false)); // no paging!!!!
}
});
page = new Page(DEFAULT_PAGE_SIZE, size);
cache = new Cache();
}
@Override
public boolean containsId(Object itemId) {
if (itemId == null) return false;
if (cache.containsItemId((K) itemId)) return true;
int index = indexOfId(itemId);
return index >= 0;
}
@Override
public Property<?> getContainerProperty(Object itemId, Object propertyId) {
Item item = getItem(itemId);
if (item == null) {
return null;
} else {
return item.getItemProperty(propertyId);
}
}
@Override
public Collection<?> getContainerPropertyIds() {
loadPropertiesIfNull();
updateContainerPropertyIds(m_properties);
return Collections.unmodifiableCollection(m_properties.keySet());
}
@Override
public Item getItem(Object itemId) {
if (itemId == null) return null;
if (cache.containsItemId((K)itemId)) return cache.getItem((K)itemId);
// not in cache, get the right page
final int index = indexOfId(itemId);
if (index == -1) return null; // not in container
// page has the item now in container
return cache.getItem((K)itemId);
}
public Class<T> getItemClass() {
return m_itemClass;
}
protected abstract K getId(T bean);
@Override
public Class<?> getType(Object propertyId) {
return m_properties.get(propertyId);
}
@Override
public boolean removeAllItems() throws UnsupportedOperationException {
m_dao.clear();
return true;
}
@Override
public boolean removeItem(Object itemId) throws UnsupportedOperationException {
m_dao.delete((K)itemId);
return true;
}
@Override
public int size() {
return size.getValue();
}
@Override
public Object firstItemId() {
if (!cache.containsIndex(0)) {
updatePage(0);
}
return cache.getItemId(0);
}
@Override
public Object lastItemId() {
int lastIndex = size() - 1;
if (!cache.containsIndex(lastIndex)) {
updatePage(lastIndex);
}
return cache.getItemId(lastIndex);
}
@Override
public boolean isFirstId(Object itemId) {
return firstItemId().equals(itemId);
}
private void updatePage(final int index) {
boolean changed = page.updateOffset(index);
if (changed) {
cache.reload(page);
}
}
@Override
public boolean isLastId(Object itemId) {
return lastItemId().equals(itemId);
}
@Override
public Object nextItemId(Object itemId) {
if (itemId == null) return null;
int nextIdIndex = indexOfId(itemId) + 1;
if(cache.getItemId(nextIdIndex) == null) {
updatePage(page.offset + page.length);
}
return cache.getItemId(nextIdIndex);
}
@Override
public Object prevItemId(Object itemId) {
if (itemId == null) return null;
int prevIdIndex = indexOfId(itemId) - 1;
if (cache.getItemId(prevIdIndex) == null) {
updatePage(prevIdIndex);
}
return cache.getItemId(prevIdIndex);
}
/**
* This function returns {@link #getContainerPropertyIds()}.
*/
@Override
public Collection<?> getSortableContainerPropertyIds() {
return this.getContainerPropertyIds();
}
@Override
public void sort(Object[] propertyId, boolean[] ascending) {
List<SortEntry> newSortEntries = createSortEntries(propertyId, ascending);
if (!m_sortEntries.equals(newSortEntries)) {
m_sortEntries.clear();
m_sortEntries.addAll(newSortEntries);
m_orders.clear();
for(int i = 0; i < propertyId.length; i++) {
final String beanProperty = (String)propertyId[i];
String hibernateProperty = m_beanToHibernatePropertyMapping.get(beanProperty);
if (hibernateProperty == null) hibernateProperty = beanProperty;
if (ascending[i]) {
m_orders.add(Order.asc(hibernateProperty));
} else {
m_orders.add(Order.desc(hibernateProperty));
}
}
cache.reload(page);
}
}
protected List<SortEntry> createSortEntries(Object[] propertyId, boolean[] ascending) {
List<SortEntry> sortEntries = new ArrayList<SortEntry>();
for (int i=0; i<propertyId.length; i++) {
sortEntries.add(new SortEntry((String)propertyId[i], ascending[i]));
}
return sortEntries;
}
@Override
public void addListener(ItemSetChangeListener listener) {
addItemSetChangeListener(listener);
}
@Override
public void removeListener(ItemSetChangeListener listener) {
removeItemSetChangeListener(listener);
}
@Override
public void addItemSetChangeListener(ItemSetChangeListener listener) {
m_itemSetChangeListeners.add(listener);
}
@Override
public void removeItemSetChangeListener(ItemSetChangeListener listener) {
m_itemSetChangeListeners.remove(listener);
}
protected void fireItemSetChangedEvent() {
ItemSetChangeEvent event = new ItemSetChangeEvent() {
private static final long serialVersionUID = -2796401359570611938L;
@Override
public Container getContainer() {
return OnmsDaoContainer.this;
}
};
for (ItemSetChangeListener listener : m_itemSetChangeListeners) {
listener.containerItemSetChange(event);
}
}
public void setRestrictions(final List<Restriction> newRestrictions) {
if (newRestrictions == m_restrictions) return;
m_restrictions.clear();
if (newRestrictions == null) return;
m_restrictions.addAll(newRestrictions);
}
public List<Restriction> getRestrictions() {
return Collections.unmodifiableList(m_restrictions);
}
public void addBeanToHibernatePropertyMapping(final String key, final String value) {
m_beanToHibernatePropertyMapping.put(key, value);
}
@Override
public Collection<?> getItemIds() {
return getItemIds(0, size());
}
@Override
public List<K> getItemIds(int startIndex, int numberOfItems) {
int endIndex = startIndex + numberOfItems;
if (endIndex > size()) endIndex = size() - 1;
List<K> itemIds = new ArrayList<K>();
for (int i=startIndex; i<endIndex; i++) {
itemIds.add(getIdByIndex(i));
}
// TODO: Hack to remove nulls and remove duplicates. MVR will fix :)
Set<K> ids = new TreeSet<K>();
for (K itemId : itemIds) {
if (itemId == null) {
continue;
}
ids.add(itemId);
}
return new ArrayList<K>(ids);
}
@Override
public int indexOfId(Object itemId) {
if (cache.containsItemId(((K) itemId)))
return cache.getIndex((K) itemId); // cache hit *yay*
//itemId is not in the cache so we try to find the right page
boolean circled = false; // we have run through the whole cache
int startOffset = page.offset;
do {
int indexOfId = page.offset + page.length; // we have to start somewhere
// check if we are not at the end, if so, start from beginning
if (indexOfId > size()) {
indexOfId = 0;
}
// reload next page
updatePage(indexOfId);
// check if element now is in cache
if (cache.containsItemId((K) itemId)) {
return cache.getIndex((K)itemId);
}
// ensure that we have not circled yet
if (startOffset == indexOfId) {
circled = true;
}
} while (!circled); // continue as far as we have not found the element yet
return -1; // not found
}
@Override
public K getIdByIndex(int index) {
if (cache.containsIndex(index)) {
return cache.getItemId(index);
}
updatePage(index);
return cache.getItemId(index); // it is now in the cache or it does not exist
}
@Override
public Object addItemAt(int index) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
@Override
public Item addItemAt(int index, Object newItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
@Override
public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
@Override
public Item addItemAfter(Object previousItemId, Object newItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
@Override
public final boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new properties to objects in this container");
}
/**
* Can be overridden if you want to support adding items.
*/
@Override
public Object addItem() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
/**
* Can be overridden if you want to support adding items.
*/
@Override
public Item addItem(Object itemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot add new items to this container");
}
@Override
public final boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Cannot remove properties from objects in this container");
}
protected void updateContainerPropertyIds(Map<Object,Class<?>> properties) {
// by default we do nothing with the properties;
}
/**
* Creates a {@link Criteria} object to get data from database.
* If considerPaging is set Limit and offset values are added as restriction.
* @param page
* @param doOrder
* @return
*/
protected Criteria getCriteria(Page page, boolean doOrder) {
Criteria tmpCriteria = new Criteria(getItemClass());
for (Restriction eachRestriction : m_restrictions) {
tmpCriteria.addRestriction(eachRestriction);
}
if (doOrder) {
tmpCriteria.setOrders(m_orders);
}
if (page != null) {
tmpCriteria.setOffset(page.offset);
tmpCriteria.setLimit(page.length);
}
addAdditionalCriteriaOptions(tmpCriteria, page, doOrder);
LOG.debug("query criteria: {}", tmpCriteria);
return tmpCriteria;
}
// must be overwritten by subclass if you want to add some alias and so on
protected void addAdditionalCriteriaOptions(Criteria criteria, Page page, boolean doOrder) {
}
protected void doItemAddedCallBack(int rowNumber, K id, T eachBean) {
}
protected List<T> getItemsForCache(final OnmsDao<T, K> dao, final Page page) {
return dao.findMatching(getCriteria(page, true));
}
protected Cache getCache() {
return cache;
}
protected Page getPage() {
return page;
}
private synchronized void loadPropertiesIfNull() {
if (m_properties == null) {
m_properties = new TreeMap<Object,Class<?>>();
BeanItem<T> item = null;
try {
item = new BeanItem<T>(m_itemClass.newInstance());
} catch (InstantiationException e) {
LoggerFactory.getLogger(getClass()).error("Class {} does not have a default constructor. Cannot create an instance.", getItemClass());
} catch (IllegalAccessException e) {
LoggerFactory.getLogger(getClass()).error("Class {} does not have a public default constructor. Cannot create an instance.", getItemClass());
}
for (Object key : item.getItemPropertyIds()) {
m_properties.put(key, item.getItemProperty(key).getType());
}
}
}
/**
* Gets the node ids from the given vertices. A node id can only be extracted from a vertex with a "nodes"' namespace.
* For a vertex with namespace "node" the "getId()" method always returns the node id.
*
* @param vertices
* @return
*/
protected List<Integer> extractNodeIds(Collection<VertexRef> vertices) {
List<Integer> nodeIdList = new ArrayList<Integer>();
for (VertexRef eachRef : vertices) {
if ("nodes".equals(eachRef.getNamespace())) {
try {
nodeIdList.add(Integer.valueOf(eachRef.getId()));
} catch (NumberFormatException e) {
LoggerFactory.getLogger(getClass()).warn("Cannot filter nodes with ID: {}", eachRef.getId());
}
} else if( ((Vertex)eachRef).isGroup() && "category".equals(eachRef.getNamespace()) ){
try{
GroupRef group = (GroupRef) eachRef;
nodeIdList.addAll(Collections2.transform(group.getChildren(), new Function<VertexRef, Integer>(){
@Override
public Integer apply(VertexRef input) {
return Integer.valueOf(input.getId());
}
}));
} catch (ClassCastException e){
LoggerFactory.getLogger(getClass()).warn("Cannot filter category with ID: {} children: {}", eachRef.getId(), ((GroupRef) eachRef).getChildren());
}
}
}
return nodeIdList;
}
} |
package org.apache.hadoop.yarn.server.nodemanager;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CoresManagerImpl implements CoresManager {
private static final Log LOG = LogFactory
.getLog(CoresManagerImpl.class);
private Set<Integer> totalCores = new HashSet<Integer>();
private Set<Integer> unUsedCores = new HashSet<Integer>();
//should be initialized at start
private Map<Integer,Set<ContainerId>> coresToContainer = new HashMap<Integer,Set<ContainerId>>();
private Map<ContainerId, Set<Integer>> containerToCores = new HashMap<ContainerId, Set<Integer>>();
@Override
public void init(Configuration conf) {
//we get cores fisrt
int virtualCores =
conf.getInt(
YarnConfiguration.NM_VCORES, YarnConfiguration.DEFAULT_NM_VCORES);
//we initialize the total cores and unused cores
for(int i=0;i<virtualCores;i++){
totalCores.add(i);
unUsedCores.add(i);
Set<ContainerId> cntIdSet = new HashSet<ContainerId>();
coresToContainer.put(i, cntIdSet);
}
}
private Set<Integer> getAvailableCores(int num) {
Set<Integer> returnedResults = new HashSet<Integer>();
int index = 0;
assert(num <= totalCores.size());
if(unUsedCores.size() > 0){
for(Integer core : unUsedCores){
returnedResults.add(core);
index++;
if(index >= num){
break;
}
}
for(Integer core : returnedResults){
unUsedCores.remove(core);
}
}
while(index < num){
Integer value = 0;
int min = Integer.MAX_VALUE;
for(Map.Entry<Integer, Set<ContainerId>> entry: coresToContainer.entrySet()){
//find min core each time
if(returnedResults.contains(entry.getKey())){
continue;
}
if(entry.getValue().size() < min){
value = entry.getKey();
min = entry.getValue().size();
}
}
returnedResults.add(value);
}
return returnedResults;
}
@Override
public Set<Integer> allocateCores(ContainerId cntId, int num){
LogOverlapWarning();
Set<Integer> returnedResults = this.getAvailableCores(num);
this.allcoateCoresforContainer(returnedResults, cntId);
return returnedResults;
}
private void allcoateCoresforContainer(Set<Integer> cores,ContainerId cntId){
for(Integer core : cores){
coresToContainer.get(core).add(cntId);
}
containerToCores.put(cntId, cores);
LOG.info("allocate cpuset "+cores);
}
@Override
public void releaseCores(ContainerId cntId) {
LogOverlapWarning();
Set<Integer> cores= containerToCores.get(cntId);
this.releaseCoresforContainer(cntId, cores);
}
private void releaseCoresforContainer(ContainerId cntId, Set<Integer> cores){
for(Integer core : cores){
coresToContainer.get(core).remove(cntId);
if(coresToContainer.get(core).size() == 0){
unUsedCores.add(core);
}
}
containerToCores.remove(cntId);
LOG.info("release cpuset "+cores);
}
@Override
public Set<Integer> resetCores(ContainerId cntId, int num) {
Set<Integer> cores = this.containerToCores.get(cntId);
Set<Integer> returnedCores = new HashSet<Integer>();
if(num < cores.size()){
//find the core that is used least
for(int i=0; i<num; i++){
int min = Integer.MAX_VALUE;
Integer value = 0;
for(Integer core : cores){
if(returnedCores.contains(core)){
continue;
}
if(coresToContainer.get(core).size() < min){
value = core;
min = coresToContainer.get(core).size();
}
}
returnedCores.add(value);
}
//remove cores to container mapping
Set<Integer> toRemoved=new HashSet<Integer>();
for(Integer core : cores){
if(returnedCores.contains(core)){
continue;
}
toRemoved.add(core);
}
this.releaseCoresforContainer(cntId, toRemoved);
//for num >= cores.size(), we need to give more cores to this container
}else{
returnedCores.addAll(cores);
int required = num - cores.size();
if(required > 0){
Set<Integer> newAllocated = this.getAvailableCores(required);
returnedCores.addAll(newAllocated);
this.allcoateCoresforContainer(newAllocated, cntId);
}
}
return returnedCores;
}
private void LogOverlapWarning(){
LOG.info("cpuset warning");
for(Integer core : this.coresToContainer.keySet()){
if(this.coresToContainer.get(core).size() > 1){
LOG.info("cpuset overlap warning on core"+core+"size:"+this.coresToContainer.get(core).size());
}
}
}
} |
package com.opengamma.analytics.financial.interestrate.future.provider;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
import org.threeten.bp.Period;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.instrument.future.SwapFuturesPriceDeliverableSecurityDefinition;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIbor;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIborMaster;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedIborDefinition;
import com.opengamma.analytics.financial.interestrate.future.calculator.FuturesPriceMulticurveCalculator;
import com.opengamma.analytics.financial.interestrate.future.derivative.SwapFuturesPriceDeliverableSecurity;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator;
import com.opengamma.analytics.financial.provider.description.MulticurveProviderDiscountDataSets;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.MultipleCurrencyAmount;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
/**
* Tests related to the pricing of deliverable interest rate swap futures as traded on CME.
*/
@Test(groups = TestGroup.UNIT)
public class SwapFuturesPriceDeliverableSecurityDiscountingMethodTest {
private static final MulticurveProviderDiscount MULTICURVES = MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
private static final IborIndex[] INDEX_LIST = MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
private static final IborIndex USDLIBOR3M = INDEX_LIST[2];
private static final Currency USD = USDLIBOR3M.getCurrency();
private static final Calendar NYC = MulticurveProviderDiscountDataSets.getUSDCalendar();
private static final GeneratorSwapFixedIbor USD6MLIBOR3M = GeneratorSwapFixedIborMaster.getInstance().getGenerator("USD6MLIBOR3M", NYC);
private static final ZonedDateTime EFFECTIVE_DATE = DateUtils.getUTCDate(2012, 12, 19);
private static final ZonedDateTime LAST_TRADING_DATE = ScheduleCalculator.getAdjustedDate(EFFECTIVE_DATE, -USD6MLIBOR3M.getSpotLag(), NYC);
private static final Period TENOR = Period.ofYears(10);
private static final double NOTIONAL = 100000;
private static final double RATE = 0.0175;
private static final SwapFixedIborDefinition SWAP_DEFINITION = SwapFixedIborDefinition.from(EFFECTIVE_DATE, TENOR, USD6MLIBOR3M, 1.0, RATE, false);
private static final SwapFuturesPriceDeliverableSecurityDefinition SWAP_FUTURES_SECURITY_DEFINITION = new SwapFuturesPriceDeliverableSecurityDefinition(LAST_TRADING_DATE, SWAP_DEFINITION, NOTIONAL);
private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2012, 9, 20);
private static final SwapFuturesPriceDeliverableSecurity SWAP_FUTURES_SECURITY = SWAP_FUTURES_SECURITY_DEFINITION.toDerivative(REFERENCE_DATE);
private static final PresentValueDiscountingCalculator PVDC = PresentValueDiscountingCalculator.getInstance();
private static final FuturesPriceMulticurveCalculator FPMC = FuturesPriceMulticurveCalculator.getInstance();
private static final double TOLERANCE_PRICE = 1.0E-10;
@Test
public void price() {
final MultipleCurrencyAmount pvSwap = SWAP_FUTURES_SECURITY.getUnderlyingSwap().accept(PVDC, MULTICURVES);
final double priceExpected = 1.0d + pvSwap.getAmount(USD) / MULTICURVES.getMulticurveProvider().getDiscountFactor(SWAP_FUTURES_SECURITY.getCurrency(), SWAP_FUTURES_SECURITY.getDeliveryTime());
final double priceComputed = SWAP_FUTURES_SECURITY.accept(FPMC, MULTICURVES);
assertEquals("DeliverableSwapFuturesSecurityDefinition: price", priceExpected, priceComputed, TOLERANCE_PRICE);
}
} |
package org.xwiki.eventstream.store.internal;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.store.XWikiHibernateStore;
import org.hibernate.Session;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.namespace.NamespaceContextExecutor;
import org.xwiki.eventstream.Event;
import org.xwiki.eventstream.EventStatus;
import org.xwiki.eventstream.EventStatusManager;
import org.xwiki.eventstream.EventStreamException;
import org.xwiki.eventstream.internal.DefaultEventStatus;
import org.xwiki.eventstream.internal.events.EventStatusAddOrUpdatedEvent;
import org.xwiki.model.namespace.WikiNamespace;
import org.xwiki.observation.ObservationManager;
import org.xwiki.query.Query;
import org.xwiki.query.QueryManager;
import org.xwiki.text.StringUtils;
import org.xwiki.wiki.descriptor.WikiDescriptorManager;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Legacy implementation of {@link EventStatusManager} which use the Activity Stream storage.
*
* @version $Id$
* @since 11.1RC1
*/
@Component
@Singleton
public class LegacyEventStatusManager implements EventStatusManager
{
@Inject
private QueryManager queryManager;
@Inject
private LegacyEventConverter eventConverter;
@Inject
private LegacyEventStreamStoreConfiguration configuration;
@Inject
private Provider<XWikiContext> contextProvider;
@Inject
private WikiDescriptorManager wikiDescriptorManager;
@Inject
private ObservationManager observation;
@Inject
private NamespaceContextExecutor namespaceContextExecutor;
@Inject
private LegacyEventLoader legacyEventLoader;
@Override
public List<EventStatus> getEventStatus(List<Event> events, List<String> entityIds) throws Exception
{
List<EventStatus> results = new ArrayList<>();
// Don't perform any query if the list of events or entities is actually empty
if (events.isEmpty() || entityIds.isEmpty()) {
return results;
}
// Get the ActivityEventStatus from the database and convert them
Query query = queryManager.createQuery("select eventStatus from LegacyEventStatus eventStatus "
+ "where eventStatus.activityEvent.id in :eventIds and eventStatus.entityId in :entityIds", Query.HQL);
query.bindValue("eventIds", getEventIds(events));
query.bindValue("entityIds", entityIds);
for (LegacyEventStatus legacyEventStatus : query.<LegacyEventStatus>execute()) {
results.add(new DefaultEventStatus(
eventConverter.convertLegacyActivityToEvent(legacyEventStatus.getActivityEvent()),
legacyEventStatus.getEntityId(),
legacyEventStatus.isRead())
);
}
// For status that are not present in the database, we create objects with read = false
for (Event event : events) {
for (String entityId : entityIds) {
if (!isPresent(event, entityId, results)) {
results.add(new DefaultEventStatus(event, entityId, false));
}
}
}
// Sort statuses by date, in the descending order, like notifications, otherwise the order is lost
Collections.sort(results,
(status1, status2) -> status2.getEvent().getDate().compareTo(status1.getEvent().getDate()));
return results;
}
/**
* @param events a list of events
* @return the list of the events' id
*/
private List<String> getEventIds(List<Event> events)
{
List<String> eventIds = new ArrayList<>();
for (Event event : events) {
eventIds.add(event.getId());
}
return eventIds;
}
/**
* @return if there is a status concerning the given event and the given entity in a list of statuses
*/
private boolean isPresent(Event event, String entityId, List<EventStatus> list)
{
for (EventStatus status : list) {
if (StringUtils.equals(status.getEvent().getId(), event.getId())
&& StringUtils.equals(status.getEntityId(), entityId)) {
return true;
}
}
return false;
}
@Override
public void saveEventStatus(EventStatus eventStatus) throws Exception
{
LegacyEventStatus status = eventConverter.convertEventStatusToLegacyActivityStatus(eventStatus);
boolean isSavedOnMainStore = false;
if (configuration.useLocalStore()) {
String currentWiki = wikiDescriptorManager.getCurrentWikiId();
saveEventStatusInStore(status, currentWiki);
isSavedOnMainStore = wikiDescriptorManager.isMainWiki(currentWiki);
}
if (configuration.useMainStore() && !isSavedOnMainStore) {
// save event into the main database (if the event was not already be recorded on the main store,
// otherwise we would duplicate the event)
saveEventStatusInStore(status, wikiDescriptorManager.getMainWikiId());
}
}
private void saveEventStatusInStore(LegacyEventStatus eventStatus, String wikiId) throws Exception
{
namespaceContextExecutor.execute(new WikiNamespace(wikiId),
() -> {
XWikiContext context = contextProvider.get();
XWikiHibernateStore hibernateStore = context.getWiki().getHibernateStore();
try {
hibernateStore.beginTransaction(context);
Session session = hibernateStore.getSession(context);
// The event status may already exists, so we use saveOrUpdate
session.saveOrUpdate(eventStatus);
hibernateStore.endTransaction(context, true);
} catch (XWikiException e) {
hibernateStore.endTransaction(context, false);
throw new EventStreamException(e);
}
this.observation.notify(new EventStatusAddOrUpdatedEvent(), eventStatus);
return null;
}
);
}
} |
package edu.cs4730.wearapp;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends WearableActivity {
private TextView mTextView;
Random myRandom = new Random();
ImageButton ib;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
mTextView.setText(" " + myRandom.nextInt(10) + " ");
//get the imagebutton (checkmark) and set up the listener for a random number.
ib = (ImageButton) findViewById(R.id.myButton);
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setText(" " + myRandom.nextInt(10) + " ");
}
});
// Enables Always-on
setAmbientEnabled();
}
} |
package org.hd.d.edh;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.hd.d.edh.FUELINST.CurrentSummary;
/**Supporting routines of general interest for handling FUELINST data.
*/
public final class FUELINSTUtils
{
private FUELINSTUtils() { /* Prevent creation of an instance. */ }
/**Longest edge of graphics building block components in pixels for HTML generation; strictly positive. */
static final int GCOMP_PX_MAX = 100;
/**If true then when data is stale then cautiously never normally show a GREEN status, but YELLOW at best. */
private static final boolean NEVER_GREEN_WHEN_STALE = true;
/**If the basic colour is GREEN but we're using pumped storage then we can indicate that with a yellowish green instead (ie mainly green, but not fully). */
static final String LESS_GREEN_STORAGE_DRAWDOWN = "olive";
/**If true then reject points with too few fuel types in mix since this is likely an error. */
final static int MIN_FUEL_TYPES_IN_MIX = 2;
/**If true, compress (GZIP) any persisted state. */
static final boolean GZIP_CACHE = true;
/**Immutable regex pattern for matching a valid fuel name (all upper-case ASCII first char, digits also allowed subsequently); non-null. */
public static final Pattern FUEL_NAME_REGEX = Pattern.compile("[A-Z][A-Z0-9]+");
/**Immutable regex pattern for matching a valid fuel intensity year 20XX; non-null. */
public static final Pattern FUEL_INTENSITY_YEAR_REGEX = Pattern.compile("20[0-9][0-9]");
/**SimpleDateFormat pattern to parse TIBCO FUELINST timestamp down to seconds (all assumed GMT/UTC); not null.
* Example TIBCO timestamp: 2009:03:09:23:57:30:GMT
* Note that SimpleDateFormat is not immutable nor thread-safe.
*/
public static final String TIBCOTIMESTAMP_FORMAT = "yyyy:MM:dd:HH:mm:ss:zzz";
/**SimpleDateFormat pattern to parse CSV FUELINST timestamp down to seconds (all assumed GMT/UTC); not null.
* Note that SimpleDateFormat is not immutable nor thread-safe.
*/
public static final String CSVTIMESTAMP_FORMAT = "yyyyMMddHHmmss";
/**SimpleDateFormat pattern to generate UTC date down to days; not null.
* Note that SimpleDateFormat is not immutable nor thread-safe.
*/
public static final String UTCDAYFILENAME_FORMAT = "yyyyMMdd";
/**SimpleDateFormat pattern to generate ISO 8601 UTC timestamp down to minutes; not null.
* Note that SimpleDateFormat is not immutable nor thread-safe.
*/
public static final String UTCMINTIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm'Z'";
/**SimpleDateFormat pattern to generate/parse compact HH:mm timestamp down to seconds (all assumed GMT/UTC); not null.
* Note that SimpleDateFormat is not immutable nor thread-safe.
*/
public static final String HHMMTIMESTAMP_FORMAT = "HH:mm";
/**GMT TimeZone; never null.
* Only package-visible because it may be mutable though we never attempt to mutate it.
* <p>
* We may share this (read-only) between threads and within this package.
*/
static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone("GMT");
/**Number of hours in a day. */
public static final int HOURS_PER_DAY = 24;
/**Compute current status of fuel intensity; never null, but may be empty/default if data not available.
* If cacheing is enabled, then this may revert to cache in case of
* difficulty retrieving new data.
* <p>
* Uses fuel intensities as of this year, ie when this call is made.
*
* @param cacheFile if non-null, file to cache (parsed) data in between calls in case of data-source problems
* @throws IOException in case of data corruption
*/
public static FUELINST.CurrentSummary computeCurrentSummary(final File cacheFile)
throws IOException
{
// Get as much set up as we can before pestering the data source...
final Map<String, String> rawProperties = MainProperties.getRawProperties();
final String dataURL = rawProperties.get(FUELINST.FUEL_INTENSITY_MAIN_PROPNAME_CURRENT_DATA_URL);
if(null == dataURL)
{ throw new IllegalStateException("Property undefined for data source URL: " + FUELINST.FUEL_INTENSITY_MAIN_PROPNAME_CURRENT_DATA_URL); }
final String template = rawProperties.get(FUELINST.FUELINST_MAIN_PROPNAME_ROW_FIELDNAMES);
if(null == template)
{ throw new IllegalStateException("Property undefined for FUELINST row field names: " + FUELINST.FUELINST_MAIN_PROPNAME_ROW_FIELDNAMES); }
// Use fuel intensities as of this year, ie when this call is made.
final LocalDate todayUTC = LocalDate.now(ZoneOffset.UTC);
final Map<String, Float> configuredIntensities = FUELINSTUtils.getConfiguredIntensities(todayUTC.getYear());
if(configuredIntensities.isEmpty())
{ throw new IllegalStateException("Properties undefined for fuel intensities: " + FUELINST.FUEL_INTENSITY_MAIN_PROPNAME_PREFIX + "*"); }
final String maxIntensityAgeS = rawProperties.get(FUELINST.FUELINST_MAIN_PROPNAME_MAX_AGE);
if(null == maxIntensityAgeS)
{ throw new IllegalStateException("Property undefined for FUELINST acceptable age (s): " + FUELINST.FUELINST_MAIN_PROPNAME_MAX_AGE); }
final long maxIntensityAge = Math.round(1000 * Double.parseDouble(maxIntensityAgeS));
final String distLossS = rawProperties.get(FUELINST.FUELINST_MAIN_PROPNAME_MAX_DIST_LOSS);
if(null == distLossS)
{ throw new IllegalStateException("Property undefined for FUELINST distribution loss: " + FUELINST.FUELINST_MAIN_PROPNAME_MAX_DIST_LOSS); }
final float distLoss = Float.parseFloat(distLossS);
if(!(distLoss >= 0) && (distLoss <= 1))
{ throw new IllegalStateException("Bad value outside range [0.0,1.0] for FUELINST distribution loss: " + FUELINST.FUELINST_MAIN_PROPNAME_MAX_DIST_LOSS); }
final String tranLossS = rawProperties.get(FUELINST.FUELINST_MAIN_PROPNAME_MAX_TRAN_LOSS);
if(null == tranLossS)
{ throw new IllegalStateException("Property undefined for FUELINST transmission loss: " + FUELINST.FUELINST_MAIN_PROPNAME_MAX_TRAN_LOSS); }
final float tranLoss = Float.parseFloat(tranLossS);
if(!(tranLoss >= 0) && (tranLoss <= 1))
{ throw new IllegalStateException("Bad value outside range [0.0,1.0] for FUELINST transmission loss: " + FUELINST.FUELINST_MAIN_PROPNAME_MAX_TRAN_LOSS); }
// Extract all fuel categories.
final Map<String, Set<String>> fuelsByCategory = getFuelsByCategory();
// Extract Set of zero-or-more 'storage'/'fuel' types/names; never null but may be empty.
final Set<String> storageTypes = (fuelsByCategory.containsKey(FUELINST.FUELINST_CATNAME_STORAGE) ?
fuelsByCategory.get(FUELINST.FUELINST_CATNAME_STORAGE) :
Collections.<String>emptySet());
final List<List<String>> parsedBMRCSV;
// Fetch and parse the CSV file from the data source.
// Return an empty summary instance in case of IO error here.
URL url = null;
try
{
// Set up URL connection to fetch the data.
url = new URL(dataURL.trim()); // Trim to avoid problems with trailing whitespace...
final URLConnection conn = url.openConnection();
conn.setAllowUserInteraction(false);
conn.setUseCaches(false); // Ensure that we get non-stale values each time.
conn.setConnectTimeout(60000); // Set a long-ish connection timeout.
conn.setReadTimeout(60000); // Set a long-ish read timeout.
final InputStreamReader is = new InputStreamReader(conn.getInputStream());
try { parsedBMRCSV = DataUtils.parseBMRCSV(is, null); }
finally { is.close(); }
}
catch(final IOException e)
{
// Could not get data, so status is unknown.
System.err.println("Could not fetch data from " + url + " error: " + e.getMessage());
// Try to retrieve from cache...
FUELINST.CurrentSummary cached = null;
try { cached = (FUELINST.CurrentSummary) DataUtils.deserialiseFromFile(cacheFile, FUELINSTUtils.GZIP_CACHE); }
catch(final IOException err) { /* Fall through... */ }
catch(final Exception err) { e.printStackTrace(); }
if(null != cached)
{
System.err.println("WARNING: using previous response from cache...");
return(cached);
}
// Return empty place-holder value.
return(new FUELINST.CurrentSummary());
}
final int rawRowCount = parsedBMRCSV.size();
System.out.println("Record/row count of CSV FUELINST data: " + rawRowCount + " from source: " + url);
// All intensity sample values from good records (assuming roughly equally spaced).
final List<Integer> allIntensitySamples = new ArrayList<Integer>(rawRowCount);
// Compute summary.
final SimpleDateFormat timestampParser = FUELINSTUtils.getCSVTimestampParser();
int goodRecordCount = 0;
int totalIntensity = 0;
long firstGoodRecordTimestamp = 0;
long lastGoodRecordTimestamp = 0;
long minIntensityRecordTimestamp = 0;
long maxIntensityRecordTimestamp = 0;
int minIntensity = Integer.MAX_VALUE;
int maxIntensity = Integer.MIN_VALUE;
int currentIntensity = 0;
long currentMW = 0;
long currentStorageDrawdownMW = 0;
Map<String,Integer> currentGenerationByFuel = Collections.emptyMap();
final int[] sampleCount = new int[FUELINSTUtils.HOURS_PER_DAY]; // Count of all good timestamped records.
final long[] totalIntensityByHourOfDay = new long[FUELINSTUtils.HOURS_PER_DAY]; // Use long to avoid overflow if many samples.
final long[] totalGenerationByHourOfDay = new long[FUELINSTUtils.HOURS_PER_DAY]; // Use long to avoid overflow if many samples.
final long[] totalZCGenerationByHourOfDay = new long[FUELINSTUtils.HOURS_PER_DAY]; // Use long to avoid overflow if many samples.
final long[] totalStorageDrawdownByHourOfDay = new long[FUELINSTUtils.HOURS_PER_DAY]; // Use long to avoid overflow if many samples.
// Set of all usable fuel types encountered.
final Set<String> usableFuels = new HashSet<String>();
// Sample-by-sample list of map of generation by fuel type (in MW) and from "" to weighted intensity (gCO2/kWh).
final List<Map<String, Integer>> sampleBySampleGenForCorr = new ArrayList<Map<String,Integer>>(parsedBMRCSV.size());
// Compute (crude) correlation between fuel use and intensity.
for(final List<String> row : parsedBMRCSV)
{
// Extract fuel values for this row and compute a weighted intensity...
final Map<String, String> namedFields = DataUtils.extractNamedFieldsByPositionFromRow(template, row);
// Special case after BMRS upgrade 2016/12/30: ignore trailing row starting "FTR ".
if(namedFields.get("type").startsWith("FTR")) { continue; }
// Reject malformed/unexpected data.
if(!"FUELINST".equals(namedFields.get("type")))
{ throw new IOException("Expected FUELINST data but got: " + namedFields.get("type")); }
final Map<String,Integer> generationByFuel = new HashMap<String,Integer>();
long thisMW = 0; // Total MW generation in this slot.
long thisStorageDrawdownMW = 0; // Total MW storage draw-down in this slot.
long thisZCGenerationMW = 0; // Total zero-carbon generation in this slot.
// Retain any field that is all caps so that we can display it.
for(final String name : namedFields.keySet())
{
// Skip if something other than a valid fuel name.
if(!FUELINSTUtils.FUEL_NAME_REGEX.matcher(name).matches())
{
// DHD20211031: all inspected were benign 'date', 'type', 'settlementperiod', 'timestamp'.
// System.err.println("Skipping invalid 'fuel' name "+name+" at " + namedFields.get("timestamp") + " from row " + row);
continue;
}
// Store the MW for this fuel.
final int fuelMW = Integer.parseInt(namedFields.get(name), 10);
if(fuelMW < 0) { continue; } // NB: -ve INTerconnector values in TIBCO data as of 2012 // { throw new IOException("Bad (-ve) fuel generation MW value: "+row); }
thisMW += fuelMW;
generationByFuel.put(name, fuelMW);
// Slices of generation/demand.
if(storageTypes.contains(name)) { thisStorageDrawdownMW += fuelMW; }
final Float fuelInt = configuredIntensities.get(name);
final boolean usableFuel = null != fuelInt;
if(usableFuel) { usableFuels.add(name); }
if(usableFuel && (fuelInt <= 0)) { thisZCGenerationMW += fuelMW; }
}
// Compute weighted intensity as gCO2/kWh for simplicity of representation.
// 'Bad' fuels such as coal are ~1000, natural gas is <400, wind and nuclear are roughly 0.
final int weightedIntensity = Math.round(1000 * FUELINSTUtils.computeWeightedIntensity(configuredIntensities, generationByFuel, MIN_FUEL_TYPES_IN_MIX));
// Reject bad (-ve) records.
if(weightedIntensity < 0)
{
System.err.println("Skipping non-positive weighed intensity record at " + namedFields.get("timestamp"));
continue;
}
allIntensitySamples.add(weightedIntensity);
// For computing correlations...
// Add entry only iff both a valid weighted intensity and at least one by-fuel number.
if(!generationByFuel.isEmpty())
{
final Map<String, Integer> corrEntry = new HashMap<String, Integer>(generationByFuel);
corrEntry.put("", weightedIntensity);
sampleBySampleGenForCorr.add(corrEntry);
}
currentMW = thisMW;
currentIntensity = weightedIntensity; // Last (good) record we process is the 'current' one as they are in date order.
currentGenerationByFuel = generationByFuel;
currentStorageDrawdownMW = thisStorageDrawdownMW; // Last (good) record is 'current'.
++goodRecordCount;
totalIntensity += weightedIntensity;
// Extract timestamp field as defined in the template, format YYYYMMDDHHMMSS.
final String rawTimestamp = namedFields.get("timestamp");
long recordTimestamp = 0; // Will be non-zero after a successful parse.
if(null == rawTimestamp)
{ System.err.println("missing FUELINST row timestamp"); }
else
{
try
{
final Date d = timestampParser.parse(rawTimestamp);
recordTimestamp = d.getTime();
lastGoodRecordTimestamp = recordTimestamp;
if(firstGoodRecordTimestamp == 0) { firstGoodRecordTimestamp = recordTimestamp; }
// Extract raw GMT hour from YYYYMMDDHH...
final int hour = Integer.parseInt(rawTimestamp.substring(8, 10), 10);
//System.out.println("H="+hour+": int="+weightedIntensity+", MW="+currentMW+" time="+d);
++sampleCount[hour];
// Accumulate intensity by hour...
totalIntensityByHourOfDay[hour] += weightedIntensity;
// Accumulate generation by hour...
totalGenerationByHourOfDay[hour] += currentMW;
// Note zero-carbon generation.
totalZCGenerationByHourOfDay[hour] += thisZCGenerationMW;
// Note storage draw-down, if any.
totalStorageDrawdownByHourOfDay[hour] += thisStorageDrawdownMW;
}
catch(final ParseException e)
{
System.err.println("Unable to parse FUELINST record timestamp " + rawTimestamp + ": " + e.getMessage());
}
}
if(weightedIntensity < minIntensity)
{ minIntensity = weightedIntensity; minIntensityRecordTimestamp = recordTimestamp; }
if(weightedIntensity > maxIntensity)
{ maxIntensity = weightedIntensity; maxIntensityRecordTimestamp = recordTimestamp; }
}
// Note if the intensity dropped/improved in the final samples.
TrafficLight recentChange = null;
if(allIntensitySamples.size() > 1)
{
final Integer prev = allIntensitySamples.get(allIntensitySamples.size() - 2);
final Integer last = allIntensitySamples.get(allIntensitySamples.size() - 1);
if(prev < last) { recentChange = TrafficLight.RED; }
else if(prev > last) { recentChange = TrafficLight.GREEN; }
else { recentChange = TrafficLight.YELLOW; }
}
// Compute traffic light status: defaults to 'unknown'.
TrafficLight status = null;
final int aveIntensity = totalIntensity / Math.max(goodRecordCount, 1);
// Always set the outputs and let the caller decide what to do with aged data.
int lowerThreshold = 0;
int upperThreshold = 0;
final int allSamplesSize = allIntensitySamples.size();
if(allSamplesSize > 3) // Only useful above some minimal set size.
{
// Normally we expect bmreports to give us 24hrs' data.
// RED will be where the current value is in the upper quartile of the last 24hrs' intensities,
// GREEN when in the lower quartile (and below the mean to be safe), so is fairly conservative,
// YELLOW otherwise.
// as long as we're on better-than-median intensity compared to the last 24 hours.
final List<Integer> sortedIntensitySamples = new ArrayList<Integer>(allIntensitySamples);
Collections.sort(sortedIntensitySamples);
upperThreshold = sortedIntensitySamples.get(allSamplesSize-1 - (allSamplesSize / 4));
lowerThreshold = Math.min(sortedIntensitySamples.get(allSamplesSize / 4), aveIntensity);
if(currentIntensity > upperThreshold) { status = TrafficLight.RED; }
else if(currentIntensity < lowerThreshold) { status = TrafficLight.GREEN; }
else { status = TrafficLight.YELLOW; }
}
else { System.err.println("Newest data point too old"); }
// Compute mean intensity by time slot.
final List<Integer> aveIntensityByHourOfDay = new ArrayList<Integer>(24);
for(int h = 0; h < 24; ++h)
{ aveIntensityByHourOfDay.add((sampleCount[h] < 1) ? null : Integer.valueOf((int) (totalIntensityByHourOfDay[h] / sampleCount[h]))); }
// Compute mean generation by time slot.
final List<Integer> aveGenerationByHourOfDay = new ArrayList<Integer>(24);
for(int h = 0; h < 24; ++h)
{ aveGenerationByHourOfDay.add((sampleCount[h] < 1) ? null : Integer.valueOf((int) (totalGenerationByHourOfDay[h] / sampleCount[h]))); }
// Compute mean zero-carbon generation by time slot.
final List<Integer> aveZCGenerationByHourOfDay = new ArrayList<Integer>(24);
for(int h = 0; h < 24; ++h)
{ aveZCGenerationByHourOfDay.add((sampleCount[h] < 1) ? null : Integer.valueOf((int) (totalZCGenerationByHourOfDay[h] / sampleCount[h]))); }
// Compute mean draw-down from storage by time slot.
final List<Integer> aveStorageDrawdownByHourOfDay = new ArrayList<Integer>(24);
for(int h = 0; h < 24; ++h)
{ aveStorageDrawdownByHourOfDay.add((sampleCount[h] < 1) ? null : Integer.valueOf((int) (totalStorageDrawdownByHourOfDay[h] / sampleCount[h]))); }
// Compute fuel/intensity correlation.
final Map<String,Float> correlationIntensityToFuel = new HashMap<String,Float>(usableFuels.size());
if(!sampleBySampleGenForCorr.isEmpty())
{
// Compute correlation by fuel, where there are enough samples.
for(final String fuel : usableFuels)
{
final List<Double> fuelMW = new ArrayList<Double>(sampleBySampleGenForCorr.size());
final List<Double> gridIntensity = new ArrayList<Double>(sampleBySampleGenForCorr.size());
for(int i = sampleBySampleGenForCorr.size(); --i >= 0; )
{
final Map<String, Integer> s = sampleBySampleGenForCorr.get(i);
// Only use matching pairs of intensity and MW values to keep lists matching by position.
if(s.containsKey("") && s.containsKey(fuel))
{
fuelMW.add(s.get(fuel).doubleValue());
gridIntensity.add(s.get("").doubleValue());
}
}
// Do not attempt unless enough samples.
if(fuelMW.size() > 1)
{
final float corr = (float) StatsUtils.ComputePearsonCorrelation(gridIntensity, fuelMW);
// Retain correlation only if sane / finite.
if(!Float.isNaN(corr) && !Float.isInfinite(corr))
{ correlationIntensityToFuel.put(fuel, corr); }
}
}
}
// Construct summary status...
final FUELINST.CurrentSummary result =
new FUELINST.CurrentSummary(status, recentChange,
lastGoodRecordTimestamp, lastGoodRecordTimestamp + maxIntensityAge,
currentMW,
currentIntensity,
currentGenerationByFuel,
currentStorageDrawdownMW,
minIntensity,
minIntensityRecordTimestamp,
aveIntensity,
maxIntensity,
maxIntensityRecordTimestamp, (lastGoodRecordTimestamp - firstGoodRecordTimestamp),
goodRecordCount,
lowerThreshold, upperThreshold,
aveIntensityByHourOfDay,
aveGenerationByHourOfDay,
aveZCGenerationByHourOfDay,
aveStorageDrawdownByHourOfDay,
tranLoss + distLoss,
correlationIntensityToFuel);
// If cacheing is enabled then persist this result, compressed.
if(null != cacheFile)
{ DataUtils.serialiseToFile(result, cacheFile, FUELINSTUtils.GZIP_CACHE, true); }
return(result);
}
/**Compute variability % of a set as a function of its (non-negative) min and max values; always in range [0,100]. */
static int computeVariability(final int min, final int max)
{
if((min < 0) || (max < 0)) { throw new IllegalArgumentException(); }
if(max == 0) { return(0); }
return(100 - ((100*min)/max));
}
/**Compute variability % of a set as a function of its min and max values; always in range [0,100]. */
static int computeVariability(final List<FUELINSTHistorical.TimestampedNonNegInt> intensities)
{
if(null == intensities) { throw new IllegalArgumentException(); }
int min = Integer.MAX_VALUE;
int max = 0;
for(final FUELINSTHistorical.TimestampedNonNegInt ti : intensities)
{
if(ti.value > max) { max = ti.value; }
if(ti.value < min) { min = ti.value; }
}
return(computeVariability(min, max));
}
/**Given a set of relative fuel usages and carbon intensities, computes an overall intensity; never null.
* This computes an intensity in the same units as the supplied values.
* Fuels whose keys are not in the intensities Map will be ignored.
* <p>
* Inputs must not be altered while this is in progress.
* <p>
* This will not attempt to alter its inputs.
*
* @param intensities Map from fuel name to CO2 per unit of energy; never null
* @param generationByFuel Map from fuel name to power being generated from that fuel; never null
* @param minFuelTypesInMix minimum number of fuel types in mix else return -1; non-negative
*
* @return weighted intensity of specified fuel mix for fuels with known intensity,
* or -1 if too few fuels in mix
*/
public static float computeWeightedIntensity(final Map<String, Float> intensities,
final Map<String, Integer> generationByFuel,
final int minFuelTypesInMix)
{
if(null == intensities) { throw new IllegalArgumentException(); }
if(null == generationByFuel) { throw new IllegalArgumentException(); }
if(minFuelTypesInMix < 0) { throw new IllegalArgumentException(); }
// Compute set of keys common to both Maps.
final Set<String> commonKeys = new HashSet<String>(intensities.keySet());
commonKeys.retainAll(generationByFuel.keySet());
// If too few fuels in the mix then quickly return -1 as a distinguished value.
if(commonKeys.size() < minFuelTypesInMix) { return(-1); }
int nonZeroFuelCount = 0;
float totalGeneration = 0;
float totalCO2 = 0;
for(final String fuelName : commonKeys)
{
final float power = generationByFuel.get(fuelName);
if(power < 0) { throw new IllegalArgumentException(); }
if(power == 0) { continue; }
++nonZeroFuelCount;
totalGeneration += power;
totalCO2 += power * intensities.get(fuelName);
}
// If too few (non-zero) fuels in the mix then quickly return -1 as a distinguished value.
if(nonZeroFuelCount < minFuelTypesInMix) { return(-1); }
final float weightedIntensity = (totalGeneration == 0) ? 0 : totalCO2 / totalGeneration;
return(weightedIntensity);
}
/**Handle the flag files that can be tested by remote servers.
* The basic ".flag" file is present unless status is green
* AND we have live data.
* <p>
* The more robust ".predicted.flag" file is present unless status is green.
* Live data is used if present, else a prediction is made from historical data.
* <p>
* The keen ".supergreen.flag" file is present unless status is green
* AND we have live data
* AND no storage is being drawn down on the grid.
* This means that we can be pretty sure that there is a surplus of energy available.
*
* @param baseFileName base file name to make flags; if null then don't do flags.
* @param statusCapped status capped to YELLOW if there is no live data
* @param statusUncapped uncapped status (can be green from prediction even if no live data)
* @throws IOException in case of problems
*/
static void doFlagFiles(final String baseFileName,
final TrafficLight statusCapped, final TrafficLight statusUncapped,
final long currentStorageDrawdownMW)
throws IOException
{
if(null == baseFileName) { return; }
// In the absence of current data,
// then create/clear the flag based on historical data (ie predictions) where possible.
// The flag file has terminating extension (from final ".") replaced with ".flag".
// (If no extension is present then ".flag" is simply appended.)
final File outputFlagFile = new File(baseFileName + ".flag");
final boolean basicFlagState = TrafficLight.GREEN != statusCapped;
System.out.println("Basic flag file is " + outputFlagFile + ": " + (basicFlagState ? "set" : "clear"));
// Remove power-low/grid-poor flag file when status is GREEN, else create it (for RED/YELLOW/unknown).
FUELINSTUtils.doPublicFlagFile(outputFlagFile, basicFlagState);
// Now deal with the flag that is prepared to make predictions from historical data,
// ie helps to ensure that the flag will probably be cleared some time each day
// even if our data source is unreliable.
// When live data is available then this should be the same as the basic flag.
final File outputPredictedFlagFile = new File(baseFileName + ".predicted.flag");
final boolean predictedFlagState = TrafficLight.GREEN != statusUncapped;
System.out.println("Predicted flag file is " + outputPredictedFlagFile + ": " + (predictedFlagState ? "set" : "clear"));
// Remove power-low/grid-poor flag file when status is GREEN, else create it (for RED/YELLOW/unknown).
FUELINSTUtils.doPublicFlagFile(outputPredictedFlagFile, predictedFlagState);
// Present unless 'capped' value is green (and thus must also be from live data)
// AND there storage is not being drawn from.
final File outputSupergreenFlagFile = new File(baseFileName + ".supergreen.flag");
final boolean supergreenFlagState = (basicFlagState) || (currentStorageDrawdownMW > 0);
System.out.println("Supergreen flag file is " + outputSupergreenFlagFile + ": " + (supergreenFlagState ? "set" : "clear"));
// Remove power-low/grid-poor flag file when status is GREEN, else create it (for RED/YELLOW/unknown).
FUELINSTUtils.doPublicFlagFile(outputSupergreenFlagFile, supergreenFlagState);
// Present when red, ie not in most carbon-intensive part of the day.
// Flag is computed even with stale data.
final File outputRedFlagFile = new File(baseFileName + ".red.flag");
final boolean redFlagState = TrafficLight.RED == statusUncapped;
System.out.println("Red flag file is " + outputRedFlagFile + ": " + (redFlagState ? "set" : "clear"));
// Remove power-low/grid-poor flag file when status is not RED, else create it (for GREEN/YELLOW/unknown).
FUELINSTUtils.doPublicFlagFile(outputRedFlagFile, redFlagState);
}
/**Create/remove public (readable by everyone) flag file as needed to match required state.
* @param outputFlagFile flag file to create (true) or remove (false) if required; non-null
* @param flagRequiredPresent desired state for flag: true indicates present, false indicates absent
* @throws IOException in case of difficulty
*/
static void doPublicFlagFile(final File outputFlagFile,
final boolean flagRequiredPresent)
throws IOException
{
if(flagRequiredPresent)
{
if(outputFlagFile.createNewFile())
{
outputFlagFile.setReadable(true);
System.out.println("Flag file created: "+outputFlagFile);
}
}
else
{ if(outputFlagFile.delete()) { System.out.println("Flag file deleted: "+outputFlagFile); } }
}
/**Implement the 'traffic lights' command line option.
* @param args optional (though usual) trailing argument (output HTML file name); never null
*/
static void doTrafficLights(final String[] args)
throws IOException
{
if(null == args) { throw new IllegalArgumentException(); }
final long startTime = System.currentTimeMillis();
System.out.println("Generating traffic-light summary "+Arrays.asList(args)+"...");
final String outputHTMLFileName = (args.length < 1) ? null : args[0];
final int lastDot = (outputHTMLFileName == null) ? -1 : outputHTMLFileName.lastIndexOf(".");
// Base/prefix onto which to append specific extensions.
final String baseFileName = (-1 == lastDot) ? outputHTMLFileName : outputHTMLFileName.substring(0, lastDot);
final File cacheFile = (null == baseFileName) ? null : (new File(baseFileName + ".cache"));
// Retrieve summary.
final CurrentSummary summary = FUELINSTUtils.computeCurrentSummary(cacheFile);
// Dump a summary of the current status re fuel.
System.out.println(summary);
// Is the data stale?
final boolean isDataStale = summary.useByTime < startTime;
// Compute intensity as seen by typical GB domestic consumer, gCO2/kWh.
final int retailIntensity = Math.round((isDataStale ?
summary.histAveIntensity :
summary.currentIntensity) * (1 + summary.totalGridLosses));
if(outputHTMLFileName != null)
{
// Status to use to drive traffic-light measure.
// If the data is current then use the latest data point,
// else extract a suitable historical value to use in its place.
final int hourOfDayHistorical = CurrentSummary.getGMTHourOfDay(startTime);
final TrafficLight statusHistorical = summary.selectColour(summary.histAveIntensityByHourOfDay.get(hourOfDayHistorical));
final TrafficLight statusHistoricalCapped = (TrafficLight.GREEN != statusHistorical) ? statusHistorical : TrafficLight.YELLOW;
final TrafficLight statusUncapped = (!isDataStale) ? summary.status : statusHistorical;
final TrafficLight status = (!isDataStale) ? summary.status :
(NEVER_GREEN_WHEN_STALE ? statusHistoricalCapped : statusHistorical);
// Handle the flag files that can be tested by remote servers.
try { FUELINSTUtils.doFlagFiles(baseFileName, status, statusUncapped, summary.currentStorageDrawdownMW); }
catch(final IOException e) { e.printStackTrace(); }
final TwitterUtils.TwitterDetails td = TwitterUtils.getTwitterHandle(false);
// Update the HTML page.
try
{
FUELINSTUtils.updateHTMLFile(startTime, outputHTMLFileName, summary, isDataStale,
hourOfDayHistorical, status, td);
}
catch(final IOException e) { e.printStackTrace(); }
// Update the XML data dump.
try
{
final String outputXMLFileName = (-1 != lastDot) ? (outputHTMLFileName.substring(0, lastDot) + ".xml") :
(outputHTMLFileName + ".xml");
if(null != outputXMLFileName)
{
FUELINSTUtils.updateXMLFile(startTime, outputXMLFileName, summary, isDataStale,
hourOfDayHistorical, status);
}
}
catch(final IOException e) { e.printStackTrace(); }
// Update the (mobile-friendly) XHTML page.
try
{
final String outputXHTMLFileName = (-1 != lastDot) ? (outputHTMLFileName.substring(0, lastDot) + ".xhtml") :
(outputHTMLFileName + ".xhtml");
// if(null != outputXHTMLFileName)
FUELINSTUtils.updateXHTMLFile(startTime, outputXHTMLFileName, summary, isDataStale,
hourOfDayHistorical, status);
}
catch(final IOException e) { e.printStackTrace(); }
// Update the plain-text intensity file.
try
{
final String outputTXTFileName = (-1 != lastDot) ? (outputHTMLFileName.substring(0, lastDot) + ".txt") :
(outputHTMLFileName + ".txt");
// if(null != outputTXTFileName)
FUELINSTUtils.updateTXTFile(startTime, outputTXTFileName, summary, isDataStale);
}
catch(final IOException e) { e.printStackTrace(); }
// Update Twitter if it is set up
// and if this represents a change from the previous status.
// We may have different messages when we're working from historical data
// because real-time / live data is not available.
try
{
if(td != null)
{
// Compute name of file in which to cache last status we sent to Twitter.
final String TwitterCacheFileName = (-1 != lastDot) ? (outputHTMLFileName.substring(0, lastDot) + ".twittercache") :
(outputHTMLFileName + ".twittercache");
// Attempt to update the displayed Twitter status as necessary
// only if we think the status changed since we last sent it
// and it has actually changed compared to what is at Twitter...
// If we can't get a hand-crafted message then we create a simple one on the fly...
// We use different messages for live and historical (stale) data.
final String tweetMessage = FUELINSTUtils.generateTweetMessage(
isDataStale, statusUncapped, retailIntensity);
TwitterUtils.setTwitterStatusIfChanged(
td,
new File(TwitterCacheFileName),
status,
tweetMessage);
}
}
catch(final IOException e) { e.printStackTrace(); }
}
// Update button(s)/icon(s).
try
{
final File bd = new File(DEFAULT_BUTTON_BASE_DIR);
if(bd.isDirectory() && bd.canWrite())
{
GraphicsUtils.writeSimpleIntensityIconPNG(DEFAULT_BUTTON_BASE_DIR, 32, summary.timestamp, summary.status, retailIntensity);
GraphicsUtils.writeSimpleIntensityIconPNG(DEFAULT_BUTTON_BASE_DIR, 48, summary.timestamp, summary.status, retailIntensity);
GraphicsUtils.writeSimpleIntensityIconPNG(DEFAULT_BUTTON_BASE_DIR, 64, summary.timestamp, summary.status, retailIntensity);
}
else { System.err.println("Missing directory for icons: " + DEFAULT_BUTTON_BASE_DIR); }
}
catch(final IOException e) { e.printStackTrace(); }
// New as of 2019-10.
// Append to the intensity log.
// Only do this for current/live data, ie if not stale.
if(isDataStale || (0 == summary.timestamp))
{ System.err.println("Will not update log, input data is stale."); }
else
{
try
{
final File id = new File(DEFAULT_INTENSITY_LOG_BASE_DIR);
if(id.isDirectory() && id.canWrite())
{
appendToRetailIntensityLog(id, summary.timestamp, retailIntensity);
}
else { System.err.println("Missing directory for intensity log: " + DEFAULT_INTENSITY_LOG_BASE_DIR); }
}
catch(final IOException e) { e.printStackTrace(); }
}
}
/**First (comment) line of retail intensity log. */
public static final String RETAIL_INTENSITY_LOG_HEADER_LINE_1 = "# Retail GB electricity carbon intensity as computed by earth.org.uk.";
/**Second (comment) line of retail intensity log. */
public static final String RETAIL_INTENSITY_LOG_HEADER_LINE_2 = "# Time gCO2e/kWh";
/**Third (comment, intensities) line prefix of retail intensity log. */
public static final String RETAIL_INTENSITY_LOG_HEADER_LINE_3_PREFIX = "# Intensities gCO2/kWh:";
/**Append to (or create if necessary) the (retail) intensity log.
* If run more often than new data is available
* this may produce duplicate/repeated records.
* <p>
* Public for testability.
*
* @param id non-null writable directory for the log file
* @param timestamp +ve timestamp of latest input available data point
* @param retailIntensity non-negative retail/domestic intensity gCO2e/kWh
* @return handle of log file, or null if none written
*/
public static File appendToRetailIntensityLog(File id, long timestamp, int retailIntensity)
throws IOException
{
if(null == id) { throw new IllegalArgumentException(); }
if(0 >= timestamp) { throw new IllegalArgumentException(); }
if(0 > retailIntensity) { throw new IllegalArgumentException(); }
// Compute the log filename.
final SimpleDateFormat fsDF = new SimpleDateFormat(UTCDAYFILENAME_FORMAT);
fsDF.setTimeZone(FUELINSTUtils.GMT_TIME_ZONE); // All timestamps should be GMT/UTC.
final String dateUTC = fsDF.format(new Date(timestamp));
//System.out.println("UTC date for log: " + dateUTC);
final File logFile = new File(id, dateUTC + ".log");
//System.out.println("Intensity log filename: " + logFile);
// Compute the timestamp string for the log record.
final SimpleDateFormat tsDF = new SimpleDateFormat(UTCMINTIMESTAMP_FORMAT);
tsDF.setTimeZone(FUELINSTUtils.GMT_TIME_ZONE); // All timestamps should be GMT/UTC.
final String timestampUTC = tsDF.format(new Date(timestamp));
// Refuse to write to a log other than today's for safety.
// This may possibly wrongly drop records at either end of the day.
final String todayDateUTC = fsDF.format(new Date());
if(!dateUTC.equals(todayDateUTC))
{
System.err.println("WARNING: will not write to intensity log for "+dateUTC+" ("+timestampUTC+") at "+(new Date()));
return(null);
}
// If multiple copies of this code run at once
// then there may be a race creating/updating the file.
// This especially applies to the header(s).
final boolean logFileExists = logFile.exists();
try(PrintWriter pw = new PrintWriter(
new BufferedWriter(new FileWriter(logFile, true))))
{
// Write a header if the file was new.
if(!logFileExists)
{
pw.println(RETAIL_INTENSITY_LOG_HEADER_LINE_1);
pw.println("# Time gCO2e/kWh");
// DHD20211031: write out intensities based on today's year (parsed for consistency!)
final Map<String, Float> configuredIntensities = getConfiguredIntensities(Integer.parseInt(todayDateUTC.substring(0, 4)));
final SortedSet<String> fuels = new TreeSet<String>(configuredIntensities.keySet());
final StringBuilder isb = new StringBuilder(RETAIL_INTENSITY_LOG_HEADER_LINE_3_PREFIX.length() + 16*fuels.size());
isb.append(RETAIL_INTENSITY_LOG_HEADER_LINE_3_PREFIX);
for(final String f : fuels)
{ isb.append(" "+f+"="+(Math.round(1000*configuredIntensities.get(f)))); }
pw.println(isb);
//System.err.println("isb: " + isb);
}
// Append the new record <timestamp> <intensity>.
pw.print(timestampUTC); pw.print(' '); pw.println(retailIntensity);
}
// Attempt to ensure that the log file is readable by all.
logFile.setReadable(true, false);
return(logFile);
}
/**Base directory for embeddable intensity buttons/icons; not null.
* Under 'out' directory of suitable vintage to get correct expiry.
*/
private static final String DEFAULT_BUTTON_BASE_DIR = "../out/hourly/button/";
/**Base directory for log of integer gCO2e/kWh intensity values; not null.
* Under 'data' directory.
* Intensity values are 'retail', ie as at a typical domestic consumer,
* after transmission and distribution losses, based on non-embedded
* generation seen on the GB national grid.
*
* The log is line-oriented with lines of the form (no leading spaces)
* [ISO8601UTCSTAMPTOMIN] [kgCO2e/kWh]
* ie two space-separated columns, eg:
* # Other comment and one-of-data here.
* # Time gCO2e/kWh
* 2019-11-17T16:02Z 352
* 2019-11-17T16:12Z 351
*
* Initial lines may be headers, starting with # in in column 1,
* and may be ignored for data purposes.
*
* This may contain repeat records if data is sampled more often
* than it is updated at the source.
*
* Records will not be generated when data is 'stale',
* ie when fresh data is not available from the source.
*
* Log files will be named with the form YYYYMMDD.log
* eg 20191117.log.
*/
private static final String DEFAULT_INTENSITY_LOG_BASE_DIR = "../data/FUELINST/log/live/";
/**Generate the text of the status Tweet.
* Public to allow testing that returned Tweets are always valid.
*
* @param isDataStale true if we are working on historical/predicted (non-live) data
* @param statusUncapped the uncapped current or predicted status; never null
* @param retailIntensity intensity in gCO2/kWh as seen by retail customer, non-negative
* @return human-readable valid Tweet message
*/
public static String generateTweetMessage(
final boolean isDataStale,
final TrafficLight statusUncapped,
final int retailIntensity) // TODO
{
if(null == statusUncapped) { throw new IllegalArgumentException(); }
final String statusTemplate = MainProperties.getRawProperties().get((isDataStale ? TwitterUtils.PNAME_PREFIX_TWITTER_TRAFFICLIGHT_PREDICTION_MESSAGES : TwitterUtils.PNAME_PREFIX_TWITTER_TRAFFICLIGHT_STATUS_MESSAGES) + statusUncapped);
final String tweetMessage = ((statusTemplate != null) && !statusTemplate.isEmpty()) ? String.format(statusTemplate, retailIntensity).trim() :
("Grid status " + statusUncapped);
return(tweetMessage);
}
/**Extract (immutable) intensity map from configuration information; never null but may be empty.
* @return map from fuel name to kgCO2/kWh non-negative intensity; never null
*/
public static Map<String, String> getConfiguredFuelNames()
{
final Map<String, String> result = new HashMap<String, String>();
// Have to scan through all keys, which may be inefficient...
final Map<String, String> rawProperties = MainProperties.getRawProperties();
for(final String key : rawProperties.keySet())
{
if(!key.startsWith(FUELINST.FUELNAME_INTENSITY_MAIN_PROPNAME_PREFIX)) { continue; }
final String fuelname = key.substring(FUELINST.FUELNAME_INTENSITY_MAIN_PROPNAME_PREFIX.length());
final String descriptiveName = rawProperties.get(key).trim();
if(!FUEL_NAME_REGEX.matcher(fuelname).matches())
{
// Stop things dead if a name is used that may break things later.
throw new IllegalArgumentException("Invalid 'fuel' name " + fuelname);
}
if(descriptiveName.isEmpty()) { continue; }
result.put(fuelname, descriptiveName);
}
return(Collections.unmodifiableMap(result));
}
/**Extract (immutable) map from fuel category to set of fuel names; never null but may be empty.
* The result only contains keys with non-empty fuelname sets.
*/
public static Map<String, Set<String>> getFuelsByCategory()
{
final Map<String, Set<String>> result = new HashMap<String, Set<String>>();
// Have to scan through all keys, which may be inefficient...
final Map<String, String> rawProperties = MainProperties.getRawProperties();
for(final String key : rawProperties.keySet())
{
if(!key.startsWith(FUELINST.FUELINST_MAIN_PROPPREFIX_STORAGE_TYPES)) { continue; }
final String category = key.substring(FUELINST.FUELINST_MAIN_PROPPREFIX_STORAGE_TYPES.length());
final String fuelnames = rawProperties.get(key).trim();
if(fuelnames.isEmpty()) { continue; }
final HashSet<String> fuels = new HashSet<String>(Arrays.asList(fuelnames.trim().split(",")));
result.put(category, Collections.unmodifiableSet(fuels));
}
return(Collections.unmodifiableMap(result));
}
/**Extract (immutable) intensity map from configuration information for a given year; never null but may be empty.
* @param year if non-null preferred year for intensity and must be [2000,];
* this will use intensity values including the given year if possible,
* else the default as for the no-argument call
*
* <p>
* A default undated form such as <code>intensity.fuel.INTEW=0.45</code> is permitted,
* in part for backward compatibility.
* <p>
* Other forms allowed have a suffix of:
* <ul>
* <li><code>.year</code> the given year, eg <code>intensity.fuel.INTEW.2021=0.45</code></li>
* <li>[TODO] <code>.startYear/endYear</code> in given year range, inclusive</li>
* <li>[TODO] <code>.startYear/</code> from given year, inclusive</li>
* <li>[TODO] <code>./endYear</code> up to given year, inclusive</li>
* </ul>
* Dates specified must be unique and non-overlapping,
* and startYear must not be after endYear.
* <p>
* This date format is potentially partly extensible to ISO8601 including ranges.
*
* TODO
*
* @return map from fuel name to kgCO2/kWh non-negative intensity; never null
*
*/
public static Map<String, Float> getConfiguredIntensities(final Integer year)
{
final Map<String, Float> result = new HashMap<String, Float>();
// Have to scan through all keys, which may be inefficient...
final Map<String, String> rawProperties = MainProperties.getRawProperties();
for(final String key : rawProperties.keySet())
{
if(!key.startsWith(FUELINST.FUEL_INTENSITY_MAIN_PROPNAME_PREFIX)) { continue; }
// Simple verification that fuel name may be valid, else reject.
final String keytail = key.substring(FUELINST.FUEL_INTENSITY_MAIN_PROPNAME_PREFIX.length());
if(keytail.length() < 2)
{
System.err.println("Trivially invalid fuel name " + key);
continue;
}
// Extract fuel name.
final String fuel;
// Is the whole keytail an unqualified fule name (no date range).
final boolean isUnqualified = FUELINSTUtils.FUEL_NAME_REGEX.matcher(keytail).matches();
// For the case where year is null, the entire tail must be a valid fuel name.
if(year == null)
{
if(!isUnqualified)
{
// Cannot use unqualified entry with null argument.
continue;
}
fuel = keytail;
}
else if(isUnqualified)
{
// This is a default (no date-range) default value.
// Usable with a non-null year iff no value already captured for this fuel.
if(!result.containsKey(keytail)) { fuel = keytail; }
else { continue; }
}
else // year != null and this is not an unqualified entry...
{
// Split key tail in two at '.'.
final String parts[] = keytail.split("[.]");
if(2 != parts.length)
{
System.err.println("Invalid fuel intensity key " + key);
continue;
}
fuel = parts[0];
if(!FUELINSTUtils.FUEL_NAME_REGEX.matcher(fuel).matches())
{
System.err.println("Invalid fuel name " + key);
continue;
}
final int y = year;
if((y < 2000) || (y >= 3000))
{ throw new IllegalArgumentException("bad year " + y); }
// Deal with date range cases.
final int slashPos = parts[1].indexOf('/');
if(-1 != slashPos)
{
// Note:
// assertEquals(1, "2012/".split("/").length);
// assertEquals("2012", "2012/".split("/")[0]);
// assertEquals(2, "/2012".split("/").length);
// assertEquals("", "/2012".split("/")[0]);
// assertEquals("2012", "/2012".split("/")[1]);
// assertEquals(2, "2011/2012".split("/").length);
// assertEquals("2011", "2011/2012".split("/")[0]);
// assertEquals("2012", "2011/2012".split("/")[1]);
final String slashParts[] = parts[1].split("/");
if(slashParts.length > 2)
{
System.err.println("Unable to parse data range for intensity value for " + key);
continue;
}
if(!"".equals(slashParts[0]) && !FUELINSTUtils.FUEL_INTENSITY_YEAR_REGEX.matcher(slashParts[0]).matches())
{
System.err.println("Unable to parse data range start for intensity value for " + key);
continue;
}
final short isYear = "".equals(slashParts[0]) ? 0 : Short.parseShort(slashParts[0]);
if(isYear > y)
{
// Range start year is after current year, so does not apply.
continue;
}
if(slashParts.length > 1)
{
if(!FUELINSTUtils.FUEL_INTENSITY_YEAR_REGEX.matcher(slashParts[1]).matches())
{
System.err.println("Unable to parse data range end for intensity value for " + key);
continue;
}
final short ieYear = Short.parseShort(slashParts[1]);
if(ieYear < isYear)
{
System.err.println("Unable to parse data range (start>end) for intensity value for " + key);
continue;
}
if(ieYear < y)
{
// Range end year is before current year, so does not apply.
continue;
}
}
}
// Deal with simple fuelname.year case.
else if(FUELINSTUtils.FUEL_INTENSITY_YEAR_REGEX.matcher(parts[1]).matches())
{
final short iYear = Short.parseShort(parts[1]);
if(iYear != y) { continue; } // Wrong year.
}
}
final Float intensity;
try { intensity = new Float(rawProperties.get(key)); }
catch(final NumberFormatException e)
{
System.err.println("Unable to parse kgCO2/kWh intensity value for " + key);
continue;
}
if(!(intensity >= 0) || Float.isInfinite(intensity) || Float.isNaN(intensity))
{
System.err.println("Invalid (non-positive) kgCO2/kWh intensity value for " + key);
continue;
}
result.put(fuel, intensity);
}
return(Collections.unmodifiableMap(result));
}
/**Extract (immutable) intensity map from configuration information; never null but may be empty.
* This will use the default (eg undated) intensity value for each fuel such as
* <code>intensity.fuel.INTEW=0.45</code>
* else the latest-dated value.
*
* @return map from each fuel name to kgCO2/kWh non-negative intensity; never null
*/
@Deprecated
public static Map<String, Float> getConfiguredIntensities()
{
return(getConfiguredIntensities(null));
}
/**Fall-back category to assign uncategorised fuels to; single token not null nor empty. */
public static final String UNCATEGORISED_FUELS = "uncategorised";
/**If true, show recent changes in intensity, though they can be very noisy. */
private static final boolean SHOW_INTENSITY_DELTA = false;
/**Extract fuel use (in MW) by category from the current summary given the fuels-by-category table; never null but may be empty.
* TODO: construct 'uncategorised' component automatically
*/
public static Map<String,Integer> getFuelMWByCategory(final Map<String,Integer> currentGenerationMWByFuel, final Map<String,Set<String>> fuelByCategory)
{
if(null == currentGenerationMWByFuel) { throw new IllegalArgumentException(); }
if(null == fuelByCategory) { throw new IllegalArgumentException(); }
final Map<String,Integer> result = new HashMap<String, Integer>((fuelByCategory.size()*2) + 3);
// Construct each category's total generation....
for(final Map.Entry<String, Set<String>> c : fuelByCategory.entrySet())
{
final String category = c.getKey();
final Set<String> fuels = c.getValue();
long total = 0;
for(final String fuel : fuels)
{
final Integer q = currentGenerationMWByFuel.get(fuel);
if(null == q) { System.err.println("no per-fuel MW value for "+fuel); continue; }
if(q < 0) { throw new IllegalArgumentException("invalid negative per-fuel MW value"); }
total += q;
}
// Check for overflow.
if(total > Integer.MAX_VALUE) { throw new ArithmeticException("overflow"); }
result.put(category, (int) total);
}
return(Collections.unmodifiableMap(result));
}
/**Get a format for the BM timestamps in at least FUELINST data; never null.
* A returned instance is not safe to share between threads.
*/
public static SimpleDateFormat getCSVTimestampParser()
{
final SimpleDateFormat sDF = new SimpleDateFormat(FUELINSTUtils.CSVTIMESTAMP_FORMAT);
sDF.setTimeZone(FUELINSTUtils.GMT_TIME_ZONE); // All bmreports timestamps are GMT/UTC.
return(sDF);
}
/**Get a format for the BM timestamps in at least FUELINST data; never null.
* A returned instance is not safe to share between threads.
*/
public static SimpleDateFormat getTIBCOTimestampParser()
{
final SimpleDateFormat sDF = new SimpleDateFormat(FUELINSTUtils.TIBCOTIMESTAMP_FORMAT);
sDF.setTimeZone(FUELINSTUtils.GMT_TIME_ZONE); // All timestamps should be GMT/UTC.
return(sDF);
}
/**Get a format compact (HH:MM) timestamps; never null.
* A returned instance is not safe to share between threads.
*/
public static SimpleDateFormat getHHMMTimestampParser()
{
final SimpleDateFormat sDF = new SimpleDateFormat(FUELINSTUtils.HHMMTIMESTAMP_FORMAT);
sDF.setTimeZone(FUELINSTUtils.GMT_TIME_ZONE); // All timestamps should be GMT/UTC.
return(sDF);
}
/**Update (atomically if possible) the HTML traffic-light page. */
public static void updateHTMLFile(final long startTime,
final String outputHTMLFileName,
final FUELINST.CurrentSummary summary,
final boolean isDataStale,
final int hourOfDayHistorical,
final TrafficLight status,
final TwitterUtils.TwitterDetails td)
throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
final PrintWriter w = new PrintWriter(baos);
try
{
final Map<String, String> rawProperties = MainProperties.getRawProperties();
// Write the preamble with the status text dropped in.
final String statusColour = (status == null) ? null : status.toString().toLowerCase();
w.write(rawProperties.get("trafficLightPage.HTML.preamble").
replace("<!-- STATUS -->", (status == null) ? "UNKNOWN" :
"<span style=\"color:"+statusColour+";background-color:black\">" + status + "</span>" + (isDataStale ? "*" : "") ));
w.println();
if(isDataStale)
{ w.println("<p><em>*WARNING: cannot obtain current data so this is partly based on predictions from historical data (for "+hourOfDayHistorical+":XX GMT).</em></p>"); }
// Write out crude 'lights' with only appropriate lamp lit
// and some appropriate text.
final int sidePixels = GCOMP_PX_MAX; // Edge length of each 'lamp'.
final String open = "<tr><th style=\"border:3px solid;height:"+sidePixels+"px;width:"+((3*sidePixels)/2)+"px";
final String close = "</th></tr>";
w.write("<div><table style=\"margin-left:auto;margin-right:auto\">");
final String weaselWord = isDataStale ? "probably " : "";
w.write(open+((status == TrafficLight.RED) ? ";background-color:red\">Grid carbon intensity is "+weaselWord+"high; please do not run big appliances such as a dishwasher or washing machine now if you can postpone" : "\"> ")+close);
w.write(open+((status == TrafficLight.YELLOW) ? ";background-color:yellow\">Grid is "+weaselWord+"OK; but you could still avoid CO2 emissions by postponing running big appliances such as dishwashers or washing machines" : ((status == null) ? "\">Status is unknown" : "\"> "))+close);
w.write(open+((status == TrafficLight.GREEN) ? ";background-color:green\">Grid is "+weaselWord+"good; you might run major loads such as your dishwasher and/or washing machine now to minimise CO2 emissions" : "\"> ")+close);
w.write("</table></div>");
w.println();
if(summary.histMinIntensity < summary.histMaxIntensity)
{
w.println("<p style=\"text-align:center\">You might have saved as much as <strong style=\"font-size:xx-large\">"+FUELINSTUtils.computeVariability(summary.histMinIntensity, summary.histMaxIntensity)+"%</strong> carbon emissions by choosing the best time to run your washing and other major loads.</p>");
}
// Note any recent change/delta iff the data is not stale.
if(SHOW_INTENSITY_DELTA && !isDataStale)
{
if(summary.recentChange == TrafficLight.GREEN)
{ w.println("<p style=\"color:green\">Good: carbon intensity (CO2 per kWh) is currently dropping.</p>"); }
else if(summary.recentChange == TrafficLight.RED)
{ w.println("<p style=\"color:red\">Bad: carbon intensity (CO2 per kWh) is currently rising.</p>"); }
}
w.println("<p>Latest data is from <strong>"+(new Date(summary.timestamp))+"</strong>. This page should be updated every few minutes: use your browser's refresh/reload button if you need to check again.</p>");
// If we have a Twitter account set up then brag about it here,
// but only if we believe that we actually have write access to be doing updates...
if(td != null)
{
w.print("<p>Follow this grid status on Twitter <a href=\"http://twitter.com/");
w.print(td.username);
w.print("\">@");
w.print(td.username);
w.print("</a>");
w.println(".</p>");
}
// A bit of explanation...
w.println(rawProperties.get("trafficLightPage.HTML.midamble"));
// Now for the numbers...
w.println("<h2>Technical Stuff</h2><p>You don't need to understand the numbers below, but some people like to see them!</p>");
// Replace estimate of end-user intensity with recent historical mean if the data is stale.
w.write("<p>");
w.write(isDataStale ?
"Recent effective carbon intensity for a domestic user at this time of day was " :
"Effective grid carbon intensity for a domestic user is currently ");
if(null != status) { w.write("<span style=\"font-size:xx-large;color:"+statusColour+";background-color:black\">"); }
w.write(String.valueOf(Math.round((isDataStale ? summary.histAveIntensity : summary.currentIntensity) * (1 + summary.totalGridLosses))));
w.write("gCO2/kWh");
if(null != status) { w.write("</span>"); }
w.write(" including transmission and distribution losses of ");
w.write(String.valueOf(Math.round(100 * summary.totalGridLosses)));
w.write("%.</p>");
w.println();
w.println("<p>Latest available grid <strong>generation</strong> carbon intensity (ignoring transmission/distribution losses) is approximately <strong>"+summary.currentIntensity+"gCO2/kWh</strong> at "+(new Date(summary.timestamp))+" over "+
summary.currentMW+"MW of generation, with a rolling average over "+((summary.histWindowSize+1800000) / 3600000)+"h of <strong>"+summary.histAveIntensity+"gCO2/kWh</strong>.</p>");
w.println("<p>Minimum grid <strong>generation</strong> carbon intensity (ignoring transmission/distribution losses) was approximately <strong>"+summary.histMinIntensity+"gCO2/kWh</strong> at "+(new Date(summary.minIntensityRecordTimestamp))+".</p>");
w.println("<p>Maximum grid <strong>generation</strong> carbon intensity (ignoring transmission/distribution losses) was approximately <strong>"+summary.histMaxIntensity+"gCO2/kWh</strong> at "+(new Date(summary.maxIntensityRecordTimestamp))+".</p>");
w.println("<p>Average/mean grid <strong>generation</strong> carbon intensity (ignoring transmission/distribution losses) was approximately <strong>"+summary.histAveIntensity+"gCO2/kWh</strong> over the sample data set, with an effective end-user intensity including transmission and distribution losses of <strong>"+(Math.round(summary.histAveIntensity * (1 + summary.totalGridLosses)))+"gCO2/kWh</strong>.</p>");
// Intensity (and generation) by hour of day.
final int newSlot = FUELINST.CurrentSummary.getGMTHourOfDay(startTime);
w.write("<div><table style=\"margin-left:auto;margin-right:auto\">");
w.write("<tr><th colspan=\"24\">");
w.write(isDataStale ? "Last available historical" : "Recent");
w.write(" mean GMT hourly generation intensity gCO2/kWh (average="+summary.histAveIntensity+"); *now (="+summary.currentIntensity+")</th></tr>");
w.write("<tr>");
// Always start at midnight GMT if the data is stale.
final int startSlot = isDataStale ? 0 : (1 + Math.max(0, newSlot)) % 24;
for(int h = 0; h < 24; ++h)
{
final StringBuffer sbh = new StringBuffer(2);
final int displayHourGMT = (h + startSlot) % 24;
sbh.append(displayHourGMT);
if(sbh.length() < 2) { sbh.insert(0, '0'); }
if(hourOfDayHistorical == displayHourGMT) { sbh.append('*'); }
w.write("<th style=\"border:1px solid\">"+sbh+"</th>");
}
w.write("</tr>");
w.write("<tr>");
boolean usedLessGreen = false;
final int maxHourlyIntensity = summary.histAveIntensityByHourOfDay.max0();
for(int h = 0; h < 24; ++h)
{
final int displayHourGMT = (h + startSlot) % 24;
final Integer hIntensity = summary.histAveIntensityByHourOfDay.get(displayHourGMT);
if((null == hIntensity) || (0 == hIntensity)) { w.write("<td></td>"); continue; /* Skip empty slot. */ }
final TrafficLight rawHourStatus = summary.selectColour(hIntensity);
// But if the colour is GREEN but we're using pumped storage
// then switch to a paler shade instead (ie mainly green, but not fully)...
final boolean lessGreen = ((TrafficLight.GREEN == rawHourStatus) && (summary.histAveStorageDrawdownByHourOfDay.get(displayHourGMT) > 0));
if(lessGreen) { usedLessGreen = true; }
final String barColour = lessGreen ? FUELINSTUtils.LESS_GREEN_STORAGE_DRAWDOWN :
rawHourStatus.toString().toLowerCase();
final int height = (GCOMP_PX_MAX*hIntensity) / Math.max(1, maxHourlyIntensity);
w.write("<td style=\"width:30px\"><ul class=\"barGraph\">");
w.write("<li style=\"background-color:"+barColour+";height:"+height+"px;left:0\">");
w.write(String.valueOf(hIntensity));
w.write("</li>");
w.write("</ul></td>");
}
w.write("</tr>");
w.write("<tr><th colspan=\"24\">Mean GMT hourly generation GW (<span style=\"color:gray\">all</span>, <span style=\"color:green\">zero-carbon</span>)</th></tr>");
w.write("<tr>");
// Compute the maximum generation in any of the hourly slots
// to give us maximum scaling of the displayed bars.
final int maxGenerationMW = summary.histAveGenerationByHourOfDay.max0();
for(int h = 0; h < 24; ++h)
{
final int displayHourGMT = (h + startSlot) % 24;
final Integer hGeneration = summary.histAveGenerationByHourOfDay.get(displayHourGMT);
if((null == hGeneration) || (0 == hGeneration)) { w.write("<td></td>"); continue; /* Skip empty slot. */ }
final int height = (GCOMP_PX_MAX*hGeneration) / Math.max(1, maxGenerationMW);
final int scaledToGW = (hGeneration + 500) / 1000;
w.write("<td style=\"width:30px\"><ul class=\"barGraph\">");
w.write("<li style=\"background-color:gray;height:"+height+"px;left:0\">");
w.write(String.valueOf(scaledToGW));
w.write("</li>");
final int hZCGeneration = summary.histAveZCGenerationByHourOfDay.get0(displayHourGMT);
if(0 != hZCGeneration)
{
w.write("<li style=\"background-color:green;height:"+((GCOMP_PX_MAX*hZCGeneration) / Math.max(1, maxGenerationMW))+"px;left:0\">");
if(hZCGeneration >= (maxGenerationMW/8)) { w.write(String.valueOf((hZCGeneration + 500) / 1000)); }
w.write("</li>");
}
// final int hDrawdown = summary.histAveStorageDrawdownByHourOfDay.get0(displayHourGMT);
// if(0 != hDrawdown)
// w.write("<li style=\"background-color:yellow;height:"+((GCOMP_PX_MAX*hDrawdown) / Math.max(1, maxGenerationMW))+"px;left:0px;\">");
// if(hDrawdown >= maxGenerationMW/8) { w.write(String.valueOf((hDrawdown + 500) / 1000)); }
// w.write("</li>");
w.write("</ul></td>");
}
w.write("</tr>");
w.write("</table></div>");
w.println();
// Footnotes
if(usedLessGreen)
{ w.println("<p>Hours that are basically <span style=\"color:green\">green</span>, but in which there is draw-down from grid-connected storage with its attendant energy losses and also suggesting that little or no excess non-dispatchable generation is available, ie that are marginally green, are shaded <span style=\"color:"+FUELINSTUtils.LESS_GREEN_STORAGE_DRAWDOWN+"\">"+FUELINSTUtils.LESS_GREEN_STORAGE_DRAWDOWN+"</span>.</p>"); }
// TODO: Show cumulative MWh and tCO2.
if(!isDataStale)
{
// Show some stats only relevant for live data...
w.write("<p>Current/latest fuel mix at ");
w.write(String.valueOf(new Date(summary.timestamp)));
w.write(':');
final SortedMap<String,Integer> power = new TreeMap<String, Integer>(summary.currentGenerationMWByFuelMW);
for(final String fuel : power.keySet())
{
w.write(' '); w.write(fuel);
w.write("@"+power.get(fuel)+"MW");
}
w.write(".</p>");
w.println();
if(summary.currentStorageDrawdownMW > 0)
{
w.write("<p>Current draw-down from storage is ");
w.write(Long.toString(summary.currentStorageDrawdownMW));
w.write("MW.</p>");
w.println();
}
// Show fuels broken down by category, if categories are assigned.
final Map<String, Set<String>> byCategory = getFuelsByCategory();
if(!byCategory.isEmpty())
{
final Map<String,Integer> byCat = getFuelMWByCategory(summary.currentGenerationMWByFuelMW, byCategory);
w.write("<p>Generation by fuel category (may overlap):</p><dl>");
final SortedMap<String,Integer> powerbyCat = new TreeMap<String, Integer>(byCat);
for(final String category : powerbyCat.keySet())
{
final Integer genMW = powerbyCat.get(category);
final int percent = Math.round((100.0f * genMW) / Math.max(1, summary.currentMW));
w.write("<dt>"); w.write(category); w.write(" @ "); w.write(Integer.toString(percent)); w.write("%</dt>");
w.write("<dd>");
// Write MW under this category.
w.write(String.valueOf(genMW)); w.write("MW");
// Write sorted fuel list...
w.write(" "); w.write((new ArrayList<String>(new TreeSet<String>(byCategory.get(category)))).toString()); w.write("");
w.write("</dd>");
}
w.write("</dl>");
w.println();
}
}
final LocalDate todayUTC = LocalDate.now(ZoneOffset.UTC);
final int intensityYear = todayUTC.getYear();
w.write("<p>Overall generation intensity (kgCO2/kWh) computed using the following fuel year-"+intensityYear+" intensities (other fuels/sources are ignored):");
final Map<String, Float> configuredIntensities = FUELINSTUtils.getConfiguredIntensities(intensityYear);
final SortedMap<String,Float> intensities = new TreeMap<String, Float>(FUELINSTUtils.getConfiguredIntensities(intensityYear));
for(final String fuel : intensities.keySet())
{
w.write(' '); w.write(fuel);
w.write("="+intensities.get(fuel));
}
w.write(".</p>");
w.println();
w.write("<p>Rolling correlation of fuel use against grid intensity (-ve implies that this fuel reduces grid intensity for non-callable sources):");
final SortedMap<String,Float> goodness = new TreeMap<String, Float>(summary.correlationIntensityToFuel);
for(final String fuel : goodness.keySet())
{
w.format(" %s=%.4f", fuel, goodness.get(fuel));
}
w.write(".</p>");
w.println();
// Key for fuel names/codes if available.
final SortedMap<String,String> fullFuelNames = new TreeMap<String,String>(FUELINSTUtils.getConfiguredFuelNames());
if(!fullFuelNames.isEmpty())
{
w.write("<p>Key to fuel codes:</p><dl>");
for(final String fuel : fullFuelNames.keySet())
{
w.write("<dt>"); w.write(fuel); w.write("</dt>");
w.write("<dd>"); w.write(fullFuelNames.get(fuel)); w.write("</dd>");
}
w.write("</dl>");
w.println();
}
w.println("<h3>Methodology</h3>");
w.println(rawProperties.get("methodology.HTML"));
w.println("<p>This page updated at "+(new Date())+"; generation time "+(System.currentTimeMillis()-startTime)+"ms.</p>");
w.println(rawProperties.get("trafficLightPage.HTML.postamble"));
w.flush();
}
finally { w.close(); /* Ensure file is flushed/closed. Release resources. */ }
// Attempt atomic replacement of HTML page...
DataUtils.replacePublishedFile(outputHTMLFileName, baos.toByteArray());
}
/**Update (atomically if possible) the plain text intensity value.
* The file will be removed if the data is stale.
*/
static void updateTXTFile(final long startTime,
final String outputTXTFileName,
final CurrentSummary summary,
final boolean isDataStale)
throws IOException
{
// In case of stale data remove the result file.
if(isDataStale)
{
(new File(outputTXTFileName)).delete();
return;
}
// TODO Auto-generated method stub
}
/**Update (atomically if possible) the mobile-friendly XHTML traffic-light page.
* The generated page is designed to be very light-weight
* and usable by a mobile phone (eg as if under the .mobi TLD).
*/
static void updateXHTMLFile(final long startTime,
final String outputXHTMLFileName,
final FUELINST.CurrentSummary summary,
final boolean isDataStale,
final int hourOfDayHistorical,
final TrafficLight status)
throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
final PrintWriter w = new PrintWriter(baos);
try
{
final Map<String, String> rawProperties = MainProperties.getRawProperties();
w.println(rawProperties.get("trafficLightPage.XHTML.preamble"));
w.println("<div style=\"background:"+((status == null) ? "gray" : status.toString().toLowerCase())+"\">");
final String weaselWord = isDataStale ? "probably " : "";
if(status == TrafficLight.RED)
{ w.println("Status RED: grid carbon intensity is "+weaselWord+"high; please do not run big appliances such as a dishwasher or washing machine now if you can postpone."); }
else if(status == TrafficLight.GREEN)
{ w.println("Status GREEN: grid is "+weaselWord+"good; run appliances now to minimise CO2 emissions."); }
else if(status == TrafficLight.YELLOW)
{ w.println("Status YELLOW: grid is "+weaselWord+"OK; but you could still avoid CO2 emissions by postponing running big appliances such as dishwashers or washing machines."); }
else
{ w.println("Grid status is UNKNOWN."); }
w.println("</div>");
if(isDataStale)
{ w.println("<p><em>*WARNING: cannot obtain current data so this is partly based on predictions from historical data (for "+hourOfDayHistorical+":XX GMT).</em></p>"); }
w.println("<p>This page updated at "+(new Date())+".</p>");
w.println(rawProperties.get("trafficLightPage.XHTML.postamble"));
w.flush();
}
finally { w.close(); /* Ensure file is flushed/closed. Release resources. */ }
// Attempt atomic replacement of XHTML page...
DataUtils.replacePublishedFile(outputXHTMLFileName, baos.toByteArray());
}
/**Update (atomically if possible) the XML traffic-light data dump.
* Dumps current-year (at time call is run) fuel intensities.
*/
public static void updateXMLFile(final long startTime,
final String outputXMLFileName,
final FUELINST.CurrentSummary summary,
final boolean isDataStale,
final int hourOfDayHistorical,
final TrafficLight status)
throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
final PrintWriter w = new PrintWriter(baos);
try
{
// final Map<String, String> rawProperties = MainProperties.getRawProperties();
w.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
w.println("<results>");
if(isDataStale)
{ w.println("<warning>*WARNING: cannot obtain current data so this is partly based on predictions from historical data (for "+hourOfDayHistorical+":XX GMT).</warning>"); }
w.println("<stale_data>"+isDataStale+"</stale_data>");
// if(status == TrafficLight.RED)
// { w.println("<status>1</status>"); }
// else if(status == TrafficLight.YELLOW)
// { w.println("<status>0</status>"); }
// else if(status == TrafficLight.GREEN)
// { w.println("<status>-1</status>"); }
w.print("<status>");
if(null != status) { w.print(status); }
w.println("</status>");
if(summary.histMinIntensity < summary.histMaxIntensity)
{ w.println("<saving>"+FUELINSTUtils.computeVariability(summary.histMinIntensity, summary.histMaxIntensity)+"</saving>"); }
// Note any recent change/delta if the data is not stale.
if(!isDataStale)
{
if(summary.recentChange == TrafficLight.GREEN)
// { w.println("<carbon_intensity>-1</carbon_intensity>"); }
{ w.println("<carbon_intensity>GREEN</carbon_intensity>"); }
else if(summary.recentChange == TrafficLight.RED)
// { w.println("<carbon_intensity>1</carbon_intensity>"); }
{ w.println("<carbon_intensity>RED</carbon_intensity>"); }
}
w.println("<timestamp>"+summary.timestamp+"</timestamp>");
w.write("<grid_carbon_intensity>");
w.write(String.valueOf(Math.round((isDataStale ? summary.histAveIntensity : summary.currentIntensity) * (1 + summary.totalGridLosses))));
w.write("</grid_carbon_intensity>");
w.println();
w.write("<transmission_losses>");
w.write(String.valueOf(Math.round(100 * summary.totalGridLosses)));
w.write("</transmission_losses>");
w.println();
w.println("<latest>");
w.println("<carbon_intensity>"+ summary.currentIntensity +"</carbon_intensity>");
w.println("<timestamp>"+ summary.timestamp +"</timestamp>");
w.println("<generation>"+ summary.currentMW+"</generation>");
w.println("<rolling_average_period>"+((summary.histWindowSize+1800000) / 3600000)+"</rolling_average_period>");
w.println("<rolling_average_carbon_intensity>"+ summary.histAveIntensity+"</rolling_average_carbon_intensity>");
w.println("</latest>");
w.println("<minimum>");
w.println("<carbon_intensity>"+ summary.histMinIntensity +"</carbon_intensity>");
w.println("<timestamp>"+ summary.minIntensityRecordTimestamp +"</timestamp>");
w.println("</minimum>");
w.println("<maximum>");
w.println("<carbon_intensity>"+ summary.histMaxIntensity +"</carbon_intensity>");
w.println("<timestamp>"+ summary.maxIntensityRecordTimestamp +"</timestamp>");
w.println("</maximum>");
// Intensity (and generation) by hour of day.
final int newSlot = FUELINST.CurrentSummary.getGMTHourOfDay(startTime);
w.println("<generation_intensity>");
w.println("<average>"+summary.histAveIntensity+"</average>");
w.println("<current>"+summary.currentIntensity+"</current>");
// Always start at midnight GMT if the data is stale.
final int startSlot = isDataStale ? 0 : (1 + Math.max(0, newSlot)) % 24;
// final int maxHourlyIntensity = summary.histAveIntensityByHourOfDay.max0();
for(int h = 0; h < 24; ++h)
{
final StringBuffer sbh = new StringBuffer(2);
final int displayHourGMT = (h + startSlot) % 24;
sbh.append(displayHourGMT);
if(sbh.length() < 2) { sbh.insert(0, '0'); }
final Integer hIntensity = summary.histAveIntensityByHourOfDay.get(displayHourGMT);
w.println("<sample>");
w.println("<hour>"+sbh+"</hour>");
w.println("<carbon_intensity>");
if((null == hIntensity) || (0 == hIntensity))
{ /* Empty slot. */ }
else
{ w.println(String.valueOf(hIntensity)); }
w.println("</carbon_intensity>");
w.println("</sample>");
}
w.println("</generation_intensity>");
w.println("<generation>");
// Compute the maximum generation in any of the hourly slots
// to give us maximum scaling of the displayed bars.
final int maxGenerationMW = summary.histAveGenerationByHourOfDay.max0();
for(int h = 0; h < 24; ++h)
{
final int displayHourGMT = (h + startSlot) % 24;
final StringBuffer sbh = new StringBuffer(2);
sbh.append(displayHourGMT);
if(sbh.length() < 2) { sbh.insert(0, '0'); }
final Integer hGeneration = summary.histAveGenerationByHourOfDay.get(displayHourGMT);
if((null == hGeneration) || (0 == hGeneration)) { continue; /* Skip empty slot. */ }
// final int height = (GCOMP_PX_MAX*hGeneration) / Math.max(1, maxGenerationMW);
final int scaledToGW = (hGeneration + 500) / 1000;
w.println("<sample>");
w.println("<hour>"+sbh+"</hour>");
w.println("<all>"+String.valueOf(scaledToGW)+"</all>");
final int hZCGeneration = summary.histAveZCGenerationByHourOfDay.get0(displayHourGMT);
if(0 != hZCGeneration)
{
if(hZCGeneration >= (maxGenerationMW/8)) { w.println("<zero_carbon>"+String.valueOf((hZCGeneration + 500) / 1000)+"</zero_carbon>"); }
}
w.println("</sample>");
}
w.println("</generation>");
// TODO: Show cumulative MWh and tCO2.
// FIXME: DHD20090608: I suggest leaving the fuel names as-is (upper case) in the XML as those are the 'formal' Elexon names; convert for display if need be.
// FIXME: DHD20090608: As fuel names may not always be XML-token-safe, maybe <fuel name="NNN">amount</fuel> would be better?
if(!isDataStale)
{
w.println("<fuel_mix>");
w.println("<timestamp>"+summary.timestamp+"</timestamp>");
final SortedMap<String,Integer> power = new TreeMap<String, Integer>(summary.currentGenerationMWByFuelMW);
for(final String fuel : power.keySet()) { w.println("<"+fuel.toLowerCase()+">"+power.get(fuel)+"</"+fuel.toLowerCase()+">"); }
w.println("</fuel_mix>");
}
w.println("<fuel_intensities>");
w.println("<timestamp>"+summary.timestamp+"</timestamp>");
// Note: current-year intensities are used.
final LocalDate todayUTC = LocalDate.now(ZoneOffset.UTC);
final int intensityYear = todayUTC.getYear();
final SortedMap<String,Float> intensities = new TreeMap<String, Float>(FUELINSTUtils.getConfiguredIntensities(intensityYear));
for(final String fuel : intensities.keySet()) { w.println("<"+fuel.toLowerCase()+">"+intensities.get(fuel)+"</"+fuel.toLowerCase()+">"); }
w.println("</fuel_intensities>");
w.println("</results>");
w.flush();
}
finally { w.close(); /* Ensure file is flushed/closed. Release resources. */ }
// Attempt atomic replacement of XML page...
DataUtils.replacePublishedFile(outputXMLFileName, baos.toByteArray());
}
} |
package com.thinkbiganalytics.nifi.provenance.model;
import com.thinkbiganalytics.nifi.provenance.util.ProvenanceEventUtil;
import org.apache.nifi.provenance.ProvenanceEventType;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public class ActiveFlowFile {
/**
* FlowFile UUID
*/
private String id;
private Set<ActiveFlowFile> parents;
private Set<ActiveFlowFile> children;
// private List<Long> events;
private Set<String> completedProcessorIds;
private List<ProvenanceEventRecordDTO> completedEvents;
private ProvenanceEventRecordDTO firstEvent;
private ActiveFlowFile rootFlowFile;
private AtomicLong completedEndingProcessors = new AtomicLong();
/**
* marker to determine if the Flow has Received a DROP event.
*/
private boolean currentFlowFileComplete = false;
//track failed events in this flow
//change to ConcurrentSkipListSet ???
private Set<ProvenanceEventRecordDTO> failedEvents;
public ActiveFlowFile(String id) {
this.id = id;
this.failedEvents = new HashSet<>();
}
/**
* Add and return the parent
*/
public ActiveFlowFile addParent(ActiveFlowFile flowFile) {
if (!flowFile.equals(this)) {
getParents().add(flowFile);
}
return flowFile;
}
/**
* add and return the child
*/
public ActiveFlowFile addChild(ActiveFlowFile flowFile) {
if (!flowFile.equals(this)) {
getChildren().add(flowFile);
}
return flowFile;
}
public Set<ActiveFlowFile> getParents() {
if (parents == null) {
parents = new HashSet<>();
}
return parents;
}
public Set<ActiveFlowFile> getChildren() {
if (children == null) {
children = new HashSet<>();
}
return children;
}
public Set<ActiveFlowFile> getAllChildren() {
Set<ActiveFlowFile> allChildren = new HashSet<>();
for (ActiveFlowFile child : getChildren()) {
allChildren.add(child);
allChildren.addAll(child.getAllChildren());
}
return allChildren;
}
public ProvenanceEventRecordDTO getFirstEvent() {
return firstEvent;
}
public void setFirstEvent(ProvenanceEventRecordDTO firstEvent) {
this.firstEvent = firstEvent;
}
public boolean hasFirstEvent() {
return firstEvent != null;
}
public void completeEndingProcessor(){
completedEndingProcessors.incrementAndGet();
}
public ActiveFlowFile getRootFlowFile() {
return rootFlowFile;
}
public void setRootFlowFile(ActiveFlowFile rootFlowFile) {
this.rootFlowFile = rootFlowFile;
}
public boolean isRootFlowFile(){
return this.rootFlowFile != null && this.rootFlowFile.equals(this);
}
public void addFailedEvent(ProvenanceEventRecordDTO event){
failedEvents.add(event);
}
/**
* gets the flow files failed events.
* if inclusive then get all children
* @param inclusive
* @return
*/
public Set<ProvenanceEventRecordDTO> getFailedEvents(boolean inclusive){
Set<ProvenanceEventRecordDTO> failedEvents = new HashSet<>();
failedEvents.addAll(failedEvents);
if(inclusive) {
for (ActiveFlowFile child : getChildren()) {
failedEvents.addAll(child.getFailedEvents(inclusive));
}
}
return failedEvents;
}
public String getId() {
return id;
}
public ProvenanceEventRecordDTO getPreviousEvent(ProvenanceEventRecordDTO event) {
if (event.getPreviousEvent() == null) {
Integer index = getCompletedEvents().indexOf(event);
if (index > 0) {
event.setPreviousEvent(getCompletedEvents().get(index - 1));
} else {
//get parent flow file for this event
if (getParents() != null && !getParents().isEmpty()) {
List<ProvenanceEventRecordDTO> previousEvents = getParents().stream()
.filter(flowFile -> event.getParentUuids().contains(flowFile.getId()))
.flatMap(flow -> flow.getCompletedEvents().stream()).sorted(ProvenanceEventUtil.provenanceEventRecordDTOComparator().reversed())
.collect(Collectors.toList());
if (previousEvents != null && !previousEvents.isEmpty()) {
event.setPreviousEvent(previousEvents.get(0));
}
}
}
}
return event.getPreviousEvent();
}
public Long calculateEventDuration(ProvenanceEventRecordDTO event) {
//lookup the flow file to get the prev event
ProvenanceEventRecordDTO prev = getPreviousEvent(event);
if (prev != null) {
long dur = event.getEventTime().getTime() - prev.getEventTime().getTime();
event.setEventDuration(dur);
return dur;
} else {
event.setEventDuration(0L);
return 0L;
}
}
public String summary(){
Set<ProvenanceEventRecordDTO> failedEvents = getFailedEvents(true);
return "Flow File (" + id + "), with first Event of (" + firstEvent + ") processed " + getCompletedEvents().size() + " events. " + failedEvents.size() + " were failure events. "
+ completedEndingProcessors.longValue() + " where leaf ending events";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ActiveFlowFile that = (ActiveFlowFile) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public Set<String> getCompletedProcessorIds() {
if (completedProcessorIds == null) {
completedProcessorIds = new HashSet<>();
}
return completedProcessorIds;
}
public List<ProvenanceEventRecordDTO> getCompletedEvents() {
if (completedEvents == null) {
completedEvents = new LinkedList<>();
}
return completedEvents;
}
public void addCompletedEvent(ProvenanceEventRecordDTO event) {
getCompletedEvents().add(event);
getCompletedProcessorIds().add(event.getComponentId());
calculateEventDuration(event);
checkAndMarkIfFlowFileIsComplete(event);
}
public void checkAndMarkIfFlowFileIsComplete(ProvenanceEventRecordDTO event) {
if (ProvenanceEventType.DROP.name().equalsIgnoreCase(event.getEventType())) {
currentFlowFileComplete = true;
}
}
public boolean isCurrentFlowFileComplete() {
return currentFlowFileComplete;
}
/**
* Walks the graph of this flow and all children to see if there is a DROP event associated with each and every flow file
*/
public boolean isFlowComplete() {
boolean complete = isCurrentFlowFileComplete();
Set<ActiveFlowFile> directChildren = getChildren();
if (complete && !directChildren.isEmpty()) {
for (ActiveFlowFile child : directChildren) {
complete &= child.isCurrentFlowFileComplete();
if (!complete) {
break;
}
}
}
return complete;
}
} |
package dr.app.beauti.priorsPanel;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.types.PriorType;
import dr.app.gui.components.RealNumberField;
import dr.app.util.OSType;
import dr.math.distributions.*;
import jam.panels.OptionsPanel;
import javax.swing.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Alexei Drummond
* @author Walter Xie
*/
abstract class PriorOptionsPanel extends OptionsPanel {
private List<JComponent> argumentFields = new ArrayList<JComponent>();
private List<String> argumentNames = new ArrayList<String>();
private boolean isInitializable = true;
private final boolean isTruncatable;
private final RealNumberField initialField = new RealNumberField();
private RealNumberField selectedField;
private final SpecialNumberPanel specialNumberPanel;
private final JCheckBox isTruncatedCheck = new JCheckBox("Truncate to:");
private final RealNumberField lowerField = new RealNumberField();
private final JLabel lowerLabel = new JLabel("Lower: ");
private final RealNumberField upperField = new RealNumberField();
private final JLabel upperLabel = new JLabel("Upper: ");
PriorOptionsPanel(boolean isTruncatable) {
super(12, (OSType.isMac() ? 6 : 24));
this.isTruncatable = isTruncatable;
setup();
initialField.setColumns(10);
lowerField.setColumns(10);
upperField.setColumns(10);
isTruncatedCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
lowerField.setEnabled(isTruncatedCheck.isSelected());
lowerLabel.setEnabled(isTruncatedCheck.isSelected());
upperField.setEnabled(isTruncatedCheck.isSelected());
upperLabel.setEnabled(isTruncatedCheck.isSelected());
}
});
specialNumberPanel = new SpecialNumberPanel();
specialNumberPanel.setEnabled(false);
KeyListener listener = new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getComponent() instanceof RealNumberField) {
String number = ((RealNumberField) e.getComponent()).getText();
if (!(number.equals("") || number.endsWith("e") || number.endsWith("E")
|| number.startsWith("-") || number.endsWith("-"))) {
// System.out.println(e.getID() + " = \"" + ((RealNumberField) e.getComponent()).getText() + "\"");
// setupChart();
// dialog.repaint();
// dialog.updateChart();
}
}
}
};
FocusListener flistener = new FocusAdapter() {
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof RealNumberField) {
selectedField = (RealNumberField) e.getComponent();
specialNumberPanel.setEnabled(true);
}
}
public void focusLost(FocusEvent e) {
selectedField = null;
specialNumberPanel.setEnabled(false);
}
};
initialField.addKeyListener(listener);
initialField.addFocusListener(flistener);
for (JComponent component : argumentFields) {
if (component instanceof RealNumberField) {
component.addKeyListener(listener);
component.addFocusListener(flistener);
}
}
lowerField.addKeyListener(listener);
upperField.addKeyListener(listener);
lowerField.addFocusListener(flistener);
upperField.addFocusListener(flistener);
}
protected void setFieldRange(RealNumberField field, boolean isNonNegative, boolean isZeroOne) {
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (isZeroOne) {
lower = 0.0;
upper = 1.0;
} else if (isNonNegative) {
lower = 0.0;
}
field.setRange(lower, upper);
}
protected void setFieldRange(RealNumberField field, boolean isNonNegative, boolean isZeroOne, double truncationLower, double truncationUpper) {
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (isZeroOne) {
lower = 0.0;
upper = 1.0;
} else if (isNonNegative) {
lower = 0.0;
}
if (lower < truncationLower) {
lower = truncationLower;
}
if (upper > truncationUpper) {
upper = truncationUpper;
}
field.setRange(lower, upper);
}
protected void addField(String name, double initialValue, double min, double max) {
RealNumberField field = new RealNumberField(min, max);
field.setValue(initialValue);
addField(name, field);
}
protected void addField(String name, RealNumberField field) {
argumentNames.add(name);
field.setColumns(10);
argumentFields.add(field);
setupComponents();
}
protected void addCheckBox(String name, JCheckBox jCheckBox) {
argumentNames.add(name);
argumentFields.add(jCheckBox);
setupComponents();
}
protected void replaceFieldName(int i, String name) {
argumentNames.set(i, name);
setupComponents();
}
protected double getValue(int i) {
return ((RealNumberField) argumentFields.get(i)).getValue();
}
private void setupComponents() {
removeAll();
if (isInitializable) {
addComponentWithLabel("Initial value: ", initialField);
}
for (int i = 0; i < argumentFields.size(); i++) {
addComponentWithLabel(argumentNames.get(i) + ":", argumentFields.get(i));
}
if (isTruncatable) {
addSpanningComponent(isTruncatedCheck);
addComponents(lowerLabel, lowerField);
addComponents(upperLabel, upperField);
}
}
RealNumberField getField(int i) {
return (RealNumberField) argumentFields.get(i);
}
Distribution getDistribution(Parameter parameter) {
Distribution dist = getDistribution();
boolean isBounded = isTruncatedCheck.isSelected();
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (parameter.isZeroOne) {
lower = 0.0;
upper = 1.0;
isBounded = true;
} else if (parameter.isNonNegative) {
lower = 0.0;
isBounded = true;
}
if (dist != null && isBounded) {
if (isTruncatedCheck.isSelected()) {
lower = lowerField.getValue();
upper = upperField.getValue();
}
dist = new TruncatedDistribution(dist, lower, upper);
}
return dist;
}
void setArguments(Parameter parameter, PriorType priorType) {
if (!parameter.isStatistic) {
setFieldRange(initialField, parameter.isNonNegative, parameter.isZeroOne);
initialField.setValue(parameter.initial);
}
isTruncatedCheck.setSelected(parameter.isTruncated);
lowerField.setValue(parameter.getLowerBound());
upperField.setValue(parameter.getUpperBound());
setArguments(parameter);
setupComponents();
}
void getArguments(Parameter parameter, PriorType priorType) {
if (!parameter.isStatistic) {
parameter.initial = initialField.getValue();
}
parameter.isTruncated = isTruncatedCheck.isSelected();
if (parameter.isTruncated) {
parameter.truncationLower = lowerField.getValue();
parameter.truncationUpper = upperField.getValue();
}
getArguments(parameter);
}
abstract void setup();
abstract Distribution getDistribution();
abstract void setArguments(Parameter parameter);
abstract void getArguments(Parameter parameter);
static final PriorOptionsPanel UNIFORM = new PriorOptionsPanel(false) {
void setup() {
addField("Lower", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Upper", 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
Distribution getDistribution() {
return new UniformDistribution(getValue(0), getValue(1));
}
void setArguments(Parameter parameter) {
super.setFieldRange(getField(0), parameter.isNonNegative, parameter.isZeroOne);
super.setFieldRange(getField(1), parameter.isNonNegative, parameter.isZeroOne);
getField(0).setValue(parameter.getLowerBound());
getField(1).setValue(parameter.getUpperBound());
}
void getArguments(Parameter parameter) {
parameter.isTruncated = true;
parameter.truncationLower = getValue(0);
parameter.truncationUpper = getValue(1);
}
};
static final PriorOptionsPanel EXPONENTIAL = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Offset", 0.0, 0.0, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new ExponentialDistribution(1.0 / getValue(0)), getValue(1));
}
public void setArguments(Parameter parameter) {
setFieldRange(getField(0), true, parameter.isZeroOne);
getField(0).setValue(parameter.mean);
getField(1).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.offset = getValue(1);
}
};
static final PriorOptionsPanel LAPLACE = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Scale", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new LaplaceDistribution(getValue(0), getValue(1));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
setFieldRange(getField(0), true, false);
getField(1).setValue(parameter.scale);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.scale = getValue(1);
}
};
static final PriorOptionsPanel NORMAL = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Stdev", 1.0, 0.0, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new NormalDistribution(getValue(0), getValue(1));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
getField(1).setValue(parameter.stdev);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.stdev = getValue(1);
}
};
static final PriorOptionsPanel LOG_NORMAL = new PriorOptionsPanel(true) {
private JCheckBox meanInRealSpaceCheck;
void setup() {
meanInRealSpaceCheck = new JCheckBox();
if (meanInRealSpaceCheck.isSelected()) {
addField("Mean", 0.01, 0.0, Double.POSITIVE_INFINITY);
} else {
addField("Log(Mean)", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
addField("Log(Stdev)", 1.0, 0.0, Double.MAX_VALUE);
addField("Offset", 0.0, 0.0, Double.MAX_VALUE);
addCheckBox("Mean In Real Space", meanInRealSpaceCheck);
meanInRealSpaceCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
if (meanInRealSpaceCheck.isSelected()) {
replaceFieldName(0, "Mean");
if (getValue(0) <= 0) {
getField(0).setValue(0.01);
}
getField(0).setRange(0.0, Double.POSITIVE_INFINITY);
} else {
replaceFieldName(0, "Log(Mean)");
getField(0).setRange(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
// dialog.updateChart();
}
});
}
public Distribution getDistribution() {
double mean = getValue(0);
if (meanInRealSpaceCheck.isSelected()) {
if (mean <= 0) {
throw new IllegalArgumentException("meanInRealSpace works only for a positive mean");
}
mean = Math.log(getValue(0)) - 0.5 * getValue(1) * getValue(1);
}
return new OffsetPositiveDistribution(
new LogNormalDistribution(mean, getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
getField(1).setValue(parameter.stdev);
getField(2).setValue(parameter.offset);
meanInRealSpaceCheck.setSelected(parameter.isMeanInRealSpace());
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.stdev = getValue(1);
parameter.offset = getValue(2);
parameter.setMeanInRealSpace(meanInRealSpaceCheck.isSelected());
}
};
static final PriorOptionsPanel GAMMA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Scale", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Offset", 0.0, 0.0, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new GammaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.scale);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.scale = getValue(1);
parameter.offset = getValue(2);
}
};
static final PriorOptionsPanel INVERSE_GAMMA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Scale", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Offset", 0.0, 0.0, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new InverseGammaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.scale);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.scale = getValue(1);
parameter.offset = getValue(2);
}
};
// class TruncatedNormalOptionsPanel extends PriorOptionsPanel {
// public TruncatedNormalOptionsPanel() {
// addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// addField("Stdev", 1.0, 0.0, Double.MAX_VALUE);
// addField("Lower", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// addField("Upper", 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// public Distribution getDistribution() {
// return new TruncatedNormalDistribution(getValue(0), getValue(1), getValue(2), getValue(3));
// public void setParameterPrior(Parameter parameter) {
// parameter.mean = getValue(0);
// parameter.stdev = getValue(1);
// parameter.isTruncated = true;
// parameter.truncationLower = getValue(2);
// parameter.truncationUpper = getValue(3);
static final PriorOptionsPanel BETA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("ShapeB", 1.0, Double.MIN_VALUE, Double.MAX_VALUE);
addField("Offset", 0.0, 0.0, Double.MAX_VALUE);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new BetaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.shapeB);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.shapeB = getValue(1);
parameter.offset = getValue(2);
}
};
static final PriorOptionsPanel CTMC_RATE_REFERENCE = new PriorOptionsPanel(true) {
void setup() {
}
public Distribution getDistribution() {
return null;
}
public void setArguments(Parameter parameter) {
}
public void getArguments(Parameter parameter) {
}
};
} |
package org.xwiki.gwt.wysiwyg.client.plugin.image.ui;
import java.util.List;
import org.xwiki.gwt.user.client.StringUtils;
import org.xwiki.gwt.user.client.ui.VerticalResizePanel;
import org.xwiki.gwt.user.client.ui.wizard.NavigationListener;
import org.xwiki.gwt.user.client.ui.wizard.SourcesNavigationEvents;
import org.xwiki.gwt.wysiwyg.client.Strings;
import org.xwiki.gwt.wysiwyg.client.plugin.image.ImageConfig;
import org.xwiki.gwt.wysiwyg.client.widget.PageSelector;
import org.xwiki.gwt.wysiwyg.client.widget.SpaceSelector;
import org.xwiki.gwt.wysiwyg.client.widget.WikiSelector;
import org.xwiki.gwt.wysiwyg.client.widget.wizard.util.AbstractSelectorWizardStep;
import org.xwiki.gwt.wysiwyg.client.wiki.AttachmentReference;
import org.xwiki.gwt.wysiwyg.client.wiki.EntityLink;
import org.xwiki.gwt.wysiwyg.client.wiki.EntityReference;
import org.xwiki.gwt.wysiwyg.client.wiki.EntityReference.EntityType;
import org.xwiki.gwt.wysiwyg.client.wiki.WikiPageReference;
import org.xwiki.gwt.wysiwyg.client.wiki.WikiServiceAsync;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
/**
* Wizard step to explore and select images from all the pages in the wiki. <br />
*
* @version $Id$
*/
public class ImagesExplorerWizardStep extends AbstractSelectorWizardStep<EntityLink<ImageConfig>> implements
ChangeHandler, SourcesNavigationEvents
{
/**
* Loading class for the time to load the step to which it has been toggled.
*/
private static final String STYLE_LOADING = "loading";
/**
* Selector for the wiki to get images from.
*/
private WikiSelector wikiSelector;
/**
* Selector for the space to get images from.
*/
private SpaceSelector spaceSelector;
/**
* Selector for the page to get images from.
*/
private PageSelector pageSelector;
/**
* Flag to mark whether this explorer should show the selector to choose an image from a different wiki or not.
*/
private boolean displayWikiSelector;
/**
* The image selector for the currently selected page in this wizard step. This will be instantiated every time the
* list of pages for a selected page needs to be displayed, and the functionality of this aggregator will be
* delegated to it.
*/
private CurrentPageImageSelectorWizardStep pageWizardStep;
/**
* The service used to access the wiki.
*/
private final WikiServiceAsync wikiService;
/**
* Builds an image explorer with the default selection on the passed resource.
*
* @param displayWikiSelector whether this explorer should show the selector to choose an image from a different
* wiki or not
* @param wikiService the service used to access the wiki
*/
public ImagesExplorerWizardStep(boolean displayWikiSelector, WikiServiceAsync wikiService)
{
super(new VerticalResizePanel());
this.wikiService = wikiService;
setStepTitle(Strings.INSTANCE.imageSelectImageTitle());
Label helpLabel = new Label(Strings.INSTANCE.imageSelectImageLocationHelpLabel());
helpLabel.addStyleName("xHelpLabel");
display().add(helpLabel);
// initialize selectors, mainPanel
display().addStyleName("xImagesExplorer");
this.displayWikiSelector = displayWikiSelector;
display().add(getSelectorsPanel());
pageWizardStep = new CurrentPageImageSelectorWizardStep(wikiService, true);
display().add(pageWizardStep.display());
display().setExpandingWidget(pageWizardStep.display(), true);
}
/**
* @return the panel with the selectors to choose the source for the attachments panel
*/
private Panel getSelectorsPanel()
{
// create selectors for the page to get images from
FlowPanel selectorsPanel = new FlowPanel();
if (displayWikiSelector) {
wikiSelector = new WikiSelector(wikiService);
wikiSelector.addChangeHandler(this);
selectorsPanel.add(wikiSelector);
}
spaceSelector = new SpaceSelector(wikiService);
spaceSelector.addChangeHandler(this);
selectorsPanel.add(spaceSelector);
pageSelector = new PageSelector(wikiService);
selectorsPanel.add(pageSelector);
Button updateImagesListButton = new Button(Strings.INSTANCE.imageUpdateListButton());
updateImagesListButton.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
WikiPageReference originPage = new WikiPageReference(getData().getOrigin());
AttachmentReference imageReferenceTemplate = new AttachmentReference();
imageReferenceTemplate.getWikiPageReference().setWikiName(
displayWikiSelector ? wikiSelector.getSelectedWiki() : originPage.getWikiName());
imageReferenceTemplate.getWikiPageReference().setSpaceName(spaceSelector.getSelectedSpace());
imageReferenceTemplate.getWikiPageReference().setPageName(pageSelector.getSelectedPage());
initCurrentPage(imageReferenceTemplate, null);
}
});
selectorsPanel.add(updateImagesListButton);
selectorsPanel.addStyleName("xPageChooser");
return selectorsPanel;
}
/**
* Refreshes the list of images with the images attached to the same page as the specified image, and then selects
* the specified image.
*
* @param imageReference a reference to the image to be selected
* @param cb the object to be notified after the specified image is selected
*/
public void setSelection(final AttachmentReference imageReference, final AsyncCallback< ? > cb)
{
if (displayWikiSelector) {
wikiService.isMultiWiki(new AsyncCallback<Boolean>()
{
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
}
}
public void onSuccess(Boolean result)
{
if (result) {
setWikiSelection(imageReference, cb);
} else {
setSpaceSelection(imageReference, cb);
}
}
});
} else {
setSpaceSelection(imageReference, cb);
}
}
/**
* Sets the selected wiki based on the specified image and updates the space selector.
*
* @param imageReference the image to be selected
* @param cb the object to be notified after the specified image is selected
*/
private void setWikiSelection(final AttachmentReference imageReference, final AsyncCallback< ? > cb)
{
wikiSelector.refreshList(imageReference.getWikiPageReference().getWikiName(), new AsyncCallback<List<String>>()
{
public void onSuccess(List<String> result)
{
setSpaceSelection(imageReference, cb);
}
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
}
}
});
}
/**
* Sets the selected space based on the specified image and updates the page selector.
*
* @param imageReference the image to be selected
* @param cb the object to be notified after the specified image is selected
*/
private void setSpaceSelection(AttachmentReference imageReference, final AsyncCallback< ? > cb)
{
// Clone the image reference because we might modify it. See the next comment.
final AttachmentReference actualImageReference = imageReference.clone();
WikiPageReference wikiPageReference = actualImageReference.getWikiPageReference();
spaceSelector.setWiki(displayWikiSelector ? wikiSelector.getSelectedWiki() : wikiPageReference.getWikiName());
// Replace the image reference components that point to missing entities with the entities selected by default.
// In this case, if the image reference points to a wiki that doesn't exist then we update the image reference
// to use the wiki selected by default.
wikiPageReference.setWikiName(spaceSelector.getWiki());
spaceSelector.refreshList(wikiPageReference.getSpaceName(), new AsyncCallback<List<String>>()
{
public void onSuccess(List<String> result)
{
setPageSelection(actualImageReference, cb);
}
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
}
}
});
}
/**
* Sets the selected page based on the specified image and updates the list of images accordingly.
*
* @param imageReference the image to be selected
* @param cb the object to be notified after the specified image is selected
*/
private void setPageSelection(final AttachmentReference imageReference, final AsyncCallback< ? > cb)
{
pageSelector.setWiki(spaceSelector.getWiki());
pageSelector.setSpace(spaceSelector.getSelectedSpace());
// Replace the image reference components that point to missing entities with the entities selected by default.
// In this case, if the image reference points to a space that doesn't exist then we update the image reference
// to use the space selected by default.
imageReference.getWikiPageReference().setSpaceName(pageSelector.getSpace());
pageSelector.refreshList(imageReference.getWikiPageReference().getPageName(), new AsyncCallback<List<String>>()
{
public void onSuccess(List<String> result)
{
// Replace the image reference components that point to missing entities with the entities selected by
// default. In this case, if the image reference points to a page that doesn't exist then we update the
// image reference to use the page selected by default.
imageReference.getWikiPageReference().setPageName(pageSelector.getSelectedPage());
initCurrentPage(imageReference, cb);
}
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
}
}
});
}
/**
* {@inheritDoc}
*
* @see ChangeHandler#onChange(ChangeEvent)
*/
public void onChange(ChangeEvent event)
{
if (event.getSource() == wikiSelector) {
spaceSelector.setWiki(wikiSelector.getSelectedWiki());
spaceSelector.refreshList(spaceSelector.getSelectedSpace(), new AsyncCallback<List<String>>()
{
public void onFailure(Throwable caught)
{
}
public void onSuccess(List<String> result)
{
pageSelector.setWiki(wikiSelector.getSelectedWiki());
pageSelector.setSpace(spaceSelector.getSelectedSpace());
pageSelector.refreshList(pageSelector.getSelectedPage());
}
});
} else if (event.getSource() == spaceSelector) {
pageSelector.setWiki(spaceSelector.getWiki());
pageSelector.setSpace(spaceSelector.getSelectedSpace());
pageSelector.refreshList(pageSelector.getSelectedPage());
}
}
/**
* Initializes and displays list of images attached to the same page as the specified image, and selects the
* specified image.
*
* @param imageReference a reference to the image to be selected after the list of images is updated
* @param cb the object to be notified after the list of images is updated
*/
protected void initCurrentPage(AttachmentReference imageReference, final AsyncCallback< ? > cb)
{
display().addStyleName(STYLE_LOADING);
getData().getDestination().setEntityReference(imageReference.getEntityReference());
pageWizardStep.init(getData(), new AsyncCallback<Object>()
{
public void onSuccess(Object result)
{
onCurrenPageInitialization();
if (cb != null) {
cb.onSuccess(null);
}
}
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
} else {
showCurrentPageInitializationError();
}
}
});
}
/**
* Helper function to handle the error on current page initialization: display an error message in the reserved
* panel.
*/
private void showCurrentPageInitializationError()
{
display().removeStyleName(STYLE_LOADING);
Label error = new Label(Strings.INSTANCE.linkErrorLoadingData());
error.addStyleName("errormessage");
display().remove(pageWizardStep.display());
display().add(error);
}
/**
* Helper function to handle the success on initialization of the current page wizard step.
*/
private void onCurrenPageInitialization()
{
// if the current page's display is not there (maybe an error before removed it), remove the error and add
if (display().getWidgetIndex(pageWizardStep.display()) < 0) {
// FIXME: the error panel shouldn't be identified by its position!
display().remove(display().getWidgetCount() - 1);
display().add(pageWizardStep.display());
}
display().removeStyleName(STYLE_LOADING);
}
/**
* {@inheritDoc}
*/
public VerticalResizePanel display()
{
return (VerticalResizePanel) super.display();
}
/**
* {@inheritDoc}
*/
public String getNextStep()
{
return pageWizardStep.getNextStep();
}
/**
* {@inheritDoc}
*/
protected void initializeSelection(AsyncCallback< ? > cb)
{
if (!StringUtils.isEmpty(getData().getData().getReference())
&& getData().getDestination().getEntityReference().getType() == EntityType.ATTACHMENT) {
// Edit internal image.
setSelection(new AttachmentReference(getData().getDestination().getEntityReference()), cb);
} else if (pageSelector.getSelectedPage() == null) {
// Insert image. No page selected so initialize the list of images.
setSelection(new AttachmentReference(getData().getOrigin()), cb);
} else {
// Insert image. There is a previous selection, preserve it and re-initialize the list of images.
EntityReference destinationReference = pageWizardStep.getData().getDestination().getEntityReference();
initCurrentPage(new AttachmentReference(destinationReference), cb);
}
}
/**
* {@inheritDoc}
*/
public void onCancel()
{
pageWizardStep.onCancel();
}
/**
* {@inheritDoc}
*/
public void onSubmit(AsyncCallback<Boolean> async)
{
pageWizardStep.onSubmit(async);
}
/**
* {@inheritDoc}
*/
public void addNavigationListener(NavigationListener listener)
{
pageWizardStep.addNavigationListener(listener);
}
/**
* {@inheritDoc}
*/
public void removeNavigationListener(NavigationListener listener)
{
pageWizardStep.removeNavigationListener(listener);
}
/**
* {@inheritDoc}
*/
@Override
public void setActive()
{
if (displayWikiSelector) {
wikiSelector.setFocus(true);
} else {
spaceSelector.setFocus(true);
}
}
/**
* {@inheritDoc}
*
* @see AbstractSelectorWizardStep#getResult()
*/
@Override
public Object getResult()
{
return pageWizardStep.getResult();
}
} |
package com.pigdogbay.wordpig;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import com.pigdogbay.library.games.BitmapButton;
import com.pigdogbay.library.games.FrameBuffer;
import com.pigdogbay.library.games.GameView;
import com.pigdogbay.library.games.ObjectTouchHandler;
import com.pigdogbay.library.games.SoundManager;
import com.pigdogbay.wordpig.model.Board;
import com.pigdogbay.wordpig.model.Tile;
import com.pigdogbay.wordpig.model.TouchTile;
public class GameScreen implements GameView.IGame, BitmapButton.OnClickListener {
private FrameBuffer _Buffer;
private ObjectTouchHandler _TouchHandler;
private Board _Board;
private BitmapButton _GoButton, _ClearButton;
private Paint _TextPaint,_TimerOuterPaint,_TimerInnerPaint, _BoomPaint;
//Need a game event system so can fire off sounds
private SoundManager _SoundManager;
public void setSoundManager(SoundManager soundManager){_SoundManager=soundManager;}
public void setBoard(Board board){ _Board = board;}
public void setTouchHandler(ObjectTouchHandler touch) {
_TouchHandler = touch;
}
public void setBuffer(FrameBuffer buffer) {
this._Buffer = buffer;
}
public GameScreen()
{
_TextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
_TextPaint.setColor(Color.WHITE);
_TextPaint.setTextSize(36);
_TimerInnerPaint = new Paint();
_TimerInnerPaint.setColor(Color.WHITE);
_TimerOuterPaint = new Paint();
_TimerOuterPaint.setColor(Color.RED);
_BoomPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
_BoomPaint.setColor(Color.RED);
_BoomPaint.setTextSize(144);
_GoButton = new BitmapButton();
_GoButton.setBitmaps(Assets.GoButton, Assets.GoButtonPressed, Defines.GO_BUTTON_X, Defines.GO_BUTTON_Y);
_GoButton.setOnClickListener(this);
_ClearButton = new BitmapButton();
_ClearButton.setBitmaps(Assets.ClearButton, Assets.ClearButtonPressed, Defines.CLEAR_BUTTON_X, Defines.CLEAR_BUTTON_Y);
_ClearButton.setOnClickListener(this);
}
public void registerTouchables()
{
_TouchHandler.add(_GoButton);
_TouchHandler.add(_ClearButton);
for (Tile t : _Board.tiles)
{
TouchTile touchTile = new TouchTile(t);
_TouchHandler.add(touchTile);
}
_SoundManager.play(R.raw.coin,0.5f);
}
//IGame
@Override
public void Update() {
_Board.update();
}
@Override
public void Render(Canvas c) {
_Buffer.clear(0);
final Canvas buffCanvas = _Buffer.getCanvas();
_Buffer.draw(Assets.WordBench, Defines.WORD_BENCH_X, Defines.WORD_BENCH_Y);
drawButtons();
drawScore(buffCanvas);
drawTimer(buffCanvas);
drawTiles();
drawBoom(buffCanvas);
_Buffer.scaleToFit(c);
}
private void drawBoom(Canvas buffCanvas)
{
if (_Board.boom.isMessageAvailable)
{
final float y = Defines.BOOM_Y - (float)(_Board.boom.count*10);
buffCanvas.drawText(_Board.boom.latestMessage, Defines.BOOM_X, y, _BoomPaint);
}
}
private void drawTiles()
{
Point point = new Point();
for (Tile t : _Board.tiles) {
getTileAtlasCoords(point,t);
_Buffer.draw(Assets.TilesAtlas, t.x, t.y, point.x, point.y, Defines.TILE_WIDTH, Defines.TILE_HEIGHT);
}
}
private void drawButtons()
{
_GoButton.draw(_Buffer);
_ClearButton.draw(_Buffer);
}
private void drawScore(Canvas buffCanvas)
{
buffCanvas.drawText("Level: "+ Integer.toString(_Board.level), Defines.LEVEL_X, Defines.LEVEL_Y, _TextPaint);
buffCanvas.drawText("Score: "+Integer.toString(_Board.score), Defines.SCORE_X, Defines.SCORE_Y, _TextPaint);
}
private void drawTimer(Canvas buffCanvas)
{
buffCanvas.drawRect(Defines.TIMER_OUTER_RECT,_TimerOuterPaint);
float len = Defines.TIMER_INNER_RIGHT - Defines.TIMER_INNER_LEFT;
len = Defines.TIMER_INNER_LEFT+ len * _Board.time/Defines.TIMER_MAX_VAL;
buffCanvas.drawRect(Defines.TIMER_INNER_LEFT,Defines.TIMER_INNER_TOP,len,Defines.TIMER_INNER_BOTTOM,_TimerInnerPaint);
}
private void getTileAtlasCoords(Point p,Tile t)
{
int i = t.letter-'a';
p.y = 0;
if (i>=13)
{
p.y = Defines.TILE_HEIGHT;
i=i-13;
}
p.x = i*Defines.TILE_WIDTH;
}
@Override
public void onClick(Object sender)
{
if (sender == _GoButton)
{
_Board.go();
}
else if (sender == _ClearButton)
{
_Board.clear();
}
}
} |
package org.jpos.util;
import java.io.*;
import java.util.*;
/**
* Peer class Logger forwards LogEvents generated by LogProducers
* to LogListeners.
* <br>
* This little <a href="/doc/LoggerGuide.html">tutorial</a>
* give you additional information on how to extend the jPOS's
* Logger subsystem.
*
* @author apr@cs.com.uy
* @version $Id$
* @see LogEvent
* @see LogProducer
* @see LogListener
* @see Loggeable
* @see SimpleLogListener
* @see RotateLogListener
* @see AntiHog
*/
public class Logger {
Vector listeners;
AntiHog antiHog;
public Logger () {
super();
listeners = new Vector ();
antiHog = null;
}
public void addListener (LogListener l) {
listeners.add (l);
}
public void removeListener (LogListener l) {
listeners.remove (l);
}
public void setAntiHog (AntiHog antiHog) {
this.antiHog = antiHog;
}
private void checkAntiHog (LogEvent ev) {
if (antiHog != null) {
int p = antiHog.nice ();
if (p > 0)
ev.addMessage ("<antiHog penalty=\""+p+"ms\"/>");
}
}
public static void log (LogEvent ev) {
Logger l = ((LogProducer) ev.getSource()).getLogger();
if (l != null) {
l.checkAntiHog (ev);
Iterator i = l.listeners.iterator();
while (i.hasNext())
((LogListener) i.next()).log (ev);
}
}
/**
* associates this Logger with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
NameRegistrar.register ("logger."+name, this);
}
/**
* @return logger instance with given name. Creates one if necessary
* @see NameRegistrar
*/
public static Logger getLogger (String name) {
Logger l;
try {
l = (Logger) NameRegistrar.get ("logger."+name);
} catch (NameRegistrar.NotFoundException e) {
l = new Logger();
l.setName (name);
}
return l;
}
} |
package org.xwiki.rendering.internal.parser.wikimodel;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.wikimodel.wem.IWemConstants;
import org.wikimodel.wem.IWemListener;
import org.wikimodel.wem.WikiFormat;
import org.wikimodel.wem.WikiParameter;
import org.wikimodel.wem.WikiParameters;
import org.wikimodel.wem.WikiReference;
import org.wikimodel.wem.WikiStyle;
import org.xwiki.rendering.listener.CompositeListener;
import org.xwiki.rendering.listener.Format;
import org.xwiki.rendering.listener.HeaderLevel;
import org.xwiki.rendering.listener.Link;
import org.xwiki.rendering.listener.LinkType;
import org.xwiki.rendering.listener.ListType;
import org.xwiki.rendering.listener.Listener;
import org.xwiki.rendering.listener.QueueListener;
import org.xwiki.rendering.parser.ImageParser;
import org.xwiki.rendering.parser.LinkParser;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.StreamParser;
import org.xwiki.rendering.renderer.PrintRenderer;
import org.xwiki.rendering.renderer.PrintRendererFactory;
import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter;
import org.xwiki.rendering.util.IdGenerator;
/**
* Transforms WikiModel events into XWiki Rendering events.
*
* @version $Id$
* @since 2.1RC1
*/
public class XWikiGeneratorListener implements IWemListener
{
/**
* Identifier of the extension used to generate id blocks.
*/
public static final String EXT_ID = "xwiki_id";
private static final Map<WikiStyle, Format> STYLES_CONVERTER = new HashMap<WikiStyle, Format>();
static {
STYLES_CONVERTER.put(IWemConstants.CODE, Format.MONOSPACE);
STYLES_CONVERTER.put(IWemConstants.EM, Format.ITALIC);
STYLES_CONVERTER.put(IWemConstants.DEL, Format.STRIKEDOUT);
STYLES_CONVERTER.put(IWemConstants.INS, Format.UNDERLINED);
STYLES_CONVERTER.put(IWemConstants.MONO, Format.MONOSPACE);
STYLES_CONVERTER.put(IWemConstants.STRIKE, Format.STRIKEDOUT);
STYLES_CONVERTER.put(IWemConstants.STRONG, Format.BOLD);
STYLES_CONVERTER.put(IWemConstants.SUB, Format.SUBSCRIPT);
STYLES_CONVERTER.put(IWemConstants.SUP, Format.SUPERSCRIPT);
STYLES_CONVERTER.put(IWemConstants.TT, Format.MONOSPACE);
// TODO: what is the best conversion for theses ?
STYLES_CONVERTER.put(IWemConstants.BIG, Format.NONE);
STYLES_CONVERTER.put(IWemConstants.CITE, Format.NONE);
STYLES_CONVERTER.put(IWemConstants.REF, Format.NONE);
STYLES_CONVERTER.put(IWemConstants.SMALL, Format.NONE);
}
/**
* Listener(s) for the generated XWiki Events. Organized as a stack so that a buffering listener can hijack all
* events for a while, for example. All generated events are sent to the top of the stack.
*/
private Stack<Listener> listener = new Stack<Listener>();
private StreamParser parser;
private LinkParser linkParser;
private ImageParser imageParser;
private IdGenerator idGenerator;
private PrintRendererFactory plainRendererFactory;
private int documentDepth = 0;
private Stack<WikiFormat> currentFormatStack = new Stack<WikiFormat>();
private WikiFormat lastEndFormat = null;
public XWikiGeneratorListener(StreamParser parser, Listener listener, LinkParser linkParser,
ImageParser imageParser, PrintRendererFactory plainRendererFactory, IdGenerator idGenerator)
{
pushListener(listener);
this.parser = parser;
this.linkParser = linkParser;
this.imageParser = imageParser;
this.idGenerator = idGenerator != null ? idGenerator : new IdGenerator();
this.plainRendererFactory = plainRendererFactory;
}
/**
* Returns the 'default' listener to send xwiki events to, the top of the listeners stack.
*
* @return the listener to send xwiki events to
*/
public Listener getListener()
{
return this.listener.peek();
}
/**
* Pushes a new listener in the listeners stack, thus making it the 'default' listener, to which all events are
* sent.
*
* @param listener the listener to add in the top of the stack
* @return the listener pushed in the top of the stack
*/
private Listener pushListener(Listener listener)
{
return this.listener.push(listener);
}
/**
* Removes the listener from the top of the stack (the current 'default' listener).
*
* @return the removed listener
*/
private Listener popListener()
{
return this.listener.pop();
}
/**
* Convert Wikimodel parameters to XWiki parameters format.
*
* @param params the wikimodel parameters to convert
* @return the parameters in XWiki format
*/
private Map<String, String> convertParameters(WikiParameters params)
{
Map<String, String> xwikiParams;
if (params.getSize() > 0) {
xwikiParams = new LinkedHashMap<String, String>();
for (WikiParameter wikiParameter : params.toList()) {
xwikiParams.put(wikiParameter.getKey(), wikiParameter.getValue());
}
} else {
xwikiParams = Listener.EMPTY_PARAMETERS;
}
return xwikiParams;
}
private Format convertFormat(WikiStyle style)
{
Format result = STYLES_CONVERTER.get(style);
if (result == null) {
result = Format.NONE;
}
return result;
}
private void flush()
{
flushInline();
}
private void flushInline()
{
flushFormat();
}
private void flushFormat()
{
flushFormat(null, null);
}
private void flushFormat(List<WikiStyle> xorStyles, List<WikiParameter> xorParameters)
{
if (this.lastEndFormat != null) {
flushFormat(this.lastEndFormat.getStyles(), this.lastEndFormat.getParams(), xorStyles, xorParameters);
}
}
private void flushFormat(List<WikiStyle> formatStyles, List<WikiParameter> formatParameters,
List<WikiStyle> xorStyles, List<WikiParameter> xorParameters)
{
Set<WikiStyle> stylesToClose = new HashSet<WikiStyle>();
Set<WikiParameter> parametersToClose = new HashSet<WikiParameter>();
if (xorStyles != null) {
for (WikiStyle style : formatStyles) {
if (!xorStyles.contains(style)) {
stylesToClose.add(style);
}
}
} else {
stylesToClose.addAll(formatStyles);
}
if (xorParameters != null) {
for (WikiParameter parameter : formatParameters) {
if (!xorParameters.contains(parameter)) {
parametersToClose.add(parameter);
}
}
} else {
parametersToClose.addAll(formatParameters);
}
for (; !stylesToClose.isEmpty() || !parametersToClose.isEmpty(); this.currentFormatStack.pop()) {
WikiFormat currentFormat = this.currentFormatStack.peek();
List<WikiStyle> currentFormatStyles = currentFormat.getStyles();
WikiStyle currentFormatStyle = currentFormatStyles.isEmpty() ? null : currentFormatStyles.get(0);
List<WikiParameter> currentFormatParameters = currentFormat.getParams();
// XOR
stylesToClose.remove(currentFormatStyle);
parametersToClose.removeAll(currentFormatParameters);
// send event
Map<String, String> parameters;
if (!currentFormatParameters.isEmpty()) {
parameters = convertParameters(new WikiParameters(currentFormatParameters));
} else {
parameters = Listener.EMPTY_PARAMETERS;
}
if (currentFormatStyle != null) {
getListener().endFormat(convertFormat(currentFormatStyle), parameters);
} else {
getListener().endFormat(Format.NONE, parameters);
}
}
for (WikiFormat format : this.currentFormatStack) {
if (xorStyles != null) {
xorStyles.removeAll(format.getStyles());
}
if (xorParameters != null) {
xorParameters.removeAll(format.getParams());
}
}
this.lastEndFormat = null;
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginDefinitionDescription()
*/
public void beginDefinitionDescription()
{
getListener().beginDefinitionDescription();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginDefinitionList(org.wikimodel.wem.WikiParameters)
*/
public void beginDefinitionList(WikiParameters params)
{
flushInline();
getListener().beginDefinitionList(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginDefinitionTerm()
*/
public void beginDefinitionTerm()
{
getListener().beginDefinitionTerm();
}
public void beginDocument()
{
beginDocument(WikiParameters.EMPTY);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginDocument(WikiParameters)
*/
public void beginDocument(WikiParameters params)
{
if (this.documentDepth > 0) {
getListener().beginGroup(convertParameters(params));
}
++this.documentDepth;
}
/**
* A format is a special formatting around an inline element, such as bold, italics, etc.
*/
public void beginFormat(WikiFormat format)
{
List<WikiStyle> formatStyles = format.getStyles();
List<WikiParameter> formatParameters = format.getParams();
// If there's any style or parameter defined, do something. The reason we need to check for this is because
// wikimodel sends an empty begin/endFormat event before starting an inline block (such as a paragraph).
if (formatStyles.size() > 0 || formatParameters.size() > 0) {
flushFormat(formatStyles, formatParameters);
// If everything is already part of the current style
if (formatStyles.size() > 0 || formatParameters.size() > 0) {
Map<String, String> parameters;
if (formatParameters.size() > 0) {
parameters = convertParameters(new WikiParameters(formatParameters));
} else {
parameters = Listener.EMPTY_PARAMETERS;
}
if (formatStyles.size() > 0) {
boolean parametersConsumed = false;
for (WikiStyle style : formatStyles) {
// Exclude previous format styles
if (!parametersConsumed) {
getListener().beginFormat(convertFormat(style), parameters);
parametersConsumed = true;
this.currentFormatStack
.push(new WikiFormat(Collections.singleton(style), formatParameters));
} else {
getListener().beginFormat(convertFormat(style), Listener.EMPTY_PARAMETERS);
this.currentFormatStack.push(new WikiFormat(style));
}
}
} else {
getListener().beginFormat(Format.NONE, parameters);
this.currentFormatStack.push(new WikiFormat(formatParameters));
}
}
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginSection(int, int, WikiParameters)
*/
public void beginSection(int docLevel, int headerLevel, WikiParameters params)
{
if (headerLevel > 0) {
getListener().beginSection(Listener.EMPTY_PARAMETERS);
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginSectionContent(int, int, WikiParameters)
*/
public void beginSectionContent(int docLevel, int headerLevel, WikiParameters params)
{
// TODO add support for it
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginHeader(int, WikiParameters)
*/
public void beginHeader(int level, WikiParameters params)
{
// Heading needs to have an id generated from a plaintext representation of its content, so the header start
// event will be sent at the end of the header, after reading the content inside and generating the id.
// For this:
// buffer all events in a queue until the header ends, and also send them to a print renderer to generate the ID
CompositeListener composite = new CompositeListener();
composite.addListener(new QueueListener());
composite.addListener(this.plainRendererFactory.createRenderer(new DefaultWikiPrinter()));
// These 2 listeners will receive all events from now on until the header ends
pushListener(composite);
}
/**
* {@inheritDoc}
*
* @see IWemListener#beginInfoBlock(String, WikiParameters)
*/
public void beginInfoBlock(String infoType, WikiParameters params)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginList(WikiParameters, boolean)
*/
public void beginList(WikiParameters params, boolean ordered)
{
flushInline();
if (ordered) {
getListener().beginList(ListType.NUMBERED, convertParameters(params));
} else {
getListener().beginList(ListType.BULLETED, convertParameters(params));
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginListItem()
*/
public void beginListItem()
{
getListener().beginListItem();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginParagraph(WikiParameters)
*/
public void beginParagraph(WikiParameters params)
{
getListener().beginParagraph(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see IWemListener#beginPropertyBlock(String, boolean)
*/
public void beginPropertyBlock(String propertyUri, boolean doc)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see IWemListener#beginPropertyInline(String)
*/
public void beginPropertyInline(String str)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginQuotation(WikiParameters)
*/
public void beginQuotation(WikiParameters params)
{
getListener().beginQuotation(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginQuotationLine()
*/
public void beginQuotationLine()
{
getListener().beginQuotationLine();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginTable(WikiParameters)
*/
public void beginTable(WikiParameters params)
{
getListener().beginTable(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginTableCell(boolean, WikiParameters)
*/
public void beginTableCell(boolean tableHead, WikiParameters params)
{
if (tableHead) {
getListener().beginTableHeadCell(convertParameters(params));
} else {
getListener().beginTableCell(convertParameters(params));
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#beginTableRow(WikiParameters)
*/
public void beginTableRow(WikiParameters params)
{
getListener().beginTableRow(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endDefinitionDescription()
*/
public void endDefinitionDescription()
{
flushInline();
getListener().endDefinitionDescription();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endDefinitionList(WikiParameters)
*/
public void endDefinitionList(WikiParameters params)
{
getListener().endDefinitionList(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endDefinitionTerm()
*/
public void endDefinitionTerm()
{
flushInline();
getListener().endDefinitionTerm();
}
public void endDocument()
{
endDocument(WikiParameters.EMPTY);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endDocument(WikiParameters)
*/
public void endDocument(WikiParameters params)
{
flush();
--this.documentDepth;
if (this.documentDepth > 0) {
getListener().endGroup(convertParameters(params));
}
}
/**
* {@inheritDoc}
*
* @see IWemListener#endFormat(WikiFormat)
*/
public void endFormat(WikiFormat format)
{
// If there's any style or parameter defined, do something. The reason we need to check for this is because
// wikimodel sends an empty begin/endFormat event before starting an inline block (such as a paragraph).
if (format.getStyles().size() > 0 || format.getParams().size() > 0) {
this.lastEndFormat = format;
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endHeader(int, WikiParameters)
*/
public void endHeader(int level, WikiParameters params)
{
// End all formats
flushInline();
CompositeListener composite = (CompositeListener) getListener();
// Get the listener where events inside the header were buffered
QueueListener queue = (QueueListener) composite.getListener(0);
// and the listener in which the id was generated
PrintRenderer renderer = (PrintRenderer) composite.getListener(1);
// Restore the 'default' listener as it was at the beginning of the header
popListener();
HeaderLevel headerLevel = HeaderLevel.parseInt(level);
// Generate the id from the content inside the header written to the renderer
String id = this.idGenerator.generateUniqueId("H", renderer.getPrinter().toString());
Map<String, String> parameters = convertParameters(params);
// Generate the begin header event to the 'default' listener
getListener().beginHeader(headerLevel, id, parameters);
// Send all buffered events to the 'default' listener
queue.consumeEvents(getListener());
// Generate the end header event to the 'default' listener
getListener().endHeader(headerLevel, id, parameters);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endSection(int, int, WikiParameters)
*/
public void endSection(int docLevel, int headerLevel, WikiParameters params)
{
if (headerLevel > 0) {
getListener().endSection(Listener.EMPTY_PARAMETERS);
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endSectionContent(int, int, WikiParameters)
*/
public void endSectionContent(int docLevel, int headerLevel, WikiParameters params)
{
// TODO add support for it
}
/**
* {@inheritDoc}
*
* @see IWemListener#endInfoBlock(String, WikiParameters)
*/
public void endInfoBlock(String infoType, WikiParameters params)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endList(WikiParameters, boolean)
*/
public void endList(WikiParameters params, boolean ordered)
{
if (ordered) {
getListener().endList(ListType.NUMBERED, convertParameters(params));
} else {
getListener().endList(ListType.BULLETED, convertParameters(params));
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endListItem()
*/
public void endListItem()
{
flushInline();
// Note: This means we support Paragraphs inside lists.
getListener().endListItem();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endParagraph(WikiParameters)
*/
public void endParagraph(WikiParameters params)
{
flushFormat();
getListener().endParagraph(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see IWemListener#endPropertyBlock(String, boolean)
*/
public void endPropertyBlock(String propertyUri, boolean doc)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see IWemListener#endPropertyInline(String)
*/
public void endPropertyInline(String inlineProperty)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endQuotation(WikiParameters)
*/
public void endQuotation(WikiParameters params)
{
getListener().endQuotation(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endQuotationLine()
*/
public void endQuotationLine()
{
flushInline();
getListener().endQuotationLine();
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endTable(WikiParameters)
*/
public void endTable(WikiParameters params)
{
getListener().endTable(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endTableCell(boolean, WikiParameters)
*/
public void endTableCell(boolean tableHead, WikiParameters params)
{
flushInline();
if (tableHead) {
getListener().endTableHeadCell(convertParameters(params));
} else {
getListener().endTableCell(convertParameters(params));
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#endTableRow(WikiParameters)
*/
public void endTableRow(WikiParameters params)
{
getListener().endTableRow(convertParameters(params));
}
/**
* Called by wikimodel when there are 2 or more empty lines between blocks. For example the following will generate
* a call to <code>onEmptyLines(2)</code>:
* <p>
* <code><pre>
* {{macro/}}
* ... empty line 1...
* ... empty line 2...
* {{macro/}}
* </pre></code>
*
* @param count the number of empty lines separating the two blocks
*/
public void onEmptyLines(int count)
{
getListener().onEmptyLines(count);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onEscape(String)
*/
public void onEscape(String str)
{
// The WikiModel XWiki parser has been modified not to generate any onEscape event so do nothing here.
// This is because we believe that WikiModel should not have an escape event since it's the
// responsibility of Renderers to perform escaping as required.
}
/**
* {@inheritDoc}
*
* @see IWemListener#onExtensionBlock(String, WikiParameters)
*/
public void onExtensionBlock(String extensionName, WikiParameters params)
{
if (EXT_ID.equals(extensionName)) {
getListener().onId(params.getParameter("name").getValue());
}
}
/**
* {@inheritDoc}
*
* @see IWemListener#onExtensionInline(String, WikiParameters)
*/
public void onExtensionInline(String extensionName, WikiParameters params)
{
if (EXT_ID.equals(extensionName)) {
getListener().onId(params.getParameter("name").getValue());
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onHorizontalLine(org.wikimodel.wem.WikiParameters)
*/
public void onHorizontalLine(WikiParameters params)
{
getListener().onHorizontalLine(convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onLineBreak()
*/
public void onLineBreak()
{
// Note that in XWiki we don't differentiate new lines and line breaks since it's the Renderers that decide
// to generate new lines or line breaks depending on the context and the target syntax.
onNewLine();
}
/**
* A macro block was found and it's separated at least by one new line from the next block. If there's no new line
* with the next block then wikimodel calls {@link #onMacroInline(String, org.wikimodel.wem.WikiParameters, String)}
* instead.
* <p>
* In wikimodel block elements can be:
* <ul>
* <li>at the very beginning of the document (no "\n")</li>
* <li>just after at least one "\n"</li>
* </ul>
*/
public void onMacroBlock(String macroName, WikiParameters params, String content)
{
getListener().onMacro(macroName, convertParameters(params), content, false);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onMacroInline(String, WikiParameters, String)
*/
public void onMacroInline(String macroName, WikiParameters params, String content)
{
flushFormat();
getListener().onMacro(macroName, convertParameters(params), content, true);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onLineBreak()
*/
public void onNewLine()
{
flushFormat();
// Note that in XWiki we don't differentiate new lines and line breaks since it's the Renderers that decide
// to generate new lines or line breaks depending on the context and the target syntax.
getListener().onNewLine();
}
/**
* {@inheritDoc}
* <p>
* Called when WikiModel finds an reference (link or image) such as a URI located directly in the text
* (free-standing URI), as opposed to a link/image inside wiki link/image syntax delimiters.
* </p>
*
* @see org.wikimodel.wem.IWemListener#onLineBreak()
*/
public void onReference(String reference)
{
onReference(reference, null, true, Listener.EMPTY_PARAMETERS);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onReference(String)
*/
public void onReference(WikiReference reference)
{
onReference(reference.getLink(), reference.getLabel(), false, convertParameters(reference.getParameters()));
}
private void onReference(String reference, String label, boolean isFreeStandingURI, Map<String, String> parameters)
{
flushFormat();
// If there's no link parser defined, don't handle links and images...
if (this.linkParser != null) {
Link link = this.linkParser.parse(reference);
if (link.getType() == LinkType.URI && link.getReference().startsWith("image:")) {
String imageLocation = link.getReference().substring("image:".length());
getListener().onImage(this.imageParser.parse(imageLocation), isFreeStandingURI, parameters);
} else {
getListener().beginLink(link, isFreeStandingURI, parameters);
if (label != null) {
try {
WikiModelParserUtils parserUtils = new WikiModelParserUtils();
parserUtils.parseInline(this.parser, label, getListener());
} catch (ParseException e) {
// TODO what should we do here ?
}
}
getListener().endLink(link, isFreeStandingURI, parameters);
}
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListenerInline#onImage(java.lang.String)
*/
public void onImage(String ref)
{
flushFormat();
getListener().onImage(this.imageParser.parse(ref), true, Listener.EMPTY_PARAMETERS);
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListenerInline#onImage(org.wikimodel.wem.WikiReference)
*/
public void onImage(WikiReference ref)
{
flushFormat();
getListener().onImage(this.imageParser.parse(ref.getLink()), false, convertParameters(ref.getParameters()));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onSpace(String)
*/
public void onSpace(String spaces)
{
flushFormat();
// We want one space event per space.
for (int i = 0; i < spaces.length(); i++) {
getListener().onSpace();
}
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onSpecialSymbol(String)
*/
public void onSpecialSymbol(String symbol)
{
flushFormat();
for (int i = 0; i < symbol.length(); i++) {
getListener().onSpecialSymbol(symbol.charAt(i));
}
}
/**
* {@inheritDoc}
*
* @see IWemListener#onTableCaption(String)
*/
public void onTableCaption(String str)
{
// Not used by XWiki Syntax 2.0
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onVerbatimBlock(String, WikiParameters)
*/
public void onVerbatimBlock(String protectedString, WikiParameters params)
{
getListener().onVerbatim(protectedString, false, convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onVerbatimInline(String, WikiParameters)
*/
public void onVerbatimInline(String protectedString, WikiParameters params)
{
flushFormat();
getListener().onVerbatim(protectedString, true, convertParameters(params));
}
/**
* {@inheritDoc}
*
* @see org.wikimodel.wem.IWemListener#onWord(String)
*/
public void onWord(String str)
{
flushFormat();
getListener().onWord(str);
}
} |
package dr.evomodel.coalescent;
import dr.inference.model.Statistic;
import dr.xml.AbstractXMLObjectParser;
import dr.xml.AttributeRule;
import dr.xml.ElementRule;
import dr.xml.XMLObject;
import dr.xml.XMLObjectParser;
import dr.xml.XMLParseException;
import dr.xml.XMLSyntaxRule;
public class GMRFPopSizeStatistic extends Statistic.Abstract{
private GMRFSkyrideLikelihood gsl;
private double[] time;
public final static String TIMES = "time";
public final static String FROM = "from";
public final static String TO = "to";
public final static String NUMBER_OF_INTERVALS = "number";
public final static String GMRF_POP_SIZE_STATISTIC = "gmrfPopSizeStatistic";
public GMRFPopSizeStatistic(double[] time, GMRFSkyrideLikelihood gsl){
super("Popsize");
this.gsl = gsl;
this.time = time;
}
public String getDimensionName(int i){
return getStatisticName() + Double.toString(time[i]);
}
public int getDimension() {
return time.length;
}
public double getStatisticValue(int dim) {
double[] coalescentHeights = gsl.getCoalescentIntervalHeights();
double[] popSizes = gsl.getPopSizeParameter().getParameterValues();
assert popSizes.length == coalescentHeights.length;
for(int i = 0; i < coalescentHeights.length; i++){
if(time[dim] < coalescentHeights[i]){
return popSizes[i];
}
}
return Double.NaN;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){
public String getParserDescription() {
return "The pop sizes at the given times";
}
public Class getReturnType() {
return GMRFPopSizeStatistic.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[]{
AttributeRule.newDoubleRule(FROM,true),
AttributeRule.newDoubleRule(TO,true),
AttributeRule.newIntegerRule(NUMBER_OF_INTERVALS,true),
AttributeRule.newDoubleArrayRule(TIMES,true),
new ElementRule(GMRFSkyrideLikelihood.class),
};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double[] times;
if( xo.hasAttribute(FROM)){
double from = xo.getDoubleAttribute(FROM);
double to = xo.getDoubleAttribute(TO);
int number = xo.getIntegerAttribute(NUMBER_OF_INTERVALS);
double length = (to - from)/number;
times = new double[number + 1];
for(int i = 0; i < times.length; i++){
times[i] = from + i*length;
}
}else{
times = xo.getDoubleArrayAttribute(TIMES);
}
GMRFSkyrideLikelihood gsl = (GMRFSkyrideLikelihood)xo.getChild(GMRFSkyrideLikelihood.class);
return new GMRFPopSizeStatistic(times, gsl);
}
public String getParserName() {
return GMRF_POP_SIZE_STATISTIC;
}
};
} |
package dr.evomodel.tree;
import dr.app.beast.BeastVersion;
import dr.evomodel.coalescent.GMRFSkyrideLikelihood;
import dr.evomodelxml.LoggerParser;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.LogFormatter;
import dr.inference.loggers.MCLogger;
import dr.inference.loggers.TabDelimitedFormatter;
import dr.math.MathUtils;
import dr.xml.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Logger;
/**
* Projects and logs the random grid of the skyride onto a fixed grid.
*
* @author Erik Bloomquist
*/
public class GMRFSkyrideFixedGridLogger extends MCLogger{
public static final String SKYRIDE_FIXED_GRID = "logSkyrideFixedGrid";
public static final String NUMBER_OF_INTERVALS = "numberOfIntervals";
public static final String GRID_HEIGHT = "gridHeight";
public static final String LOG_SCALE = "logScale";
private GMRFSkyrideLikelihood gmrfLike;
private double[] fixedPopSize;
private double intervalNumber;
private double gridHeight;
private final boolean gridHeightSameAsTreeHeight;
private final boolean logScale;
public GMRFSkyrideFixedGridLogger(LogFormatter formatter, int logEvery,
GMRFSkyrideLikelihood gmrfLike, int intervalNumber, double gridHeight,boolean logScale) {
super(formatter, logEvery,false);
this.gmrfLike = gmrfLike;
this.intervalNumber = intervalNumber;
this.gridHeight = gridHeight;
if(gridHeight == -99){
gridHeightSameAsTreeHeight = true;
}else{
gridHeightSameAsTreeHeight = false;
}
this.logScale = logScale;
fixedPopSize = new double[intervalNumber];
}
private void calculateGrid(){
//The first random interval is the coalescent interval closest to the sampling time
//The last random interval corresponds to the root.
double[] randomInterval = gmrfLike.getCopyOfCoalescentIntervals();
double[] randomPopSize = gmrfLike.getPopSizeParameter().getParameterValues();
for(int i = 1; i < randomInterval.length; i++)
randomInterval[i] += randomInterval[i-1];
if(gridHeightSameAsTreeHeight){
gridHeight = randomInterval[randomInterval.length-1];
}
if(!logScale){
for(int i = 0; i < randomPopSize.length; i++)
randomPopSize[i] = Math.exp(randomPopSize[i]);
}
double intervalLength = gridHeight/intervalNumber;
double startTime = 0;
double endTime = 0;
int interval = 0;
for(int i = 0; i < fixedPopSize.length; i++){
fixedPopSize[i] = 0;
if(interval < randomInterval.length){
endTime += intervalLength;
double timeLeft = intervalLength;
while(interval < randomInterval.length &&
randomInterval[interval] <= endTime){
fixedPopSize[i] += (randomInterval[interval] - startTime - intervalLength + timeLeft)*
randomPopSize[interval];
timeLeft = (intervalLength - randomInterval[interval] + startTime);
interval++;
}
if(interval < randomInterval.length){
fixedPopSize[i] += timeLeft*randomPopSize[interval];
fixedPopSize[i] /= intervalLength;
}else{
fixedPopSize[i] /= (intervalLength - timeLeft);
}
startTime += intervalLength;
}else{
fixedPopSize[i] = -99;
}
}
}
private void getStringGrid(String[] values){
calculateGrid();
//First value in the string array is the state.
for(int i = 0; i < fixedPopSize.length; i++){
if(fixedPopSize[i] == -99){
values[i+1] = "NA";
}else{
values[i+1] = Double.toString(fixedPopSize[i]);
}
}
}
public void log(int state){
if (logEvery <= 0 || ((state % logEvery) == 0)) {
String[] values = new String[fixedPopSize.length + 1];
values[0] = Integer.toString(state);
getStringGrid(values);
logValues(values);
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){
public String getParserDescription() {
return "Projects the random grid of the skyride onto a fixed grid";
}
public Class getReturnType() {
return GMRFSkyrideFixedGridLogger.class;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
AttributeRule.newIntegerRule(NUMBER_OF_INTERVALS),
AttributeRule.newDoubleRule(GRID_HEIGHT,true), //If no grid height specified, uses tree height.
AttributeRule.newBooleanRule(LOG_SCALE,true),
new ElementRule(GMRFSkyrideLikelihood.class),
};
public XMLSyntaxRule[] getSyntaxRules() {
return null;
}
public String getParserName() {
return SKYRIDE_FIXED_GRID;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Logger.getLogger("dr.evolmodel").info("Creating GMRF Skyride Fixed Grid Logger");
GMRFSkyrideLikelihood g = (GMRFSkyrideLikelihood)xo.getChild(GMRFSkyrideLikelihood.class);
String fileName = null;
int logEvery = 1;
int intervalNumber = xo.getIntegerAttribute(NUMBER_OF_INTERVALS);
Logger.getLogger("dr.evomodel").info("Number of Intervals = " + intervalNumber);
double gridHeight = -99;
if(xo.hasAttribute(GRID_HEIGHT)){
gridHeight = xo.getDoubleAttribute(GRID_HEIGHT);
Logger.getLogger("dr.evomodel").info("Grid Height = " + gridHeight);
}else{
Logger.getLogger("dr.evomodel").info("Grid Height = same as tree height");
}
if (xo.hasAttribute(LoggerParser.FILE_NAME)) {
fileName = xo.getStringAttribute(LoggerParser.FILE_NAME);
}
if (xo.hasAttribute(LoggerParser.LOG_EVERY)) {
logEvery = xo.getIntegerAttribute(LoggerParser.LOG_EVERY);
}
boolean logScale = true;
if (xo.hasAttribute(LOG_SCALE)){
logScale = xo.getBooleanAttribute(LOG_SCALE);
}
PrintWriter pw;
if (fileName != null) {
try {
File file = new File(fileName);
String name = file.getName();
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
pw = new PrintWriter(new FileOutputStream(new File(parent, name)));
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
}
} else {
pw = new PrintWriter(System.out);
}
LogFormatter lf = new TabDelimitedFormatter(pw);
MCLogger logger = new GMRFSkyrideFixedGridLogger(lf,logEvery,g,intervalNumber,gridHeight,logScale);
//After constructing the logger, setup the columns.
final BeastVersion version = new BeastVersion();
logger.setTitle("BEAST " + version.getVersionString() + ", " +
version.getBuildString() + "\n" +
"Generated " + (new Date()).toString() +
"\nFirst value corresponds to coalescent interval closet to sampling time\n" +
"Last value corresponds to coalescent interval closet to the root\n" +
"Grid Height = " +
(gridHeight == -99 ? "Based on tree height" : Double.toString(gridHeight)) +
"\nNumber of intervals = " + intervalNumber);
for(int i = 0 ; i < intervalNumber; i++){
logger.addColumn(new LogColumn.Default("V" + (i+1),null));
}
return (GMRFSkyrideFixedGridLogger)logger;
}
};
} |
package edu.asu.scrapbook.digital.api;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import edu.asu.scrapbook.digital.dao.ImageDAO;
import edu.asu.scrapbook.digital.dao.ImageDAOFactory;
import edu.asu.scrapbook.digital.dao.UserDAO;
import edu.asu.scrapbook.digital.dao.UserDAOFactory;
import edu.asu.scrapbook.digital.model.Image;
import edu.asu.scrapbook.digital.model.User;
import edu.asu.scrapbook.digital.util.ImageUtil;
import edu.asu.scrapbook.digital.util.UserUtil;
@Path("/images")
public class ImageResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Image> getUserImageIds() {
String username = UserUtil.getRequestUsername();
ImageDAO imageDao = ImageDAOFactory.getInstance();
UserDAO userDao = UserDAOFactory.getInstance();
try {
User user = userDao.findById(username);
List<Image> imageIds = null;
// user should never be null
if (user != null) {
imageIds = imageDao.getAllImagesByUser(user);
}
return imageIds;
} catch (Exception e) {
throw new InternalServerErrorException(e);
}
}
@PUT
@Path("{id}/edit")
@Consumes(MediaType.TEXT_PLAIN)
public void editImage(String base64ImageData, @PathParam("id") long id) {
String username = UserUtil.getRequestUsername();
byte[] imageData = DatatypeConverter.parseBase64Binary(base64ImageData);
ImageDAO imageDao = ImageDAOFactory.getInstance();
UserDAO userDao = UserDAOFactory.getInstance();
try {
User user = userDao.findById(username);
List<Image> userImages = imageDao.getAllImagesByUser(user);
for (Image image : userImages) {
if (image.getId() == id) {
ImageUtil.updateEditedImage(image, imageData);
break;
}
}
} catch (Exception e) {
throw new InternalServerErrorException(e);
}
}
@DELETE
@Path("{id}")
public void delete(@PathParam("id") long id) {
String username = UserUtil.getRequestUsername();
ImageDAO imageDao = ImageDAOFactory.getInstance();
UserDAO userDao = UserDAOFactory.getInstance();
try {
User user = userDao.findById(username);
if (user != null) {
List<Image> images = imageDao.getAllImagesByUser(user);
Image image = images.get(0);
for (Iterator<Image> iter = images.iterator(); iter.hasNext(); image = iter.next()) {
if (image.getId() == id) {
BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
bs.delete(image.getBlobKey());
iter.remove();
userDao.update(user);
break;
}
}
}
} catch (Exception e) {
throw new InternalServerErrorException(e);
}
}
} |
package com.xpn.xwiki.plugin.lucene;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.jmock.Expectations;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.xwiki.display.internal.DisplayConfiguration;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.plugin.lucene.internal.AttachmentData;
import com.xpn.xwiki.test.AbstractBridgedComponentTestCase;
import com.xpn.xwiki.web.XWikiServletContext;
import com.xpn.xwiki.XWikiException;
/**
* Unit tests for {@link AttachmentData}.
*
* @version $Id$
*/
public class AttachmentDataTest extends AbstractBridgedComponentTestCase
{
private XWikiDocument document;
private XWikiAttachment attachment;
private AttachmentData attachmentData;
private ServletContext mockServletContext;
@Before
public void setUp() throws Exception
{
super.setUp();
this.document = new XWikiDocument(new DocumentReference("wiki", "space", "page"));
this.document.setSyntax(Syntax.XWIKI_2_0);
this.attachment = new XWikiAttachment(this.document, "filename");
this.document.getAttachmentList().add(this.attachment);
this.mockServletContext = getMockery().mock(ServletContext.class, "AttachmentDataTest");
getMockery().checking(new Expectations()
{
{
oneOf(mockServletContext).getMimeType(with(any(String.class)));
will(returnValue("default"));
}
});
XWikiServletContext xwikiServletContext = new XWikiServletContext(mockServletContext);
getContext().setEngineContext(xwikiServletContext);
this.attachmentData = new AttachmentData(this.attachment, getContext(), false);
}
@Override
protected void registerComponents() throws Exception
{
super.registerComponents();
// Setup display configuration.
final DisplayConfiguration mockDisplayConfiguration = registerMockComponent(DisplayConfiguration.class);
getMockery().checking(new Expectations()
{
{
allowing(mockDisplayConfiguration).getDocumentDisplayerHint();
will(returnValue("default"));
allowing(mockDisplayConfiguration).getTitleHeadingDepth();
will(returnValue(2));
}
});
}
private void assertGetFullText(String expect, String filename) throws IOException
{
this.attachment.setFilename(filename);
this.attachment.setContent(getClass().getResourceAsStream("/" + filename));
this.attachmentData.setFilename(filename);
String fullText = this.attachmentData.getFullText(this.document, getContext());
Assert.assertEquals("Wrong attachment content indexed", expect, fullText);
}
private void assertGetMimeType(String expect, String filename)throws XWikiException
{
this.attachmentData.setMimeType(this.attachment.getMimeType(getContext()));
String mimeType = this.attachmentData.getMimeType();
Assert.assertEquals("Wrong mimetype content indexed", expect, mimeType);
}
private void setUpMockServletContext(final String expectedFileName, final String expectedMimeType)
{
getMockery().checking(new Expectations()
{
{
allowing(mockServletContext).getMimeType(with(expectedFileName));
will(returnValue(expectedMimeType));
}
});
getContext().setEngineContext(new XWikiServletContext(mockServletContext));
}
@Test
public void getFullTextFromTxt() throws IOException, XWikiException
{
setUpMockServletContext("txt.txt", "text/plain");
assertGetFullText("text content\n", "txt.txt");
assertGetMimeType("text/plain", "txt.txt");
}
@Test
public void getFullTextFromMSOffice97() throws IOException, XWikiException
{
setUpMockServletContext("msoffice97.doc", "application/msword");
assertGetFullText("ms office 97 content\n\n", "msoffice97.doc");
assertGetMimeType("application/msword" , "msoffice97.doc");
}
@Test
public void getFullTextFromOpenXML() throws IOException, XWikiException
{
setUpMockServletContext("openxml.docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
assertGetFullText("openxml content\n", "openxml.docx");
assertGetMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "openxml.docx");
}
@Test
public void getFullTextFromOpenDocument() throws IOException, XWikiException
{
setUpMockServletContext("opendocument.odt", "application/vnd.oasis.opendocument.text");
assertGetFullText("opendocument content\n", "opendocument.odt");
assertGetMimeType("application/vnd.oasis.opendocument.text", "opendocument.odt");
}
@Test
public void getFullTextFromPDF() throws IOException, XWikiException
{
setUpMockServletContext("pdf.pdf", "application/pdf");
assertGetFullText("\npdf content\n\n\n", "pdf.pdf");
assertGetMimeType("application/pdf", "pdf.pdf");
}
@Test
public void getFullTextFromZIP() throws IOException , XWikiException
{
setUpMockServletContext("zip.zip", "application/zip");
assertGetFullText("\nzip.txt\nzip content\n\n\n\n", "zip.zip");
assertGetMimeType("application/zip", "zip.zip");
}
@Test
public void getFullTextFromHTML() throws IOException, XWikiException
{
setUpMockServletContext("html.html", "text/html");
assertGetFullText("something\n", "html.html");
assertGetMimeType("text/html", "html.html");
}
@Test
@Ignore("Remove once http://jira.xwiki.org/browse/XWIKI-8656 is fixed")
public void getFullTextFromClass() throws IOException, XWikiException
{
// TODO: For some unknown reason XWikiAttachment.getMimeType puts the filename in lowercase...
setUpMockServletContext("helloworld.class", "application/java-vm");
String expectedContent = "public synchronized class helloworld {\n"
+ " public void helloworld();\n"
+ " public static void main(string[]);\n"
+ "}\n\n";
assertGetFullText(expectedContent, "HelloWorld.class");
assertGetMimeType("application/java-vm", "HelloWorld.class");
}
} |
package org.wso2.carbon.appmgt.sample.deployer.javascriptwrite;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class InvokeStatistcsJavascriptBuilder {
private String jsFunction;
public InvokeStatistcsJavascriptBuilder(String trackingID, String ipAddress) {
jsFunction = "function invokeStatistics(){\n" +
" var tracking_code = \"" + trackingID + "\";\n" +
" var request = $.ajax({\n" +
" url: \"http://" + ipAddress + ":8280/statistics/\",\n" +
" type: \"GET\",\n" +
" headers: {\n" +
" \"trackingCode\":tracking_code,\n" +
" }\n" +
" \n" +
" });\n" +
"}";
}
public void buildInvokeStaticsJavascriptFile(String filePath) throws IOException {
File file = new File(filePath + "/invokeStatistcs.js");
if (file.exists()) {
file.delete();
}
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(jsFunction);
output.close();
}
} |
package edu.wheaton.simulator.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
/**
*
* @author daniel.davenport daniel.gill
*
*/
public class EditTriggerScreen extends Screen {
private static final long serialVersionUID = 3261558461232576081L;
private JButton addConditional;
private JButton addBehavior;
private JTextField nameField;
private JSpinner prioritySpinner;
private ArrayList<JComboBox> conditionals;
private ArrayList<JComboBox> behaviors;
private JScrollPane conditionalLayout;
private JScrollPane behaviorLayout;
public EditTriggerScreen(Manager sm) {
super(sm);
this.setLayout(new GridBagLayout());
addNameField(new GridBagConstraints());
addSpinner(new GridBagConstraints());
addIf(new GridBagConstraints());
addConditionsLayout(new GridBagConstraints());
addThen(new GridBagConstraints());
addBehaviorLayout(new GridBagConstraints());
}
private void addBehaviorLayout(GridBagConstraints constraints) {
behaviorLayout = new JScrollPane();
constraints.gridwidth = 3;
constraints.gridheight = 1;
constraints.gridx = 0;
constraints.gridy = 4;
constraints.fill = GridBagConstraints.BOTH;
behaviorLayout.setBackground(Color.black);
add(behaviorLayout, constraints);
}
private void addThen(GridBagConstraints constraints) {
JLabel thenLabel = new JLabel("Then:");
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 0;
constraints.gridy = 3;
constraints.fill = GridBagConstraints.NONE;
add(thenLabel, constraints);
}
private void addConditionsLayout(GridBagConstraints constraints) {
conditionalLayout = new JScrollPane();
constraints.gridwidth = 3;
constraints.gridheight = 1;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.fill = GridBagConstraints.BOTH;
conditionalLayout.setBackground(Color.blue);
add(conditionalLayout, constraints);
}
private void addIf(GridBagConstraints constraints) {
JLabel ifLabel = new JLabel("If:");
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.fill = GridBagConstraints.NONE;
add(ifLabel, constraints);
}
private void addSpinner(GridBagConstraints constraints) {
prioritySpinner = new JSpinner();
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 2;
constraints.gridy = 0;
//TODO: Set minimum value of spinner to 0.
add(prioritySpinner, constraints);
}
private void addNameField(GridBagConstraints constraints){
nameField = new JTextField();
constraints.gridheight = 1;
constraints.gridwidth = 2;
constraints.gridx = 0;
constraints.gridy = 0;
this.add(nameField, constraints);
}
@Override
public void load() {
// TODO Auto-generated method stub
}
} |
package org.xwiki.officeimporter.internal;
import java.util.Properties;
import org.apache.velocity.VelocityContext;
import org.jmock.Expectations;
import org.junit.Assert;
import org.junit.Test;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.script.service.ScriptService;
import org.xwiki.test.jmock.AbstractComponentTestCase;
import org.xwiki.velocity.VelocityContextFactory;
import org.xwiki.velocity.VelocityContextInitializer;
/**
* Integration tests for various {@link VelocityContextInitializer} implementations specific to the Office Importer
* module.
*
* @version $Id$
* @since 1.9RC2
*/
public class VelocityContextInitializerTest extends AbstractComponentTestCase
{
@Override
protected void registerComponents() throws Exception
{
super.registerComponents();
registerMockComponent(ScriptService.class, "officeimporter", "importer");
registerMockComponent(ScriptService.class, "officemanager", "manager");
final ConfigurationSource configurationSource = registerMockComponent(ConfigurationSource.class);
getMockery().checking(new Expectations()
{
{
oneOf(configurationSource).getProperty("logging.deprecated.enabled", true);
will(returnValue(true));
oneOf(configurationSource).getProperty("velocity.tools", Properties.class);
will(returnValue(new Properties()));
}
});
}
/**
* Test the presence of velocity bridges.
*
* @throws Exception
*/
@Test
public void testVelocityBridges() throws Exception
{
// Make sure the execution context is not null when velocity bridges are initialized.
getComponentManager().<Execution> getInstance(Execution.class).setContext(new ExecutionContext());
VelocityContextFactory factory = getComponentManager().getInstance(VelocityContextFactory.class);
VelocityContext context = factory.createContext();
Assert.assertNotNull(context.get("officeimporter"));
Assert.assertNotNull(context.get("ooconfig"));
Assert.assertNotNull(context.get("oomanager"));
}
} |
package edu.cuny.citytech.defaultrefactoring.core.refactorings;
import static org.eclipse.jdt.ui.JavaElementLabels.ALL_FULLY_QUALIFIED;
import static org.eclipse.jdt.ui.JavaElementLabels.getElementLabel;
import static org.eclipse.jdt.ui.JavaElementLabels.getTextLabel;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.CreationReference;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperFieldAccess;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.SuperMethodReference;
import org.eclipse.jdt.core.dom.ThisExpression;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.core.refactoring.CompilationUnitChange;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRewriteUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.ReferenceFinderUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableMaplet;
import org.eclipse.jdt.internal.corext.refactoring.structure.HierarchyProcessor.TypeVariableMapper;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.GroupCategorySet;
import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.osgi.framework.FrameworkUtil;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor;
import edu.cuny.citytech.defaultrefactoring.core.messages.Messages;
import edu.cuny.citytech.defaultrefactoring.core.messages.PreconditionFailure;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
import edu.cuny.citytech.defaultrefactoring.core.utils.TimeCollector;
import edu.cuny.citytech.defaultrefactoring.core.utils.TypeVariableUtil;
import edu.cuny.citytech.defaultrefactoring.core.utils.Util;
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
@SuppressWarnings({ "restriction" })
public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends RefactoringProcessor {
private final class SourceMethodBodyAnalysisVisitor extends ASTVisitor {
private boolean methodContainsSuperReference;
private boolean methodContainsCallToProtectedObjectMethod;
private boolean methodContainsTypeIncompatibleThisReference;
private Set<IMethod> calledProtectedObjectMethodSet = new HashSet<>();
private IMethod sourceMethod;
private Optional<IProgressMonitor> monitor;
public SourceMethodBodyAnalysisVisitor(IMethod sourceMethod, Optional<IProgressMonitor> monitor) {
super(false);
this.sourceMethod = sourceMethod;
this.monitor = monitor;
}
protected Set<IMethod> getCalledProtectedObjectMethodSet() {
return calledProtectedObjectMethodSet;
}
@Override
public boolean visit(SuperConstructorInvocation node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
protected boolean doesMethodContainsSuperReference() {
return methodContainsSuperReference;
}
protected boolean doesMethodContainsCallToProtectedObjectMethod() {
return methodContainsCallToProtectedObjectMethod;
}
protected boolean doesMethodContainsTypeIncompatibleThisReference() {
return methodContainsTypeIncompatibleThisReference;
}
@Override
public boolean visit(SuperFieldAccess node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(SuperMethodInvocation node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(SuperMethodReference node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(MethodInvocation node) {
// check for calls to particular java.lang.Object
// methods #144.
IMethodBinding methodBinding = node.resolveMethodBinding();
if (methodBinding.getDeclaringClass().getQualifiedName().equals("java.lang.Object")) {
IMethod calledObjectMethod = (IMethod) methodBinding.getJavaElement();
try {
if (Flags.isProtected(calledObjectMethod.getFlags())) {
this.methodContainsCallToProtectedObjectMethod = true;
this.calledProtectedObjectMethodSet.add(calledObjectMethod);
}
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
}
return super.visit(node);
}
@Override
public boolean visit(ThisExpression node) {
// #153: Precondition missing for compile-time type of this
// TODO: #153 There is actually a lot more checks we should add
// here.
/*
* TODO: Actually need to examine every kind of expression where
* `this` may appear. #149. Really, type constraints can (or should)
* be used for this. Actually, similar to enum problem, especially
* with finding the parameter from where the `this` expression came.
* Assignment is only one kind of expression, we need to also look
* at comparison and switches.
*/
ASTNode parent = node.getParent();
process(parent, node);
return super.visit(node);
}
private void process(ASTNode node, ThisExpression thisExpression) {
switch (node.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
case ASTNode.CLASS_INSTANCE_CREATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
// NOTE: super isn't allowed inside the source method body.
case ASTNode.ASSIGNMENT:
case ASTNode.RETURN_STATEMENT:
case ASTNode.VARIABLE_DECLARATION_FRAGMENT: {
// get the target method.
IMethod targetMethod = null;
try {
targetMethod = getTargetMethod(this.sourceMethod,
this.monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
IType destinationInterface = targetMethod.getDeclaringType();
// get the destination interface.
ITypeBinding destinationInterfaceTypeBinding = null;
try {
destinationInterfaceTypeBinding = ASTNodeSearchUtil.getTypeDeclarationNode(destinationInterface,
getCompilationUnit(destinationInterface.getTypeRoot(), new SubProgressMonitor(
this.monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)))
.resolveBinding();
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
if (node.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
ConstructorInvocation constructorInvocation = (ConstructorInvocation) node;
List<?> arguments = constructorInvocation.arguments();
IMethodBinding methodBinding = constructorInvocation.resolveConstructorBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) node;
List<?> arguments = classInstanceCreation.arguments();
IMethodBinding methodBinding = classInstanceCreation.resolveConstructorBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.METHOD_INVOCATION) {
MethodInvocation methodInvocation = (MethodInvocation) node;
List<?> arguments = methodInvocation.arguments();
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment = (Assignment) node;
Expression leftHandSide = assignment.getLeftHandSide();
Expression rightHandSide = assignment.getRightHandSide();
processAssignment(assignment, thisExpression, destinationInterfaceTypeBinding, leftHandSide,
rightHandSide);
} else if (node.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) node;
Expression initializer = vdf.getInitializer();
SimpleName name = vdf.getName();
processAssignment(vdf, thisExpression, destinationInterfaceTypeBinding, name, initializer);
} else if (node.getNodeType() == ASTNode.RETURN_STATEMENT) {
ReturnStatement returnStatement = (ReturnStatement) node;
// sanity check.
Expression expression = returnStatement.getExpression();
expression = (Expression) Util.stripParenthesizedExpressions(expression);
Assert.isTrue(expression == thisExpression, "The return expression should be this.");
MethodDeclaration targetMethodDeclaration = null;
try {
targetMethodDeclaration = ASTNodeSearchUtil
.getMethodDeclarationNode(targetMethod,
getCompilationUnit(targetMethod.getTypeRoot(),
new SubProgressMonitor(this.monitor.orElseGet(NullProgressMonitor::new),
IProgressMonitor.UNKNOWN)));
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
ITypeBinding returnType = targetMethodDeclaration.resolveBinding().getReturnType();
// ensure that the destination type is assignment compatible
// with the return type.
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, returnType))
this.methodContainsTypeIncompatibleThisReference = true;
} else
throw new IllegalStateException("Unexpected node type: " + node.getNodeType());
break;
}
case ASTNode.PARENTHESIZED_EXPRESSION: {
process(node.getParent(), thisExpression);
}
}
}
/**
* Process a list of arguments stemming from a method-like call.
*
* @param arguments
* The list of arguments to process.
* @param methodBinding
* The binding of the corresponding method call.
* @param thisExpression
* The this expression we are looking for.
* @param destinationInterfaceTypeBinding
* The binding of the destination interface.
*/
private void processArguments(List<?> arguments, IMethodBinding methodBinding, ThisExpression thisExpression,
ITypeBinding destinationInterfaceTypeBinding) {
// find where (or if) the this expression occurs in the
// method
// invocation arguments.
for (int i = 0; i < arguments.size(); i++) {
Object object = arguments.get(i);
// if we are at the argument where this appears.
if (object == thisExpression) {
// get the type binding from the corresponding
// parameter.
ITypeBinding parameterTypeBinding = methodBinding.getParameterTypes()[i];
// the type of this will change to the destination
// interface. Let's check whether an expression of
// the destination type can be assigned to a
// variable of
// the parameter type.
// TODO: Does `isAssignmentCompatible()` also work
// with
// comparison?
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, parameterTypeBinding)) {
this.methodContainsTypeIncompatibleThisReference = true;
break;
}
}
}
}
private boolean isAssignmentCompatible(ITypeBinding typeBinding, ITypeBinding otherTypeBinding) {
// Workaround
if (typeBinding == null && otherTypeBinding == null)
return true;
else if (typeBinding == null || otherTypeBinding == null)
return false;
else
return typeBinding.isAssignmentCompatible(otherTypeBinding)
|| typeBinding.isInterface() && otherTypeBinding.isInterface()
&& (typeBinding.isEqualTo(otherTypeBinding)
|| Arrays.stream(typeBinding.getInterfaces())
.anyMatch(itb -> itb.isEqualTo(otherTypeBinding)));
}
private void processAssignment(ASTNode node, ThisExpression thisExpression,
ITypeBinding destinationInterfaceTypeBinding, Expression leftHandSide, Expression rightHandSide) {
// if `this` appears on the LHS.
if (leftHandSide == thisExpression) {
// in this case, we need to check that the RHS can be
// assigned to a variable of the destination type.
if (!isAssignmentCompatible(rightHandSide.resolveTypeBinding(), destinationInterfaceTypeBinding))
this.methodContainsTypeIncompatibleThisReference = true;
} else if (rightHandSide == thisExpression) {
// otherwise, if `this` appears on the RHS. Then, we
// need to check that the LHS can receive a variable of
// the destination type.
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, leftHandSide.resolveTypeBinding()))
this.methodContainsTypeIncompatibleThisReference = true;
} else {
throw new IllegalStateException(
"this: " + thisExpression + " must appear either on the LHS or RHS of the assignment: " + node);
}
}
}
private final class FieldAccessAnalysisSearchRequestor extends SearchRequestor {
private final Optional<IProgressMonitor> monitor;
private boolean accessesFieldsFromImplicitParameter;
private FieldAccessAnalysisSearchRequestor(Optional<IProgressMonitor> monitor) {
this.monitor = monitor;
}
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.isInsideDocComment())
return;
// get the AST node corresponding to the field
// access. It should be some kind of name
// (simple of qualified).
ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit(
((IMember) match.getElement()).getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
// examine the node's parent.
ASTNode parent = node.getParent();
switch (parent.getNodeType()) {
case ASTNode.FIELD_ACCESS: {
FieldAccess fieldAccess = (FieldAccess) parent;
// the expression is the LHS of the
// selection operator.
Expression expression = fieldAccess.getExpression();
if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION)
// either there is nothing on the LHS
// or it's this, in which case we fail.
this.accessesFieldsFromImplicitParameter = true;
break;
}
case ASTNode.SUPER_FIELD_ACCESS: {
// super will also tell us that it's an
// instance field access of this.
this.accessesFieldsFromImplicitParameter = true;
break;
}
default: {
// it must be an unqualified field access,
// meaning that it's an instance field access of this.
this.accessesFieldsFromImplicitParameter = true;
}
}
}
public boolean hasAccessesToFieldsFromImplicitParameter() {
return accessesFieldsFromImplicitParameter;
}
}
private final class MethodReceiverAnalysisVisitor extends ASTVisitor {
private IMethod accessedMethod;
private boolean encounteredThisReceiver;
public boolean hasEncounteredThisReceiver() {
return encounteredThisReceiver;
}
private MethodReceiverAnalysisVisitor(IMethod accessedMethod) {
this.accessedMethod = accessedMethod;
}
@Override
public boolean visit(MethodInvocation methodInvocation) {
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
IJavaElement javaElement = methodBinding.getJavaElement();
if (javaElement == null)
logWarning("Could not get Java element from binding: " + methodBinding + " while processing: "
+ methodInvocation);
else if (javaElement.equals(accessedMethod)) {
Expression expression = methodInvocation.getExpression();
expression = (Expression) Util.stripParenthesizedExpressions(expression);
// FIXME: It's not really that the expression is a `this`
// expression but that the type of the expression comes from a
// `this` expression. In other words, we may need to climb the
// AST.
if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION) {
this.encounteredThisReceiver = true;
}
}
return super.visit(methodInvocation);
}
@Override
public boolean visit(SuperMethodInvocation node) {
if (node.resolveMethodBinding().getJavaElement().equals(accessedMethod))
this.encounteredThisReceiver = true;
return super.visit(node);
}
}
private Set<IMethod> sourceMethods = new LinkedHashSet<>();
private Set<IMethod> unmigratableMethods = new UnmigratableMethodSet(sourceMethods);
private static final String FUNCTIONAL_INTERFACE_ANNOTATION_NAME = "FunctionalInterface";
private Map<ICompilationUnit, CompilationUnitRewrite> compilationUnitToCompilationUnitRewriteMap = new HashMap<>();
private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>();
@SuppressWarnings("unused")
private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet(
new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$
Messages.CategoryName, Messages.CategoryDescription));
private static Map<IMethod, IMethod> methodToTargetMethodMap = new HashMap<>();
/** The code generation settings, or <code>null</code> */
private CodeGenerationSettings settings;
/** Does the refactoring use a working copy layer? */
private final boolean layer;
private static Table<IMethod, IType, IMethod> methodTargetInterfaceTargetMethodTable = HashBasedTable.create();
private SearchEngine searchEngine = new SearchEngine();
/**
* For excluding AST parse time.
*/
private TimeCollector excludedTimeCollector = new TimeCollector();
/**
* The minimum logging level, one of the constants in
* org.eclipse.core.runtime.IStatus.
*/
private int loggingLevel = IStatus.WARNING;
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
* @throws JavaModelException
*/
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, boolean layer, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
this.settings = settings;
this.layer = layer;
Collections.addAll(this.getSourceMethods(), methods);
monitor.ifPresent(m -> m.beginTask("Finding target methods ...", methods.length));
for (IMethod method : methods) {
// this will populate the map if needed.
getTargetMethod(method, monitor);
monitor.ifPresent(m -> m.worked(1));
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, Optional<IProgressMonitor> monitor) throws JavaModelException {
this(methods, settings, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(Optional<IProgressMonitor> monitor)
throws JavaModelException {
this(null, null, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException {
this(null, null, false, Optional.empty());
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getElements() {
return getMigratableMethods().toArray();
}
public Set<IMethod> getMigratableMethods() {
Set<IMethod> difference = new LinkedHashSet<>(this.getSourceMethods());
difference.removeAll(this.getUnmigratableMethods());
return difference;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
this.clearCaches();
this.getExcludedTimeCollector().clear();
if (this.getSourceMethods().isEmpty())
return RefactoringStatus.createFatalErrorStatus(Messages.MethodsNotSpecified);
else {
RefactoringStatus status = new RefactoringStatus();
pm.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size());
for (IMethod sourceMethod : this.getSourceMethods()) {
status.merge(checkDeclaringType(sourceMethod, Optional.of(new SubProgressMonitor(pm, 0))));
status.merge(checkCandidateDestinationInterfaces(sourceMethod,
Optional.of(new SubProgressMonitor(pm, 0))));
pm.worked(1);
}
return status;
}
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
pm.done();
}
}
private RefactoringStatus checkDestinationInterfaceTargetMethods(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
logInfo("Checking destination interface target methods...");
// Ensure that target methods are not already default methods.
// For each method to move, add a warning if the associated target
// method is already default.
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null) {
int targetMethodFlags = targetMethod.getFlags();
if (Flags.isDefaultMethod(targetMethodFlags)) {
RefactoringStatusEntry entry = addError(status, sourceMethod,
PreconditionFailure.TargetMethodIsAlreadyDefault, targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
private RefactoringStatus checkDestinationInterfaces(Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.beginTask("Checking destination interfaces ...", this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
final Optional<IType> targetInterface = this.getDestinationInterface(sourceMethod);
// Can't be empty.
if (!targetInterface.isPresent()) {
addErrorAndMark(status, PreconditionFailure.NoDestinationInterface, sourceMethod);
return status;
}
// Must be a pure interface.
if (!isPureInterface(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationTypeMustBePureInterface, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Make sure it exists.
RefactoringStatus existence = checkExistence(targetInterface.get(),
PreconditionFailure.DestinationInterfaceDoesNotExist);
status.merge(existence);
if (!existence.isOK())
addUnmigratableMethod(sourceMethod, existence.getEntryWithHighestSeverity());
// Make sure we can write to it.
RefactoringStatus writabilitiy = checkWritabilitiy(targetInterface.get(),
PreconditionFailure.DestinationInterfaceNotWritable);
status.merge(writabilitiy);
if (!writabilitiy.isOK())
addUnmigratableMethod(sourceMethod, writabilitiy.getEntryWithHighestSeverity());
// Make sure it doesn't have compilation errors.
RefactoringStatus structure = checkStructure(targetInterface.get());
status.merge(structure);
if (!structure.isOK())
addUnmigratableMethod(sourceMethod, structure.getEntryWithHighestSeverity());
// #35: The target interface should not be a
// @FunctionalInterface.
if (isInterfaceFunctional(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationInterfaceIsFunctional, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Can't be strictfp if all the methods to be migrated aren't
// also strictfp
if (Flags.isStrictfp(targetInterface.get().getFlags())
&& !allMethodsToMoveInTypeAreStrictFP(sourceMethod.getDeclaringType())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationInterfaceIsStrictFP, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
status.merge(checkDestinationInterfaceTargetMethods(sourceMethod));
monitor.ifPresent(m -> m.worked(1));
}
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private IType[] getTypesReferencedInMovedMembers(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
// TODO: Cache this result.
final IType[] types = ReferenceFinderUtil.getTypesReferencedIn(new IJavaElement[] { sourceMethod },
monitor.orElseGet(NullProgressMonitor::new));
final List<IType> result = new ArrayList<IType>(types.length);
final List<IMember> members = Arrays.asList(new IMember[] { sourceMethod });
for (int index = 0; index < types.length; index++) {
if (!members.contains(types[index]) && !types[index].equals(sourceMethod.getDeclaringType()))
result.add(types[index]);
}
return result.toArray(new IType[result.size()]);
}
private boolean canBeAccessedFrom(IMethod sourceMethod, final IMember member, final IType target,
final ITypeHierarchy hierarchy) throws JavaModelException {
Assert.isTrue(!(member instanceof IInitializer));
if (member.exists()) {
if (target.equals(member.getDeclaringType()))
return true;
if (target.equals(member))
return true;
// NOTE: We are not creating stubs (for now).
/*
* if (member instanceof IMethod) { final IMethod method = (IMethod)
* member; final IMethod stub =
* target.getMethod(method.getElementName(),
* method.getParameterTypes()); if (stub.exists()) return true; }
*/
if (member.getDeclaringType() == null) {
if (!(member instanceof IType))
return false;
if (JdtFlags.isPublic(member))
return true;
if (!JdtFlags.isPackageVisible(member))
return false;
if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment()))
return true;
final IType type = member.getDeclaringType();
if (type != null)
return hierarchy.contains(type);
return false;
}
final IType declaringType = member.getDeclaringType();
// if the member's declaring type isn't accessible from the target
// type.
if (!canBeAccessedFrom(sourceMethod, declaringType, target, hierarchy))
return false; // then, the member isn't accessible from the
// target type.
// otherwise, the member's declaring type is accessible from the
// target type.
// We are going to be moving the source method from it's
// declaring type.
// We know that the member's declaring type is accessible from
// the target.
// We also know that the member's declaring type and the target
// type are different.
// The question now is if the target type can access the
// particular member given that
// the target type can access the member's declaring type.
// if it's public, the answer is yes.
if (JdtFlags.isPublic(member))
return true;
// if the member is private, the answer is no.
else if (JdtFlags.isPrivate(member))
return false;
// if it's package-private or protected.
else if (JdtFlags.isPackageVisible(member) || JdtFlags.isProtected(member)) {
// then, if the member's declaring type in the same package
// as the target's declaring type, the answer is yes.
if (JavaModelUtil.isVisible(member, target.getPackageFragment()))
return true;
// otherwise, if it's protected.
else if (JdtFlags.isProtected(member))
// then, the answer is yes if the target type is a
// sub-type of the member's declaring type. Otherwise,
// the answer is no.
return hierarchy.contains(declaringType);
} else
throw new IllegalStateException("Member: " + member + " has no known visibility.");
return true;
}
return false;
}
private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy hierarchy) throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor);
final IType destination = getDestinationInterface(sourceMethod).get();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
for (int index = 0; index < accessedTypes.length; index++) {
final IType type = accessedTypes[index];
if (!type.exists())
continue;
if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.TypeNotAccessible.getMessage(),
new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(type),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccessedFields(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
final IField[] accessedFields = ReferenceFinderUtil.getFieldsReferencedIn(new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1));
final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destiantion interface."));
for (int index = 0; index < accessedFields.length; index++) {
final IField accessedField = accessedFields[index];
if (!accessedField.exists())
continue;
boolean isAccessible = pulledUpList.contains(accessedField) || canBeAccessedFrom(sourceMethod,
accessedField, destination, destinationInterfaceSuperTypeHierarchy)
|| Flags.isEnum(accessedField.getFlags());
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.FieldNotAccessible.getMessage(),
new String[] {
JavaElementLabels.getTextLabel(accessedField, JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedField),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.FieldNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
} else if (!JdtFlags.isStatic(accessedField) && !accessedField.getDeclaringType().isInterface()) {
// it's accessible and it's an instance field.
// Let's decide if the source method is accessing it from this
// object or another. If it's from this object, we fail.
// First, find all references of the accessed field in the
// source method.
FieldAccessAnalysisSearchRequestor requestor = new FieldAccessAnalysisSearchRequestor(monitor);
this.getSearchEngine().search(
SearchPattern.createPattern(accessedField, IJavaSearchConstants.REFERENCES,
SearchPattern.R_EXACT_MATCH),
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
SearchEngine.createJavaSearchScope(new IJavaElement[] { sourceMethod }), requestor,
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN));
if (requestor.hasAccessesToFieldsFromImplicitParameter())
addErrorAndMark(result, PreconditionFailure.SourceMethodAccessesInstanceField, sourceMethod,
accessedField);
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccessedMethods(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 3));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
final Set<IMethod> accessedMethods = new LinkedHashSet<>(
Arrays.asList(ReferenceFinderUtil.getMethodsReferencedIn(new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1))));
// also add constructors.
accessedMethods.addAll(getConstructorsReferencedIn(new IJavaElement[] { sourceMethod },
monitor.map(m -> new SubProgressMonitor(m, 1))));
final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destiantion interface."));
for (IMethod accessedMethod : accessedMethods) {
if (!accessedMethod.exists())
continue;
boolean isAccessible = pulledUpList.contains(accessedMethod) || canBeAccessedFrom(sourceMethod,
accessedMethod, destination, destinationInterfaceSuperTypeHierarchy);
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.MethodNotAccessible.getMessage(),
new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
} else if (!JdtFlags.isStatic(accessedMethod)) {
// it's accessible and it's not static.
// we'll need to check the implicit parameters.
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
getCompilationUnit(sourceMethod.getTypeRoot(), new SubProgressMonitor(
monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
MethodReceiverAnalysisVisitor visitor = new MethodReceiverAnalysisVisitor(accessedMethod);
sourceMethodDeclaration.getBody().accept(visitor);
// if this is the implicit parameter.
if (visitor.hasEncounteredThisReceiver()) {
// let's check to see if the method is somewhere in the
// hierarchy.
IType methodDeclaringType = accessedMethod.getDeclaringType();
// is this method declared in a type that is in the
// declaring type's super type hierarchy?
ITypeHierarchy declaringTypeSuperTypeHierarchy = getSuperTypeHierarchy(
sourceMethod.getDeclaringType(),
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
if (declaringTypeSuperTypeHierarchy.contains(methodDeclaringType)) {
// if so, then we need to check that it is in the
// destination interface's super type hierarchy.
boolean methodInHiearchy = isMethodInHierarchy(accessedMethod,
destinationInterfaceSuperTypeHierarchy);
if (!methodInHiearchy) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.MethodNotAccessible.getMessage(),
new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
}
}
}
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private Collection<? extends IMethod> getConstructorsReferencedIn(IJavaElement[] elements,
final Optional<IProgressMonitor> monitor) throws CoreException {
Collection<IMethod> ret = new LinkedHashSet<>();
SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CONSTRUCTOR,
IJavaSearchConstants.REFERENCES, SearchPattern.R_PATTERN_MATCH);
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements, true);
SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
this.getSearchEngine().search(pattern, participants, scope, new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.isInsideDocComment())
return;
ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit(
((IMember) match.getElement()).getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
node = Util.stripParenthesizedExpressions(node);
IMethod constructor = extractConstructor(node);
if (constructor != null)
ret.add(constructor);
}
private IMethod extractConstructor(ASTNode node) {
if (node == null)
throw new IllegalArgumentException("Node is null");
else {
switch (node.getNodeType()) {
case ASTNode.CLASS_INSTANCE_CREATION: {
ClassInstanceCreation creation = (ClassInstanceCreation) node;
IMethodBinding binding = creation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.CONSTRUCTOR_INVOCATION: {
ConstructorInvocation invocation = (ConstructorInvocation) node;
IMethodBinding binding = invocation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: {
SuperConstructorInvocation invocation = (SuperConstructorInvocation) node;
IMethodBinding binding = invocation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.CREATION_REFERENCE: {
CreationReference reference = (CreationReference) node;
IMethodBinding binding = reference.resolveMethodBinding();
if (binding == null) {
logWarning("Could not resolve method binding from creation reference: " + reference);
return null;
}
IMethod javaElement = (IMethod) binding.getJavaElement();
return javaElement;
}
default: {
// try the parent node.
return extractConstructor(node.getParent());
}
}
}
}
}, monitor.orElseGet(NullProgressMonitor::new));
return ret;
}
private static boolean isMethodInHierarchy(IMethod method, ITypeHierarchy hierarchy) {
// TODO: Cache this?
return Stream.of(hierarchy.getAllTypes()).parallel().anyMatch(t -> {
IMethod[] methods = t.findMethods(method);
return methods != null && methods.length > 0;
});
}
private RefactoringStatus checkAccesses(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws CoreException {
final RefactoringStatus result = new RefactoringStatus();
try {
monitor.ifPresent(
m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 4));
IType destinationInterface = getDestinationInterface(sourceMethod)
.orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destination interface."));
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy = getSuperTypeHierarchy(destinationInterface,
monitor.map(m -> new SubProgressMonitor(m, 1)));
result.merge(checkAccessedTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
result.merge(checkAccessedFields(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
result.merge(checkAccessedMethods(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return result;
}
private boolean allMethodsToMoveInTypeAreStrictFP(IType type) throws JavaModelException {
for (Iterator<IMethod> iterator = this.getSourceMethods().iterator(); iterator.hasNext();) {
IMethod method = iterator.next();
if (method.getDeclaringType().equals(type) && !Flags.isStrictfp(method.getFlags()))
return false;
}
return true;
}
private static boolean isInterfaceFunctional(final IType anInterface) throws JavaModelException {
// TODO: #37: Compute effectively functional interfaces.
return Stream.of(anInterface.getAnnotations()).parallel().map(IAnnotation::getElementName)
.anyMatch(s -> s.contains(FUNCTIONAL_INTERFACE_ANNOTATION_NAME));
}
private RefactoringStatus checkValidInterfacesInDeclaringTypeHierarchy(IMethod sourceMethod,
Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
ITypeHierarchy hierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);
IType[] declaringTypeSuperInterfaces = hierarchy.getAllSuperInterfaces(sourceMethod.getDeclaringType());
// the number of methods sourceMethod is implementing.
long numberOfImplementedMethods = Arrays.stream(declaringTypeSuperInterfaces).parallel().distinct()
.flatMap(i -> Arrays.stream(Optional.ofNullable(i.findMethods(sourceMethod)).orElse(new IMethod[] {})))
.count();
if (numberOfImplementedMethods > 1)
addErrorAndMark(status, PreconditionFailure.SourceMethodImplementsMultipleMethods, sourceMethod);
return status;
}
private Optional<IType> getDestinationInterface(IMethod sourceMethod) throws JavaModelException {
return Optional.ofNullable(getTargetMethod(sourceMethod, Optional.empty())).map(IMethod::getDeclaringType);
}
private RefactoringStatus checkValidClassesInDeclaringTypeHierarchy(IMethod sourceMethod,
final ITypeHierarchy declaringTypeHierarchy) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType[] allDeclaringTypeSuperclasses = declaringTypeHierarchy
.getAllSuperclasses(sourceMethod.getDeclaringType());
// is the source method overriding anything in the declaring type
// hierarchy? If so, don't allow the refactoring to proceed #107.
if (Stream.of(allDeclaringTypeSuperclasses).parallel().anyMatch(c -> {
IMethod[] methods = c.findMethods(sourceMethod);
return methods != null && methods.length > 0;
}))
addErrorAndMark(status, PreconditionFailure.SourceMethodOverridesMethod, sourceMethod);
return status;
}
private void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure) {
addWarning(status, sourceMethod, failure, new IJavaElement[] {});
}
private RefactoringStatus checkDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType type = sourceMethod.getDeclaringType();
if (type.isAnnotation())
addErrorAndMark(status, PreconditionFailure.NoMethodsInAnnotationTypes, sourceMethod, type);
if (type.isInterface())
addErrorAndMark(status, PreconditionFailure.NoMethodsInInterfaces, sourceMethod, type);
if (type.isBinary())
addErrorAndMark(status, PreconditionFailure.NoMethodsInBinaryTypes, sourceMethod, type);
if (type.isReadOnly())
addErrorAndMark(status, PreconditionFailure.NoMethodsInReadOnlyTypes, sourceMethod, type);
if (type.isAnonymous())
addErrorAndMark(status, PreconditionFailure.NoMethodsInAnonymousTypes, sourceMethod, type);
if (type.isLambda())
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInLambdas, sourceMethod, type);
if (type.isLocal())
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInLocals, sourceMethod, type);
if (type.isMember())
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInMemberTypes, sourceMethod, type);
if (type.getInitializers().length != 0)
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithInitializers, sourceMethod, type);
if (type.getTypes().length != 0)
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithType, sourceMethod, type);
if (type.getSuperInterfaceNames().length == 0)
// TODO enclosing type must implement an interface, at least for
// now,
// which one of which will become the target interface.
// it is probably possible to still perform the refactoring
// without this condition but I believe that this is
// the particular pattern we are targeting.
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesThatDontImplementInterfaces, sourceMethod,
type);
if (Flags.isStatic(type.getFlags()))
// TODO no static types for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInStaticTypes, sourceMethod, type);
status.merge(checkDeclaringTypeHierarchy(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))));
return status;
}
private void addErrorAndMark(RefactoringStatus status, PreconditionFailure failure, IMethod sourceMethod,
IMember... related) {
RefactoringStatusEntry error = addError(status, sourceMethod, failure, sourceMethod, related);
addUnmigratableMethod(sourceMethod, error);
}
private RefactoringStatus checkDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.subTask("Checking declaring type hierarchy..."));
final ITypeHierarchy declaringTypeHierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);
status.merge(checkValidClassesInDeclaringTypeHierarchy(sourceMethod, declaringTypeHierarchy));
status.merge(checkValidInterfacesInDeclaringTypeHierarchy(sourceMethod, monitor));
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkCandidateDestinationInterfaces(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType[] interfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
if (interfaces.length == 0)
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithNoCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
else if (interfaces.length > 1)
// TODO: For now, let's make sure there's only one candidate type
// #129.
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithMultipleCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
return status;
}
/**
* Returns the possible target interfaces for the migration. NOTE: One
* difference here between this refactoring and pull up is that we can have
* a much more complex type hierarchy due to multiple interface inheritance
* in Java.
* <p>
* TODO: It should be possible to pull up a method into an interface (i.e.,
* "Pull Up Method To Interface") that is not implemented explicitly. For
* example, there may be a skeletal implementation class that implements all
* the target interface's methods without explicitly declaring so.
* Effectively skeletal?
*
* @param monitor
* A progress monitor.
* @return The possible target interfaces for the migration.
* @throws JavaModelException
* upon Java model problems.
*/
public static IType[] getCandidateDestinationInterfaces(IMethod sourcMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving candidate types...", IProgressMonitor.UNKNOWN));
IType[] superInterfaces = getSuperInterfaces(sourcMethod.getDeclaringType(),
monitor.map(m -> new SubProgressMonitor(m, 1)));
Stream<IType> candidateStream = Stream.of(superInterfaces).parallel().filter(Objects::nonNull)
.filter(IJavaElement::exists).filter(t -> !t.isReadOnly()).filter(t -> !t.isBinary());
Set<IType> ret = new HashSet<>();
for (Iterator<IType> iterator = candidateStream.iterator(); iterator.hasNext();) {
IType superInterface = iterator.next();
IMethod[] interfaceMethods = superInterface.findMethods(sourcMethod);
if (interfaceMethods != null)
// the matching methods cannot already be default.
for (IMethod method : interfaceMethods)
if (!JdtFlags.isDefaultMethod(method))
ret.add(superInterface);
}
return ret.toArray(new IType[ret.size()]);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static IType[] getSuperInterfaces(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving type super interfaces...", IProgressMonitor.UNKNOWN));
return getSuperTypeHierarchy(type, monitor.map(m -> new SubProgressMonitor(m, 1)))
.getAllSuperInterfaces(type);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private ITypeHierarchy getDeclaringTypeHierarchy(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring type hierarchy..."));
IType declaringType = sourceMethod.getDeclaringType();
return this.getTypeHierarchy(declaringType, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
@SuppressWarnings("unused")
private ITypeHierarchy getDestinationInterfaceHierarchy(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving destination type hierarchy..."));
IType destinationInterface = getDestinationInterface(sourceMethod).get();
return this.getTypeHierarchy(destinationInterface, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static Map<IType, ITypeHierarchy> typeToSuperTypeHierarchyMap = new HashMap<>();
private static Map<IType, ITypeHierarchy> getTypeToSuperTypeHierarchyMap() {
return typeToSuperTypeHierarchyMap;
}
private static ITypeHierarchy getSuperTypeHierarchy(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring super type hierarchy..."));
if (getTypeToSuperTypeHierarchyMap().containsKey(type))
return getTypeToSuperTypeHierarchyMap().get(type);
else {
ITypeHierarchy newSupertypeHierarchy = type
.newSupertypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
getTypeToSuperTypeHierarchyMap().put(type, newSupertypeHierarchy);
return newSupertypeHierarchy;
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkSourceMethods(Optional<IProgressMonitor> pm) throws CoreException {
try {
RefactoringStatus status = new RefactoringStatus();
pm.ifPresent(m -> m.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
RefactoringStatus existenceStatus = checkExistence(sourceMethod,
PreconditionFailure.MethodDoesNotExist);
if (!existenceStatus.isOK()) {
status.merge(existenceStatus);
addUnmigratableMethod(sourceMethod, existenceStatus.getEntryWithHighestSeverity());
}
RefactoringStatus writabilityStatus = checkWritabilitiy(sourceMethod,
PreconditionFailure.CantChangeMethod);
if (!writabilityStatus.isOK()) {
status.merge(writabilityStatus);
addUnmigratableMethod(sourceMethod, writabilityStatus.getEntryWithHighestSeverity());
}
RefactoringStatus structureStatus = checkStructure(sourceMethod);
if (!structureStatus.isOK()) {
status.merge(structureStatus);
addUnmigratableMethod(sourceMethod, structureStatus.getEntryWithHighestSeverity());
}
if (sourceMethod.isConstructor()) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoConstructors,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkAnnotations(sourceMethod));
// synchronized methods aren't allowed in interfaces (even
// if they're default).
if (Flags.isSynchronized(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod,
PreconditionFailure.NoSynchronizedMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isStatic(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoStaticMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isAbstract(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoAbstractMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// final methods aren't allowed in interfaces.
if (Flags.isFinal(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoFinalMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// native methods don't have bodies. As such, they can't
// be skeletal implementors.
if (JdtFlags.isNative(sourceMethod)) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoNativeMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (sourceMethod.isLambdaMethod()) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoLambdaMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkExceptions(sourceMethod));
// ensure that the method has a target.
if (getTargetMethod(sourceMethod,
pm.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))) == null)
addErrorAndMark(status, PreconditionFailure.SourceMethodHasNoTargetMethod, sourceMethod);
else {
status.merge(checkParameters(sourceMethod));
status.merge(checkReturnType(sourceMethod));
status.merge(checkAccesses(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkGenericDeclaringType(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkProjectCompliance(sourceMethod));
}
pm.ifPresent(m -> m.worked(1));
}
return status;
} finally {
pm.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkGenericDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
final RefactoringStatus status = new RefactoringStatus();
try {
final IMember[] pullables = new IMember[] { sourceMethod };
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, pullables.length));
monitor.ifPresent(m -> m.beginTask("Retrieving target method.", IProgressMonitor.UNKNOWN));
IMethod targetMethod = getTargetMethod(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
final IType declaring = sourceMethod.getDeclaringType();
final ITypeParameter[] parameters = declaring.getTypeParameters();
if (parameters.length > 0) {
final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToInheritedType(declaring,
targetMethod.getDeclaringType());
IMember member = null;
int length = 0;
for (int index = 0; index < pullables.length; index++) {
member = pullables[index];
final String[] unmapped = TypeVariableUtil.getUnmappedVariables(mapping, declaring, member);
length = unmapped.length;
String superClassLabel = BasicElementLabels
.getJavaElementName(targetMethod.getDeclaringType().getElementName());
switch (length) {
case 0:
break;
case 1:
status.addEntry(RefactoringStatus.ERROR,
String.format(PreconditionFailure.TypeVariableNotAvailable.getMessage(), unmapped[0],
superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariableNotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
case 2:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariable2NotAvailable.getMessage(),
unmapped[0], unmapped[1], superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariable2NotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
case 3:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariable3NotAvailable.getMessage(),
unmapped[0], unmapped[1], unmapped[2], superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariable3NotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
default:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariablesNotAvailable.getMessage(),
superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariablesNotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
}
monitor.ifPresent(m -> m.worked(1));
monitor.ifPresent(m -> {
if (m.isCanceled())
throw new OperationCanceledException();
});
}
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return status;
}
/**
* Annotations between source and target methods must be consistent. Related
* to #45.
*
* @param sourceMethod
* The method to check annotations.
* @return The resulting {@link RefactoringStatus}.
* @throws JavaModelException
* If the {@link IAnnotation}s cannot be retrieved.
*/
private RefactoringStatus checkAnnotations(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null && (!checkAnnotations(sourceMethod, targetMethod).isOK()
|| !checkAnnotations(sourceMethod.getDeclaringType(), targetMethod.getDeclaringType()).isOK()))
addErrorAndMark(status, PreconditionFailure.AnnotationMismatch, sourceMethod, targetMethod);
return status;
}
private void addUnmigratableMethod(IMethod method, Object reason) {
this.getUnmigratableMethods().add(method);
this.logInfo(
"Method " + getElementLabel(method, ALL_FULLY_QUALIFIED) + " is not migratable because: " + reason);
}
private RefactoringStatus checkAnnotations(IAnnotatable source, IAnnotatable target) throws JavaModelException {
// a set of annotations from the source method.
Set<IAnnotation> sourceAnnotationSet = new HashSet<>(Arrays.asList(source.getAnnotations()));
// remove any annotations to not consider.
removeSpecialAnnotations(sourceAnnotationSet);
// a set of source method annotation names.
Set<String> sourceMethodAnnotationElementNames = sourceAnnotationSet.parallelStream()
.map(IAnnotation::getElementName).collect(Collectors.toSet());
// a set of target method annotation names.
Set<String> targetAnnotationElementNames = getAnnotationElementNames(target);
// if the source method annotation names don't match the target method
// annotation names.
if (!sourceMethodAnnotationElementNames.equals(targetAnnotationElementNames))
return RefactoringStatus.createErrorStatus(PreconditionFailure.AnnotationNameMismatch.getMessage(),
new RefactoringStatusContext() {
@Override
public Object getCorrespondingElement() {
return source;
}
});
else { // otherwise, we have the same annotations names. Check the
// values.
for (IAnnotation sourceAnnotation : sourceAnnotationSet) {
IMemberValuePair[] sourcePairs = sourceAnnotation.getMemberValuePairs();
IAnnotation targetAnnotation = target.getAnnotation(sourceAnnotation.getElementName());
IMemberValuePair[] targetPairs = targetAnnotation.getMemberValuePairs();
// sanity check.
Assert.isTrue(sourcePairs.length == targetPairs.length, "Source and target pairs differ.");
Arrays.parallelSort(sourcePairs, Comparator.comparing(IMemberValuePair::getMemberName));
Arrays.parallelSort(targetPairs, Comparator.comparing(IMemberValuePair::getMemberName));
for (int i = 0; i < sourcePairs.length; i++)
if (!sourcePairs[i].getMemberName().equals(targetPairs[i].getMemberName())
|| sourcePairs[i].getValueKind() != targetPairs[i].getValueKind()
|| !(sourcePairs[i].getValue().equals(targetPairs[i].getValue())))
return RefactoringStatus.createErrorStatus(
formatMessage(PreconditionFailure.AnnotationValueMismatch.getMessage(),
sourceAnnotation, targetAnnotation),
JavaStatusContext.create(findEnclosingMember(sourceAnnotation)));
}
}
return new RefactoringStatus();
}
/**
* Remove any annotations that we don't want considered.
*
* @param annotationSet
* The set of annotations to work with.
*/
private void removeSpecialAnnotations(Set<IAnnotation> annotationSet) {
// Special case: don't consider the @Override annotation in the source
// (the target will never have this)
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getName()));
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getSimpleName()));
}
private static IMember findEnclosingMember(IJavaElement element) {
if (element == null)
return null;
else if (element instanceof IMember)
return (IMember) element;
else
return findEnclosingMember(element.getParent());
}
private Set<String> getAnnotationElementNames(IAnnotatable annotatable) throws JavaModelException {
return Arrays.stream(annotatable.getAnnotations()).parallel().map(IAnnotation::getElementName)
.collect(Collectors.toSet());
}
/**
* #44: Ensure that exception types between the source and target methods
* match.
*
* @param sourceMethod
* The source method.
* @return The corresponding {@link RefactoringStatus}.
* @throws JavaModelException
* If there is trouble retrieving exception types from
* sourceMethod.
*/
private RefactoringStatus checkExceptions(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null) {
Set<String> sourceMethodExceptionTypeSet = getExceptionTypeSet(sourceMethod);
Set<String> targetMethodExceptionTypeSet = getExceptionTypeSet(targetMethod);
if (!sourceMethodExceptionTypeSet.equals(targetMethodExceptionTypeSet)) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.ExceptionTypeMismatch,
sourceMethod, targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
private static Set<String> getExceptionTypeSet(IMethod method) throws JavaModelException {
return Stream.of(method.getExceptionTypes()).parallel().collect(Collectors.toSet());
}
/**
* Check that the annotations in the parameters are consistent between the
* source and target.
*
* FIXME: What if the annotation type is not available in the target?
*
* @param sourceMethod
* The method to check.
* @return {@link RefactoringStatus} indicating the result of the check.
* @throws JavaModelException
*/
private RefactoringStatus checkParameters(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
// for each parameter.
for (int i = 0; i < sourceMethod.getParameters().length; i++) {
ILocalVariable sourceParameter = sourceMethod.getParameters()[i];
// get the corresponding target parameter.
ILocalVariable targetParameter = targetMethod.getParameters()[i];
if (!checkAnnotations(sourceParameter, targetParameter).isOK())
addErrorAndMark(status, PreconditionFailure.MethodContainsInconsistentParameterAnnotations,
sourceMethod, targetMethod);
}
return status;
}
/**
* Check that return types are compatible between the source and target
* methods.
*
* @param sourceMethod
* The method to check.
* @param monitor
* Optional progress monitor.
* @return {@link RefactoringStatus} indicating the result of the check.
* @throws JavaModelException
*/
private RefactoringStatus checkReturnType(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
String sourceMethodReturnType = Util.getQualifiedNameFromTypeSignature(sourceMethod.getReturnType(),
sourceMethod.getDeclaringType());
String targetMethodReturnType = Util.getQualifiedNameFromTypeSignature(targetMethod.getReturnType(),
targetMethod.getDeclaringType());
if (!sourceMethodReturnType.equals(targetMethodReturnType))
addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod, targetMethod);
return status;
}
@SuppressWarnings("unused")
private ITypeBinding resolveReturnTypeBinding(IMethod method, Optional<IProgressMonitor> monitor)
throws JavaModelException {
MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method,
getCompilationUnit(method.getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
if (methodDeclarationNode != null) {
Type returnType = methodDeclarationNode.getReturnType2();
return returnType.resolveBinding();
} else
return null;
}
private RefactoringStatus checkStructure(IMember member) throws JavaModelException {
if (!member.isStructureKnown()) {
return RefactoringStatus.createErrorStatus(
MessageFormat.format(Messages.CUContainsCompileErrors, getElementLabel(member, ALL_FULLY_QUALIFIED),
getElementLabel(member.getCompilationUnit(), ALL_FULLY_QUALIFIED)),
JavaStatusContext.create(member.getCompilationUnit()));
}
return new RefactoringStatus();
}
private static RefactoringStatusEntry getLastRefactoringStatusEntry(RefactoringStatus status) {
return status.getEntryAt(status.getEntries().length - 1);
}
private RefactoringStatus checkWritabilitiy(IMember member, PreconditionFailure failure) {
if (member.isBinary() || member.isReadOnly()) {
return createError(failure, member);
}
return new RefactoringStatus();
}
private RefactoringStatus checkExistence(IMember member, PreconditionFailure failure) {
if (member == null || !member.exists()) {
return createError(failure, member);
}
return new RefactoringStatus();
}
public Set<IMethod> getSourceMethods() {
return this.sourceMethods;
}
public Set<IMethod> getUnmigratableMethods() {
return this.unmigratableMethods;
}
private RefactoringStatus checkSourceMethodBodies(Optional<IProgressMonitor> pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
pm.ifPresent(m -> m.beginTask("Checking source method bodies ...", this.getSourceMethods().size()));
Iterator<IMethod> it = this.getSourceMethods().iterator();
while (it.hasNext()) {
IMethod sourceMethod = it.next();
MethodDeclaration declaration = getMethodDeclaration(sourceMethod, pm);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
SourceMethodBodyAnalysisVisitor visitor = new SourceMethodBodyAnalysisVisitor(sourceMethod, pm);
body.accept(visitor);
if (visitor.doesMethodContainsSuperReference())
addErrorAndMark(status, PreconditionFailure.MethodContainsSuperReference, sourceMethod);
if (visitor.doesMethodContainsCallToProtectedObjectMethod())
addErrorAndMark(status, PreconditionFailure.MethodContainsCallToProtectedObjectMethod,
sourceMethod,
visitor.getCalledProtectedObjectMethodSet().stream().findAny().orElseThrow(
() -> new IllegalStateException("No associated object method")));
if (visitor.doesMethodContainsTypeIncompatibleThisReference()) {
// FIXME: The error context should be the this
// reference that caused the error.
addErrorAndMark(status, PreconditionFailure.MethodContainsTypeIncompatibleThisReference,
sourceMethod);
}
}
}
pm.ifPresent(m -> m.worked(1));
}
return status;
} finally {
pm.ifPresent(IProgressMonitor::done);
}
}
private MethodDeclaration getMethodDeclaration(IMethod method, Optional<IProgressMonitor> pm)
throws JavaModelException {
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = this.getCompilationUnit(root,
new SubProgressMonitor(pm.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN));
MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
return declaration;
}
private static void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure,
IJavaElement... relatedElementCollection) {
addEntry(status, sourceMethod, RefactoringStatus.WARNING, failure, relatedElementCollection);
}
private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod,
PreconditionFailure failure, IJavaElement... relatedElementCollection) {
addEntry(status, sourceMethod, RefactoringStatus.ERROR, failure, relatedElementCollection);
return getLastRefactoringStatusEntry(status);
}
private static void addEntry(RefactoringStatus status, IMethod sourceMethod, int severity,
PreconditionFailure failure, IJavaElement... relatedElementCollection) {
String message = formatMessage(failure.getMessage(), relatedElementCollection);
// add the first element as the context if appropriate.
if (relatedElementCollection.length > 0 && relatedElementCollection[0] instanceof IMember) {
IMember member = (IMember) relatedElementCollection[0];
RefactoringStatusContext context = JavaStatusContext.create(member);
status.addEntry(new RefactoringStatusEntry(severity, message, context,
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod));
} else // otherwise, just add the message.
status.addEntry(new RefactoringStatusEntry(severity, message, null,
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod));
}
private static String formatMessage(String message, IJavaElement... relatedElementCollection) {
Object[] elementNames = Arrays.stream(relatedElementCollection).parallel().filter(Objects::nonNull)
.map(re -> getElementLabel(re, ALL_FULLY_QUALIFIED)).toArray();
message = MessageFormat.format(message, elementNames);
return message;
}
private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod,
PreconditionFailure failure, IMember member, IMember... more) {
List<String> elementNames = new ArrayList<>();
elementNames.add(getElementLabel(member, ALL_FULLY_QUALIFIED));
Stream<String> stream = Arrays.asList(more).parallelStream().map(m -> getElementLabel(m, ALL_FULLY_QUALIFIED));
Stream<String> concat = Stream.concat(elementNames.stream(), stream);
List<String> collect = concat.collect(Collectors.toList());
status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(failure.getMessage(), collect.toArray()),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod);
return getLastRefactoringStatusEntry(status);
}
private static RefactoringStatus createWarning(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createWarningStatus);
}
private RefactoringStatus createError(PreconditionFailure failure, IMember member) {
return createRefactoringStatus(failure.getMessage(), member, RefactoringStatus::createErrorStatus);
}
private static RefactoringStatus createFatalError(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createFatalErrorStatus);
}
private static RefactoringStatus createRefactoringStatus(String message, IMember member,
BiFunction<String, RefactoringStatusContext, RefactoringStatus> function) {
String elementName = getElementLabel(member, ALL_FULLY_QUALIFIED);
return function.apply(MessageFormat.format(message, elementName), JavaStatusContext.create(member));
}
/**
* Creates a working copy layer if necessary.
*
* @param monitor
* the progress monitor to use
* @return a status describing the outcome of the operation
*/
private RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
try {
monitor.beginTask(Messages.CheckingPreconditions, 1);
// TODO ICompilationUnit unit =
// getDeclaringType().getCompilationUnit();
// if (fLayer)
// unit = unit.findWorkingCopy(fOwner);
// resetWorkingCopies(unit);
return new RefactoringStatus();
} finally {
monitor.done();
}
}
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context)
throws CoreException, OperationCanceledException {
try {
monitor.beginTask(Messages.CheckingPreconditions, 12);
final RefactoringStatus status = new RefactoringStatus();
if (!this.getSourceMethods().isEmpty())
status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkSourceMethods(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkSourceMethodBodies(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
// TODO: Should this be a separate method?
status.merge(checkDestinationInterfaces(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkTargetMethods(Optional.of(new SubProgressMonitor(monitor, 1))));
// check if there are any methods left to migrate.
if (this.getUnmigratableMethods().containsAll(this.getSourceMethods()))
// if not, we have a fatal error.
status.addFatalError(Messages.NoMethodsHavePassedThePreconditions);
// TODO:
// Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()),
// context);
return status;
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
monitor.done();
}
}
private RefactoringStatus checkTargetMethods(Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// first, create a map of target methods to their set of migratable
// source methods.
Map<IMethod, Set<IMethod>> targetMethodToMigratableSourceMethodsMap = createTargetMethodToMigratableSourceMethodsMap(
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
monitor.ifPresent(m -> m.beginTask("Checking target methods ...",
targetMethodToMigratableSourceMethodsMap.keySet().size()));
// for each target method.
for (IMethod targetMethod : targetMethodToMigratableSourceMethodsMap.keySet()) {
Set<IMethod> migratableSourceMethods = targetMethodToMigratableSourceMethodsMap.get(targetMethod);
// if the target method is associated with multiple source methods.
if (migratableSourceMethods.size() > 1) {
// we need to decide which of the source methods will be
// migrated and which will not. We'll build equivalence sets to
// see which of the source method bodies are the same. Then,
// we'll pick the largest equivalence set to migrate. That will
// reduce the greatest number of methods in the system. The
// other sets will become unmigratable. Those methods will just
// override the new default method.
// (MakeSet).
Set<Set<IMethod>> equivalenceSets = createEquivalenceSets(migratableSourceMethods);
// merge the sets.
mergeEquivalenceSets(equivalenceSets, monitor);
// find the largest set size.
equivalenceSets.stream().map(s -> s.size()).max(Integer::compareTo)
// find the first set with this size.
.flatMap(size -> equivalenceSets.stream().filter(s -> s.size() == size).findFirst()).ifPresent(
// for all of the methods in the other sets ...
fls -> equivalenceSets.stream().filter(s -> s != fls).flatMap(s -> s.stream())
// mark them as unmigratable.
.forEach(m -> addErrorAndMark(status,
PreconditionFailure.TargetMethodHasMultipleSourceMethods, m,
targetMethod)));
}
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
return status;
}
private void mergeEquivalenceSets(Set<Set<IMethod>> equivalenceSets, Optional<IProgressMonitor> monitor)
throws JavaModelException {
// A map of methods to their equivalence set.
Map<IMethod, Set<IMethod>> methodToEquivalenceSetMap = new LinkedHashMap<>();
for (Set<IMethod> set : equivalenceSets) {
for (IMethod method : set) {
methodToEquivalenceSetMap.put(method, set);
}
}
monitor.ifPresent(
m -> m.beginTask("Merging method equivalence sets ...", methodToEquivalenceSetMap.keySet().size()));
for (IMethod method : methodToEquivalenceSetMap.keySet()) {
for (IMethod otherMethod : methodToEquivalenceSetMap.keySet()) {
if (method != otherMethod) {
Set<IMethod> methodSet = methodToEquivalenceSetMap.get(method); // Find(method)
Set<IMethod> otherMethodSet = methodToEquivalenceSetMap.get(otherMethod); // Find(otherMethod)
// if they are different sets and the elements are
// equivalent.
if (methodSet != otherMethodSet && isEquivalent(method, otherMethod,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)))) {
// Union(Find(method), Find(otherMethod))
methodSet.addAll(otherMethodSet);
equivalenceSets.remove(otherMethodSet);
// update the map.
for (IMethod methodInOtherMethodSet : otherMethodSet) {
methodToEquivalenceSetMap.put(methodInOtherMethodSet, methodSet);
}
}
}
}
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
}
private boolean isEquivalent(IMethod method, IMethod otherMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
monitor.ifPresent(m -> m.beginTask("Checking method equivalence ...", 2));
MethodDeclaration methodDeclaration = this.getMethodDeclaration(method,
monitor.map(m -> new SubProgressMonitor(m, 1)));
MethodDeclaration otherMethodDeclaration = this.getMethodDeclaration(otherMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
monitor.ifPresent(IProgressMonitor::done);
Block methodDeclarationBody = methodDeclaration.getBody();
Block otherMethodDeclarationBody = otherMethodDeclaration.getBody();
boolean match = methodDeclarationBody.subtreeMatch(new ASTMatcher(), otherMethodDeclarationBody);
return match;
}
private static Set<Set<IMethod>> createEquivalenceSets(Set<IMethod> migratableSourceMethods) {
Set<Set<IMethod>> ret = new LinkedHashSet<>();
migratableSourceMethods.stream().forEach(m -> {
Set<IMethod> set = new LinkedHashSet<>();
set.add(m);
ret.add(set);
});
return ret;
}
private Map<IMethod, Set<IMethod>> createTargetMethodToMigratableSourceMethodsMap(
Optional<IProgressMonitor> monitor) throws JavaModelException {
Map<IMethod, Set<IMethod>> ret = new LinkedHashMap<>();
Set<IMethod> migratableMethods = this.getMigratableMethods();
monitor.ifPresent(m -> m.beginTask("Finding migratable source methods for each target method ...",
migratableMethods.size()));
for (IMethod sourceMethod : migratableMethods) {
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
ret.compute(targetMethod, (k, v) -> {
if (v == null) {
Set<IMethod> sourceMethodSet = new LinkedHashSet<>();
sourceMethodSet.add(sourceMethod);
return sourceMethodSet;
} else {
v.add(sourceMethod);
return v;
}
});
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
return ret;
}
private void clearCaches() {
getTypeToSuperTypeHierarchyMap().clear();
getMethodToTargetMethodMap().clear();
getTypeToTypeHierarchyMap().clear();
getCompilationUnitToCompilationUnitRewriteMap().clear();
}
public TimeCollector getExcludedTimeCollector() {
return excludedTimeCollector;
}
private RefactoringStatus checkProjectCompliance(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
IJavaProject destinationProject = targetMethod.getJavaProject();
if (!JavaModelUtil.is18OrHigher(destinationProject))
addErrorAndMark(status, PreconditionFailure.DestinationProjectIncompatible, sourceMethod, targetMethod);
return status;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.CreatingChange, 1);
final TextEditBasedChangeManager manager = new TextEditBasedChangeManager();
Set<IMethod> migratableMethods = this.getMigratableMethods();
if (migratableMethods.isEmpty())
return new NullChange(Messages.NoMethodsToMigrate);
// the set of target methods that we transformed to default methods.
Set<IMethod> transformedTargetMethods = new HashSet<>(migratableMethods.size());
for (IMethod sourceMethod : migratableMethods) {
// get the source method declaration.
CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm);
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
sourceCompilationUnit);
logInfo("Source method declaration: " + sourceMethodDeclaration);
CompilationUnitRewrite sourceRewrite = getCompilationUnitRewrite(sourceMethod.getCompilationUnit(),
sourceCompilationUnit);
// Find the target method.
IMethod targetMethod = getTargetMethod(sourceMethod,
Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN)));
// if we have not already transformed this method
if (!transformedTargetMethods.contains(targetMethod)) {
IType destinationInterface = targetMethod.getDeclaringType();
logInfo("Migrating method: " + getElementLabel(sourceMethod, ALL_FULLY_QUALIFIED)
+ " to interface: " + destinationInterface.getFullyQualifiedName());
CompilationUnit destinationCompilationUnit = this
.getCompilationUnit(destinationInterface.getTypeRoot(), pm);
CompilationUnitRewrite destinationCompilationUnitRewrite = getCompilationUnitRewrite(
targetMethod.getCompilationUnit(), destinationCompilationUnit);
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(destinationCompilationUnit,
destinationCompilationUnitRewrite.getImportRewrite());
MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod,
destinationCompilationUnit);
final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToSuperType(
sourceMethod.getDeclaringType(), targetMethod.getDeclaringType(),
targetMethod.getDeclaringType());
// tack on the source method body to the target method.
pm.beginTask("Copying source method body ...", IProgressMonitor.UNKNOWN);
copyMethodBody(sourceRewrite, destinationCompilationUnitRewrite, sourceMethod,
sourceMethodDeclaration, targetMethodDeclaration, mapping,
new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN));
// add any static imports needed to the target method's
// compilation unit for static fields referenced in the
// source method.
addStaticImports(sourceMethodDeclaration, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
// alter the target parameter names to match that of the
// source method if necessary #148.
changeTargetMethodParametersToMatchSource(sourceMethodDeclaration, targetMethodDeclaration,
destinationCompilationUnitRewrite.getASTRewrite());
// Change the target method to default.
convertToDefault(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// Remove any abstract modifiers from the target method as
// both abstract and default are not allowed.
removeAbstractness(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// TODO: Do we need to worry about preserving ordering of
// the
// modifiers?
// if the source method is strictfp.
// FIXME: Actually, I think we need to check that, in the
// case the target method isn't already strictfp, that the
// other
// methods in the hierarchy are.
if ((Flags.isStrictfp(sourceMethod.getFlags())
|| Flags.isStrictfp(sourceMethod.getDeclaringType().getFlags()))
&& !Flags.isStrictfp(targetMethod.getFlags()))
// change the target method to strictfp.
convertToStrictFP(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// deal with imports
ImportRewriteUtil.addImports(destinationCompilationUnitRewrite, context, sourceMethodDeclaration,
new HashMap<Name, String>(), new HashMap<Name, String>(), false);
transformedTargetMethods.add(targetMethod);
}
// Remove the source method.
removeMethod(sourceMethodDeclaration, sourceRewrite.getASTRewrite());
sourceRewrite.getImportRemover().registerRemovedNode(sourceMethodDeclaration);
}
// save the source changes.
ICompilationUnit[] units = this.getCompilationUnitToCompilationUnitRewriteMap().keySet().stream()
.filter(cu -> !manager.containsChangesIn(cu)).toArray(ICompilationUnit[]::new);
for (ICompilationUnit cu : units) {
CompilationUnit compilationUnit = getCompilationUnit(cu, pm);
manageCompilationUnit(manager, getCompilationUnitRewrite(cu, compilationUnit),
Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN)));
}
final Map<String, String> arguments = new HashMap<>();
int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
// TODO: Fill in description.
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor(
null, "TODO", null, arguments, flags);
return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges());
} finally {
pm.done();
this.clearCaches();
}
}
/**
* Add any static imports needed to the target method's compilation unit for
* static fields referenced in the source method.
*
* @param sourceMethodDeclaration
* The method being migrated.
* @param targetMethodDeclaration
* The target for the migration.
* @param destinationCompilationUnitRewrite
* The rewrite associated with the target's compilation unit.
* @param context
* The context in which to add static imports if necessary.
*/
private void addStaticImports(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration,
CompilationUnitRewrite destinationCompilationUnitRewrite, ImportRewriteContext context) {
sourceMethodDeclaration.accept(new ASTVisitor() {
@Override
public boolean visit(SimpleName node) {
// add any necessary static imports.
if (node.getParent().getNodeType() != ASTNode.QUALIFIED_NAME) {
IBinding binding = node.resolveBinding();
if (binding.getKind() == IBinding.VARIABLE) {
IVariableBinding variableBinding = ((IVariableBinding) binding);
if (variableBinding.isField()) {
ITypeBinding declaringClass = variableBinding.getDeclaringClass();
processStaticImport(variableBinding, declaringClass, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
}
}
}
return super.visit(node);
}
private void processStaticImport(IBinding binding, ITypeBinding declaringClass,
MethodDeclaration targetMethodDeclaration, CompilationUnitRewrite destinationCompilationUnitRewrite,
ImportRewriteContext context) {
if (Modifier.isStatic(binding.getModifiers())
&& !declaringClass.isEqualTo(targetMethodDeclaration.resolveBinding().getDeclaringClass()))
destinationCompilationUnitRewrite.getImportRewrite().addStaticImport(binding, context);
}
@Override
public boolean visit(MethodInvocation node) {
if (node.getExpression() == null) { // it's an
// unqualified
// method call.
IMethodBinding methodBinding = node.resolveMethodBinding();
ITypeBinding declaringClass = methodBinding.getDeclaringClass();
processStaticImport(methodBinding, declaringClass, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
}
return super.visit(node);
}
});
}
private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) {
CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root);
if (compilationUnit == null) {
this.getExcludedTimeCollector().start();
compilationUnit = RefactoringASTParser.parseWithASTProvider(root, true, pm);
this.getExcludedTimeCollector().stop();
this.typeRootToCompilationUnitMap.put(root, compilationUnit);
}
return compilationUnit;
}
private CompilationUnitRewrite getCompilationUnitRewrite(ICompilationUnit unit, CompilationUnit root) {
CompilationUnitRewrite rewrite = this.getCompilationUnitToCompilationUnitRewriteMap().get(unit);
if (rewrite == null) {
rewrite = new CompilationUnitRewrite(unit, root);
this.getCompilationUnitToCompilationUnitRewriteMap().put(unit, rewrite);
}
return rewrite;
}
private void manageCompilationUnit(final TextEditBasedChangeManager manager, CompilationUnitRewrite rewrite,
Optional<IProgressMonitor> monitor) throws CoreException {
monitor.ifPresent(m -> m.beginTask("Creating change ...", IProgressMonitor.UNKNOWN));
CompilationUnitChange change = rewrite.createChange(false, monitor.orElseGet(NullProgressMonitor::new));
change.setTextType("java");
manager.manage(rewrite.getCu(), change);
}
private void changeTargetMethodParametersToMatchSource(MethodDeclaration sourceMethodDeclaration,
MethodDeclaration targetMethodDeclaration, ASTRewrite destinationRewrite) {
Assert.isLegal(sourceMethodDeclaration.parameters().size() == targetMethodDeclaration.parameters().size());
// iterate over the source method parameters.
for (int i = 0; i < sourceMethodDeclaration.parameters().size(); i++) {
// get the parameter for the source method.
SingleVariableDeclaration sourceParameter = (SingleVariableDeclaration) sourceMethodDeclaration.parameters()
.get(i);
// get the corresponding target method parameter.
SingleVariableDeclaration targetParameter = (SingleVariableDeclaration) targetMethodDeclaration.parameters()
.get(i);
// if the names don't match.
if (!sourceParameter.getName().equals(targetParameter.getName())) {
// change the target method parameter to match it since that is
// what the body will use.
ASTNode sourceParameterNameCopy = ASTNode.copySubtree(destinationRewrite.getAST(),
sourceParameter.getName());
destinationRewrite.replace(targetParameter.getName(), sourceParameterNameCopy, null);
}
}
}
private void copyMethodBody(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite,
final IMethod method, final MethodDeclaration oldMethod, final MethodDeclaration newMethod,
final TypeVariableMaplet[] mapping, final IProgressMonitor monitor) throws JavaModelException {
final Block body = oldMethod.getBody();
if (body == null) {
newMethod.setBody(null);
return;
}
try {
final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents());
final ASTRewrite rewrite = ASTRewrite.create(body.getAST());
final ITrackedNodePosition position = rewrite.track(body);
body.accept(new TypeVariableMapper(rewrite, mapping));
rewrite.rewriteAST(document, method.getJavaProject().getOptions(true)).apply(document, TextEdit.NONE);
String content = document.get(position.getStartPosition(), position.getLength());
final String[] lines = Strings.convertIntoLines(content);
Strings.trimIndentation(lines, method.getJavaProject(), false);
content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
ASTNode stringPlaceholder = targetRewrite.getASTRewrite().createStringPlaceholder(content, ASTNode.BLOCK);
targetRewrite.getASTRewrite().set(newMethod, MethodDeclaration.BODY_PROPERTY, stringPlaceholder, null);
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
}
private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
// TODO: Do we need an edit group??
rewrite.remove(methodDeclaration, null);
}
private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.DEFAULT_KEYWORD, rewrite);
}
private void removeAbstractness(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
removeModifierKeyword(methodDeclaration, ModifierKeyword.ABSTRACT_KEYWORD, rewrite);
}
private void convertToStrictFP(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.STRICTFP_KEYWORD, rewrite);
}
private void addModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword,
ASTRewrite rewrite) {
Modifier modifier = rewrite.getAST().newModifier(modifierKeyword);
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.insertLast(modifier, null);
}
@SuppressWarnings("unchecked")
private void removeModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword,
ASTRewrite rewrite) {
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.getOriginalList().stream().filter(o -> o instanceof Modifier).map(Modifier.class::cast)
.filter(m -> ((Modifier) m).getKeyword().equals(modifierKeyword)).findAny()
.ifPresent(m -> listRewrite.remove((ASTNode) m, null));
}
private static Map<IMethod, IMethod> getMethodToTargetMethodMap() {
return methodToTargetMethodMap;
}
/**
* Finds the target (interface) method declaration in the destination
* interface for the given source method.
*
* TODO: Something is very wrong here. There can be multiple targets for a
* given source method because it can be declared in multiple interfaces up
* and down the hierarchy. What this method right now is really doing is
* finding the target method for the given source method in the destination
* interface. As such, we should be sure what the destination is prior to
* this call.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @return The target method that will be manipulated or null if not found.
* @throws JavaModelException
*/
public static IMethod getTargetMethod(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
IMethod targetMethod = getMethodToTargetMethodMap().get(sourceMethod);
if (targetMethod == null) {
IType destinationInterface = getDestinationInterface(sourceMethod, monitor);
if (getMethodTargetInterfaceTargetMethodTable().contains(sourceMethod, destinationInterface))
targetMethod = getMethodTargetInterfaceTargetMethodTable().get(sourceMethod, destinationInterface);
else if (destinationInterface != null) {
targetMethod = findTargetMethod(sourceMethod, destinationInterface);
getMethodTargetInterfaceTargetMethodTable().put(sourceMethod, destinationInterface, targetMethod);
}
getMethodToTargetMethodMap().put(sourceMethod, targetMethod);
}
return targetMethod;
}
private static IType getDestinationInterface(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
IType[] candidateDestinationInterfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
// FIXME: Really just returning the first match here
return Arrays.stream(candidateDestinationInterfaces).findFirst().orElse(null);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
/**
* Finds the target (interface) method declaration in the given type for the
* given source method.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @param targetInterface
* The interface for which sourceMethod will be migrated.
* @return The target method that will be manipulated or null if not found.
* @throws JavaModelException
*/
private static IMethod findTargetMethod(IMethod sourceMethod, IType targetInterface) throws JavaModelException {
if (targetInterface == null)
return null; // not found.
Assert.isNotNull(sourceMethod);
Assert.isLegal(sourceMethod.exists(), "Source method does not exist.");
Assert.isLegal(targetInterface.exists(), "Target interface does not exist.");
Assert.isLegal(targetInterface.isInterface(), "Target interface must be an interface.");
IMethod ret = null;
for (IMethod method : targetInterface.getMethods()) {
if (method.exists() && method.getElementName().equals(sourceMethod.getElementName())) {
ILocalVariable[] parameters = method.getParameters();
ILocalVariable[] sourceParameters = sourceMethod.getParameters();
if (parameterListMatches(parameters, method, sourceParameters, sourceMethod)) {
if (ret != null)
throw new IllegalStateException("Found multiple matches of method: "
+ sourceMethod.getElementName() + " in interface: " + targetInterface.getElementName());
else
ret = method;
}
}
}
return ret;
}
private static boolean parameterListMatches(ILocalVariable[] parameters, IMethod method,
ILocalVariable[] sourceParameters, IMethod sourceMethod) throws JavaModelException {
if (parameters.length == sourceParameters.length) {
for (int i = 0; i < parameters.length; i++) {
String paramString = Util.getQualifiedNameFromTypeSignature(parameters[i].getTypeSignature(),
method.getDeclaringType());
String sourceParamString = Util.getQualifiedNameFromTypeSignature(
sourceParameters[i].getTypeSignature(), sourceMethod.getDeclaringType());
if (!paramString.equals(sourceParamString))
return false;
}
return true;
} else
return false;
}
private void log(int severity, String message) {
if (severity >= this.getLoggingLevel()) {
String name = FrameworkUtil.getBundle(this.getClass()).getSymbolicName();
IStatus status = new Status(severity, name, message);
JavaPlugin.log(status);
}
}
private void logInfo(String message) {
log(IStatus.INFO, message);
}
private void logWarning(String message) {
log(IStatus.WARNING, message);
}
@Override
public String getIdentifier() {
return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID;
}
@Override
public String getProcessorName() {
return Messages.Name;
}
@Override
public boolean isApplicable() throws CoreException {
return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getSourceMethods().parallelStream()
.filter(m -> !this.getUnmigratableMethods().contains(m)).toArray(IMethod[]::new), Optional.empty());
}
/**
* Returns true if the given type is a pure interface, i.e., it is an
* interface but not an annotation.
*
* @param type
* The type to check.
* @return True if the given type is a pure interface and false otherwise.
* @throws JavaModelException
*/
private static boolean isPureInterface(IType type) throws JavaModelException {
return type != null && type.isInterface() && !type.isAnnotation();
}
private Map<IType, ITypeHierarchy> typeToTypeHierarchyMap = new HashMap<>();
private Map<IType, ITypeHierarchy> getTypeToTypeHierarchyMap() {
return typeToTypeHierarchyMap;
}
private ITypeHierarchy getTypeHierarchy(IType type, Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
ITypeHierarchy ret = this.getTypeToTypeHierarchyMap().get(type);
if (ret == null) {
ret = type.newTypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
this.getTypeToTypeHierarchyMap().put(type, ret);
}
return ret;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
@Override
public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants)
throws CoreException {
return new RefactoringParticipant[0];
}
private static Table<IMethod, IType, IMethod> getMethodTargetInterfaceTargetMethodTable() {
return methodTargetInterfaceTargetMethodTable;
}
private SearchEngine getSearchEngine() {
return searchEngine;
}
/**
* Minimum logging level. One of the constants in
* org.eclipse.core.runtime.IStatus.
*
* @param level
* The minimum logging level to set.
* @see org.eclipse.core.runtime.IStatus.
*/
public void setLoggingLevel(int level) {
this.loggingLevel = level;
}
protected int getLoggingLevel() {
return this.loggingLevel;
}
protected Map<ICompilationUnit, CompilationUnitRewrite> getCompilationUnitToCompilationUnitRewriteMap() {
return this.compilationUnitToCompilationUnitRewriteMap;
}
} |
package edu.cuny.citytech.defaultrefactoring.core.refactorings;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTRequestor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.HierarchyProcessor;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.GroupCategorySet;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEdit;
import org.osgi.framework.FrameworkUtil;
import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor;
import edu.cuny.citytech.defaultrefactoring.core.messages.Messages;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
// TODO: Are we checking the target interface? I think that the target interface should be completely empty for now.
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
@SuppressWarnings({ "restriction" })
public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends HierarchyProcessor {
/**
* The destination interface.
*/
private IType destinationInterface;
private Map<CompilationUnit, ASTRewrite> compilationUnitToASTRewriteMap = new HashMap<>();
private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>();
@SuppressWarnings("unused")
private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet(
new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CategoryName,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CategoryDescription));
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
* @throws JavaModelException
*/
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, boolean layer, IProgressMonitor monitor) throws JavaModelException {
super(methods, settings, layer);
if (methods != null && methods.length > 0) {
IType[] candidateTypes = this.getCandidateTypes(monitor);
if (candidateTypes != null && candidateTypes.length > 0) {
// TODO: For now,
if (candidateTypes.length > 1)
logWarning("Encountered multiple candidate types (" + candidateTypes.length + ").");
this.setDestinationType(candidateTypes[0]);
}
}
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, IProgressMonitor monitor) throws JavaModelException {
this(methods, settings, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(IProgressMonitor monitor)
throws JavaModelException {
this(null, null, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException {
this(null, null, false, new NullProgressMonitor());
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getElements() {
return fMembersToMove;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 1);
if (this.fMembersToMove.length == 0)
return RefactoringStatus.createFatalErrorStatus(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodsNotSpecified);
else if (this.fMembersToMove.length > 1) {
// TODO: For now.
return RefactoringStatus.createFatalErrorStatus(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMoreThanOneMethod);
} else {
final RefactoringStatus status = new RefactoringStatus();
status.merge(checkDeclaringType(new SubProgressMonitor(pm, 1)));
if (status.hasFatalError())
return status;
status.merge(checkIfMembersExist());
return status;
}
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
pm.done();
}
}
protected RefactoringStatus checkDestinationInterfaceMethods(IProgressMonitor monitor) throws JavaModelException {
final IType targetInterface = this.getDestinationInterface();
Assert.isNotNull(targetInterface);
RefactoringStatus status = new RefactoringStatus();
// TODO: For now, the target interface must only contain the target
// method.
List<IMethod> methodsToMoveList = Arrays.asList(this.getMethodsToMove());
Set<IMethod> methodsToMoveSet = new HashSet<>(methodsToMoveList);
List<IMethod> destinationInterfaceMethodsList = Arrays.asList(targetInterface.getMethods());
Set<IMethod> destinationInterfaceMethodsSet = new HashSet<>(destinationInterfaceMethodsList);
// ensure that the methods to move are the same as the ones in the
// interface.
boolean equals;
// if they are different sizes, they can't be the same.
if (methodsToMoveSet.size() != destinationInterfaceMethodsSet.size())
equals = false;
else
// make sure there's a match for each method.
equals = methodsToMoveSet.parallelStream().map(targetInterface::findMethods).map(Optional::ofNullable)
.map(o -> o.map(a -> a.length)).mapToInt(o -> o.orElse(0)).allMatch(l -> l == 1);
if (!equals)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceMustOnlyDeclareTheMethodToMigrate,
destinationInterface);
return status;
}
protected RefactoringStatus checkDestinationInterface(IProgressMonitor monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// TODO
final IType destinationInterface = this.getDestinationInterface();
// Can't be null.
if (destinationInterface == null) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoDestinationInterface);
return status;
}
// Must be an interface.
if (!isPureInterface(destinationInterface))
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationTypeMustBePureInterface,
destinationInterface);
status.merge(checkDestinationInterfaceMethods(new SubProgressMonitor(monitor, 1)));
return status;
}
private void addWarning(RefactoringStatus status, String message) {
addWarning(status, message, null);
}
@Override
protected RefactoringStatus checkDeclaringType(IProgressMonitor monitor) throws JavaModelException {
RefactoringStatus status = super.checkDeclaringType(monitor);
if (!status.hasFatalError()) {
final IType type = getDeclaringType();
if (type.isAnonymous()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInAnonymousTypes, type);
}
// TODO: This is being checked by the super implementation but need
// to revisit. It might be okay to have an enum. In that case, we
// can't call the super method.
// if (type.isEnum()) {
// // TODO for now.
// addWarning(status,
// Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInEnums,
// method);
if (type.isLambda()) {
// TODO for now.
return createFatalError(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInLambdas,
type);
}
if (type.isLocal()) {
// TODO for now.
return createFatalError(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInLocals,
type);
}
if (type.isMember()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInMemberTypes, type);
}
if (!type.isClass()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodsOnlyInClasses, type);
}
if (type.getAnnotations().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInAnnotatedTypes, type);
}
if (type.getFields().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithFields, type);
}
if (type.getInitializers().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithInitializers,
type);
}
if (type.getMethods().length > 1) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithMoreThanOneMethod,
type);
}
if (type.getTypeParameters().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithTypeParameters,
type);
}
if (type.getTypes().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithType, type);
}
if (type.getSuperclassName() != null) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithSuperType,
type);
}
if (type.getSuperInterfaceNames().length == 0) {
// enclosing type must implement an interface, at least for now,
// which one of which will become the target interface.
// it is probably possible to still perform the refactoring
// without this condition but I believe that this is
// the particular pattern we are targeting.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesThatDontImplementInterfaces,
type);
}
if (type.getSuperInterfaceNames().length > 1) {
// TODO for now. Let's only deal with a single interface as that
// is part of the targeted pattern.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesThatExtendMultipleInterfaces,
type);
}
if (!Flags.isAbstract(type.getFlags())) {
// TODO for now. This follows the target pattern. Maybe we can
// relax this but that would require checking for
// instantiations.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInConcreteTypes, type);
}
if (Flags.isStatic(type.getFlags())) {
// TODO no static types for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInStaticTypes, type);
}
status.merge(checkDeclaringSuperTypes(monitor));
}
return status;
}
protected RefactoringStatus checkDeclaringSuperTypes(final IProgressMonitor monitor) throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
IType[] interfaces = getCandidateTypes(monitor);
if (interfaces.length == 0) {
IType declaringType = getDeclaringType();
final String msg = MessageFormat.format(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithNoCandidateTargetTypes,
createLabel(declaringType));
return RefactoringStatus.createWarningStatus(msg);
} else if (interfaces.length > 1) {
// TODO For now, let's make sure there's only one candidate type.
IType declaringType = getDeclaringType();
final String msg = MessageFormat.format(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithMultipleCandidateTargetTypes,
JavaElementLabels.getTextLabel(declaringType, JavaElementLabels.ALL_FULLY_QUALIFIED));
return RefactoringStatus.createWarningStatus(msg);
}
return result;
}
/**
* Returns the possible target interfaces for the migration. NOTE: One
* difference here between this refactoring and pull up is that we can have
* a much more complex type hierarchy due to multiple interface inheritance
* in Java.
*
* TODO: It should be possible to pull up a method into an interface (i.e.,
* "Pull Up Method To Interface") that is not implemented explicitly. For
* example, there may be a skeletal implementation class that implements all
* the target interface's methods without explicitly declaring so.
*
* @param monitor
* A progress monitor.
* @return The possible target interfaces for the migration.
* @throws JavaModelException
* upon Java model problems.
*/
public IType[] getCandidateTypes(final IProgressMonitor monitor) throws JavaModelException {
IType declaringType = getDeclaringType();
IType[] superInterfaces = declaringType.newSupertypeHierarchy(monitor).getAllSuperInterfaces(declaringType);
return Stream.of(superInterfaces).parallel()
.filter(t -> t != null && t.exists() && !t.isReadOnly() && !t.isBinary()).toArray(IType[]::new);
}
protected RefactoringStatus checkMethodsToMove(IProgressMonitor pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
Iterator<IMethod> it = getMethodsToMoveIterator();
while (it.hasNext()) {
IMethod method = it.next();
if (!method.exists()) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodDoesNotExist,
method);
}
if (method.isBinary() || method.isReadOnly()) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CantChangeMethod,
method);
}
if (!method.isStructureKnown()) {
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CUContainsCompileErrors,
method);
}
if (method.isConstructor()) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoConstructors,
method);
}
if (method.getAnnotations().length > 0) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoAnnotations,
method);
}
if (Flags.isStatic(method.getFlags())) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoStaticMethods,
method);
}
if (JdtFlags.isNative(method)) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoNativeMethods,
method);
}
if (method.isLambdaMethod()) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoLambdaMethods,
method);
}
if (method.getExceptionTypes().length != 0) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsThatThrowExceptions,
method);
}
if (method.getParameters().length != 0) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithParameters,
method);
}
if (!method.getReturnType().equals(Signature.SIG_VOID)) {
// return type must be void.
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithReturnTypes,
method);
}
if (method.getTypeParameters().length != 0) {
// TODO for now but this will be an important one.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithTypeParameters,
method);
}
pm.worked(1);
}
if (!status.hasFatalError())
status.merge(checkMethodsToMoveBodies(new SubProgressMonitor(pm, fMembersToMove.length)));
return status;
} finally {
pm.done();
}
}
protected Iterator<IMethod> getMethodsToMoveIterator() {
return Stream.of(fMembersToMove).parallel().filter(m -> m instanceof IMethod).map(m -> (IMethod) m).iterator();
}
protected IMethod[] getMethodsToMove() {
return Stream.of(fMembersToMove).parallel().filter(m -> m instanceof IMethod).map(m -> (IMethod) m)
.toArray(IMethod[]::new);
}
protected RefactoringStatus checkMethodsToMoveBodies(IProgressMonitor pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
Iterator<IMethod> it = this.getMethodsToMoveIterator();
while (it.hasNext()) {
IMethod method = it.next();
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = this.getCompilationUnit(root, new SubProgressMonitor(pm, 1));
MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
@SuppressWarnings("rawtypes")
List statements = body.statements();
if (!statements.isEmpty()) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithStatements,
method);
}
}
}
pm.worked(1);
}
return status;
} finally {
pm.done();
}
}
private static void addWarning(RefactoringStatus status, String message, IMember member) {
if (member != null) { // workaround
String elementName = JavaElementLabels.getElementLabel(member, JavaElementLabels.ALL_FULLY_QUALIFIED);
message = MessageFormat.format(message, elementName);
}
RefactoringStatusContext context = JavaStatusContext.create(member);
status.addWarning(message, context);
}
private static void addError(RefactoringStatus status, String message, IMember member, IMember... more) {
List<String> elementNames = new ArrayList<>();
elementNames.add(JavaElementLabels.getElementLabel(member, JavaElementLabels.ALL_FULLY_QUALIFIED));
Stream<String> stream = Arrays.asList(more).parallelStream()
.map(MigrateSkeletalImplementationToInterfaceRefactoringProcessor::createLabel);
Stream<String> concat = Stream.concat(elementNames.stream(), stream);
List<String> collect = concat.collect(Collectors.toList());
status.addError(MessageFormat.format(message, collect.toArray()), JavaStatusContext.create(member));
}
private static RefactoringStatus createFatalError(String message, IType type) {
String elementName = createLabel(type);
return RefactoringStatus.createFatalErrorStatus(MessageFormat.format(message, elementName),
JavaStatusContext.create(type));
}
/**
* Creates a working copy layer if necessary.
*
* @param monitor
* the progress monitor to use
* @return a status describing the outcome of the operation
*/
protected RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
try {
monitor.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 1);
ICompilationUnit unit = getDeclaringType().getCompilationUnit();
if (fLayer)
unit = unit.findWorkingCopy(fOwner);
resetWorkingCopies(unit);
return new RefactoringStatus();
} finally {
monitor.done();
}
}
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context)
throws CoreException, OperationCanceledException {
try {
monitor.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 12);
clearCaches();
final RefactoringStatus status = new RefactoringStatus();
if (fMembersToMove.length > 0)
status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkMethodsToMove(new SubProgressMonitor(monitor, 1)));
if (status.hasFatalError())
return status;
status.merge(checkDestinationInterface(new SubProgressMonitor(monitor, 1)));
if (status.hasFatalError())
return status;
// if (fMembersToMove.length > 0)
// TODO: Check project compliance.
// status.merge(checkProjectCompliance(
// getCompilationUnitRewrite(compilationUnitRewrites,
// getDeclaringType().getCompilationUnit()),
// getDestinationType(), fMembersToMove));
// TODO: More checks, perhaps resembling those in
// org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor.checkFinalConditions(IProgressMonitor,
// CheckConditionsContext).
return status;
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
monitor.done();
}
}
protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite sourceRewriter, IType destination,
IMember[] members) {
RefactoringStatus status = HierarchyProcessor.checkProjectCompliance(sourceRewriter, destination, members);
if (!JavaModelUtil.is18OrHigher(destination.getJavaProject())) {
Arrays.asList(members).stream().filter(e -> e instanceof IMethod).map(IMethod.class::cast)
.filter(IMethod::isLambdaMethod)
.forEach(m -> addError(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_IncompatibleLanguageConstruct,
m, destination));
}
return status;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CreatingChange, 1);
CompilationUnit destinationCompilationUnit = this
.getCompilationUnit(getDestinationInterface().getTypeRoot(), pm);
ASTRewrite destinationRewrite = getASTRewrite(destinationCompilationUnit);
final TextEditBasedChangeManager manager = new TextEditBasedChangeManager();
Iterator<IMethod> methodsToMoveIterator = getMethodsToMoveIterator();
while (methodsToMoveIterator.hasNext()) {
IMethod sourceMethod = methodsToMoveIterator.next();
logInfo("Migrating method: "
+ JavaElementLabels.getElementLabel(sourceMethod, JavaElementLabels.ALL_FULLY_QUALIFIED)
+ " to interface: " + destinationInterface.getFullyQualifiedName());
CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm);
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
sourceCompilationUnit);
logInfo("Source method declaration: " + sourceMethodDeclaration);
// Find the target method.
IMethod targetMethod = getTargetMethod(sourceMethod);
MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod,
destinationCompilationUnit);
// tack on the source method body to the target method.
copyMethodBody(sourceMethodDeclaration, targetMethodDeclaration, destinationRewrite);
// Change the target method to default.
convertToDefault(targetMethodDeclaration, destinationRewrite);
// Remove the source method.
ASTRewrite sourceRewrite = getASTRewrite(sourceCompilationUnit);
removeMethod(sourceMethodDeclaration, sourceRewrite);
// save the source changes.
// TODO: Need to deal with imports
if (!manager.containsChangesIn(sourceMethod.getCompilationUnit()))
manageCompilationUnit(manager, sourceMethod.getCompilationUnit(), sourceRewrite);
}
if (!manager.containsChangesIn(getDestinationInterface().getCompilationUnit()))
manageCompilationUnit(manager, getDestinationInterface().getCompilationUnit(), destinationRewrite);
final Map<String, String> arguments = new HashMap<>();
int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor(
null, "TODO", null, arguments, flags);
return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges());
} finally {
pm.done();
}
}
private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) {
CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root);
if (compilationUnit == null) {
compilationUnit = RefactoringASTParser.parseWithASTProvider(root, false, pm);
this.typeRootToCompilationUnitMap.put(root, compilationUnit);
}
return compilationUnit;
}
private ASTRewrite getASTRewrite(CompilationUnit compilationUnit) {
ASTRewrite rewrite = this.compilationUnitToASTRewriteMap.get(compilationUnit);
if (rewrite == null) {
rewrite = ASTRewrite.create(compilationUnit.getAST());
this.compilationUnitToASTRewriteMap.put(compilationUnit, rewrite);
}
return rewrite;
}
private void manageCompilationUnit(final TextEditBasedChangeManager manager, ICompilationUnit compilationUnit,
ASTRewrite rewrite) throws JavaModelException {
TextEdit edit = rewrite.rewriteAST();
TextChange change = (TextChange) manager.get(compilationUnit);
change.setTextType("java");
if (change.getEdit() == null)
change.setEdit(edit);
else
change.addEdit(edit);
manager.manage(compilationUnit, change);
}
private void copyMethodBody(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration,
ASTRewrite destinationRewrite) {
Block sourceMethodBody = sourceMethodDeclaration.getBody();
Assert.isNotNull(sourceMethodBody, "Source method has a null body.");
ASTNode sourceMethodBodyCopy = ASTNode.copySubtree(destinationRewrite.getAST(), sourceMethodBody);
destinationRewrite.set(targetMethodDeclaration, MethodDeclaration.BODY_PROPERTY, sourceMethodBodyCopy, null);
}
private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
// TODO: Do I need an edit group??
rewrite.remove(methodDeclaration, null);
}
private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
Modifier modifier = rewrite.getAST().newModifier(ModifierKeyword.DEFAULT_KEYWORD);
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.insertLast(modifier, null);
}
/**
* Finds the target (interface) method declaration for the given source
* method.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @return The target method that will be manipulated or null if not found.
*/
private IMethod getTargetMethod(IMethod sourceMethod) {
IMethod[] methods = this.getDestinationInterface().findMethods(sourceMethod);
Assert.isTrue(methods.length <= 1,
"Found multiple target methods for method: " + sourceMethod.getElementName());
if (methods.length == 1)
return methods[0];
else
return null; // not found.
}
private void log(int severity, String message) {
String name = FrameworkUtil.getBundle(this.getClass()).getSymbolicName();
IStatus status = new Status(severity, name, message);
JavaPlugin.log(status);
}
private void logInfo(String message) {
log(IStatus.INFO, message);
}
private void logWarning(String message) {
log(IStatus.WARNING, message);
}
@Override
public String getIdentifier() {
return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID;
}
@Override
public String getProcessorName() {
return Messages.MigrateSkeletalImplementationToInferfaceRefactoring_Name;
}
@Override
public boolean isApplicable() throws CoreException {
return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getMethodsToMove());
}
public IMethod[] getMigratableMembersOfDeclaringType() {
try {
return RefactoringAvailabilityTester.getMigratableSkeletalImplementations(getDeclaringType());
} catch (JavaModelException e) {
return new IMethod[0];
}
}
@Override
protected RefactoringStatus checkConstructorCalls(IType type, IProgressMonitor monitor) throws JavaModelException {
// TODO Auto-generated method stub
return super.checkConstructorCalls(type, monitor);
}
/**
* @return the destinationType
*/
public IType getDestinationInterface() {
return destinationInterface;
}
/**
* Sets the destination interface.
*
* @param destinationInterface
* The destination interface.
* @throws JavaModelException
*/
protected void setDestinationType(IType destinationInterface) throws JavaModelException {
Assert.isNotNull(destinationInterface);
// TODO: Cache type hierarchy?
this.destinationInterface = destinationInterface;
}
/**
* Returns true if the given type is a pure interface, i.e., it is an
* interface but not an annotation.
*
* @param type
* The type to check.
* @return True if the given type is a pure interface and false otherwise.
* @throws JavaModelException
*/
private static boolean isPureInterface(IType type) throws JavaModelException {
return type != null && type.isInterface() && !type.isAnnotation();
}
@Override
protected void rewriteTypeOccurrences(TextEditBasedChangeManager manager, ASTRequestor requestor,
CompilationUnitRewrite rewrite, ICompilationUnit unit, CompilationUnit node, Set<String> replacements,
IProgressMonitor monitor) throws CoreException {
// TODO Auto-generated method stub
}
} |
package edu.cuny.citytech.defaultrefactoring.core.refactorings;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTRequestor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.HierarchyProcessor;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.GroupCategorySet;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEdit;
import org.osgi.framework.FrameworkUtil;
import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor;
import edu.cuny.citytech.defaultrefactoring.core.messages.Messages;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
// TODO: Are we checking the target interface? I think that the target interface should be completely empty for now.
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
@SuppressWarnings({ "restriction" })
public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends HierarchyProcessor {
/**
* The destination interface.
*/
private IType destinationInterface;
private Map<CompilationUnit, ASTRewrite> compilationUnitToASTRewriteMap = new HashMap<>();
private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>();
@SuppressWarnings("unused")
private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet(
new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CategoryName,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CategoryDescription));
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
* @throws JavaModelException
*/
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, boolean layer, IProgressMonitor monitor) throws JavaModelException {
super(methods, settings, layer);
if (methods != null && methods.length > 0) {
IType[] candidateTypes = this.getCandidateTypes(monitor);
if (candidateTypes != null && candidateTypes.length > 0) {
// TODO: For now,
if (candidateTypes.length > 1)
logWarning("Encountered multiple candidate types (" + candidateTypes.length + ").");
this.setDestinationInterface(candidateTypes[0]);
}
}
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, IProgressMonitor monitor) throws JavaModelException {
this(methods, settings, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(IProgressMonitor monitor)
throws JavaModelException {
this(null, null, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException {
this(null, null, false, new NullProgressMonitor());
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getElements() {
return fMembersToMove;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 1);
if (this.fMembersToMove.length == 0)
return RefactoringStatus.createFatalErrorStatus(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodsNotSpecified);
else if (this.fMembersToMove.length > 1) {
// TODO: For now.
return RefactoringStatus.createFatalErrorStatus(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMoreThanOneMethod);
} else {
final RefactoringStatus status = new RefactoringStatus();
status.merge(checkDeclaringType(new SubProgressMonitor(pm, 1)));
if (status.hasFatalError())
return status;
status.merge(checkIfMembersExist());
return status;
}
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
pm.done();
}
}
protected RefactoringStatus checkDestinationInterfaceTargetMethods(Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.subTask("Checking destination interface target methods..."));
// Ensure that target methods are not already default methods.
// For each method to move, add a warning if the associated target
// method is already default.
Iterator<IMethod> iterator = getTargetMethodIterator(Objects::nonNull);
while (iterator.hasNext()) {
final IMethod targetMethod = iterator.next();
final int targetMethodFlags = targetMethod.getFlags();
if (Flags.isDefaultMethod(targetMethodFlags))
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_TargetMethodIsAlreadyDefault,
targetMethod);
monitor.ifPresent(m -> m.worked(1));
}
return status;
}
private Iterator<IMethod> getTargetMethodIterator(Predicate<? super IMethod> filterPredicate) {
return getTargetMethodStream(filterPredicate).iterator();
}
private Stream<IMethod> getTargetMethodStream(Predicate<? super IMethod> filterPredicate) {
return Stream.of(this.getMethodsToMove()).parallel().map(this::getTargetMethod).filter(filterPredicate);
}
protected RefactoringStatus checkDestinationInterfaceOnlyDeclaresTargetMethods(IProgressMonitor monitor)
throws JavaModelException {
final IType targetInterface = this.getDestinationInterface();
Assert.isNotNull(targetInterface);
RefactoringStatus status = new RefactoringStatus();
// TODO: For now, the target interface must only contain the target
// method.
List<IMethod> methodsToMoveList = Arrays.asList(this.getMethodsToMove());
Set<IMethod> methodsToMoveSet = new HashSet<>(methodsToMoveList);
List<IMethod> destinationInterfaceMethodsList = Arrays.asList(targetInterface.getMethods());
Set<IMethod> destinationInterfaceMethodsSet = new HashSet<>(destinationInterfaceMethodsList);
// ensure that all the methods to move have target methods in the target
// interface.
boolean allSourceMethodsHaveTargets;
// if they are different sizes, they can't be the same.
if (methodsToMoveSet.size() != destinationInterfaceMethodsSet.size())
allSourceMethodsHaveTargets = false;
else
// make sure there's a match for each method.
allSourceMethodsHaveTargets = methodsToMoveSet.parallelStream()
// parallel.
.map(this::getTargetMethod) // find the target method in the
// target interface.
.allMatch(Objects::nonNull); // make sure they are all
// there.
if (!allSourceMethodsHaveTargets)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceMustOnlyDeclareTheMethodToMigrate,
targetInterface);
return status;
}
protected RefactoringStatus checkDestinationInterface(IProgressMonitor monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// TODO
final IType destinationInterface = this.getDestinationInterface();
// Can't be null.
if (destinationInterface == null) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoDestinationInterface);
return status;
}
// Must be an interface.
if (!isPureInterface(destinationInterface))
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationTypeMustBePureInterface,
destinationInterface);
// Make sure it exists.
checkExistance(status, destinationInterface,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceDoesNotExist);
// Make sure we can write to it.
checkWritabilitiy(status, destinationInterface,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceNotWritable);
// Make sure it doesn't have compilation errors.
checkStructure(status, destinationInterface);
// TODO: For now, no annotated target interfaces.
if (destinationInterface.getAnnotations().length != 0)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInteraceHasAnnotations,
destinationInterface);
// TODO: For now, only top-level types.
if (destinationInterface.getDeclaringType() != null)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInteraceIsNotTopLevel,
destinationInterface);
// TODO: For now, no fields.
if (destinationInterface.getFields().length != 0)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInteraceDeclaresFields,
destinationInterface);
// TODO: For now, no super interfaces.
if (destinationInterface.getSuperInterfaceNames().length != 0)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInteraceExtendsInterface,
destinationInterface);
// TODO: For now, no type parameters.
if (destinationInterface.getTypeParameters().length != 0)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceDeclaresTypeParameters,
destinationInterface);
// TODO: For now, no member types.
if (destinationInterface.getTypes().length != 0)
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_DestinationInterfaceDeclaresMemberTypes,
destinationInterface);
status.merge(checkDestinationInterfaceOnlyDeclaresTargetMethods(new SubProgressMonitor(monitor, 1)));
status.merge(checkDestinationInterfaceTargetMethods(
Optional.of(new SubProgressMonitor(monitor, this.getTargetMethods().size()))));
return status;
}
private Set<IMethod> getTargetMethods() {
return this.getTargetMethodStream(Objects::nonNull).collect(Collectors.toSet());
}
private void addWarning(RefactoringStatus status, String message) {
addWarning(status, message, null);
}
@Override
protected RefactoringStatus checkDeclaringType(IProgressMonitor monitor) throws JavaModelException {
RefactoringStatus status = super.checkDeclaringType(monitor);
if (!status.hasFatalError()) {
final IType type = getDeclaringType();
if (type.isAnonymous()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInAnonymousTypes, type);
}
// TODO: This is being checked by the super implementation but need
// to revisit. It might be okay to have an enum. In that case, we
// can't call the super method.
// if (type.isEnum()) {
// // TODO for now.
// addWarning(status,
// Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInEnums,
// method);
if (type.isLambda()) {
// TODO for now.
return createFatalError(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInLambdas,
type);
}
if (type.isLocal()) {
// TODO for now.
return createFatalError(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInLocals,
type);
}
if (type.isMember()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInMemberTypes, type);
}
if (!type.isClass()) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodsOnlyInClasses, type);
}
if (type.getAnnotations().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInAnnotatedTypes, type);
}
if (type.getFields().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithFields, type);
}
if (type.getInitializers().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithInitializers,
type);
}
if (type.getMethods().length > 1) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithMoreThanOneMethod,
type);
}
if (type.getTypeParameters().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithTypeParameters,
type);
}
if (type.getTypes().length != 0) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithType, type);
}
if (type.getSuperclassName() != null) {
// TODO for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithSuperType,
type);
}
if (type.getSuperInterfaceNames().length == 0) {
// enclosing type must implement an interface, at least for now,
// which one of which will become the target interface.
// it is probably possible to still perform the refactoring
// without this condition but I believe that this is
// the particular pattern we are targeting.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesThatDontImplementInterfaces,
type);
}
if (type.getSuperInterfaceNames().length > 1) {
// TODO for now. Let's only deal with a single interface as that
// is part of the targeted pattern.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesThatExtendMultipleInterfaces,
type);
}
if (!Flags.isAbstract(type.getFlags())) {
// TODO for now. This follows the target pattern. Maybe we can
// relax this but that would require checking for
// instantiations.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInConcreteTypes, type);
}
if (Flags.isStatic(type.getFlags())) {
// TODO no static types for now.
return createFatalError(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInStaticTypes, type);
}
status.merge(checkDeclaringSuperTypes(monitor));
}
return status;
}
protected RefactoringStatus checkDeclaringSuperTypes(final IProgressMonitor monitor) throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
IType[] interfaces = getCandidateTypes(monitor);
if (interfaces.length == 0) {
IType declaringType = getDeclaringType();
final String msg = MessageFormat.format(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithNoCandidateTargetTypes,
createLabel(declaringType));
return RefactoringStatus.createWarningStatus(msg);
} else if (interfaces.length > 1) {
// TODO For now, let's make sure there's only one candidate type.
IType declaringType = getDeclaringType();
final String msg = MessageFormat.format(
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsInTypesWithMultipleCandidateTargetTypes,
JavaElementLabels.getTextLabel(declaringType, JavaElementLabels.ALL_FULLY_QUALIFIED));
return RefactoringStatus.createWarningStatus(msg);
}
return result;
}
/**
* Returns the possible target interfaces for the migration. NOTE: One
* difference here between this refactoring and pull up is that we can have
* a much more complex type hierarchy due to multiple interface inheritance
* in Java.
*
* TODO: It should be possible to pull up a method into an interface (i.e.,
* "Pull Up Method To Interface") that is not implemented explicitly. For
* example, there may be a skeletal implementation class that implements all
* the target interface's methods without explicitly declaring so.
*
* @param monitor
* A progress monitor.
* @return The possible target interfaces for the migration.
* @throws JavaModelException
* upon Java model problems.
*/
public IType[] getCandidateTypes(final IProgressMonitor monitor) throws JavaModelException {
IType declaringType = getDeclaringType();
IType[] superInterfaces = declaringType.newSupertypeHierarchy(monitor).getAllSuperInterfaces(declaringType);
return Stream.of(superInterfaces).parallel()
.filter(t -> t != null && t.exists() && !t.isReadOnly() && !t.isBinary()).toArray(IType[]::new);
}
protected RefactoringStatus checkMethodsToMove(IProgressMonitor pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
Iterator<IMethod> it = getMethodsToMoveIterator();
while (it.hasNext()) {
IMethod method = it.next();
checkExistance(status, method,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_MethodDoesNotExist);
checkWritabilitiy(status, method,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CantChangeMethod);
checkStructure(status, method);
if (method.isConstructor()) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoConstructors,
method);
}
if (method.getAnnotations().length > 0) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoAnnotations,
method);
}
if (Flags.isStatic(method.getFlags())) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoStaticMethods,
method);
}
if (JdtFlags.isNative(method)) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoNativeMethods,
method);
}
if (method.isLambdaMethod()) {
// TODO for now.
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoLambdaMethods,
method);
}
if (method.getExceptionTypes().length != 0) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsThatThrowExceptions,
method);
}
if (method.getParameters().length != 0) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithParameters,
method);
}
if (!method.getReturnType().equals(Signature.SIG_VOID)) {
// return type must be void.
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithReturnTypes,
method);
}
if (method.getTypeParameters().length != 0) {
// TODO for now but this will be an important one.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithTypeParameters,
method);
}
pm.worked(1);
}
if (!status.hasFatalError())
status.merge(checkMethodsToMoveBodies(new SubProgressMonitor(pm, fMembersToMove.length)));
return status;
} finally {
pm.done();
}
}
private void checkStructure(RefactoringStatus status, IMember member) throws JavaModelException {
if (!member.isStructureKnown()) {
addWarning(status, Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CUContainsCompileErrors,
member.getCompilationUnit());
}
}
private void checkWritabilitiy(RefactoringStatus status, IMember member, String message) {
if (member.isBinary() || member.isReadOnly()) {
addWarning(status, message, member);
}
}
private void checkExistance(RefactoringStatus status, IMember member, String message) {
if (!member.exists()) {
addWarning(status, message, member);
}
}
protected Iterator<IMethod> getMethodsToMoveIterator() {
return Stream.of(fMembersToMove).parallel().filter(m -> m instanceof IMethod).map(m -> (IMethod) m).iterator();
}
protected IMethod[] getMethodsToMove() {
return Stream.of(fMembersToMove).parallel().filter(m -> m instanceof IMethod).map(m -> (IMethod) m)
.toArray(IMethod[]::new);
}
protected RefactoringStatus checkMethodsToMoveBodies(IProgressMonitor pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
Iterator<IMethod> it = this.getMethodsToMoveIterator();
while (it.hasNext()) {
IMethod method = it.next();
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = this.getCompilationUnit(root, new SubProgressMonitor(pm, 1));
MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
@SuppressWarnings("rawtypes")
List statements = body.statements();
if (!statements.isEmpty()) {
// TODO for now.
addWarning(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_NoMethodsWithStatements,
method);
}
}
}
pm.worked(1);
}
return status;
} finally {
pm.done();
}
}
private static void addWarning(RefactoringStatus status, String message, IJavaElement relatedElement) {
if (relatedElement != null) { // workaround
String elementName = JavaElementLabels.getElementLabel(relatedElement,
JavaElementLabels.ALL_FULLY_QUALIFIED);
message = MessageFormat.format(message, elementName);
}
if (relatedElement instanceof IMember) {
IMember member = (IMember) relatedElement;
RefactoringStatusContext context = JavaStatusContext.create(member);
status.addWarning(message, context);
} else
status.addWarning(message);
}
private static void addError(RefactoringStatus status, String message, IMember member, IMember... more) {
List<String> elementNames = new ArrayList<>();
elementNames.add(JavaElementLabels.getElementLabel(member, JavaElementLabels.ALL_FULLY_QUALIFIED));
Stream<String> stream = Arrays.asList(more).parallelStream()
.map(MigrateSkeletalImplementationToInterfaceRefactoringProcessor::createLabel);
Stream<String> concat = Stream.concat(elementNames.stream(), stream);
List<String> collect = concat.collect(Collectors.toList());
status.addError(MessageFormat.format(message, collect.toArray()), JavaStatusContext.create(member));
}
private static RefactoringStatus createFatalError(String message, IType type) {
String elementName = createLabel(type);
return RefactoringStatus.createFatalErrorStatus(MessageFormat.format(message, elementName),
JavaStatusContext.create(type));
}
/**
* Creates a working copy layer if necessary.
*
* @param monitor
* the progress monitor to use
* @return a status describing the outcome of the operation
*/
protected RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
try {
monitor.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 1);
ICompilationUnit unit = getDeclaringType().getCompilationUnit();
if (fLayer)
unit = unit.findWorkingCopy(fOwner);
resetWorkingCopies(unit);
return new RefactoringStatus();
} finally {
monitor.done();
}
}
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context)
throws CoreException, OperationCanceledException {
try {
monitor.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CheckingPreconditions, 12);
clearCaches();
final RefactoringStatus status = new RefactoringStatus();
if (fMembersToMove.length > 0)
status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkMethodsToMove(new SubProgressMonitor(monitor, 1)));
if (status.hasFatalError())
return status;
status.merge(checkDestinationInterface(new SubProgressMonitor(monitor, 1)));
if (status.hasFatalError())
return status;
// if (fMembersToMove.length > 0)
// TODO: Check project compliance.
// status.merge(checkProjectCompliance(
// getCompilationUnitRewrite(compilationUnitRewrites,
// getDeclaringType().getCompilationUnit()),
// getDestinationType(), fMembersToMove));
// TODO: More checks, perhaps resembling those in
// org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor.checkFinalConditions(IProgressMonitor,
// CheckConditionsContext).
return status;
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
monitor.done();
}
}
protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite sourceRewriter, IType destination,
IMember[] members) {
RefactoringStatus status = HierarchyProcessor.checkProjectCompliance(sourceRewriter, destination, members);
if (!JavaModelUtil.is18OrHigher(destination.getJavaProject())) {
Arrays.asList(members).stream().filter(e -> e instanceof IMethod).map(IMethod.class::cast)
.filter(IMethod::isLambdaMethod)
.forEach(m -> addError(status,
Messages.MigrateSkeletalImplementationToInferfaceRefactoring_IncompatibleLanguageConstruct,
m, destination));
}
return status;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.MigrateSkeletalImplementationToInferfaceRefactoring_CreatingChange, 1);
CompilationUnit destinationCompilationUnit = this
.getCompilationUnit(getDestinationInterface().getTypeRoot(), pm);
ASTRewrite destinationRewrite = getASTRewrite(destinationCompilationUnit);
final TextEditBasedChangeManager manager = new TextEditBasedChangeManager();
Iterator<IMethod> methodsToMoveIterator = getMethodsToMoveIterator();
while (methodsToMoveIterator.hasNext()) {
IMethod sourceMethod = methodsToMoveIterator.next();
logInfo("Migrating method: "
+ JavaElementLabels.getElementLabel(sourceMethod, JavaElementLabels.ALL_FULLY_QUALIFIED)
+ " to interface: " + destinationInterface.getFullyQualifiedName());
CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm);
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
sourceCompilationUnit);
logInfo("Source method declaration: " + sourceMethodDeclaration);
// Find the target method.
IMethod targetMethod = getTargetMethod(sourceMethod);
MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod,
destinationCompilationUnit);
// tack on the source method body to the target method.
copyMethodBody(sourceMethodDeclaration, targetMethodDeclaration, destinationRewrite);
// Change the target method to default.
convertToDefault(targetMethodDeclaration, destinationRewrite);
// Remove the source method.
ASTRewrite sourceRewrite = getASTRewrite(sourceCompilationUnit);
removeMethod(sourceMethodDeclaration, sourceRewrite);
// save the source changes.
// TODO: Need to deal with imports
if (!manager.containsChangesIn(sourceMethod.getCompilationUnit()))
manageCompilationUnit(manager, sourceMethod.getCompilationUnit(), sourceRewrite);
}
if (!manager.containsChangesIn(getDestinationInterface().getCompilationUnit()))
manageCompilationUnit(manager, getDestinationInterface().getCompilationUnit(), destinationRewrite);
final Map<String, String> arguments = new HashMap<>();
int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor(
null, "TODO", null, arguments, flags);
return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges());
} finally {
pm.done();
}
}
private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) {
CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root);
if (compilationUnit == null) {
compilationUnit = RefactoringASTParser.parseWithASTProvider(root, false, pm);
this.typeRootToCompilationUnitMap.put(root, compilationUnit);
}
return compilationUnit;
}
private ASTRewrite getASTRewrite(CompilationUnit compilationUnit) {
ASTRewrite rewrite = this.compilationUnitToASTRewriteMap.get(compilationUnit);
if (rewrite == null) {
rewrite = ASTRewrite.create(compilationUnit.getAST());
this.compilationUnitToASTRewriteMap.put(compilationUnit, rewrite);
}
return rewrite;
}
private void manageCompilationUnit(final TextEditBasedChangeManager manager, ICompilationUnit compilationUnit,
ASTRewrite rewrite) throws JavaModelException {
TextEdit edit = rewrite.rewriteAST();
TextChange change = (TextChange) manager.get(compilationUnit);
change.setTextType("java");
if (change.getEdit() == null)
change.setEdit(edit);
else
change.addEdit(edit);
manager.manage(compilationUnit, change);
}
private void copyMethodBody(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration,
ASTRewrite destinationRewrite) {
Block sourceMethodBody = sourceMethodDeclaration.getBody();
Assert.isNotNull(sourceMethodBody, "Source method has a null body.");
ASTNode sourceMethodBodyCopy = ASTNode.copySubtree(destinationRewrite.getAST(), sourceMethodBody);
destinationRewrite.set(targetMethodDeclaration, MethodDeclaration.BODY_PROPERTY, sourceMethodBodyCopy, null);
}
private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
// TODO: Do I need an edit group??
rewrite.remove(methodDeclaration, null);
}
private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
Modifier modifier = rewrite.getAST().newModifier(ModifierKeyword.DEFAULT_KEYWORD);
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.insertLast(modifier, null);
}
/**
* Finds the target (interface) method declaration for the given source
* method.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @return The target method that will be manipulated or null if not found.
*/
private IMethod getTargetMethod(IMethod sourceMethod) {
// TODO: Should somehow cache this.
final IType targetInterface = this.getDestinationInterface();
if (targetInterface == null)
return null; // not found.
IMethod[] methods = targetInterface.findMethods(sourceMethod);
if (methods == null)
return null; // not found.
Assert.isTrue(methods.length <= 1,
"Found multiple target methods for method: " + sourceMethod.getElementName());
if (methods.length == 1)
return methods[0];
else
return null; // not found.
}
private void log(int severity, String message) {
String name = FrameworkUtil.getBundle(this.getClass()).getSymbolicName();
IStatus status = new Status(severity, name, message);
JavaPlugin.log(status);
}
private void logInfo(String message) {
log(IStatus.INFO, message);
}
private void logWarning(String message) {
log(IStatus.WARNING, message);
}
@Override
public String getIdentifier() {
return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID;
}
@Override
public String getProcessorName() {
return Messages.MigrateSkeletalImplementationToInferfaceRefactoring_Name;
}
@Override
public boolean isApplicable() throws CoreException {
return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getMethodsToMove());
}
public IMethod[] getMigratableMembersOfDeclaringType() {
try {
return RefactoringAvailabilityTester.getMigratableSkeletalImplementations(getDeclaringType());
} catch (JavaModelException e) {
return new IMethod[0];
}
}
@Override
protected RefactoringStatus checkConstructorCalls(IType type, IProgressMonitor monitor) throws JavaModelException {
// TODO Auto-generated method stub
return super.checkConstructorCalls(type, monitor);
}
/**
* @return the destinationType
*/
public IType getDestinationInterface() {
return destinationInterface;
}
/**
* Sets the destination interface.
*
* @param destinationInterface
* The destination interface.
* @throws JavaModelException
*/
protected void setDestinationInterface(IType destinationInterface) throws JavaModelException {
Assert.isNotNull(destinationInterface);
this.destinationInterface = destinationInterface;
}
/**
* Returns true if the given type is a pure interface, i.e., it is an
* interface but not an annotation.
*
* @param type
* The type to check.
* @return True if the given type is a pure interface and false otherwise.
* @throws JavaModelException
*/
private static boolean isPureInterface(IType type) throws JavaModelException {
return type != null && type.isInterface() && !type.isAnnotation();
}
@Override
protected void rewriteTypeOccurrences(TextEditBasedChangeManager manager, ASTRequestor requestor,
CompilationUnitRewrite rewrite, ICompilationUnit unit, CompilationUnit node, Set<String> replacements,
IProgressMonitor monitor) throws CoreException {
// TODO Auto-generated method stub
}
} |
package org.carewebframework.security.spring.mock;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.carewebframework.api.security.ISecurityDomain;
import org.carewebframework.api.spring.SpringUtil;
import org.carewebframework.security.spring.AbstractSecurityService;
import org.carewebframework.security.spring.Constants;
import org.zkoss.util.resource.Labels;
/**
* Mock Spring-based service implementation.
*/
public class MockSecurityService extends AbstractSecurityService {
private final List<ISecurityDomain> securityDomains = new ArrayList<ISecurityDomain>();
/**
* Validates the current user's password.
*
* @param password The password
* @return True if the password is valid.
*/
@Override
public boolean validatePassword(final String password) {
return password.equals(SpringUtil.getProperty("mock.password"));
}
/**
* Generates a new random password Length of password dictated by
* {@link Constants#LBL_PASSWORD_RANDOM_CHARACTER_LENGTH}
*
* @return String The generated password
*/
@Override
public String generateRandomPassword() {
int len = NumberUtils.toInt(Labels.getLabel(Constants.LBL_PASSWORD_RANDOM_CHARACTER_LENGTH), 12);
return RandomStringUtils.random(len);
}
/**
* Changes the user's password.
*
* @param oldPassword Current password.
* @param newPassword New password.
* @return Null or empty if succeeded. Otherwise, displayable reason why change failed.
*/
@Override
public String changePassword(final String oldPassword, final String newPassword) {
return "Operation not supported";
}
/**
* Return login disabled message.
*/
@Override
public String loginDisabled() {
return null;
}
@Override
public List<ISecurityDomain> getSecurityDomains() {
return securityDomains;
}
public void setSecurityDomain(ISecurityDomain securityDomain) {
securityDomains.add(securityDomain);
}
} |
package org.xwiki.wiki.internal.descriptor.document;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.sheet.SheetBinder;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.internal.mandatory.AbstractMandatoryDocumentInitializer;
import com.xpn.xwiki.objects.classes.BaseClass;
/**
* Update the XWiki.XWikiServerClass document with all required information.
*
* @version $Id$
* @since 5.0M2
*/
@Component
@Named("XWiki.XWikiServerClass")
@Singleton
public class XWikiServerClassDocumentInitializer extends AbstractMandatoryDocumentInitializer
{
/**
* The name of the mandatory document.
*/
public static final String DOCUMENT_NAME = "XWikiServerClass";
/**
* Reference to the server class.
*/
public static final EntityReference SERVER_CLASS = new EntityReference(DOCUMENT_NAME, EntityType.DOCUMENT,
new EntityReference(XWiki.SYSTEM_SPACE, EntityType.SPACE));
/**
* Default list separators of XWiki.XWikiServerClass fields.
*/
public static final String DEFAULT_FIELDS_SEPARATOR = "|";
/**
* Name of field <code>prettyname</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_WIKIPRETTYNAME = "wikiprettyname";
/**
* Pretty name of field <code>prettyname</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_WIKIPRETTYNAME = "Wiki pretty name";
/**
* Name of field <code>owner</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_OWNER = "owner";
/**
* Pretty name of field <code>owner</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_OWNER = "Owner";
/**
* Name of field <code>description</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_DESCRIPTION = "description";
/**
* Pretty name of field <code>description</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_DESCRIPTION = "Description";
/**
* Name of field <code>server</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_SERVER = "server";
/**
* Pretty name of field <code>server</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_SERVER = "Server";
/**
* Name of field <code>visibility</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_VISIBILITY = "visibility";
/**
* First possible values for <code>visibility</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_VISIBILITY_PUBLIC = "public";
/**
* Second possible values for <code>visibility</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_VISIBILITY_PRIVATE = "private";
/**
* List of possible values for <code>visibility</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_VISIBILITY = FIELDL_VISIBILITY_PUBLIC + DEFAULT_FIELDS_SEPARATOR
+ FIELDL_VISIBILITY_PRIVATE + DEFAULT_FIELDS_SEPARATOR;
/**
* Pretty name of field <code>visibility</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_VISIBILITY = "Visibility";
/**
* Name of field <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_STATE = "state";
/**
* First possible values for <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_STATE_ACTIVE = "active";
/**
* Second possible values for <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_STATE_INACTIVE = "inactive";
/**
* Third possible values for <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_STATE_LOCKED = "locked";
/**
* List of possible values for <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_STATE = FIELDL_STATE_ACTIVE + DEFAULT_FIELDS_SEPARATOR + FIELDL_STATE_INACTIVE
+ DEFAULT_FIELDS_SEPARATOR + FIELDL_STATE_LOCKED;
/**
* Pretty name of field <code>state</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_STATE = "State";
/**
* Name of field <code>language</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_LANGUAGE = "language";
/**
* List of possible values for <code>language</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDL_LANGUAGE = "en|fr";
/**
* Pretty name of field <code>language</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_LANGUAGE = "Language";
/**
* Name of field <code>secure</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_SECURE = "secure";
/**
* Pretty name of field <code>secure</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_SECURE = "Secure";
/**
* Display type of field <code>secure</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDDT_SECURE = "checkbox";
/**
* Default value of field <code>secure</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final Boolean DEFAULT_SECURE = Boolean.FALSE;
/**
* Name of field <code>homepage</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELD_HOMEPAGE = "homepage";
/**
* Pretty name of field <code>homepage</code> for the XWiki class XWiki.XWikiServerClass.
*/
public static final String FIELDPN_HOMEPAGE = "Home page";
/**
* Used to bind a class to a document sheet.
*/
@Inject
@Named("class")
private SheetBinder classSheetBinder;
/**
* Used to access current XWikiContext.
*/
@Inject
private Provider<XWikiContext> xcontextProvider;
/**
* Overriding the abstract class' private reference.
*/
private DocumentReference reference;
/**
* Default constructor.
*/
public XWikiServerClassDocumentInitializer()
{
// Since we can`t get the main wiki here, this is just to be able to use the Abstract class.
// getDocumentReference() returns the actual main wiki document reference.
super(XWiki.SYSTEM_SPACE, DOCUMENT_NAME);
}
/**
* Initialize and return the main wiki's class document reference.
*
* @return {@inheritDoc}
*/
@Override
public EntityReference getDocumentReference()
{
if (this.reference == null) {
synchronized (this) {
if (this.reference == null) {
String mainWikiName = xcontextProvider.get().getMainXWiki();
this.reference = new DocumentReference(mainWikiName, XWiki.SYSTEM_SPACE, DOCUMENT_NAME);
}
}
}
return this.reference;
}
@Override
public boolean updateDocument(XWikiDocument document)
{
boolean needsUpdate = false;
// Add missing class fields
BaseClass baseClass = document.getXClass();
needsUpdate |= baseClass.addTextField(FIELD_WIKIPRETTYNAME, FIELDPN_WIKIPRETTYNAME, 30);
needsUpdate |= baseClass.addUsersField(FIELD_OWNER, FIELDPN_OWNER, false);
needsUpdate |= baseClass.addTextAreaField(FIELD_DESCRIPTION, FIELDPN_DESCRIPTION, 40, 5);
needsUpdate |= baseClass.addTextField(FIELD_SERVER, FIELDPN_SERVER, 30);
needsUpdate |= baseClass.addStaticListField(FIELD_VISIBILITY, FIELDPN_VISIBILITY, FIELDL_VISIBILITY);
needsUpdate |= baseClass.addStaticListField(FIELD_STATE, FIELDPN_STATE, FIELDL_STATE);
needsUpdate |= baseClass.addStaticListField(FIELD_LANGUAGE, FIELDPN_LANGUAGE, FIELDL_LANGUAGE);
needsUpdate |= baseClass.addBooleanField(FIELD_SECURE, FIELDPN_SECURE, FIELDDT_SECURE);
needsUpdate |= updateBooleanClassDefaultValue(baseClass, FIELD_SECURE, DEFAULT_SECURE);
needsUpdate |= baseClass.addTextField(FIELD_HOMEPAGE, FIELDPN_HOMEPAGE, 30);
// Add missing document fields
needsUpdate |= setClassDocumentFields(document, "XWiki Server Class");
// Use XWikiServerClassSheet to display documents having XWikiServerClass objects if no other class sheet is
// specified.
if (this.classSheetBinder.getSheets(document).isEmpty()) {
String wikiName = document.getDocumentReference().getWikiReference().getName();
DocumentReference sheet = new DocumentReference(wikiName, XWiki.SYSTEM_SPACE, "XWikiServerClassSheet");
needsUpdate |= this.classSheetBinder.bind(document, sheet);
}
return needsUpdate;
}
} |
package edu.cuny.citytech.defaultrefactoring.eval.handlers;
import static com.google.common.io.Files.touch;
import static edu.cuny.citytech.defaultrefactoring.core.utils.Util.createMigrateSkeletalImplementationToInterfaceRefactoringProcessor;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring;
import org.osgi.framework.FrameworkUtil;
import edu.cuny.citytech.defaultrefactoring.core.refactorings.MigrateSkeletalImplementationToInterfaceRefactoringProcessor;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
import edu.cuny.citytech.defaultrefactoring.core.utils.TimeCollector;
import edu.cuny.citytech.defaultrefactoring.eval.utils.Util;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class EvaluateMigrateSkeletalImplementationToInterfaceRefactoringHandler extends AbstractHandler {
private static final boolean ALLOW_CONCRETE_CLASSES = true;
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Job.create("Evaluating Migrate Skeletal Implementation to Interface Refactoring ...", monitor -> {
CSVPrinter resultsPrinter = null;
CSVPrinter candidateMethodPrinter = null;
CSVPrinter migratableMethodPrinter = null;
CSVPrinter unmigratableMethodPrinter = null;
CSVPrinter errorPrinter = null;
try {
IJavaProject[] javaProjects = Util.getSelectedJavaProjectsFromEvent(event);
resultsPrinter = createCSVPrinter("results.csv",
new String[] { "subject", "#methods", "#migration available methods", "#migratable methods",
"#failed preconditions", "#methods after refactoring", "time (s)" });
candidateMethodPrinter = createCSVPrinter("candidate_methods.csv",
new String[] { "method", "type FQN" });
migratableMethodPrinter = createCSVPrinter("migratable_methods.csv",
new String[] { "subject", "method", "type FQN", "destination interface FQN" });
unmigratableMethodPrinter = createCSVPrinter("unmigratable_methods.csv",
new String[] { "subject", "method", "type FQN", "destination interface FQN" });
errorPrinter = createCSVPrinter("failed_preconditions.csv",
new String[] { "method", "type FQN", "destination interface FQN", "code", "message" });
for (IJavaProject javaProject : javaProjects) {
if (!javaProject.isStructureKnown())
throw new IllegalStateException(
String.format("Project: %s should compile beforehand.", javaProject.getElementName()));
resultsPrinter.print(javaProject.getElementName());
/*
* TODO: We probably need to filter these. Actually, we
* could use the initial precondition check for filtering (I
* think) but there's enough TODOs in there that it's not
* possible right now.
*/
Set<IMethod> allMethods = getAllMethods(javaProject);
resultsPrinter.print(allMethods.size());
Set<IMethod> interfaceMigrationAvailableMethods = new HashSet<IMethod>();
TimeCollector resultsTimeCollector = new TimeCollector();
// TODO: Remove this and just clear caches after this call?
resultsTimeCollector.start();
for (IMethod method : allMethods)
if (RefactoringAvailabilityTester.isInterfaceMigrationAvailable(method, ALLOW_CONCRETE_CLASSES,
Optional.of(monitor)))
interfaceMigrationAvailableMethods.add(method);
resultsTimeCollector.stop();
resultsPrinter.print(interfaceMigrationAvailableMethods.size());
// candidate methods.
for (IMethod method : interfaceMigrationAvailableMethods) {
candidateMethodPrinter.printRecord(Util.getMethodIdentifier(method),
method.getDeclaringType().getFullyQualifiedName());
}
resultsTimeCollector.start();
MigrateSkeletalImplementationToInterfaceRefactoringProcessor processor = createMigrateSkeletalImplementationToInterfaceRefactoringProcessor(
javaProject, interfaceMigrationAvailableMethods.toArray(
new IMethod[interfaceMigrationAvailableMethods.size()]),
Optional.of(monitor));
resultsTimeCollector.stop();
System.out.println(
"Original methods before preconditions: " + interfaceMigrationAvailableMethods.size());
System.out.println("Source methods before preconditions: " + processor.getSourceMethods().size());
System.out.println(
"Unmigratable methods before preconditions: " + processor.getUnmigratableMethods().size());
System.out.println(
"Migratable methods before preconditions: " + processor.getMigratableMethods().size());
// run the precondition checking.
resultsTimeCollector.start();
ProcessorBasedRefactoring processorBasedRefactoring = new ProcessorBasedRefactoring(processor);
RefactoringStatus status = processorBasedRefactoring.checkAllConditions(new NullProgressMonitor());
resultsTimeCollector.stop();
System.out.println(
"Original methods after preconditions: " + interfaceMigrationAvailableMethods.size());
System.out.println("Source methods after preconditions: " + processor.getSourceMethods().size());
File file = new File("source.txt");
touch(file);
Files.write(
file.toPath(), processor.getSourceMethods().parallelStream()
.map(m -> m.getHandleIdentifier()).collect(Collectors.toSet()),
StandardOpenOption.APPEND);
System.out.println(
"Unmigratable methods after preconditions: " + processor.getUnmigratableMethods().size());
file = new File("unmigratable.txt");
touch(file);
Files.write(
file.toPath(), processor.getUnmigratableMethods().parallelStream()
.map(m -> m.getHandleIdentifier()).collect(Collectors.toSet()),
StandardOpenOption.APPEND);
System.out.println(
"Migratable methods after preconditions: " + processor.getMigratableMethods().size());
file = new File("migratable.txt");
touch(file);
Files.write(
file.toPath(), processor.getMigratableMethods().parallelStream()
.map(m -> m.getHandleIdentifier()).collect(Collectors.toSet()),
StandardOpenOption.APPEND);
// passed methods.
resultsPrinter.print(processor.getMigratableMethods().size()); // number.
for (IMethod method : processor.getMigratableMethods()) {
migratableMethodPrinter.printRecord(javaProject.getElementName(),
Util.getMethodIdentifier(method), method.getDeclaringType().getFullyQualifiedName(),
getDestinationTypeFullyQualifiedName(method, monitor));
}
// failed methods.
for (IMethod method : processor.getUnmigratableMethods()) {
unmigratableMethodPrinter.printRecord(javaProject.getElementName(),
Util.getMethodIdentifier(method), method.getDeclaringType().getFullyQualifiedName(),
getDestinationTypeFullyQualifiedName(method, monitor));
}
// failed preconditions.
resultsPrinter.print(status.getEntries().length); // number.
for (RefactoringStatusEntry entry : status.getEntries()) {
if (!entry.isFatalError()) {
Object correspondingElement = entry.getData();
if (!(correspondingElement instanceof IMethod))
throw new IllegalStateException("The element: " + correspondingElement
+ " corresponding to a failed precondition is not a method. Instead, it is a: "
+ correspondingElement.getClass());
IMethod failedMethod = (IMethod) correspondingElement;
errorPrinter.printRecord(Util.getMethodIdentifier(failedMethod),
failedMethod.getDeclaringType().getFullyQualifiedName(),
getDestinationTypeFullyQualifiedName(failedMethod, monitor), entry.getCode(),
entry.getMessage());
}
}
// actually perform the refactoring if there are no fatal
// errors.
if (!status.hasFatalError()) {
resultsTimeCollector.start();
Change change = processorBasedRefactoring
.createChange(new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN));
change.perform(new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN));
resultsTimeCollector.stop();
}
// ensure that we can build the project.
if (!javaProject.isConsistent())
javaProject.makeConsistent(new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN));
if (!javaProject.isStructureKnown())
throw new IllegalStateException(String.format("Project: %s should compile after refactoring.",
javaProject.getElementName()));
// TODO: Count warnings?
// count the new number of methods.
resultsPrinter.print(getAllMethods(javaProject).size());
// overall results time.
resultsPrinter.print((resultsTimeCollector.getCollectedTime()
- processor.getExcludedTimeCollector().getCollectedTime()) / 1000.0);
// end the record.
resultsPrinter.println();
}
} catch (Exception e) {
return new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
"Encountered exception during evaluation", e);
} finally {
try {
// closing the files writer after done writing
if (resultsPrinter != null)
resultsPrinter.close();
if (candidateMethodPrinter != null)
candidateMethodPrinter.close();
if (migratableMethodPrinter != null)
migratableMethodPrinter.close();
if (unmigratableMethodPrinter != null)
unmigratableMethodPrinter.close();
if (errorPrinter != null)
errorPrinter.close();
} catch (IOException e) {
return new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
"Encountered exception during file closing", e);
}
}
return new Status(IStatus.OK, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
"Evaluation successful.");
}).schedule();
return null;
}
private static String getDestinationTypeFullyQualifiedName(IMethod method, IProgressMonitor monitor)
throws JavaModelException {
return MigrateSkeletalImplementationToInterfaceRefactoringProcessor
.getTargetMethod(method, Optional.of(monitor)).getDeclaringType().getFullyQualifiedName();
}
private static Set<IMethod> getAllMethods(IJavaProject javaProject) throws JavaModelException {
Set<IMethod> methods = new HashSet<>();
// collect all methods from this project.
IPackageFragment[] packageFragments = javaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
IType[] allTypes = iCompilationUnit.getAllTypes();
for (IType type : allTypes) {
Collections.addAll(methods, type.getMethods());
}
}
}
return methods;
}
private static CSVPrinter createCSVPrinter(String fileName, String[] header) throws IOException {
return new CSVPrinter(new FileWriter(fileName, true), CSVFormat.EXCEL.withHeader(header));
}
} |
package eu.e43.impeller.content;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
import eu.e43.impeller.R;
import eu.e43.impeller.Utils;
public class PumpContentProvider extends ContentProvider {
public static final String AUTHORITY = "eu.e43.impeller.content";
public static final String URL = "content://eu.e43.impeller.content";
public static final String FEED_URL = "content://eu.e43.impeller.content/feed";
public static final String ACTIVITY_URL = "content://eu.e43.impeller.content/activity";
public static final String OBJECT_URL = "content://eu.e43.impeller.content/object";
private static final String TAG = "PumpContentProvider";
private static final UriMatcher ms_uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final Map<String,String> ms_objectProjection
= new HashMap<String, String>();
private static final Map<String, String> ms_activityProjection
= new HashMap<String, String>();
private static final Map<String, String> ms_feedProjection
= new HashMap<String, String>();
private SQLiteDatabase m_database;
/* URIs */
private static final int OBJECTS = 1;
private static final int OBJECT = 2;
private static final int ACTIVITIES = 3;
private static final int ACTIVITY = 4;
private static final int FEED = 5;
private static void addStateProjections(Map<String, String> proj, String idField) {
proj.put("replies", "(SELECT COUNT(*) from objects as _rob WHERE _rob.inReplyTo=" + idField +")");
proj.put("likes", "(SELECT COUNT(*) from activities as _lac WHERE _lac.object=" + idField + " AND _lac.verb IN ('like', 'favorite'))");
proj.put("shares", "(SELECT COUNT(*) from activities as _sac WHERE _sac.object=" + idField + " AND _sac.verb='share')");
}
static {
ms_uriMatcher.addURI(AUTHORITY, "object", OBJECTS);
/** Ensure the object is in the database */ |
package flatgui.core.websocket;
import flatgui.core.FGHostStateEvent;
import flatgui.core.FGWebContainerWrapper;
import flatgui.core.IFGContainer;
import flatgui.core.IFGTemplate;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.function.Consumer;
/**
* @author Denis Lebedev
*/
public class FGContainerWebSocket implements WebSocketListener
{
private final FGContainerSessionHolder sessionHolder_;
// TODO have some template provider instead
private final IFGTemplate template_;
private final Consumer<IFGContainer> containerConsumer_;
private volatile Session session_;
private volatile FGWebContainerWrapper container_;
private volatile FGInputEventDecoder parser_;
private volatile FGContainerSession fgSession_;
public FGContainerWebSocket(IFGTemplate template, FGContainerSessionHolder sessionHolder)
{
this (template, sessionHolder, null);
}
public FGContainerWebSocket(IFGTemplate template, FGContainerSessionHolder sessionHolder, Consumer<IFGContainer> containerConsumer)
{
template_ = template;
sessionHolder_ = sessionHolder;
containerConsumer_ = containerConsumer;
FGAppServer.getFGLogger().info("WS Listener created " + System.identityHashCode(this));
}
@Override
public void onWebSocketClose(int statusCode, String reason)
{
FGAppServer.getFGLogger().info("WS Connect " + System.identityHashCode(this) +
" session: " + fgSession_ +
" remote: " + session_.getRemoteAddress() +
" reason = " + reason);
container_.unInitialize();
fgSession_.markIdle();
session_ = null;
}
@Override
public void onWebSocketConnect(Session session)
{
session_ = session;
StringBuilder statusMessage = new StringBuilder("Creating session...");
setTextToRemote(statusMessage.toString());
fgSession_ = sessionHolder_.getSession(template_, session_.getRemoteAddress().getAddress());
statusMessage.append("|created session");
setTextToRemote(statusMessage.toString());
FGAppServer.getFGLogger().info("WS Connect " + System.identityHashCode(this) +
" session: " + fgSession_ +
" remote: " + session.getRemoteAddress());
container_ = fgSession_.getContainer();
statusMessage.append("|created app");
setTextToRemote(statusMessage.toString());
container_.initialize();
if (containerConsumer_ != null)
{
containerConsumer_.accept(container_.getContainer());
}
statusMessage.append("|initialized app");
setTextToRemote(statusMessage.toString());
parser_ = fgSession_.getParser();
statusMessage.append("|retrieving initial state...");
setTextToRemote(statusMessage.toString());
container_.resetCache();
collectAndSendResponse(false);
}
@Override
public void onWebSocketError(Throwable cause)
{
FGAppServer.getFGLogger().error(fgSession_ + " WS error: " + cause.getMessage());
}
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len)
{
//logger_.debug("Received message #" + debugMessageCount_ + ": " + message);
fgSession_.markAccesed();
Object e = parser_.getInputEvent(new FGInputEventDecoder.BinaryInput(payload, offset, len));
processInputEvent(e);
}
@Override
public void onWebSocketText(String message)
{
//logger_.debug("Received message #" + debugMessageCount_ + ": " + message);
}
private void processInputEvent(Object e)
{
if (e == null)
{
//logger_.debug("Processed message #" + debugMessageCount_ + ": not an input event.");
//debugMessageCount_++;
return;
}
// Feed input event received from the remote endpoint to the engine
container_.feedEvent(e);
// TODO Do not send response if new event is coming?
collectAndSendResponse(e instanceof FGHostStateEvent);
//debugMessageCount_++;
}
private void collectAndSendResponse(boolean forceRepaint)
{
Collection<ByteBuffer> response = container_.getResponseForClient();
if (response.size() > 0)
{
response.forEach(this::sendBytesToRemote);
sendBytesToRemote(ByteBuffer.wrap(new byte[]{FGWebContainerWrapper.REPAINT_CACHED_COMMAND_CODE}));
//logger_.debug("Finished sending " + response.size() + " responses and repaint cmd for #" + debugMessageCount_);
}
else if (forceRepaint)
{
sendBytesToRemote(ByteBuffer.wrap(new byte[]{FGWebContainerWrapper.REPAINT_CACHED_COMMAND_CODE}));
}
}
private void sendBytesToRemote(ByteBuffer bytes)
{
try
{
session_.getRemote().sendBytes(bytes);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
private void setTextToRemote(String text)
{
try
{
session_.getRemote().sendString(text);
}
catch (IOException e)
{
e.printStackTrace();
}
}
} |
package ifc.awt;
import lib.MultiPropertyTest;
import util.utils;
/**
* Testing <code>com.sun.star.awt.UnoControlScrollBarModel</code>
* service properties :
* <ul>
* <li><code> BlockIncrement</code></li>
* <li><code> Border</code></li>
* <li><code> DefaultControl</code></li>
* <li><code> Enabled</code></li>
* <li><code> HelpText</code></li>
* <li><code> HelpURL</code></li>
* <li><code> LineIncrement</code></li>
* <li><code> Orientation</code></li>
* <li><code> Printable</code></li>
* <li><code> ScrollValue</code></li>
* <li><code> ScrollValueMax</code></li>
* <li><code> VisibleSize</code></li>
* </ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.awt.UnoControlScrollBarModel
*/
public class _UnoControlScrollBarModel extends MultiPropertyTest {
/**
* This property can be VOID, and in case if it is so new
* value must defined.
*/
public void _BackgroundColor() {
testProperty("BackgroundColor", new PropertyTester() {
protected Object getNewValue(String p, Object old) {
return utils.isVoid(old) ? new Integer(32768) : null ;
}
}) ;
}
/**
* This property can be VOID, and in case if it is so new
* value must defined.
*/
public void _BorderColor() {
testProperty("BorderColor", new PropertyTester() {
protected Object getNewValue(String p, Object old) {
return utils.isVoid(old) ? new Integer(1234) : null ;
}
}) ;
}
/**
* This property can be VOID, and in case if it is so new
* value must defined.
*/
public void _SymbolColor() {
testProperty("SymbolColor", new PropertyTester() {
protected Object getNewValue(String p, Object old) {
return utils.isVoid(old) ? new Integer(65324) : null ;
}
}) ;
}
/**
* This property can be VOID, and in case if it is so new
* value must defined.
*/
public void _ScrollValue() {
testProperty("ScrollValue", new PropertyTester() {
protected Object getNewValue(String p, Object old) {
return utils.isVoid(old) ? new Integer(10) : new Integer(15) ;
}
}) ;
}
/**
* This property can be VOID, and in case if it is so new
* value must defined.
*/
public void _VisibleSize() {
testProperty("VisibleSize", new PropertyTester() {
protected Object getNewValue(String p, Object old) {
return utils.isVoid(old) ? new Integer(10) : null ;
}
}) ;
}
} |
package org.xwiki.observation.remote.internal.jgroups;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.observation.remote.RemoteEventData;
import org.xwiki.observation.remote.RemoteObservationManager;
/**
* Default implementation of JGroupsReceiver. Receive remote events and send them as is to
* {@link RemoteObservationManager} to be converted and injected as local events.
*
* @version $Id$
* @since 2.0M3
*/
@Component
@Singleton
public class DefaultJGroupsReceiver extends ReceiverAdapter
{
/**
* Used to send events for conversion.
*/
private RemoteObservationManager remoteObservationManager;
/**
* Used to lookup {@link RemoteObservationManager}. To avoid cross-dependency issues.
*/
@Inject
private ComponentManager componentManager;
/**
* The logger to log.
*/
@Inject
private Logger logger;
/**
* @return the RemoteObservationManager
*/
public RemoteObservationManager getRemoteObservationManager()
{
if (this.remoteObservationManager == null) {
try {
this.remoteObservationManager = componentManager.lookup(RemoteObservationManager.class);
} catch (ComponentLookupException e) {
this.logger.error("Failed to lookup the Remote Observation Manager.", e);
}
}
return remoteObservationManager;
}
/**
* {@inheritDoc}
*
* @see org.jgroups.MessageListener#receive(org.jgroups.Message)
*/
public void receive(Message msg)
{
RemoteEventData remoteEvent = (RemoteEventData) msg.getObject();
this.logger.debug("Received JGroups remote event [" + remoteEvent + "]");
getRemoteObservationManager().notify(remoteEvent);
}
} |
package io.quarkus.smallrye.reactivemessaging.kafka.deployment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.config.ConfigValue;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.MethodParameterInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Consume;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
import io.quarkus.deployment.builditem.RunTimeConfigurationDefaultBuildItem;
import io.quarkus.deployment.builditem.RuntimeConfigSetupCompleteBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.logging.LogCleanupFilterBuildItem;
import io.quarkus.smallrye.reactivemessaging.deployment.items.ConnectorManagedChannelBuildItem;
import io.quarkus.smallrye.reactivemessaging.kafka.ReactiveMessagingKafkaConfig;
import io.smallrye.mutiny.tuples.Functions.TriConsumer;
import io.vertx.kafka.client.consumer.impl.KafkaReadStreamImpl;
public class SmallRyeReactiveMessagingKafkaProcessor {
private static final Logger LOGGER = Logger.getLogger("io.quarkus.smallrye-reactive-messaging-kafka.deployment.processor");
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.SMALLRYE_REACTIVE_MESSAGING_KAFKA);
}
@BuildStep
public void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
// Required for the throttled commit strategy
reflectiveClass.produce(
ReflectiveClassBuildItem.builder(KafkaReadStreamImpl.class)
.fields(true)
.methods(true)
.constructors(true)
.finalFieldsWritable(true)
.build());
}
@BuildStep
public void ignoreDuplicateJmxRegistrationInDevAndTestModes(LaunchModeBuildItem launchMode,
BuildProducer<LogCleanupFilterBuildItem> log) {
if (launchMode.getLaunchMode().isDevOrTest()) {
log.produce(new LogCleanupFilterBuildItem(
"org.apache.kafka.common.utils.AppInfoParser",
"Error registering AppInfo mbean"));
}
}
/**
* Handles the serializer/deserializer detection and whether the graceful shutdown should be used in dev mode.
*/
@BuildStep
public void defaultChannelConfiguration(
LaunchModeBuildItem launchMode,
ReactiveMessagingKafkaBuildTimeConfig buildTimeConfig,
ReactiveMessagingKafkaConfig runtimeConfig,
CombinedIndexBuildItem combinedIndex,
List<ConnectorManagedChannelBuildItem> channelsManagedByConnectors,
BuildProducer<RunTimeConfigurationDefaultBuildItem> defaultConfigProducer,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflection) {
DefaultSerdeDiscoveryState discoveryState = new DefaultSerdeDiscoveryState(combinedIndex.getIndex());
if (buildTimeConfig.serializerAutodetectionEnabled) {
discoverDefaultSerdeConfig(discoveryState, channelsManagedByConnectors, defaultConfigProducer,
buildTimeConfig.serializerGenerationEnabled ? generatedClass : null, reflection);
}
if (launchMode.getLaunchMode().isDevOrTest()) {
if (!runtimeConfig.enableGracefulShutdownInDevAndTestMode) {
List<AnnotationInstance> incomings = discoveryState.findAnnotationsOnMethods(DotNames.INCOMING);
List<AnnotationInstance> channels = discoveryState.findAnnotationsOnInjectionPoints(DotNames.CHANNEL);
List<AnnotationInstance> annotations = new ArrayList<>();
annotations.addAll(incomings);
annotations.addAll(channels);
for (AnnotationInstance annotation : annotations) {
String channelName = annotation.value().asString();
if (!discoveryState.isKafkaConnector(channelsManagedByConnectors, true, channelName)) {
continue;
}
String key = "mp.messaging.incoming." + channelName + ".graceful-shutdown";
discoveryState.ifNotYetConfigured(key, () -> {
defaultConfigProducer.produce(new RunTimeConfigurationDefaultBuildItem(key, "false"));
});
}
}
}
}
// visible for testing
void discoverDefaultSerdeConfig(DefaultSerdeDiscoveryState discovery,
List<ConnectorManagedChannelBuildItem> channelsManagedByConnectors,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflection) {
Map<String, String> alreadyGeneratedSerializers = new HashMap<>();
Map<String, String> alreadyGeneratedDeserializers = new HashMap<>();
for (AnnotationInstance annotation : discovery.findAnnotationsOnMethods(DotNames.INCOMING)) {
String channelName = annotation.value().asString();
if (!discovery.isKafkaConnector(channelsManagedByConnectors, true, channelName)) {
continue;
}
MethodInfo method = annotation.target().asMethod();
Type incomingType = getIncomingTypeFromMethod(method);
processIncomingType(discovery, config, incomingType, channelName, generatedClass, reflection,
alreadyGeneratedDeserializers);
}
for (AnnotationInstance annotation : discovery.findAnnotationsOnMethods(DotNames.OUTGOING)) {
String channelName = annotation.value().asString();
if (!discovery.isKafkaConnector(channelsManagedByConnectors, false, channelName)) {
continue;
}
MethodInfo method = annotation.target().asMethod();
Type outgoingType = getOutgoingTypeFromMethod(method);
processOutgoingType(discovery, outgoingType, (keySerializer, valueSerializer) -> {
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".key.serializer", keySerializer);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".value.serializer", valueSerializer);
handleAdditionalProperties("mp.messaging.outgoing." + channelName + ".", discovery,
config, keySerializer, valueSerializer);
}, generatedClass, reflection, alreadyGeneratedSerializers);
}
for (AnnotationInstance annotation : discovery.findAnnotationsOnInjectionPoints(DotNames.CHANNEL)) {
String channelName = annotation.value().asString();
if (!discovery.isKafkaConnector(channelsManagedByConnectors, false, channelName)
&& !discovery.isKafkaConnector(channelsManagedByConnectors, true, channelName)) {
continue;
}
Type injectionPointType = getInjectionPointType(annotation);
if (injectionPointType == null) {
continue;
}
Type incomingType = getIncomingTypeFromChannelInjectionPoint(injectionPointType);
processIncomingType(discovery, config, incomingType, channelName, generatedClass, reflection,
alreadyGeneratedDeserializers);
processKafkaTransactions(discovery, config, channelName, injectionPointType);
Type outgoingType = getOutgoingTypeFromChannelInjectionPoint(injectionPointType);
processOutgoingType(discovery, outgoingType, (keySerializer, valueSerializer) -> {
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".key.serializer", keySerializer);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".value.serializer", valueSerializer);
handleAdditionalProperties("mp.messaging.outgoing." + channelName + ".", discovery,
config, keySerializer, valueSerializer);
}, generatedClass, reflection, alreadyGeneratedSerializers);
}
}
private void processKafkaTransactions(DefaultSerdeDiscoveryState discovery,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config, String channelName, Type injectionPointType) {
if (injectionPointType != null && isKafkaEmitter(injectionPointType)) {
LOGGER.infof("Transactional producer detected for channel '%s', setting following default config values: "
+ "'mp.messaging.outgoing.%s.transactional.id=${quarkus.application.name}-${channelName}', "
+ "'mp.messaging.outgoing.%s.enable.idempotence=true', "
+ "'mp.messaging.outgoing.%s.acks=all'", channelName, channelName, channelName, channelName);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".transactional.id",
"${quarkus.application.name}-" + channelName);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".enable.idempotence", "true");
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.outgoing." + channelName + ".acks", "all");
}
}
private void processIncomingType(DefaultSerdeDiscoveryState discovery,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config, Type incomingType, String channelName,
BuildProducer<GeneratedClassBuildItem> generatedClass, BuildProducer<ReflectiveClassBuildItem> reflection,
Map<String, String> alreadyGeneratedDeserializers) {
extractKeyValueType(incomingType, (key, value, isBatchType) -> {
Result keyDeserializer = deserializerFor(discovery, key, generatedClass, reflection, alreadyGeneratedDeserializers);
Result valueDeserializer = deserializerFor(discovery, value, generatedClass, reflection,
alreadyGeneratedDeserializers);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.incoming." + channelName + ".key.deserializer", keyDeserializer);
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.incoming." + channelName + ".value.deserializer", valueDeserializer);
if (Boolean.TRUE.equals(isBatchType)) {
produceRuntimeConfigurationDefaultBuildItem(discovery, config,
"mp.messaging.incoming." + channelName + ".batch", "true");
}
handleAdditionalProperties("mp.messaging.incoming." + channelName + ".", discovery,
config, keyDeserializer, valueDeserializer);
});
}
private Type getInjectionPointType(AnnotationInstance annotation) {
switch (annotation.target().kind()) {
case FIELD:
return annotation.target().asField().type();
case METHOD_PARAMETER:
MethodParameterInfo parameter = annotation.target().asMethodParameter();
return parameter.method().parameters().get(parameter.position());
default:
return null;
}
}
private void handleAdditionalProperties(String configPropertyBase, DefaultSerdeDiscoveryState discovery,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config, Result... results) {
for (Result result : results) {
if (result == null) {
continue;
}
result.additionalProperties.forEach((key, value) -> {
produceRuntimeConfigurationDefaultBuildItem(discovery, config, configPropertyBase + key, value);
});
}
}
private void produceRuntimeConfigurationDefaultBuildItem(DefaultSerdeDiscoveryState discovery,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config, String key, Result result) {
if (result == null) {
return;
}
produceRuntimeConfigurationDefaultBuildItem(discovery, config, key, result.value);
}
private void produceRuntimeConfigurationDefaultBuildItem(DefaultSerdeDiscoveryState discovery,
BuildProducer<RunTimeConfigurationDefaultBuildItem> config, String key, String value) {
if (value == null) {
return;
}
if (discovery.shouldNotConfigure(key)) {
return;
}
discovery.ifNotYetConfigured(key, () -> {
config.produce(new RunTimeConfigurationDefaultBuildItem(key, value));
});
}
private Type getIncomingTypeFromMethod(MethodInfo method) {
List<Type> parameterTypes = method.parameters();
int parametersCount = parameterTypes.size();
Type returnType = method.returnType();
Type incomingType = null;
// @Incoming
if ((isVoid(returnType) && parametersCount == 1)
|| (isCompletionStage(returnType) && parametersCount == 1)
|| (isUni(returnType) && parametersCount == 1)) {
incomingType = parameterTypes.get(0);
} else if ((isSubscriber(returnType) && parametersCount == 0)
|| (isSubscriberBuilder(returnType) && parametersCount == 0)) {
incomingType = returnType.asParameterizedType().arguments().get(0);
}
// @Incoming @Outgoing
if (method.hasAnnotation(DotNames.OUTGOING)) {
if ((isCompletionStage(returnType) && parametersCount == 1)
|| (isUni(returnType) && parametersCount == 1)
|| (isPublisher(returnType) && parametersCount == 1)
|| (isPublisherBuilder(returnType) && parametersCount == 1)
|| (isMulti(returnType) && parametersCount == 1)) {
incomingType = parameterTypes.get(0);
} else if ((isProcessor(returnType) && parametersCount == 0)
|| (isProcessorBuilder(returnType) && parametersCount == 0)) {
incomingType = returnType.asParameterizedType().arguments().get(0);
} else if (parametersCount == 1) {
incomingType = parameterTypes.get(0);
}
// @Incoming @Outgoing stream manipulation
if (incomingType != null
&& (isPublisher(incomingType) || isPublisherBuilder(incomingType) || isMulti(incomingType))) {
incomingType = incomingType.asParameterizedType().arguments().get(0);
}
}
return incomingType;
}
private Type getIncomingTypeFromChannelInjectionPoint(Type injectionPointType) {
if (injectionPointType == null) {
return null;
}
if (isPublisher(injectionPointType) || isPublisherBuilder(injectionPointType) || isMulti(injectionPointType)) {
return injectionPointType.asParameterizedType().arguments().get(0);
} else {
return null;
}
}
private Type getOutgoingTypeFromMethod(MethodInfo method) {
List<Type> parameterTypes = method.parameters();
int parametersCount = parameterTypes.size();
Type returnType = method.returnType();
Type outgoingType = null;
// @Outgoing
if ((isPublisher(returnType) && parametersCount == 0)
|| (isPublisherBuilder(returnType) && parametersCount == 0)
|| (isMulti(returnType) && parametersCount == 0)
|| (isCompletionStage(returnType) && parametersCount == 0)
|| (isUni(returnType) && parametersCount == 0)) {
outgoingType = returnType.asParameterizedType().arguments().get(0);
} else if (parametersCount == 0) {
outgoingType = returnType;
}
// @Incoming @Outgoing
if (method.hasAnnotation(DotNames.INCOMING)) {
if ((isCompletionStage(returnType) && parametersCount == 1)
|| (isUni(returnType) && parametersCount == 1)
|| (isPublisher(returnType) && parametersCount == 1)
|| (isPublisherBuilder(returnType) && parametersCount == 1)
|| (isMulti(returnType) && parametersCount == 1)) {
outgoingType = returnType.asParameterizedType().arguments().get(0);
} else if ((isProcessor(returnType) && parametersCount == 0)
|| (isProcessorBuilder(returnType) && parametersCount == 0)) {
outgoingType = returnType.asParameterizedType().arguments().get(1);
} else if (parametersCount == 1) {
outgoingType = returnType;
}
// @Incoming @Outgoing stream manipulation
if (outgoingType != null
&& (isPublisher(outgoingType) || isPublisherBuilder(outgoingType) || isMulti(outgoingType))) {
outgoingType = outgoingType.asParameterizedType().arguments().get(0);
}
}
return outgoingType;
}
private Type getOutgoingTypeFromChannelInjectionPoint(Type injectionPointType) {
if (injectionPointType == null) {
return null;
}
if (isEmitter(injectionPointType) || isMutinyEmitter(injectionPointType) || isKafkaEmitter(injectionPointType)) {
return injectionPointType.asParameterizedType().arguments().get(0);
} else {
return null;
}
}
private void processOutgoingType(DefaultSerdeDiscoveryState discovery, Type outgoingType,
BiConsumer<Result, Result> serializerAcceptor, BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflection, Map<String, String> alreadyGeneratedSerializer) {
extractKeyValueType(outgoingType, (key, value, isBatch) -> {
Result keySerializer = serializerFor(discovery, key, generatedClass, reflection, alreadyGeneratedSerializer);
Result valueSerializer = serializerFor(discovery, value, generatedClass, reflection, alreadyGeneratedSerializer);
serializerAcceptor.accept(keySerializer, valueSerializer);
});
}
private void extractKeyValueType(Type type, TriConsumer<Type, Type, Boolean> keyValueTypeAcceptor) {
if (type == null) {
return;
}
if (isMessage(type)) {
List<Type> typeArguments = type.asParameterizedType().arguments();
Type messageTypeParameter = typeArguments.get(0);
if (isList(messageTypeParameter)) {
List<Type> messageListTypeArguments = messageTypeParameter.asParameterizedType().arguments();
keyValueTypeAcceptor.accept(null, messageListTypeArguments.get(0), true);
} else {
keyValueTypeAcceptor.accept(null, messageTypeParameter, false);
}
} else if (isList(type)) {
List<Type> typeArguments = type.asParameterizedType().arguments();
keyValueTypeAcceptor.accept(null, typeArguments.get(0), true);
} else if (isKafkaRecord(type) || isRecord(type) || isProducerRecord(type) || isConsumerRecord(type)) {
List<Type> typeArguments = type.asParameterizedType().arguments();
keyValueTypeAcceptor.accept(typeArguments.get(0), typeArguments.get(1), false);
} else if (isConsumerRecords(type) || isKafkaBatchRecord(type)) {
List<Type> typeArguments = type.asParameterizedType().arguments();
keyValueTypeAcceptor.accept(typeArguments.get(0), typeArguments.get(1), true);
} else if (isRawMessage(type)) {
keyValueTypeAcceptor.accept(null, type, false);
}
}
private static boolean isVoid(Type type) {
return type.kind() == Type.Kind.VOID;
}
private static boolean isCompletionStage(Type type) {
// raw type CompletionStage is wrong, must be CompletionStage<Something>
return DotNames.COMPLETION_STAGE.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isUni(Type type) {
// raw type Uni is wrong, must be Uni<Something>
return DotNames.UNI.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isMulti(Type type) {
// raw type Multi is wrong, must be Multi<Something>
return DotNames.MULTI.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isSubscriber(Type type) {
// raw type Subscriber is wrong, must be Subscriber<Something>
return DotNames.SUBSCRIBER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isSubscriberBuilder(Type type) {
// raw type SubscriberBuilder is wrong, must be SubscriberBuilder<Something, SomethingElse>
return DotNames.SUBSCRIBER_BUILDER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isPublisher(Type type) {
// raw type Publisher is wrong, must be Publisher<Something>
return DotNames.PUBLISHER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isPublisherBuilder(Type type) {
// raw type PublisherBuilder is wrong, must be PublisherBuilder<Something, SomethingElse>
return DotNames.PUBLISHER_BUILDER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isProcessor(Type type) {
// raw type Processor is wrong, must be Processor<Something, SomethingElse>
return DotNames.PROCESSOR.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isProcessorBuilder(Type type) {
// raw type ProcessorBuilder is wrong, must be ProcessorBuilder<Something, SomethingElse>
return DotNames.PROCESSOR_BUILDER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isEmitter(Type type) {
// raw type Emitter is wrong, must be Emitter<Something>
return DotNames.EMITTER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isMutinyEmitter(Type type) {
// raw type MutinyEmitter is wrong, must be MutinyEmitter<Something>
return DotNames.MUTINY_EMITTER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isKafkaEmitter(Type type) {
// raw type KafkaTransactions is wrong, must be KafkaTransactions<Something>
return DotNames.KAFKA_EMITTER.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isMessage(Type type) {
// raw type Message is wrong, must be Message<Something>
return DotNames.MESSAGE.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isKafkaRecord(Type type) {
// raw type KafkaRecord is wrong, must be KafkaRecord<Something, SomethingElse>
return DotNames.KAFKA_RECORD.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isRecord(Type type) {
// raw type Record is wrong, must be Record<Something, SomethingElse>
return DotNames.RECORD.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isConsumerRecord(Type type) {
// raw type ConsumerRecord is wrong, must be ConsumerRecord<Something, SomethingElse>
return DotNames.CONSUMER_RECORD.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isProducerRecord(Type type) {
// raw type ProducerRecord is wrong, must be ProducerRecord<Something, SomethingElse>
return DotNames.PRODUCER_RECORD.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isList(Type type) {
return DotNames.LIST.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 1;
}
private static boolean isKafkaBatchRecord(Type type) {
return DotNames.KAFKA_BATCH_RECORD.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isConsumerRecords(Type type) {
return DotNames.CONSUMER_RECORDS.equals(type.name())
&& type.kind() == Type.Kind.PARAMETERIZED_TYPE
&& type.asParameterizedType().arguments().size() == 2;
}
private static boolean isRawMessage(Type type) {
switch (type.kind()) {
case PRIMITIVE:
case CLASS:
case ARRAY:
return true;
default:
return false;
}
}
// @formatter:off
private static final Map<DotName, String> KNOWN_DESERIALIZERS = Map.ofEntries(
// Java types with built-in Kafka deserializer
// primitives
Map.entry(DotName.createSimple("short"), org.apache.kafka.common.serialization.ShortDeserializer.class.getName()),
Map.entry(DotName.createSimple("int"), org.apache.kafka.common.serialization.IntegerDeserializer.class.getName()),
Map.entry(DotName.createSimple("long"), org.apache.kafka.common.serialization.LongDeserializer.class.getName()),
Map.entry(DotName.createSimple("float"), org.apache.kafka.common.serialization.FloatDeserializer.class.getName()),
Map.entry(DotName.createSimple("double"), org.apache.kafka.common.serialization.DoubleDeserializer.class.getName()),
// primitive wrappers
Map.entry(DotName.createSimple(java.lang.Short.class.getName()), org.apache.kafka.common.serialization.ShortDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Integer.class.getName()), org.apache.kafka.common.serialization.IntegerDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Long.class.getName()), org.apache.kafka.common.serialization.LongDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Float.class.getName()), org.apache.kafka.common.serialization.FloatDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Double.class.getName()), org.apache.kafka.common.serialization.DoubleDeserializer.class.getName()),
// arrays
Map.entry(DotName.createSimple("[B"), org.apache.kafka.common.serialization.ByteArrayDeserializer.class.getName()),
// other
Map.entry(DotName.createSimple(java.lang.Void.class.getName()), org.apache.kafka.common.serialization.VoidDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.String.class.getName()), org.apache.kafka.common.serialization.StringDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.util.UUID.class.getName()), org.apache.kafka.common.serialization.UUIDDeserializer.class.getName()),
Map.entry(DotName.createSimple(java.nio.ByteBuffer.class.getName()), org.apache.kafka.common.serialization.ByteBufferDeserializer.class.getName()),
// Kafka types
Map.entry(DotName.createSimple(org.apache.kafka.common.utils.Bytes.class.getName()), org.apache.kafka.common.serialization.BytesDeserializer.class.getName()),
// Vert.x types
Map.entry(DotName.createSimple(io.vertx.core.buffer.Buffer.class.getName()), io.vertx.kafka.client.serialization.BufferDeserializer.class.getName()),
Map.entry(DotName.createSimple(io.vertx.core.json.JsonObject.class.getName()), io.vertx.kafka.client.serialization.JsonObjectDeserializer.class.getName()),
Map.entry(DotName.createSimple(io.vertx.core.json.JsonArray.class.getName()), io.vertx.kafka.client.serialization.JsonArrayDeserializer.class.getName())
);
private static final Map<DotName, String> KNOWN_SERIALIZERS = Map.ofEntries(
// Java types with built-in Kafka serializer
// primitives
Map.entry(DotName.createSimple("short"), org.apache.kafka.common.serialization.ShortSerializer.class.getName()),
Map.entry(DotName.createSimple("int"), org.apache.kafka.common.serialization.IntegerSerializer.class.getName()),
Map.entry(DotName.createSimple("long"), org.apache.kafka.common.serialization.LongSerializer.class.getName()),
Map.entry(DotName.createSimple("float"), org.apache.kafka.common.serialization.FloatSerializer.class.getName()),
Map.entry(DotName.createSimple("double"), org.apache.kafka.common.serialization.DoubleSerializer.class.getName()),
// primitives wrappers
Map.entry(DotName.createSimple(java.lang.Short.class.getName()), org.apache.kafka.common.serialization.ShortSerializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Integer.class.getName()), org.apache.kafka.common.serialization.IntegerSerializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Long.class.getName()), org.apache.kafka.common.serialization.LongSerializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Float.class.getName()), org.apache.kafka.common.serialization.FloatSerializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.Double.class.getName()), org.apache.kafka.common.serialization.DoubleSerializer.class.getName()),
// arrays
Map.entry(DotName.createSimple("[B"), org.apache.kafka.common.serialization.ByteArraySerializer.class.getName()),
// other
Map.entry(DotName.createSimple(java.lang.Void.class.getName()), org.apache.kafka.common.serialization.VoidSerializer.class.getName()),
Map.entry(DotName.createSimple(java.lang.String.class.getName()), org.apache.kafka.common.serialization.StringSerializer.class.getName()),
Map.entry(DotName.createSimple(java.util.UUID.class.getName()), org.apache.kafka.common.serialization.UUIDSerializer.class.getName()),
Map.entry(DotName.createSimple(java.nio.ByteBuffer.class.getName()), org.apache.kafka.common.serialization.ByteBufferSerializer.class.getName()),
// Kafka types
Map.entry(DotName.createSimple(org.apache.kafka.common.utils.Bytes.class.getName()), org.apache.kafka.common.serialization.BytesSerializer.class.getName()),
// Vert.x types
Map.entry(DotName.createSimple(io.vertx.core.buffer.Buffer.class.getName()), io.vertx.kafka.client.serialization.BufferSerializer.class.getName()),
Map.entry(DotName.createSimple(io.vertx.core.json.JsonObject.class.getName()), io.vertx.kafka.client.serialization.JsonObjectSerializer.class.getName()),
Map.entry(DotName.createSimple(io.vertx.core.json.JsonArray.class.getName()), io.vertx.kafka.client.serialization.JsonArraySerializer.class.getName())
);
// @formatter:on
private Result deserializerFor(DefaultSerdeDiscoveryState discovery, Type type,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflection,
Map<String, String> alreadyGeneratedSerializers) {
Result result = serializerDeserializerFor(discovery, type, false);
if (result != null && !result.exists) {
// avoid returning Result.nonexistent() to callers, they expect a non-null Result to always be known
return null;
}
// if result is null, generate a jackson serializer, generatedClass is null if the generation is disabled.
// also, only generate the serializer/deserializer for classes and only generate once
if (result == null && type != null && generatedClass != null && type.kind() == Type.Kind.CLASS) {
// Check if already generated
String clazz = alreadyGeneratedSerializers.get(type.toString());
if (clazz == null) {
clazz = JacksonSerdeGenerator.generateDeserializer(generatedClass, type);
LOGGER.infof("Generating Jackson deserializer for type %s", type.name().toString());
// Deserializers are access by reflection.
reflection.produce(new ReflectiveClassBuildItem(true, true, false, clazz));
alreadyGeneratedSerializers.put(type.toString(), clazz);
}
result = Result.of(clazz);
}
return result;
}
private Result serializerFor(DefaultSerdeDiscoveryState discovery, Type type,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<ReflectiveClassBuildItem> reflection,
Map<String, String> alreadyGeneratedSerializers) {
Result result = serializerDeserializerFor(discovery, type, true);
if (result != null && !result.exists) {
// avoid returning Result.nonexistent() to callers, they expect a non-null Result to always be known
return null;
}
// if result is null, generate a jackson deserializer, generatedClass is null if the generation is disabled.
// also, only generate the serializer/deserializer for classes and only generate once
if (result == null && type != null && generatedClass != null && type.kind() == Type.Kind.CLASS) {
// Check if already generated
String clazz = alreadyGeneratedSerializers.get(type.toString());
if (clazz == null) {
clazz = JacksonSerdeGenerator.generateSerializer(generatedClass, type);
LOGGER.infof("Generating Jackson serializer for type %s", type.name().toString());
// Serializers are access by reflection.
reflection.produce(new ReflectiveClassBuildItem(true, true, false, clazz));
alreadyGeneratedSerializers.put(type.toString(), clazz);
}
result = Result.of(clazz);
}
return result;
}
private Result serializerDeserializerFor(DefaultSerdeDiscoveryState discovery, Type type, boolean serializer) {
if (type == null) {
return null;
}
DotName typeName = type.name();
// Serializer/deserializer implementations
ClassInfo implementation = discovery.getImplementorOfWithTypeArgument(
serializer ? DotNames.KAFKA_SERIALIZER : DotNames.KAFKA_DESERIALIZER, typeName);
if (implementation != null) {
return Result.of(implementation.name().toString());
}
// statically known serializer/deserializer
Map<DotName, String> map = serializer ? KNOWN_SERIALIZERS : KNOWN_DESERIALIZERS;
if (map.containsKey(typeName)) {
return Result.of(map.get(typeName));
}
// Avro generated class or GenericRecord (serializer/deserializer provided by Confluent or Apicurio)
boolean isAvroGenerated = discovery.isAvroGenerated(typeName);
if (isAvroGenerated || DotNames.AVRO_GENERIC_RECORD.equals(typeName)) {
int avroLibraries = 0;
avroLibraries += discovery.hasConfluent() ? 1 : 0;
avroLibraries += discovery.hasApicurio1() ? 1 : 0;
avroLibraries += discovery.hasApicurio2() ? 1 : 0;
if (avroLibraries > 1) {
LOGGER.debugf("Skipping Avro serde autodetection for %s, because multiple Avro serde libraries are present",
typeName);
return Result.nonexistent();
}
if (discovery.hasConfluent()) {
return serializer
? Result.of("io.confluent.kafka.serializers.KafkaAvroSerializer")
: Result.of("io.confluent.kafka.serializers.KafkaAvroDeserializer")
.with(isAvroGenerated, "specific.avro.reader", "true");
} else if (discovery.hasApicurio1()) {
return serializer
? Result.of("io.apicurio.registry.utils.serde.AvroKafkaSerializer")
: Result.of("io.apicurio.registry.utils.serde.AvroKafkaDeserializer")
.with(isAvroGenerated, "apicurio.registry.use-specific-avro-reader", "true");
} else if (discovery.hasApicurio2()) {
return serializer
? Result.of("io.apicurio.registry.serde.avro.AvroKafkaSerializer")
: Result.of("io.apicurio.registry.serde.avro.AvroKafkaDeserializer")
.with(isAvroGenerated, "apicurio.registry.use-specific-avro-reader", "true");
} else {
// we know it is an Avro type, no point in serializing it as JSON
return Result.nonexistent();
}
}
// Jackson-based serializer/deserializer
// note that Jackson is always present with Kafka, so no need to check
{
ClassInfo subclass = discovery.getSubclassOfWithTypeArgument(
serializer ? DotNames.OBJECT_MAPPER_SERIALIZER : DotNames.OBJECT_MAPPER_DESERIALIZER, typeName);
if (subclass != null) {
return Result.of(subclass.name().toString());
}
}
// Jsonb-based serializer/deserializer
if (discovery.hasJsonb()) {
ClassInfo subclass = discovery.getSubclassOfWithTypeArgument(
serializer ? DotNames.JSONB_SERIALIZER : DotNames.JSONB_DESERIALIZER, typeName);
if (subclass != null) {
return Result.of(subclass.name().toString());
}
}
// unknown
return null;
}
@BuildStep
@Consume(RuntimeConfigSetupCompleteBuildItem.class)
public void reflectiveValueSerializerPayload(CombinedIndexBuildItem combinedIndex,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
IndexView index = combinedIndex.getIndex();
Config config = ConfigProvider.getConfig();
processOutgoingForReflectiveClassPayload(index, config,
(annotation, payloadType) -> produceReflectiveClass(reflectiveClass, payloadType));
processOutgoingChannelForReflectiveClassPayload(index, config,
(annotation, payloadType) -> produceReflectiveClass(reflectiveClass, payloadType));
processIncomingForReflectiveClassPayload(index, config,
(annotation, payloadType) -> produceReflectiveClass(reflectiveClass, payloadType));
processIncomingChannelForReflectiveClassPayload(index, config,
(annotation, payloadType) -> produceReflectiveClass(reflectiveClass, payloadType));
}
void produceReflectiveClass(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, Type type) {
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, true, type.name().toString()));
}
// visible for testing
void processOutgoingForReflectiveClassPayload(IndexView index, Config config,
BiConsumer<AnnotationInstance, Type> annotationAcceptor) {
processAnnotationsForReflectiveClassPayload(index, config, DotNames.OUTGOING, true,
annotation -> getOutgoingTypeFromMethod(annotation.target().asMethod()), annotationAcceptor);
}
// visible for testing
void processOutgoingChannelForReflectiveClassPayload(IndexView index, Config config,
BiConsumer<AnnotationInstance, Type> annotationAcceptor) {
processAnnotationsForReflectiveClassPayload(index, config, DotNames.CHANNEL, true,
annotation -> getOutgoingTypeFromChannelInjectionPoint(getInjectionPointType(annotation)), annotationAcceptor);
}
// visible for testing
void processIncomingForReflectiveClassPayload(IndexView index, Config config,
BiConsumer<AnnotationInstance, Type> annotationAcceptor) {
processAnnotationsForReflectiveClassPayload(index, config, DotNames.INCOMING, false,
annotation -> getIncomingTypeFromMethod(annotation.target().asMethod()), annotationAcceptor);
}
// visible for testing
void processIncomingChannelForReflectiveClassPayload(IndexView index, Config config,
BiConsumer<AnnotationInstance, Type> annotationAcceptor) {
processAnnotationsForReflectiveClassPayload(index, config, DotNames.CHANNEL, false,
annotation -> getIncomingTypeFromChannelInjectionPoint(getInjectionPointType(annotation)),
annotationAcceptor);
}
private void processAnnotationsForReflectiveClassPayload(IndexView index, Config config, DotName annotationType,
boolean serializer, Function<AnnotationInstance, Type> typeExtractor,
BiConsumer<AnnotationInstance, Type> annotationAcceptor) {
for (AnnotationInstance annotation : index.getAnnotations(annotationType)) {
String channelName = annotation.value().asString();
Type type = typeExtractor.apply(annotation);
extractKeyValueType(type, (key, value, isBatch) -> {
if (key != null && isSerdeJson(index, config, channelName, serializer, true)) {
annotationAcceptor.accept(annotation, key);
}
if (value != null && isSerdeJson(index, config, channelName, serializer, false)) {
annotationAcceptor.accept(annotation, value);
}
});
}
}
private boolean isSerdeJson(IndexView index, Config config, String channelName, boolean serializer, boolean isKey) {
ConfigValue configValue = config.getConfigValue(getConfigName(channelName, serializer, isKey));
if (configValue.getValue() != null) {
DotName serdeName = DotName.createSimple(configValue.getValue());
return serializer ? isSubclassOfJsonSerializer(index, serdeName) : isSubclassOfJsonDeserializer(index, serdeName);
}
return false;
}
String getConfigName(String channelName, boolean serializer, boolean isKey) {
return "mp.messaging." +
(serializer ? "outgoing" : "incoming") + "." +
channelName + "." +
(isKey ? "key" : "value") + "." +
(serializer ? "serializer" : "deserializer");
}
private boolean isSubclassOfJsonSerializer(IndexView index, DotName serializerName) {
return isSubclassOf(index, DotNames.OBJECT_MAPPER_SERIALIZER, serializerName) ||
isSubclassOf(index, DotNames.JSONB_SERIALIZER, serializerName);
}
private boolean isSubclassOfJsonDeserializer(IndexView index, DotName serializerName) {
return isSubclassOf(index, DotNames.OBJECT_MAPPER_DESERIALIZER, serializerName) ||
isSubclassOf(index, DotNames.JSONB_DESERIALIZER, serializerName);
}
private boolean isSubclassOf(IndexView index, DotName superclass, DotName expectedType) {
if (superclass.equals(expectedType)) {
return true;
}
return index.getKnownDirectSubclasses(superclass)
.stream()
.anyMatch(ci -> ci.name().equals(expectedType));
}
} |
package com.czbix.v2ex.model;
import android.os.Parcel;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.czbix.v2ex.common.exception.FatalException;
import com.czbix.v2ex.network.RequestHelper;
import com.czbix.v2ex.ui.widget.ExArrayAdapter;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.text.Collator;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Node extends Page implements Comparable<Node>,ExArrayAdapter.Filterable {
private static final Pattern PATTERN = Pattern.compile("/go/(.+?)(?:\\W|$)");
private static final Collator COLLATOR = Collator.getInstance(Locale.CHINA);
private final int mId;
private final String mTitle;
private final String mName;
private final String mTitleAlternative;
private final int mTopics;
private final Avatar mAvatar;
private final boolean mHasInfo;
public Node(String title, int id, Avatar avatar, String name, String alternative,
int topics) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(name));
mId = id;
mTitle = title;
mAvatar = avatar;
mName = name;
mTitleAlternative = alternative;
mTopics = topics;
mHasInfo = !Strings.isNullOrEmpty(title);
}
public int getId() {
return mId;
}
@Override
public String getTitle() {
return mTitle;
}
@Nullable
public Avatar getAvatar() {
return mAvatar;
}
public String getName() {
return mName;
}
public String getTitleAlternative() {
return mTitleAlternative;
}
public int getTopics() {
return mTopics;
}
public boolean hasInfo() {
return mHasInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Node)) return false;
Node node = (Node) o;
return Objects.equal(mId, node.mId) &&
Objects.equal(mTopics, node.mTopics) &&
Objects.equal(mName, node.mName) &&
Objects.equal(mTitleAlternative, node.mTitleAlternative) &&
Objects.equal(mAvatar, node.mAvatar);
}
@Override
public int hashCode() {
return Objects.hashCode(mId, mName, mTitleAlternative, mTopics, mAvatar);
}
public static String buildUrlByName(String name) {
return RequestHelper.BASE_URL + "/go/" + name;
}
public static String getNameFromUrl(String url) {
final Matcher matcher = PATTERN.matcher(url);
Preconditions.checkState(matcher.find(), "match name for node failed: " + url);
return matcher.group(1);
}
@Override
public String getUrl() {
return buildUrlByName(getName());
}
@Override
public boolean filter(String query) {
if (Strings.isNullOrEmpty(query)) {
return true;
}
if (mName.contains(query) || mTitle.contains(query)) {
return true;
}
if (mTitleAlternative != null && mTitleAlternative.contains(query)) {
return true;
}
return false;
}
@Override
public int compareTo(@NonNull Node another) {
return COLLATOR.compare(getTitle(), another.getTitle());
}
public static class Builder {
private static final Cache<String, Node> CACHE;
static {
CACHE = CacheBuilder.newBuilder()
.softValues()
.initialCapacity(32)
.maximumSize(128)
.build();
}
private int mId;
private String mTitle;
private Avatar mAvatar;
private String mName;
private String mTitleAlternative;
private int mTopics;
public Builder setId(int id) {
mId = id;
return this;
}
public Builder setTitle(String title) {
mTitle = title;
return this;
}
public Builder setAvatar(Avatar avatar) {
mAvatar = avatar;
return this;
}
public Builder setName(String name) {
mName = name;
return this;
}
public Builder setTitleAlternative(String titleAlternative) {
mTitleAlternative = titleAlternative;
return this;
}
public Builder setTopics(int topics) {
mTopics = topics;
return this;
}
public Node createNode() {
try {
if (mTitle == null) {
return new Node(null, mId, mAvatar, mName, mTitleAlternative, mTopics);
}
return CACHE.get(mName, () -> new Node(mTitle, mId, mAvatar, mName, mTitleAlternative, mTopics));
} catch (ExecutionException e) {
throw new FatalException(e);
}
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.mId);
dest.writeString(this.mTitle);
dest.writeString(this.mName);
dest.writeString(this.mTitleAlternative);
dest.writeInt(this.mTopics);
dest.writeParcelable(this.mAvatar, 0);
dest.writeByte(mHasInfo ? (byte) 1 : (byte) 0);
}
protected Node(Parcel in) {
this.mId = in.readInt();
this.mTitle = in.readString();
this.mName = in.readString();
this.mTitleAlternative = in.readString();
this.mTopics = in.readInt();
this.mAvatar = in.readParcelable(Avatar.class.getClassLoader());
this.mHasInfo = in.readByte() != 0;
}
public static final Creator<Node> CREATOR = new Creator<Node>() {
public Node createFromParcel(Parcel source) {
return new Node(source);
}
public Node[] newArray(int size) {
return new Node[size];
}
};
} |
package org.xwiki.officeimporter.test.ui;
import java.io.File;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.xwiki.administration.test.po.AdministrationPage;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.officeimporter.test.po.OfficeImporterPage;
import org.xwiki.officeimporter.test.po.OfficeImporterResultPage;
import org.xwiki.officeimporter.test.po.OfficeServerAdministrationSectionPage;
import org.xwiki.test.docker.junit5.TestConfiguration;
import org.xwiki.test.docker.junit5.UITest;
import org.xwiki.test.docker.junit5.servletengine.ServletEngine;
import org.xwiki.test.ui.TestUtils;
import org.xwiki.test.ui.po.AttachmentsPane;
import org.xwiki.test.ui.po.ConfirmationPage;
import org.xwiki.test.ui.po.CreatePagePage;
import org.xwiki.test.ui.po.DeletingPage;
import org.xwiki.test.ui.po.ViewPage;
import org.xwiki.test.ui.po.editor.WikiEditPage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Functional tests for the office importer.
*
* @version $Id$
* @since 7.3M1
*/
@UITest(office = true, servletEngine = ServletEngine.TOMCAT,
forbiddenEngines = {
// These tests need to have XWiki running inside a Docker container (we chose Tomcat since it's the most
// used one), because they need LibreOffice to be installed, and we cannot guarantee that it is installed on the
// host machine.
ServletEngine.JETTY_STANDALONE
},
properties = {
// Add the FileUploadPlugin which is needed by the test to upload some office files to import
"xwikiCfgPlugins=com.xpn.xwiki.plugin.fileupload.FileUploadPlugin"
}
)
public class OfficeImporterIT
{
private TestUtils setup;
private TestConfiguration testConfiguration;
@BeforeEach
public void setUp(TestUtils setup, TestConfiguration testConfiguration)
{
this.setup = setup;
this.testConfiguration = testConfiguration;
setup.loginAsSuperAdmin();
// Connect the wiki to the office server if it is not already done
AdministrationPage administrationPage = AdministrationPage.gotoPage();
administrationPage.clickSection("Content", "Office Server");
OfficeServerAdministrationSectionPage officeServerAdministrationSectionPage =
new OfficeServerAdministrationSectionPage();
if (!"Connected".equals(officeServerAdministrationSectionPage.getServerState())) {
officeServerAdministrationSectionPage.startServer();
}
}
@Test
public void verifyImport(TestInfo info)
{
verifyImports(info);
verifySplitByHeadings(info);
verifyChildNamingMethodInputVisibility(info);
}
/**
* A basic test that imports some documents and verify they are correctly imported TODO: do a more advanced check
* about styling and content
*/
private void verifyImports(TestInfo info)
{
String testName = info.getTestMethod().get().getName();
// Test word file
ViewPage resultPage = importFile(testName, "msoffice.97-2003/Test.doc");
assertTrue(StringUtils.contains(resultPage.getContent(), "This is a test document."));
deletePage(testName);
// Test power point file
resultPage = importFile(testName, "msoffice.97-2003/Test.ppt");
AttachmentsPane attachmentsPane = resultPage.openAttachmentsDocExtraPane();
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide0.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide1.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide2.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide3.jpg"));
deletePage(testName);
// Test excel file
resultPage = importFile(testName, "msoffice.97-2003/Test.xls");
assertTrue(StringUtils.contains(resultPage.getContent(), "Sheet1"));
assertTrue(StringUtils.contains(resultPage.getContent(), "Sheet2"));
deletePage(testName);
// Test ODT file
resultPage = importFile(testName, "ooffice.3.0/Test.odt");
assertTrue(StringUtils.contains(resultPage.getContent(), "This is a test document."));
WikiEditPage wikiEditPage = resultPage.editWiki();
String regex = "(?<imageName>Test_html_[\\w]+\\.png)";
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(wikiEditPage.getContent());
assertTrue(matcher.find());
String imageName = matcher.group("imageName");
resultPage = wikiEditPage.clickCancel();
attachmentsPane = resultPage.openAttachmentsDocExtraPane();
assertEquals(4, attachmentsPane.getNumberOfAttachments());
assertTrue(attachmentsPane.attachmentExistsByFileName(imageName));
deletePage(testName);
// Test ODP file
resultPage = importFile(testName, "ooffice.3.0/Test.odp");
attachmentsPane = resultPage.openAttachmentsDocExtraPane();
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide0.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide1.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide2.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test-slide3.jpg"));
deletePage(testName);
// Test ODS file
resultPage = importFile(testName, "ooffice.3.0/Test.ods");
assertTrue(StringUtils.contains(resultPage.getContent(), "Sheet1"));
assertTrue(StringUtils.contains(resultPage.getContent(), "Sheet2"));
deletePage(testName);
// Test ODT file with accents
resultPage = importFile(testName, "ooffice.3.0/Test_accents & é$ù !-_.+();@=.odt");
assertTrue(StringUtils.contains(resultPage.getContent(), "This is a test document."));
wikiEditPage = resultPage.editWiki();
regex = "(?<imageName>Test_accents & e\\$u !-_\\.\\+\\(\\);\\\\@=_html_[\\w]+\\.png)";
pattern = Pattern.compile(regex, Pattern.MULTILINE);
matcher = pattern.matcher(wikiEditPage.getContent());
assertTrue(matcher.find());
imageName = matcher.group("imageName");
resultPage = wikiEditPage.clickCancel();
attachmentsPane = resultPage.openAttachmentsDocExtraPane();
assertEquals(4, attachmentsPane.getNumberOfAttachments());
// the \ before the @ needs to be removed as it's not in the filename
assertTrue(attachmentsPane.attachmentExistsByFileName(imageName.replaceAll("\\\\@", "@")));
deletePage(testName);
// Test power point file with accents
resultPage = importFile(testName, "msoffice.97-2003/Test_accents & é$ù !-_.+();@=.ppt");
attachmentsPane = resultPage.openAttachmentsDocExtraPane();
assertTrue(attachmentsPane.attachmentExistsByFileName("Test_accents & e$u !-_.+();@=-slide0.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test_accents & e$u !-_.+();@=-slide1.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test_accents & e$u !-_.+();@=-slide2.jpg"));
assertTrue(attachmentsPane.attachmentExistsByFileName("Test_accents & e$u !-_.+();@=-slide3.jpg"));
wikiEditPage = resultPage.editWiki();
assertTrue(wikiEditPage.getContent().contains("[[image:Test_accents & e$u !-_.+();\\@=-slide0.jpg]]"));
resultPage = wikiEditPage.clickCancel();
deletePage(testName);
}
public void verifySplitByHeadings(TestInfo info)
{
String testName = info.getTestMethod().get().getName();
ViewPage resultPage = importFile(testName, "ToSplit.odt", true);
assertTrue(StringUtils.contains(resultPage.getContent(), "Introduction"));
// See children
verifyChild(testName, "First Part", "Hello, this is the first part of my story!");
verifyChild(testName, "Second Part", "This is the second part of my story!");
verifyChild(testName, "Last Part", "It's finished. Thanks you!");
// Go back to the parent
resultPage = this.setup.gotoPage(new DocumentReference("xwiki", getClass().getSimpleName(), testName));
deletePageWithChildren(resultPage);
}
/**
* Test if the expected child exists at the expected place (as a children of the target page).
*/
private void verifyChild(String testName, String expectedName, String expectedContent)
{
ViewPage child = this.setup.gotoPage(
new DocumentReference("xwiki", Arrays.asList(getClass().getSimpleName(), testName), expectedName));
assertTrue(child.exists());
assertEquals(expectedName, child.getDocumentTitle());
assertTrue(StringUtils.contains(child.getContent(), expectedContent));
}
/**
* Depending on if the target page is terminal or not, the "childNamingMethod" input is displayed or not.
*/
public void verifyChildNamingMethodInputVisibility(TestInfo info)
{
DocumentReference testDocument =
new DocumentReference("xwiki", Arrays.asList(getClass().getSimpleName()),
info.getTestMethod().get().getName());
// Cleaning
this.setup.deletePage(testDocument);
// 1: create a terminal page
CreatePagePage createPagePage = this.setup.gotoPage(testDocument).createPage();
createPagePage.setType("office");
createPagePage.setTerminalPage(true);
createPagePage.clickCreate();
OfficeImporterPage officeImporterPage = new OfficeImporterPage();
// Test
assertTrue(officeImporterPage.isChildPagesNamingMethodDisplayed());
// 2: create a non terminal page
createPagePage = this.setup.gotoPage(testDocument).createPage();
createPagePage.setType("office");
createPagePage.setTerminalPage(false);
createPagePage.clickCreate();
officeImporterPage = new OfficeImporterPage();
// Test
assertFalse(officeImporterPage.isChildPagesNamingMethodDisplayed());
}
/**
* Import an office file in the wiki.
*
* @param fileName name of the file to import (the file should be located in test /resources/ folder)
* @return the result page
*/
private ViewPage importFile(String testName, String fileName)
{
return importFile(testName, fileName, false);
}
private File getResourceFile(String filename)
{
return new File(this.testConfiguration.getBrowser().getTestResourcesPath(), filename);
}
/**
* Import an office file in the wiki.
*
* @param fileName name of the file to import (the file should be located in test /resources/ folder)
* @param splitByHeadings either the option splitByHeadings should be use or not
* @return the result page
*/
private ViewPage importFile(String testName, String fileName, boolean splitByHeadings)
{
ViewPage page = this.setup.gotoPage(
new DocumentReference("xwiki", Arrays.asList(getClass().getSimpleName(), testName), "WebHome"));
CreatePagePage createPage = page.createPage();
createPage.setType("office");
createPage.clickCreate();
OfficeImporterPage officeImporterPage = new OfficeImporterPage();
File resourceFile = this.getResourceFile(fileName);
officeImporterPage.setFile(resourceFile);
officeImporterPage.setFilterStyle(true);
officeImporterPage.setSplitDocument(splitByHeadings);
OfficeImporterResultPage officeImporterResultPage = officeImporterPage.clickImport();
assertEquals("Conversion succeeded. You can view the result, or you can Go back to convert another document.",
officeImporterResultPage.getMessage());
return officeImporterResultPage.viewResult();
}
/**
* Delete a page with all its children.
*
* @param pageToDelete the page to delete
*/
private void deletePageWithChildren(ViewPage pageToDelete)
{
ConfirmationPage confirmationPage = pageToDelete.delete();
if (confirmationPage.hasAffectChildrenOption()) {
confirmationPage.setAffectChildren(true);
}
DeletingPage deletingPage = confirmationPage.confirmDeletePage();
deletingPage.waitUntilFinished();
assertTrue(deletingPage.isSuccess());
}
private void deletePage(String testName)
{
DocumentReference pageToDelete =
new DocumentReference("xwiki", Arrays.asList(getClass().getSimpleName(), testName), "WebHome");
this.setup.deletePage(pageToDelete);
}
} |
import java.io.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class ftp_client {
private static Console console = System.console();
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static FTPClient ftpClient = new FTPClient();
private static FileInputStream fileInputStream = null;
public static void main(String[] args) {
setupFTPClient(args);
String command;
String localDir = System.getProperty("user.dir");
while(ftpClient.isConnected()) {
command = getVar("command");
switch(command) {
case "list remote":
case "lsr":
listRemote(null);
break;
case "list local":
case "lsl":
listLocal(localDir);
break;
case "exit":
case "logout":
exit();
break;
case "help":
help();
break;
case "cls":
case "clear":
clear();
break;
default:
//REGEX Matching
//change directory - cd local/cdl
if(command.matches("cd local (.*)") || command.matches("cdl (.*)")) {
localDir = changeDirectory(localDir, command);
}
else
//put file - put/p
if(command.matches("put (.*)") || command.matches("cdl (.*)")) {
//put the given file in the given location
putFile(localDir, command);
} else {
System.out.println("\tCommand not found. For help input \"help\"");
}
}
}
logout();
System.exit(0);
}
//Puts the specified file from the local server to the specified location on the remote server
private static boolean putFile(String localDir, String input) {
//The file to put, the location to put
File file;
String outFile;
String location = ftpClient.getLocalAddress().toString();
//remove "put"/"p" from input
input = input.replace("put","");
input = input.replace("p","");
//split on whitespaces
String[] inputList = input.split(" "); //need to change, should match more than one whitespace
//if provided, the location to put the file
if (inputList[1] != null) {
location.concat(inputList[1]);
}
//get the provided file
outFile = localDir;
outFile.concat(inputList[0]);
file = new File(outFile);
//check the file actually exists
try {
if (file.exists()) {
//if so, put the file out
fileInputStream = new FileInputStream(outFile);
ftpClient.storeFile(outFile, fileInputStream);
}
else {
System.out.println("File not found :(");
return false;
}
}
catch(Exception e) {
System.out.println("Something went wrong :(");
return false;
}
//TODO
return false;
}
//Lists the remote files/folders in the provided directory
private static boolean listRemote(String dir) {
try {
FTPFile[] fileList = ftpClient.listFiles(dir);
//get the full path before printing
dir = ftpClient.getLocalAddress().toString();
System.out.println("Remote Directory: " + dir);
for (int i = 0; i < fileList.length; ++i) {
if(fileList[i].isFile()) {
System.out.println("\t" + fileList[i].getName());
}
else if(fileList[i].isDirectory()) {
System.out.println("\t" + fileList[i].getName());
}
}
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
//Lists the local files/folders in the provided directory
private static boolean listLocal(String dir) {
System.out.println();
try {
File folder = new File(dir);
File[] fileList = folder.listFiles();
System.out.println("Current Directory: " + dir);
for (int i = 0; i < fileList.length; ++i) {
if(fileList[i].isFile()) {
System.out.println("\t" + fileList[i].getName());
}
else if(fileList[i].isDirectory()) {
System.out.println("\t" + fileList[i].getName());
}
}
System.out.println();
}
catch(Exception e) {
return false;
}
return true;
}
private static String changeDirectory(String dir, String input) {
input = input.replace("cdl","");
input = input.replace("cd local","");
input = input.trim();
File newDir = new File(dir, input);
try {
if (newDir.exists()) {
System.out.println("Changed Directory to: " + newDir.toPath().normalize().toString());
return newDir.toPath().normalize().toString();
}
else {
System.out.println("Folder not found :(");
return dir;
}
}
catch(Exception e) {
System.out.println("Something went wrong :(");
return dir;
}
}
//Prints the help menu
private static void help() {
System.out.println("RTFM"); //fix me
System.out.println();
}
//Clears the console
private static void clear() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
//Logoff and exit
private static void exit() {
logout();
}
//gets reply from the server
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
//if there are messages, display each one in order
if (replies != null && replies.length > 0)
for (String reply : replies)
System.out.println("SERVER: " + reply);
}
//Gets input from user or args and calls login
private static void setupFTPClient(String[] args) {
//shouldn't be more than 3 args - error
if(args.length > 3)
System.out.println("RTFM!"); //Yes, I know there is no manual
String server = (args.length < 1) ? getVar("Server") : args[0];
int port = 21;
String username = (args.length < 2) ? getVar("User") : args[1];
String password = (args.length < 3) ? getPrivateVar("Password") : args[2];
login(server,port,username,password);
}
private static boolean login(String server, int port, String user, String password) {
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("Could not connect");
return false;
}
return ftpClient.login(user, password);
}
catch(Exception ex) {
System.out.println("Something went wrong :( - couldn't connect to the server");
return false;
}
}
private static boolean logout() {
if(ftpClient.isConnected()) {
try {
System.out.println("Logging out...");
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Succesfully Disconnected");
return true;
}
catch(Exception ex) {
System.out.println("Something went wrong :( - Couldn't logout and disconnect correctly");
return false;
}
}
return false;
}
//Prompts user and returns a string
//Bugfix for eclipse?
private static String getVar(String request) {
System.out.print(request + ": ");
if(console != null) {
return console.readLine();
}
else {
try {
return in.readLine();
}
catch(Exception ex) {
return null;
}
}
}
//Prompts user and returns a string w/o outputing it
//Does not work in eclipse so redirects to getVar()
private static String getPrivateVar(String request) {
if(console != null) {
System.out.print(request + ": ");
return new String(console.readPassword());
}
else
return getVar(request);
}
} |
package org.commcare.android.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.models.RangeXYValueSeries;
import org.commcare.android.util.InvalidStateException;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.ConfigurableData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import org.javarosa.core.model.utils.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private Context mContext;
private int mTextSize;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context, String title) {
mContext = context;
mTextSize = (int)context.getResources().getDimension(R.dimen.text_large);
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer(2); // initialize with two scales, to support a secondary y axis
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(mTextSize);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int)mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int)mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int)mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle(1).equals("")) {
rightMargin += textAllowance;
}
int leftMargin = (int)mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int)mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
// AChartEngine doesn't handle x label margins as desired, so do it here
if (mRenderer.isShowLabels()) {
bottomMargin += textAllowance;
}
// Bar charts have text labels that are likely to be long (names, etc.).
// At some point there'll need to be a more robust solution for setting
// margins that respond to data and screen size. For now, give them no margin
// and push the labels onto the graph area itself by manually padding the labels.
if (Graph.TYPE_BAR.equals(mData.getType()) && getOrientation().equals(XYMultipleSeriesRenderer.Orientation.VERTICAL)) {
bottomMargin = 0;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
private void render(GraphData data) throws InvalidStateException {
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
}
public Intent getIntent(GraphData data) throws InvalidStateException {
render(data);
setPanAndZoom(Boolean.valueOf(mData.getConfiguration("zoom", "false")));
String title = mRenderer.getChartTitle();
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return ChartFactory.getBubbleChartIntent(mContext, mDataset, mRenderer, title);
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return ChartFactory.getTimeChartIntent(mContext, mDataset, mRenderer, getTimeFormat(), title);
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
return ChartFactory.getBarChartIntent(mContext, mDataset, mRenderer, getBarChartType(), title);
}
return ChartFactory.getLineChartIntent(mContext, mDataset, mRenderer, title);
}
private BarChart.Type getBarChartType() {
if (Boolean.valueOf(mData.getConfiguration("stack", "false")).equals(Boolean.TRUE)) {
return BarChart.Type.STACKED;
}
return BarChart.Type.DEFAULT;
}
/**
* Enable or disable pan and zoom settings for this view.
*
* @param allow Whether or not to enabled pan and zoom.
*/
private void setPanAndZoom(boolean allow) {
mRenderer.setPanEnabled(allow, allow);
mRenderer.setZoomEnabled(allow, allow);
mRenderer.setZoomButtonsVisible(allow);
if (allow) {
DefaultRenderer.Location loc = stringToLocation(mData.getConfiguration("zoom-location", "bottom-right"));
mRenderer.setZoomLocation(loc);
}
}
private DefaultRenderer.Location stringToLocation(String str) {
switch (str) {
case "top-left":
return DefaultRenderer.Location.TOP_LEFT;
case "top-right":
return DefaultRenderer.Location.TOP_RIGHT;
case "bottom-left":
return DefaultRenderer.Location.BOTTOM_LEFT;
default:
return DefaultRenderer.Location.BOTTOM_RIGHT;
}
}
private JSONObject getC3Config() {
JSONObject config = new JSONObject();
try {
// Actual data: array of arrays, where first element is a string id
// and later elements are data, either x values or y values.
JSONArray columns = new JSONArray();
// Hash that pairs up the arrays defined in columns,
// y-values-array-id => x-values-array-id
JSONObject xs = new JSONObject();
int seriesIndex = 0;
for (SeriesData s : mData.getSeries()) {
JSONArray xValues = new JSONArray();
JSONArray yValues = new JSONArray();
String xID = "x" + seriesIndex;
String yID = "y" + seriesIndex;
xs.put(yID, xID);
xValues.put(xID);
yValues.put(yID);
for (XYPointData p : s.getPoints()) {
xValues.put(p.getX());
yValues.put(p.getY());
}
columns.put(xValues);
columns.put(yValues);
seriesIndex++;
}
JSONObject data = new JSONObject();
data.put("xs", xs);
data.put("columns", columns);
config.put("data", data);
} catch (JSONException e) {
e.printStackTrace(); // TODO: don't fail silently
}
return config;
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public View getView(GraphData data) throws InvalidStateException {
mData = data;
WebView.setWebContentsDebuggingEnabled(true); // TODO: only if in dev
WebView webView = new WebView(mContext);
configureSettings(webView);
String html =
"<html>" +
"<head>" +
"<link rel='stylesheet' type='text/css' href='file:///android_asset/graphing/c3.min.css'></link>" +
"<link rel='stylesheet' type='text/css' href='file:///android_asset/graphing/graph.css'></link>" +
"<script type='text/javascript' src='file:///android_asset/graphing/d3.min.js'></script>" +
"<script type='text/javascript' src='file:///android_asset/graphing/c3.min.js' charset='utf-8'></script>" +
"<script type='text/javascript'>var config = " + getC3Config().toString() + ";</script>" +
"<script type='text/javascript' src='file:///android_asset/graphing/graph.js'></script>" +
"</head>" +
"<body><div id='chart'></div></body>" +
"</html>";
webView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
return webView;
/*
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return ChartFactory.getTimeChartView(mContext, mDataset, mRenderer, getTimeFormat());
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
return ChartFactory.getBarChartView(mContext, mDataset, mRenderer, getBarChartType());
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);*/
}
private void configureSettings(WebView view) {
WebSettings settings = view.getSettings();
settings.setJavaScriptEnabled(true);
// Improve performance
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setSupportZoom(false);
}
/**
* Fetch date format for displaying time-based x labels.
*
* @return String, a SimpleDateFormat pattern.
*/
private String getTimeFormat() {
return mData.getConfiguration("x-labels-time-format", "yyyy-MM-dd");
}
/*
* Allow or disallow clicks on this graph - really, on the view generated by getView.
*/
public void setClickable(boolean enabled) {
mRenderer.setClickEnabled(enabled);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) throws InvalidStateException {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series = createSeries(Boolean.valueOf(s.getConfiguration("secondary-y", "false")).equals(Boolean.TRUE) ? 1 : 0);
series.setTitle(s.getConfiguration("name", ""));
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries)series).setMaxValue(parseYValue(s.getConfiguration("radius-max"), "radius-max"));
}
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Comparator<XYPointData> comparator;
if (Graph.TYPE_BAR.equals(mData.getType())) {
String barSort = s.getConfiguration("bar-sort", "");
switch (barSort) {
case "ascending":
comparator = new AscendingValuePointComparator();
break;
case "descending":
comparator = new DescendingValuePointComparator();
break;
default:
comparator = new StringPointComparator();
break;
}
} else {
comparator = new NumericPointComparator();
}
Collections.sort(sortedPoints, comparator);
int barIndex = 1;
JSONObject barLabels = new JSONObject();
for (XYPointData p : sortedPoints) {
String description = "point (" + p.getX() + ", " + p.getY() + ")";
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
BubblePointData b = (BubblePointData)p;
description += " with radius " + b.getRadius();
((RangeXYValueSeries)series).add(parseXValue(b.getX(), description), parseYValue(b.getY(), description), parseRadiusValue(b.getRadius(), description));
} else if (Graph.TYPE_TIME.equals(mData.getType())) {
((TimeSeries)series).add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
} else if (Graph.TYPE_BAR.equals(mData.getType())) {
// In CommCare, bar graphs are specified with x as a set of text labels
// and y as a set of values. In AChartEngine, bar graphs are a subclass
// of XY graphs, with numeric x and y values. Deal with this by
// assigning an arbitrary, evenly-spaced x value to each bar and then
// populating x-labels with the user's x values.
series.add(barIndex, parseYValue(p.getY(), description));
try {
// For horizontal graphs, force labels right so they appear on the graph itself
String padding = getOrientation().equals(XYMultipleSeriesRenderer.Orientation.VERTICAL) ? " " : "";
barLabels.put(Double.toString(barIndex), padding + p.getX());
} catch (JSONException e) {
throw new InvalidStateException("Could not handle bar label '" + p.getX() + "': " + e.getMessage());
}
barIndex++;
} else {
series.add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
}
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
mData.setConfiguration("x-min", Double.toString(0.5));
mData.setConfiguration("x-max", Double.toString(sortedPoints.size() + 0.5));
mData.setConfiguration("x-labels", barLabels.toString());
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public static LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
/**
* Get graph's desired aspect ratio.
*
* @return Ratio, expressed as a double: width / height.
*/
public double getRatio() {
// Most graphs are drawn with aspect ratio 2:1, which is mostly arbitrary
// and happened to look nice for partographs. Vertically-oriented graphs,
// however, get squished unless they're drawn as a square. Expect to revisit
// this eventually (make all graphs square? user-configured aspect ratio?).
if (Graph.TYPE_BAR.equals(mData.getType())) {
return 1;
}
return 2;
}
private XYMultipleSeriesRenderer.Orientation getOrientation() {
// AChartEngine's horizontal/vertical definitions are counter-intuitive
String orientation = mData.getConfiguration("bar-orientation", "");
if (orientation.equalsIgnoreCase("vertical")) {
return XYMultipleSeriesRenderer.Orientation.HORIZONTAL;
} else {
return XYMultipleSeriesRenderer.Orientation.VERTICAL;
}
}
/**
* Create series appropriate to the current graph type.
*
* @return An XYSeries-derived object.
*/
private XYSeries createSeries() {
return createSeries(0);
}
/**
* Create series appropriate to the current graph type.
*
* @return An XYSeries-derived object.
*/
private XYSeries createSeries(int scaleIndex) {
// TODO: Bubble and time graphs ought to respect scaleIndex, but XYValueSeries
// and TimeSeries don't expose the (String title, int scaleNumber) constructor.
if (scaleIndex > 0 && !Graph.TYPE_XY.equals(mData.getType())) {
throw new IllegalArgumentException("This series does not support a secondary y axis");
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return new TimeSeries("");
}
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return new RangeXYValueSeries("");
}
return new XYSeries("", scaleIndex);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() throws InvalidStateException {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
XYSeries series = createSeries();
for (AnnotationData a : annotations) {
String text = a.getAnnotation();
String description = "annotation '" + text + "' at (" + a.getX() + ", " + a.getY() + ")";
series.addAnnotation(text, parseXValue(a.getX(), description), parseYValue(a.getY(), description));
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(mTextSize);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.color.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow other shapes or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
switch (pointStyle) {
case "circle":
style = PointStyle.CIRCLE;
break;
case "x":
style = PointStyle.X;
break;
case "square":
style = PointStyle.SQUARE;
break;
case "triangle":
style = PointStyle.TRIANGLE;
break;
case "diamond":
style = PointStyle.DIAMOND;
break;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
currentRenderer.setPointStrokeWidth(2);
mRenderer.setPointSize(6);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor == null) {
currentRenderer.setColor(Color.BLACK);
} else {
currentRenderer.setColor(Color.parseColor(lineColor));
}
currentRenderer.setLineWidth(2);
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() throws InvalidStateException {
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.color.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.color.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(1, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsAlign(Align.LEFT, 1);
mRenderer.setYAxisAlign(Align.RIGHT, 1);
mRenderer.setAxesColor(mContext.getResources().getColor(R.color.grey_lighter));
mRenderer.setLabelsTextSize(mTextSize);
mRenderer.setAxisTitleTextSize(mTextSize);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowGrid(true);
int padding = 10;
mRenderer.setXLabelsPadding(padding);
mRenderer.setYLabelsPadding(padding);
mRenderer.setYLabelsVerticalPadding(padding);
if (Graph.TYPE_BAR.equals(mData.getType())) {
mRenderer.setBarSpacing(0.5);
}
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-title", ""));
mRenderer.setYTitle(mData.getConfiguration("secondary-y-title", ""), 1);
if (Graph.TYPE_BAR.equals(mData.getType())) {
XYMultipleSeriesRenderer.Orientation orientation = getOrientation();
mRenderer.setOrientation(orientation);
if (orientation.equals(XYMultipleSeriesRenderer.Orientation.VERTICAL)) {
mRenderer.setXLabelsAlign(Align.LEFT);
mRenderer.setXLabelsPadding(0);
}
}
if (mData.getConfiguration("x-min") != null) {
mRenderer.setXAxisMin(parseXValue(mData.getConfiguration("x-min"), "x-min"));
}
if (mData.getConfiguration("y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("y-min"), "y-min"));
}
if (mData.getConfiguration("secondary-y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("secondary-y-min"), "secondary-y-min"), 1);
}
if (mData.getConfiguration("x-max") != null) {
mRenderer.setXAxisMax(parseXValue(mData.getConfiguration("x-max"), "x-max"));
}
if (mData.getConfiguration("y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("y-max"), "y-max"));
}
if (mData.getConfiguration("secondary-y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("secondary-y-max"), "secondary-y-max"), 1);
}
boolean showGrid = Boolean.valueOf(mData.getConfiguration("show-grid", "true")).equals(Boolean.TRUE);
mRenderer.setShowGridX(showGrid);
mRenderer.setShowGridY(showGrid);
mRenderer.setShowCustomTextGridX(showGrid);
mRenderer.setShowCustomTextGridY(showGrid);
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
// Legend
boolean showLegend = Boolean.valueOf(mData.getConfiguration("show-legend", "false"));
mRenderer.setShowLegend(showLegend);
mRenderer.setFitLegend(showLegend);
mRenderer.setLegendTextSize(mTextSize);
// Labels
boolean hasX = configureLabels("x-labels");
boolean hasY = configureLabels("y-labels");
configureLabels("secondary-y-labels");
boolean showLabels = hasX || hasY;
mRenderer.setShowLabels(showLabels);
// Tick marks are sometimes ugly, so let's be minimalist and always leave the off
mRenderer.setShowTickMarks(false);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseXValue(String value, String description) throws InvalidStateException {
if (Graph.TYPE_TIME.equals(mData.getType())) {
Date parsed = DateUtils.parseDateTime(value);
if (parsed == null) {
throw new InvalidStateException("Could not parse date '" + value + "' in " + description);
}
return parseDouble(String.valueOf(parsed.getTime()), description);
}
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseYValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseRadiusValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Attempt to parse a double, but fail on NumberFormatException.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseDouble(String value, String description) throws InvalidStateException {
try {
Double numeric = Double.valueOf(value);
if (numeric.isNaN()) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
return numeric;
} catch (NumberFormatException nfe) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
}
/**
* Customize labels.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @return True iff axis has any labels at all
*/
private boolean configureLabels(String key) throws InvalidStateException {
boolean hasLabels = true;
// The labels setting might be a JSON array of numbers,
// a JSON object of number => string, or a single number
String labelString = mData.getConfiguration(key);
if (labelString != null) {
try {
// Array: label each given value
JSONArray labels = new JSONArray(labelString);
setLabelCount(key, 0);
for (int i = 0; i < labels.length(); i++) {
String value = labels.getString(i);
addTextLabel(key, parseXValue(value, "x label '" + key + "'"), value);
}
hasLabels = labels.length() > 0;
} catch (JSONException je) {
// Assume try block failed because labelString isn't an array.
// Try parsing it as an object.
try {
// Object: each keys is a location on the axis,
// and the value is the text with which to label it
JSONObject labels = new JSONObject(labelString);
setLabelCount(key, 0);
Iterator i = labels.keys();
hasLabels = false;
while (i.hasNext()) {
String location = (String)i.next();
addTextLabel(key, parseXValue(location, "x label at " + location), labels.getString(location));
hasLabels = true;
}
} catch (JSONException e) {
// Assume labelString is just a scalar, which
// represents the number of labels the user wants.
Integer count = Integer.valueOf(labelString);
setLabelCount(key, count);
hasLabels = count != 0;
}
}
}
return hasLabels;
}
/**
* Helper for configureLabels. Adds a label to the appropriate axis.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param location Point on axis to add label
* @param text String for label
*/
private void addTextLabel(String key, Double location, String text) {
if (isXKey(key)) {
mRenderer.addXTextLabel(location, text);
} else {
int scaleIndex = getScaleIndex(key);
if (mRenderer.getYAxisAlign(scaleIndex) == Align.RIGHT) {
text = " " + text;
}
mRenderer.addYTextLabel(location, text, scaleIndex);
}
}
/**
* Helper for configureLabels. Sets desired number of labels for the appropriate axis.
* AChartEngine will then determine how to space the labels.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param value Number of labels
*/
private void setLabelCount(String key, int value) {
if (isXKey(key)) {
mRenderer.setXLabels(value);
} else {
mRenderer.setYLabels(value);
}
}
/**
* Helper for turning key into scale.
*
* @param key Something like "x-labels" or "y-secondary-labels"
* @return Index for passing to AChartEngine functions that accept a scale
*/
private int getScaleIndex(String key) {
return key.contains("secondary") ? 1 : 0;
}
/**
* Helper for parsing axis from configuration key.
*
* @param key Something like "x-min" or "y-labels"
* @return True iff key is relevant to x axis
*/
private boolean isXKey(String key) {
return key.startsWith("x-");
}
/**
* Comparator to sort XYPointData-derived objects by x value.
*
* @author jschweers
*/
private class NumericPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getX(), "").compareTo(parseXValue(rhs.getX(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPointData-derived objects by x value without parsing them.
* Useful for bar graphs, where x values are text.
*
* @author jschweers
*/
private class StringPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
return lhs.getX().compareTo(rhs.getX());
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in ascending order.
* Useful for bar graphs, nonsensical for other graphs.
*
* @author jschweers
*/
private class AscendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getY(), "").compareTo(parseXValue(rhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in descending order.
* Useful for bar graphs, nonsensical for other graphs.
*
* @author jschweers
*/
private class DescendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(rhs.getY(), "").compareTo(parseXValue(lhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
} |
package com.allaboutolaf;
import android.app.Application;
import android.net.http.HttpResponseCache;
import android.os.Bundle;
import android.util.Log;
// keep these sorted alphabetically
import com.avishayil.rnrestart.ReactNativeRestartPackage;
import com.bugsnag.BugsnagReactNative;
import com.BV.LinearGradient.LinearGradientPackage;
import com.calendarevents.CalendarEventsPackage;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
import com.github.droibit.android.reactnative.customtabs.CustomTabsPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.mapbox.rctmgl.RCTMGLPackage;
import com.oblador.keychain.KeychainPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.pusherman.networkinfo.RNNetworkInfoPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
// please keep these sorted alphabetically
BugsnagReactNative.getPackage(),
new CalendarEventsPackage(),
new CustomTabsPackage(),
new KeychainPackage(),
new LinearGradientPackage(),
new RCTMGLPackage(),
new ReactNativeOneSignalPackage(),
new ReactNativeRestartPackage(),
new RNDeviceInfo(),
new RNGestureHandlerPackage(),
new RNNetworkInfoPackage(),
new VectorIconsPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
// set up network cache
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 20 * 1024 * 1024; // 20 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Log.i("allaboutolaf", "HTTP response cache installation failed:", e);
// Log.i(TAG, "HTTP response cache installation failed:", e);
}
}
public void onStop() {
HttpResponseCache cache = HttpResponseCache.getInstalled();
if (cache != null) {
cache.flush();
}
}
} |
package org.commcare.android.view;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.models.RangeXYValueSeries;
import org.commcare.android.util.InvalidStateException;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import org.javarosa.core.model.utils.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private Context mContext;
private int mTextSize;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context, String title) {
mContext = context;
mTextSize = (int) context.getResources().getDimension(R.dimen.text_large);
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer(2); // initialize with two scales, to support a secondary y axis
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(mTextSize);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int) mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle(1).equals("")) {
rightMargin += textAllowance;
}
int leftMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
private void render(GraphData data) throws InvalidStateException {
mData = data;
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
}
public Intent getIntent(GraphData data) throws InvalidStateException {
render(data);
String title = mRenderer.getChartTitle();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartIntent(mContext, mDataset, mRenderer, title);
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return ChartFactory.getTimeChartIntent(mContext, mDataset, mRenderer, title, getTimeFormat());
}
return ChartFactory.getLineChartIntent(mContext, mDataset, mRenderer, title);
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
public View getView(GraphData data) throws InvalidStateException {
render(data);
// Graph will not render correctly unless it has data, so
// add a dummy series if needed.
boolean hasPoints = false;
Vector<SeriesData> allSeries = data.getSeries();
for (int i = 0; i < allSeries.size() && !hasPoints; i++) {
hasPoints = hasPoints || allSeries.get(i).getPoints().size() > 0;
}
if (!hasPoints) {
SeriesData s = new SeriesData();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
s.addPoint(new BubblePointData("0", "0", "0"));
}
else if (mData.getType().equals(Graph.TYPE_TIME)) {
s.addPoint(new XYPointData(DateUtils.formatDate(new Date(), DateUtils.FORMAT_ISO8601), "0"));
}
else {
s.addPoint(new XYPointData("0", "0"));
}
s.setConfiguration("line-color", "#00000000");
s.setConfiguration("point-style", "none");
renderSeries(s);
}
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return ChartFactory.getTimeChartView(mContext, mDataset, mRenderer, getTimeFormat());
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);
}
/**
* Fetch date format for displaying time-based x labels.
* @return String, a SimpleDateFormat pattern.
*/
private String getTimeFormat() {
return mData.getConfiguration("x-labels-time-format", "yyyy-MM-dd");
}
/*
* Allow or disallow clicks on this graph - really, on the view generated by getView.
*/
public void setClickable(boolean enabled) {
mRenderer.setClickEnabled(enabled);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) throws InvalidStateException {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series = createSeries(Boolean.valueOf(s.getConfiguration("secondary-y", "false")).equals(Boolean.TRUE) ? 1 : 0);
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries) series).setMaxValue(parseYValue(s.getConfiguration("radius-max"), "radius-max"));
}
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Collections.sort(sortedPoints, new PointComparator());
for (XYPointData p : sortedPoints) {
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
BubblePointData b = (BubblePointData) p;
((RangeXYValueSeries) series).add(parseXValue(b.getX(), "x value"), parseYValue(b.getY(), "y value"), parseRadiusValue(b.getRadius(), "radius"));
}
else if (mData.getType().equals(Graph.TYPE_TIME)) {
((TimeSeries) series).add(parseXValue(p.getX(), "x value"), parseYValue(p.getY(), "y value"));
}
else {
series.add(parseXValue(p.getX(), "y value"), parseYValue(p.getY(), "y value"));
}
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public static LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
/**
* Create series appropriate to the current graph type.
* @return An XYSeries-derived object.
*/
private XYSeries createSeries() {
return createSeries(0);
}
/**
* Create series appropriate to the current graph type.
* @param scaleIndex
* @return An XYSeries-derived object.
*/
private XYSeries createSeries(int scaleIndex) {
// TODO: Bubble and time graphs ought to respect scaleIndex, but XYValueSeries
// and TimeSeries don't expose the (String title, int scaleNumber) constructor.
if (scaleIndex > 0 && !mData.getType().equals(Graph.TYPE_XY)) {
throw new IllegalArgumentException("This series does not support a secondary y axis");
}
if (mData.getType().equals(Graph.TYPE_TIME)) {
return new TimeSeries("");
}
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return new RangeXYValueSeries("");
}
return new XYSeries("", scaleIndex);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() throws InvalidStateException {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
XYSeries series = createSeries();
for (AnnotationData a : annotations) {
String text = a.getAnnotation();
series.addAnnotation(text, parseXValue(a.getX(), "x value for annotation '" + text + "'"), parseYValue(a.getY(), "y value for annotation '" + text + "'"));
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(mTextSize);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.color.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow other shapes or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
if (pointStyle.equals("circle")) {
style = PointStyle.CIRCLE;
}
else if (pointStyle.equals("x")) {
style = PointStyle.X;
}
else if (pointStyle.equals("square")) {
style = PointStyle.SQUARE;
}
else if (pointStyle.equals("triangle")) {
style = PointStyle.TRIANGLE;
}
else if (pointStyle.equals("diamond")) {
style = PointStyle.DIAMOND;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
currentRenderer.setPointStrokeWidth(2);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor == null) {
currentRenderer.setColor(Color.BLACK);
}
else {
currentRenderer.setColor(Color.parseColor(lineColor));
}
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() throws InvalidStateException{
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.color.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.color.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(1, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsAlign(Align.LEFT, 1);
mRenderer.setYLabelsPadding(10);
mRenderer.setYAxisAlign(Align.RIGHT, 1);
mRenderer.setAxesColor(mContext.getResources().getColor(R.color.grey_lighter));
mRenderer.setLabelsTextSize(mTextSize);
mRenderer.setAxisTitleTextSize(mTextSize);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowLegend(false);
mRenderer.setShowGrid(true);
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-title", ""));
mRenderer.setYTitle(mData.getConfiguration("secondary-y-title", ""), 1);
if (mData.getConfiguration("x-min") != null) {
mRenderer.setXAxisMin(parseXValue(mData.getConfiguration("x-min"), "x-min"));
}
if (mData.getConfiguration("y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("y-min"), "y-min"));
}
if (mData.getConfiguration("secondary-y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("secondary-y-min"), "secondary-y-min"), 1);
}
if (mData.getConfiguration("x-max") != null) {
mRenderer.setXAxisMax(parseXValue(mData.getConfiguration("x-max"), "x-max"));
}
if (mData.getConfiguration("y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("y-max"), "y-max"));
}
if (mData.getConfiguration("secondary-y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("secondary-y-max"), "secondary-y-max"), 1);
}
String showGrid = mData.getConfiguration("show-grid", "true");
if (Boolean.valueOf(showGrid).equals(Boolean.FALSE)) {
mRenderer.setShowGridX(false);
mRenderer.setShowGridY(false);
}
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
// Labels
configureLabels("x-labels");
configureLabels("y-labels");
configureLabels("secondary-y-labels");
boolean panAndZoom = Boolean.valueOf(mData.getConfiguration("zoom", "false")).equals(Boolean.TRUE);
mRenderer.setPanEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomButtonsVisible(panAndZoom);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
*/
private Double parseXValue(String value, String description) throws InvalidStateException {
if (mData.getType().equals(Graph.TYPE_TIME)) {
return parseDouble(String.valueOf(DateUtils.parseDateTime(value).getTime()), "x value");
}
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
* @throws InvalidStateException
*/
private Double parseYValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
*/
private Double parseRadiusValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Attempt to parse a double, but fail on NumberFormatException.
* @param value
* @param description Something to identify the kind of value, used to augment any error message.
* @return
* @throws InvalidStateException
*/
private Double parseDouble(String value, String description) throws InvalidStateException {
try {
return Double.valueOf(value);
}
catch (NumberFormatException nfe) {
throw new InvalidStateException("Could not understand " + description + " '" + value + "'");
}
}
/**
* Customize labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
*/
private void configureLabels(String key) throws InvalidStateException {
// The labels setting might be a JSON array of numbers,
// a JSON object of number => string, or a single number
String labelString = mData.getConfiguration(key);
if (labelString != null) {
try {
// Array: label each given value
JSONArray labels = new JSONArray(labelString);
setLabelCount(key, 0);
for (int i = 0; i < labels.length(); i++) {
String value = labels.getString(i);
addTextLabel(key, parseXValue(value, "x label '" + key + "'"), value);
}
}
catch (JSONException je) {
// Assume try block failed because labelString isn't an array.
// Try parsing it as an object.
try {
// Object: each keys is a location on the axis,
// and the value is the text with which to label it
JSONObject labels = new JSONObject(labelString);
setLabelCount(key, 0);
Iterator i = labels.keys();
while (i.hasNext()) {
String location = (String) i.next();
addTextLabel(key, parseXValue(location, "x label at " + location), labels.getString(location));
}
}
catch (JSONException e) {
// Assume labelString is just a scalar, which
// represents the number of labels the user wants.
Integer count = Integer.valueOf(labelString);
setLabelCount(key, count);
}
}
}
}
/**
* Helper for configureLabels. Adds a label to the appropriate axis.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param location Point on axis to add label
* @param text String for label
*/
private void addTextLabel(String key, Double location, String text) {
if (isXKey(key)) {
mRenderer.addXTextLabel(location, text);
}
else {
int scaleIndex = getScaleIndex(key);
if (mRenderer.getYAxisAlign(scaleIndex) == Align.RIGHT) {
text = " " + text;
}
mRenderer.addYTextLabel(location, text, scaleIndex);
}
}
/**
* Helper for configureLabels. Sets desired number of labels for the appropriate axis.
* AChartEngine will then determine how to space the labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param value Number of labels
*/
private void setLabelCount(String key, int value) {
if (isXKey(key)) {
mRenderer.setXLabels(value);
}
else {
mRenderer.setYLabels(value);
}
}
/**
* Helper for turning key into scale.
* @param key Something like "x-labels" or "y-secondary-labels"
* @return Index for passing to AChartEngine functions that accept a scale
*/
private int getScaleIndex(String key) {
return key.contains("secondary") ? 1 : 0;
}
/**
* Helper for parsing axis from configuration key.
* @param key Something like "x-min" or "y-labels"
* @return True iff key is relevant to x axis
*/
private boolean isXKey(String key) {
return key.startsWith("x-");
}
/**
* Comparator to sort XYPointData-derived objects by x value.
* @author jschweers
*/
private class PointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getX(), "").compareTo(parseXValue(rhs.getX(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
} |
package com.rnim.rn.audio;
import android.content.Context;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableMap;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import android.os.Environment;
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.util.Log;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.FileInputStream;
class AudioPlayerManager extends ReactContextBaseJavaModule {
private Context context;
private MediaPlayer mediaPlayer;
private String currentFileName;
private int currentPosition;
private boolean isPlaying = false;
private boolean isPaused = false;
private static final String DocumentDirectoryPath = "DocumentDirectoryPath";
private static final String PicturesDirectoryPath = "PicturesDirectoryPath";
private static final String MainBundlePath = "MainBundlePath";
private static final String CachesDirectoryPath = "CachesDirectoryPath";
private static final String LibraryDirectoryPath = "LibraryDirectoryPath";
private static final String MusicDirectoryPath = "MusicDirectoryPath";
private static final String DownloadsDirectoryPath = "DownloadsDirectoryPath";
public AudioPlayerManager(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext;
}
@Override
public String getName() {
return "AudioPlayerManager";
}
@Override
public Map<String, Object> getConstants() {
Map<String, Object> constants = new HashMap<>();
constants.put(DocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath());
constants.put(PicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
constants.put(MainBundlePath, "");
constants.put(CachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath());
constants.put(LibraryDirectoryPath, "");
constants.put(MusicDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
constants.put(DownloadsDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
return constants;
}
@ReactMethod
public void getDurationFromPath(String path, Promise promise ) {
if (path == null) {
Log.e("PATH_NOT_SET", "Please add path");
promise.reject("PATH_NOT_SET", "Please add path");
return;
}
boolean mediaPlayerReady = preparePlaybackAtPath("local", path, promise);
if (!mediaPlayerReady){
return;
}
promise.resolve(mediaPlayer.getDuration());
}
@ReactMethod
public void getDuration(Promise promise) {
if (mediaPlayer == null) {
Log.e("PLAYER_NOT_PREPARED", "Please call startPlaying before stopping playback");
promise.reject("PLAYER_NOT_PREPARED", "Please call startPlaying before stopping playback");
return;
}
promise.resolve(mediaPlayer.getDuration());
}
@ReactMethod
public void stop(Promise promise) {
if (!isPlaying) {
Log.e("INVALID_STATE", "Please call play or playWithURL before stopping playback");
promise.reject("INVALID_STATE", "Please call play or playWithURL before stopping playback");
return;
}
mediaPlayer.stop();
mediaPlayer.release();
isPlaying = false;
isPaused = false;
promise.resolve(currentFileName);
}
@ReactMethod
public void pause(Promise promise) {
if (!isPlaying) {
Log.e("INVALID_STATE", "Please call play or playWithURL before pausing playback");
promise.reject("INVALID_STATE", "Please call play or playWithURL before pausing playback");
return;
}
mediaPlayer.pause();
currentPosition = mediaPlayer.getCurrentPosition();
isPaused = true;
isPlaying = false;
promise.resolve(currentFileName);
}
@ReactMethod
public void unpause(Promise promise) {
if (!isPaused) {
Log.e("INVALID_STATE", "Please call pause before unpausing playback");
promise.reject("INVALID_STATE", "Please call pause before unpausing playback");
return;
}
mediaPlayer.seekTo(currentPosition);
mediaPlayer.start();
isPaused = false;
isPlaying = true;
promise.resolve(currentFileName);
}
@ReactMethod
public void play(String path, ReadableMap playbackSettings, final Promise promise) {
if (isPlaying) {
Log.e("INVALID_STATE", "Please wait for previous playback to finish.");
promise.reject("INVALID_STATE", "Please set valid path");
return;
}
if (isPaused) {
unpause(promise);
return;
}
if (path == null) {
Log.e("INVALID_PATH", "Please set valid path");
promise.reject("INVALID_PATH", "Please set valid path");
return;
}
mediaPlayer = new MediaPlayer();
playMedia("local", path, promise);
isPlaying = true;
isPaused = false;
return;
}
@ReactMethod
public void setCurrentTime(int position, final Promise promise) {
Log.d("NOT_SUPPORTED","Not supported in android using skipToSeconds method");
skipToSeconds(position, promise);
}
@ReactMethod
public void skipToSeconds(int position, final Promise promise) {
if (mediaPlayer == null) {
Log.e("INVALID_STATE", "No playback");
promise.reject("INVALID_STATE", "No playback");
return;
}
mediaPlayer.seekTo(position);
}
@ReactMethod
public void playWithUrl(String url, ReadableMap playbackOptions, final Promise promise) {
if (isPlaying) {
Log.e("INVALID_STATE", "Please wait for previous playback to finish.");
promise.reject("INVALID_STATE", "Please set valid path");
return;
}
if (isPaused) {
unpause(promise);
return;
}
playMedia("remote", url, promise);
sendEvent("playerFinished", null);
isPlaying = true;
isPaused = false;
return;
}
private void playMedia(String type, final String path, final Promise promise) {
boolean playbackReady = preparePlaybackAtPath(type, path, promise);
if (!playbackReady) {
return;
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
promise.resolve(path);
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
isPlaying = false;
isPaused = false;
}
});
mediaPlayer.start();
}
private boolean preparePlaybackAtPath(String pathType, String path, Promise promise) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
} else {
mediaPlayer.reset();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
if (pathType == "local") {
FileInputStream fis = new FileInputStream(new File(path));
mediaPlayer.setDataSource(fis.getFD());
} else if (pathType == "remote") {
mediaPlayer.setDataSource(path);
}
} catch (IllegalArgumentException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
e.printStackTrace();
} catch (SecurityException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
e.printStackTrace();
} catch (IllegalStateException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
} catch (IOException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
e.printStackTrace();
}
try {
mediaPlayer.prepare();
return true;
} catch (IllegalStateException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
promise.reject("COULDNT_PREPARE_MEDIAPLAYER", e.getMessage());
e.printStackTrace();
}
return false;
}
private void sendEvent(String eventName, Object params) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
} |
package org.appcelerator.titanium;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.commons.codec.binary.Base64;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.util.KrollStreamHelper;
import org.appcelerator.titanium.io.TiBaseFile;
import org.appcelerator.titanium.io.TitaniumBlob;
import org.appcelerator.titanium.util.TiImageHelper;
import org.appcelerator.titanium.util.TiMimeTypeHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
/**
* A Titanium Blob object. A Blob can represent any opaque data or input stream.
*/
@Kroll.proxy
public class TiBlob extends KrollProxy
{
private static final String TAG = "TiBlob";
/**
* Represents a Blob that contains image data.
* @module.api
*/
public static final int TYPE_IMAGE = 0;
/**
* Represents a Blob that contains file data.
* @module.api
*/
public static final int TYPE_FILE = 1;
/**
* Represents a Blob that contains data.
* @module.api
*/
public static final int TYPE_DATA = 2;
/**
* Represents a Blob that contains String data.
* @module.api
*/
public static final int TYPE_STRING = 3;
private int type;
private Object data;
private String mimetype;
private Bitmap image;
private int width, height;
private TiBlob(int type, Object data, String mimetype)
{
super();
this.type = type;
this.data = data;
this.mimetype = mimetype;
this.image = null;
this.width = 0;
this.height = 0;
}
/**
* Creates a new TiBlob object from String data.
* @param data the data used to create blob.
* @return new instance of TiBlob.
* @module.api
*/
public static TiBlob blobFromString(String data)
{
return new TiBlob(TYPE_STRING, data, "text/plain");
}
/**
* Creates a blob from a file and sets a mimeType based on the file name.
* @param file the file used to create blob.
* @return new instane of TiBlob.
* @module.api
*/
public static TiBlob blobFromFile(TiBaseFile file)
{
return blobFromFile(file, TiMimeTypeHelper.getMimeType(file.nativePath()));
}
/**
* Creates a blob from a file with the specified mimeType. If the passed mimeType is null,
* the mimeType will be determined using the file name.
* @param file the file used to create blob.
* @param mimeType the mimeType used to create blob.
* @return new instance of TiBlob.
* @module.api
*/
public static TiBlob blobFromFile(TiBaseFile file, String mimeType)
{
if (mimeType == null) {
mimeType = TiMimeTypeHelper.getMimeType(file.nativePath());
}
TiBlob blob = new TiBlob(TYPE_FILE, file, mimeType);
blob.loadBitmapInfo();
return blob;
}
/**
* Creates a blob from a bitmap.
* @param image the image used to create blob.
* @return new instance of TiBlob.
* @module.api
*/
public static TiBlob blobFromImage(Bitmap image)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte data[] = new byte[0];
if (image.hasAlpha()) {
if (image.compress(CompressFormat.PNG, 100, bos)) {
data = bos.toByteArray();
}
}
else {
if (image.compress(CompressFormat.JPEG, 100, bos)) {
data = bos.toByteArray();
}
}
TiBlob blob = new TiBlob(TYPE_IMAGE, data, "image/bitmap");
blob.image = image;
blob.width = image.getWidth();
blob.height = image.getHeight();
return blob;
}
/**
* Creates a blob from binary data, with mimeType as "application/octet-stream".
* @param data data used to create blob.
* @return new instance of TiBlob.
* @module.api
*/
public static TiBlob blobFromData(byte[] data)
{
return blobFromData(data, "application/octet-stream");
}
/**
* Creates a blob from binary data with the specified mimetype.
* If the passed mimetype is null, "application/octet-stream" will be used instead.
* @param data binary data used to create blob.
* @param mimetype mimetype used to create blob.
* @return a new instance of TiBlob.
* @module.api
*/
public static TiBlob blobFromData(byte[] data, String mimetype)
{
if (mimetype == null || mimetype.length() == 0) {
return new TiBlob(TYPE_DATA, data, "application/octet-stream");
}
TiBlob blob = new TiBlob(TYPE_DATA, data, mimetype);
blob.loadBitmapInfo();
return blob;
}
/**
* Determines the MIME-type by reading first few characters from the given input stream.
* @return the guessed MIME-type or null if the type could not be determined.
*/
public String guessContentTypeFromStream()
{
String mt = null;
InputStream is = getInputStream();
if (is != null) {
try {
mt = URLConnection.guessContentTypeFromStream(is);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e, Log.DEBUG_MODE);
}
}
return mt;
}
/**
* Update width and height if the file / data can be decoded into a bitmap successfully.
*/
public void loadBitmapInfo()
{
String mt = guessContentTypeFromStream();
// Update mimetype based on the guessed MIME-type.
if (mt != null && mt != mimetype) {
mimetype = mt;
}
/**
* Returns the content of blob in form of binary data. Exception will be thrown
* if blob's type is unknown.
* @return binary data.
* @module.api
*/
public byte[] getBytes()
{
byte[] bytes = new byte[0];
switch(type) {
case TYPE_STRING :
try {
bytes = ((String) data).getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e.getMessage(), e);
}
break;
case TYPE_DATA:
case TYPE_IMAGE:
//TODO deal with mimetypes.
bytes = (byte[]) data;
break;
case TYPE_FILE:
InputStream stream = getInputStream();
if (stream != null) {
try {
bytes = KrollStreamHelper.toByteArray(stream, getLength());
} finally {
try {
stream.close();
} catch (IOException e) {
Log.w(TAG, e.getMessage(), e);
}
}
}
break;
default :
throw new IllegalArgumentException("Unknown Blob type id " + type);
}
return bytes;
}
@Kroll.getProperty @Kroll.method
public int getLength()
{
switch (type) {
case TYPE_FILE:
long fileSize;
if (data instanceof TitaniumBlob) {
fileSize = ((TitaniumBlob) data).getFile().length();
} else {
fileSize = ((TiBaseFile) data).size();
}
return (int) fileSize;
case TYPE_DATA:
case TYPE_IMAGE:
return ((byte[])data).length;
default:
// this is probably overly expensive.. is there a better way?
return getBytes().length;
}
}
/**
* @return An InputStream for reading the data of this blob.
* @module.api
*/
public InputStream getInputStream()
{
switch (type) {
case TYPE_FILE:
try {
return ((TiBaseFile)data).getInputStream();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
default:
return new ByteArrayInputStream(getBytes());
}
}
@Kroll.method
public void append(TiBlob blob)
{
switch(type) {
case TYPE_STRING :
try {
String dataString = (String)data;
dataString += new String(blob.getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e.getMessage(), e);
}
break;
case TYPE_IMAGE:
case TYPE_DATA :
byte[] dataBytes = (byte[]) data;
byte[] appendBytes = blob.getBytes();
byte[] newData = new byte[dataBytes.length + appendBytes.length];
System.arraycopy(dataBytes, 0, newData, 0, dataBytes.length);
System.arraycopy(appendBytes, 0, newData, dataBytes.length, appendBytes.length);
data = newData;
break;
case TYPE_FILE :
throw new IllegalStateException("Not yet implemented. TYPE_FILE");
// break;
default :
throw new IllegalArgumentException("Unknown Blob type id " + type);
}
}
@Kroll.getProperty @Kroll.method
public String getText()
{
String result = null;
// Only support String and Data. Same as iPhone
switch(type) {
case TYPE_STRING :
result = (String) data;
case TYPE_DATA:
case TYPE_FILE:
// Don't try to return a string if we can see the
// mimetype is binary, unless it's application/octet-stream, which means
// we don't really know what it is, so assume the user-developer knows
// what she's doing.
if (mimetype != null && TiMimeTypeHelper.isBinaryMimeType(mimetype) && mimetype != "application/octet-stream") {
return null;
}
try {
result = new String(getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
Log.w(TAG, "Unable to convert to string.");
}
break;
}
return result;
}
@Kroll.getProperty @Kroll.method
public String getMimeType()
{
return mimetype;
}
/**
* @return the blob's data.
* @module.api
*/
public Object getData()
{
return data;
}
/**
* @return The type of this Blob.
* @see TiBlob#TYPE_DATA
* @see TiBlob#TYPE_FILE
* @see TiBlob#TYPE_IMAGE
* @see TiBlob#TYPE_STRING
* @module.api
*/
@Kroll.getProperty @Kroll.method
public int getType()
{
return type;
}
@Kroll.getProperty @Kroll.method
public int getWidth()
{
return width;
}
@Kroll.getProperty @Kroll.method
public int getHeight()
{
return height;
}
@Kroll.method
public String toString()
{
// blob should return the text value on toString
// if it's not null
String text = getText();
if (text != null) {
return text;
}
return "[object TiBlob]";
}
@Kroll.getProperty @Kroll.method
public String getNativePath()
{
if (data == null) {
return null;
}
if (this.type != TYPE_FILE) {
Log.w(TAG, "getNativePath not supported for non-file blob types.");
return null;
} else if (!(data instanceof TiBaseFile)) {
Log.w(TAG, "getNativePath unable to return value: underlying data is not file, rather " + data.getClass().getName());
return null;
} else {
String path = ((TiBaseFile)data).nativePath();
if (path != null && path.startsWith("content:
File f = ((TiBaseFile)data).getNativeFile();
if (f != null) {
path = f.getAbsolutePath();
if (path != null && path.startsWith("/")) {
path = "file://" + path;
}
}
}
return path;
}
}
@Kroll.getProperty @Kroll.method
public TiFileProxy getFile()
{
if (data == null) {
return null;
}
if (this.type != TYPE_FILE) {
Log.w(TAG, "getFile not supported for non-file blob types.");
return null;
} else if (!(data instanceof TiBaseFile)) {
Log.w(TAG, "getFile unable to return value: underlying data is not file, rather " + data.getClass().getName());
return null;
} else {
return new TiFileProxy((TiBaseFile)data);
}
}
@Kroll.method
public String toBase64()
{
return new String(Base64.encodeBase64(getBytes()));
}
public Bitmap getImage()
{
// If the image is not available but the width and height of the image are successfully fetched, the image can
if (image == null && (width > 0 && height > 0)) {
switch (type) {
case TYPE_FILE:
return BitmapFactory.decodeStream(getInputStream());
case TYPE_DATA:
byte[] byteArray = (byte[]) data;
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
}
return image;
}
@Kroll.method
public TiBlob imageAsCropped(Object params)
{
Bitmap img = getImage();
if (img == null) {
return null;
}
if (!(params instanceof HashMap)) {
Log.e(TAG, "Argument for imageAsCropped must be a dictionary");
return null;
}
KrollDict options = new KrollDict((HashMap) params);
int widthCropped = options.optInt(TiC.PROPERTY_WIDTH, width);
int heightCropped = options.optInt(TiC.PROPERTY_HEIGHT, height);
int x = options.optInt(TiC.PROPERTY_X, (width - widthCropped) / 2);
int y = options.optInt(TiC.PROPERTY_Y, (height - heightCropped) / 2);
try {
Bitmap imageCropped = Bitmap.createBitmap(img, x, y, widthCropped, heightCropped);
return blobFromImage(imageCropped);
} catch (OutOfMemoryError e) {
Log.e(TAG, "Unable to crop the image. Not enough memory: " + e.getMessage(), e);
return null;
}
}
@Kroll.method
public TiBlob imageAsResized(Number width, Number height)
{
Bitmap img = getImage();
if (img == null) {
return null;
}
int dstWidth = width.intValue();
int dstHeight = height.intValue();
try {
Bitmap imageResized = Bitmap.createScaledBitmap(img, dstWidth, dstHeight, true);
return blobFromImage(imageResized);
} catch (OutOfMemoryError e) {
Log.e(TAG, "Unable to resize the image. Not enough memory: " + e.getMessage(), e);
return null;
}
}
@Kroll.method
public TiBlob imageAsThumbnail(Number size, @Kroll.argument(optional = true) Number borderSize,
@Kroll.argument(optional = true) Number cornerRadius)
{
Bitmap img = getImage();
if (img == null) {
return null;
}
int thumbnailSize = size.intValue();
Bitmap imageThumbnail = ThumbnailUtils.extractThumbnail(img, thumbnailSize, thumbnailSize);
float border = 1f;
if (borderSize != null) {
border = borderSize.floatValue();
}
float radius = 0f;
if (cornerRadius != null) {
radius = cornerRadius.floatValue();
}
if (border == 0 && radius == 0) {
return blobFromImage(imageThumbnail);
}
Bitmap imageThumbnailBorder = TiImageHelper.imageWithRoundedCorner(imageThumbnail, radius, border);
return blobFromImage(imageThumbnailBorder);
}
@Kroll.method
public TiBlob imageWithAlpha()
{
Bitmap img = getImage();
if (img == null) {
return null;
}
Bitmap imageWithAlpha = TiImageHelper.imageWithAlpha(img);
return blobFromImage(imageWithAlpha);
}
@Kroll.method
public TiBlob imageWithRoundedCorner(Number cornerRadius, @Kroll.argument(optional = true) Number borderSize)
{
Bitmap img = getImage();
if (img == null) {
return null;
}
float radius = cornerRadius.floatValue();
float border = 1f;
if (borderSize != null) {
border = borderSize.floatValue();
}
Bitmap imageRoundedCorner = TiImageHelper.imageWithRoundedCorner(img, radius, border);
return blobFromImage(imageRoundedCorner);
}
@Kroll.method
public TiBlob imageWithTransparentBorder(Number size)
{
Bitmap img = getImage();
if (img == null) {
return null;
}
int borderSize = size.intValue();
Bitmap imageWithBorder = TiImageHelper.imageWithTransparentBorder(img, borderSize);
return blobFromImage(imageWithBorder);
}
} |
package org.gemoc.execution.sequential.javaengine.ui.launcher.tabs;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider;
import org.eclipse.xtext.naming.QualifiedName;
import org.gemoc.commons.eclipse.emf.URIHelper;
import org.gemoc.commons.eclipse.ui.dialogs.SelectAnyIFileDialog;
import org.gemoc.execution.sequential.javaengine.PlainK3ExecutionEngine;
import org.gemoc.execution.sequential.javaengine.ui.Activator;
import org.gemoc.execution.sequential.javaengine.ui.launcher.LauncherMessages;
import org.gemoc.executionframework.engine.commons.MelangeHelper;
import org.gemoc.executionframework.engine.ui.commons.RunConfiguration;
import org.gemoc.executionframework.ui.utils.ENamedElementQualifiedNameLabelProvider;
import org.gemoc.xdsmlframework.ui.utils.dialogs.SelectAIRDIFileDialog;
import org.gemoc.xdsmlframework.ui.utils.dialogs.SelectAnyEObjectDialog;
import org.gemoc.xdsmlframework.ui.utils.dialogs.SelectMainMethodDialog;
import org.osgi.framework.Bundle;
import fr.obeo.dsl.debug.ide.launch.AbstractDSLLaunchConfigurationDelegate;
import fr.obeo.dsl.debug.ide.sirius.ui.launch.AbstractDSLLaunchConfigurationDelegateUI;
/**
* Sequential engine launch configuration main tab
*
* @author Didier Vojtisek<didier.vojtisek@inria.fr>
*/
public class LaunchConfigurationMainTab extends LaunchConfigurationTab {
protected Composite _parent;
protected Text _modelLocationText;
protected Text _modelInitializationMethodText;
protected Text _modelInitializationArgumentsText;
protected Text _siriusRepresentationLocationText;
protected Button _animateButton;
protected Text _delayText;
protected Text _melangeQueryText;
protected Button _animationFirstBreak;
protected Group _k3Area;
protected Text _entryPointModelElementText;
protected Label _entryPointModelElementLabel;
protected Text _entryPointMethodText;
protected Combo _languageCombo;
protected Text modelofexecutionglml_LocationText;
/**
* default width for the grids
*/
public int gridDefaultWidth = 200;
protected IProject _modelProject;
@Override
public void createControl(Composite parent) {
_parent = parent;
Composite area = new Composite(parent, SWT.NULL);
GridLayout gl = new GridLayout(1, false);
gl.marginHeight = 0;
area.setLayout(gl);
area.layout();
setControl(area);
Group modelArea = createGroup(area, "Model:");
createModelLayout(modelArea, null);
Group languageArea = createGroup(area, "Language:");
createLanguageLayout(languageArea, null);
Group debugArea = createGroup(area, "Animation:");
createAnimationLayout(debugArea, null);
_k3Area = createGroup(area, "Sequential DSA execution:");
createK3Layout(_k3Area, null);
}
@Override
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(RunConfiguration.LAUNCH_DELAY, 1000);
configuration.setAttribute(RunConfiguration.LAUNCH_MODEL_ENTRY_POINT, "");
configuration.setAttribute(RunConfiguration.LAUNCH_METHOD_ENTRY_POINT, "");
configuration.setAttribute(RunConfiguration.LAUNCH_SELECTED_LANGUAGE, "");
}
@Override
public void initializeFrom(ILaunchConfiguration configuration) {
try {
RunConfiguration runConfiguration = new RunConfiguration(
configuration);
_modelLocationText.setText(URIHelper
.removePlatformScheme(runConfiguration
.getExecutedModelURI()));
if (runConfiguration.getAnimatorURI() != null)
_siriusRepresentationLocationText
.setText(URIHelper
.removePlatformScheme(runConfiguration
.getAnimatorURI()));
else
_siriusRepresentationLocationText.setText("");
_delayText.setText(Integer.toString(runConfiguration
.getAnimationDelay()));
_animationFirstBreak.setSelection(runConfiguration.getBreakStart());
_entryPointModelElementText.setText(runConfiguration
.getModelEntryPoint());
_entryPointMethodText.setText(runConfiguration
.getExecutionEntryPoint());
_languageCombo.setText(runConfiguration
.getLanguageName());
_modelInitializationArgumentsText.setText(runConfiguration.getModelInitializationArguments());
_entryPointModelElementLabel.setText("");
updateMainElementName();
} catch (CoreException e) {
Activator.error(e.getMessage(), e);
}
}
@Override
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(
AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI,
this._modelLocationText.getText());
configuration.setAttribute(
AbstractDSLLaunchConfigurationDelegateUI.SIRIUS_RESOURCE_URI,
this._siriusRepresentationLocationText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_DELAY,
Integer.parseInt(_delayText.getText()));
configuration.setAttribute(RunConfiguration.LAUNCH_SELECTED_LANGUAGE,
_languageCombo.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_MELANGE_QUERY,
_melangeQueryText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_MODEL_ENTRY_POINT,
_entryPointModelElementText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_METHOD_ENTRY_POINT,
_entryPointMethodText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_INITIALIZATION_METHOD,
_modelInitializationMethodText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_INITIALIZATION_ARGUMENTS,
_modelInitializationArgumentsText.getText());
configuration.setAttribute(RunConfiguration.LAUNCH_BREAK_START,
_animationFirstBreak.getSelection());
// DebugModelID for sequential engine
configuration.setAttribute(RunConfiguration.DEBUG_MODEL_ID, Activator.DEBUG_MODEL_ID);
}
@Override
public String getName() {
return "Main";
}
/**
* Basic modify listener that can be reused if there is no more precise need
*/
private ModifyListener fBasicModifyListener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent arg0) {
updateLaunchConfigurationDialog();
}
};
/***
* Create the Fields where user enters model to execute
*
* @param parent container composite
* @param font used font
* @return the created composite containing the fields
*/
public Composite createModelLayout(Composite parent, Font font) {
createTextLabelLayout(parent, "Model to execute");
// Model location text
_modelLocationText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_modelLocationText.setLayoutData(createStandardLayout());
_modelLocationText.setFont(font);
_modelLocationText.addModifyListener(fBasicModifyListener);
Button modelLocationButton = createPushButton(parent, "Browse", null);
modelLocationButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
// handleModelLocationButtonSelected();
// TODO launch the appropriate selector
SelectAnyIFileDialog dialog = new SelectAnyIFileDialog();
if (dialog.open() == Dialog.OK) {
String modelPath = ((IResource) dialog.getResult()[0])
.getFullPath().toPortableString();
_modelLocationText.setText(modelPath);
updateLaunchConfigurationDialog();
_modelProject = ((IResource) dialog.getResult()[0]).getProject();
}
}
});
createTextLabelLayout(parent, "Model initialization method");
_modelInitializationMethodText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_modelInitializationMethodText.setLayoutData(createStandardLayout());
_modelInitializationMethodText.setFont(font);
_modelInitializationMethodText.setEditable(false);
createTextLabelLayout(parent, "");
createTextLabelLayout(parent, "Model initialization arguments");
_modelInitializationArgumentsText = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
_modelInitializationArgumentsText.setToolTipText("one argument per line");
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.heightHint = 40;
_modelInitializationArgumentsText.setLayoutData(gridData);
//_modelInitializationArgumentsText.setLayoutData(createStandardLayout());
_modelInitializationArgumentsText.setFont(font);
_modelInitializationArgumentsText.setEditable(true);
_modelInitializationArgumentsText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateLaunchConfigurationDialog();
}
});
createTextLabelLayout(parent, "");
return parent;
}
private Composite createAnimationLayout(Composite parent, Font font) {
createTextLabelLayout(parent, "Animator");
_siriusRepresentationLocationText = new Text(parent, SWT.SINGLE
| SWT.BORDER);
_siriusRepresentationLocationText.setLayoutData(createStandardLayout());
_siriusRepresentationLocationText.setFont(font);
_siriusRepresentationLocationText
.addModifyListener(fBasicModifyListener);
Button siriusRepresentationLocationButton = createPushButton(parent,
"Browse", null);
siriusRepresentationLocationButton
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
// handleModelLocationButtonSelected();
// TODO launch the appropriate selector
SelectAIRDIFileDialog dialog = new SelectAIRDIFileDialog();
if (dialog.open() == Dialog.OK) {
String modelPath = ((IResource) dialog.getResult()[0])
.getFullPath().toPortableString();
_siriusRepresentationLocationText
.setText(modelPath);
updateLaunchConfigurationDialog();
}
}
});
createTextLabelLayout(parent, "Delay");
_delayText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_delayText.setLayoutData(createStandardLayout());
_delayText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateLaunchConfigurationDialog();
}
});
createTextLabelLayout(parent, "(in milliseconds)");
new Label(parent, SWT.NONE).setText("");
_animationFirstBreak = new Button(parent, SWT.CHECK);
_animationFirstBreak.setText("Break at start");
_animationFirstBreak.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
updateLaunchConfigurationDialog();
}
}
);
return parent;
}
private GridData createStandardLayout() {
return new GridData(SWT.FILL, SWT.CENTER, true, false);
}
/***
* Create the Field where user enters the language used to execute
*
* @param parent container composite
* @param font used font
* @return the created composite containing the fields
*/
public Composite createLanguageLayout(Composite parent, Font font) {
// Language
createTextLabelLayout(parent, "Melange languages");
_languageCombo = new Combo(parent, SWT.NONE);
_languageCombo.setLayoutData(createStandardLayout());
List<String> languagesNames = MelangeHelper.getAllLanguages();
String[] empty = {};
_languageCombo.setItems(languagesNames.toArray(empty));
_languageCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//String selection = _languageCombo.getText();
//List<String> modelTypeNames = MelangeHelper.getModelTypes(selection);
updateLaunchConfigurationDialog();
}
});
createTextLabelLayout(parent, "");
createTextLabelLayout(parent, "Melange resource adapter query");
_melangeQueryText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_melangeQueryText.setLayoutData(createStandardLayout());
_melangeQueryText.setFont(font);
_melangeQueryText.setEditable(false);
createTextLabelLayout(parent, "");
return parent;
}
private Composite createK3Layout(Composite parent, Font font) {
createTextLabelLayout(parent, "Main method");
_entryPointMethodText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_entryPointMethodText.setLayoutData(createStandardLayout());
_entryPointMethodText.setFont(font);
_entryPointMethodText.setEditable(false);
_entryPointMethodText.addModifyListener(fBasicModifyListener);
Button mainMethodBrowseButton = createPushButton(parent, "Browse", null);
mainMethodBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if(_languageCombo.getText() == null){
setErrorMessage("Please select a language.");
}
else{
Set<Class<?>> candidateAspects = MelangeHelper.getAspects(_languageCombo.getText());
SelectMainMethodDialog dialog = new SelectMainMethodDialog(
candidateAspects, new ENamedElementQualifiedNameLabelProvider());
int res = dialog.open();
if (res == WizardDialog.OK) {
Method selection = (Method) dialog.getFirstResult();
_entryPointMethodText.setText(selection.toString());
}
}
}
});
createTextLabelLayout(parent, "Main model element path");
_entryPointModelElementText = new Text(parent, SWT.SINGLE | SWT.BORDER);
_entryPointModelElementText.setLayoutData(createStandardLayout());
_entryPointModelElementText.setFont(font);
_entryPointModelElementText.setEditable(false);
_entryPointModelElementText.addModifyListener(event -> updateMainElementName());
_entryPointModelElementText.addModifyListener(fBasicModifyListener);
Button mainModelElemBrowseButton = createPushButton(parent, "Browse",
null);
mainModelElemBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Resource model = getModel();
if( model == null){
setErrorMessage("Please select a model to execute.");
}
else if(_entryPointMethodText.getText() == null || _entryPointMethodText.getText().equals("")){
setErrorMessage("Please select a main method.");
}
else {
SelectAnyEObjectDialog dialog = new SelectAnyEObjectDialog(
PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell(),
model.getResourceSet(),
new ENamedElementQualifiedNameLabelProvider()){
protected boolean select(EObject obj) {
String methodSignature = _entryPointMethodText.getText();
String firstParamType = MelangeHelper.getParametersType(methodSignature)[0];
String simpleParamType = MelangeHelper.lastSegment(firstParamType);
return obj.eClass().getName().equals(simpleParamType);
}
};
int res = dialog.open();
if (res == WizardDialog.OK) {
EObject selection = (EObject) dialog.getFirstResult();
String uriFragment = selection.eResource()
.getURIFragment(selection);
_entryPointModelElementText.setText(uriFragment);
}
}
}
});
createTextLabelLayout(parent, "Main model element name");
_entryPointModelElementLabel = new Label(parent, SWT.HORIZONTAL);
_entryPointModelElementLabel.setText("");
return parent;
}
@Override
protected void updateLaunchConfigurationDialog() {
super.updateLaunchConfigurationDialog();
_k3Area.setVisible(true);
_modelInitializationMethodText.setText(getModelInitializationMethodName());
_modelInitializationArgumentsText.setEnabled(!_modelInitializationMethodText.getText().isEmpty());
_melangeQueryText.setText(computeMelangeQuery());
}
/**
* compute the Melange query for loading the given model as the requested language
* If the language is already the good one, the query will be empty. (ie. melange downcast is not used)
* @return
*/
protected String computeMelangeQuery(){
String result = "";
String languageName = this._languageCombo.getText();
if(!this._modelLocationText.getText().isEmpty() && !languageName.isEmpty()){
Resource model = getModel();
List<String> modelNativeLanguages = MelangeHelper.getNativeLanguagesUsedByResource(model);
if(!modelNativeLanguages.isEmpty() && !modelNativeLanguages.get(0).equals(languageName)){
// TODO this version consider only the first native language, we need to think about models containing elements coming from several languages
String languageMT = MelangeHelper.getModelType(languageName);
if(languageMT == null){ languageMT = languageName+"MT"; }
// result="?lang="+languageName+"&mt="+languageMT;
result="?lang="+languageName; // we need a simple downcast without adapter
}
}
return result;
}
protected String getModelInitializationMethodName(){
String entryPointClassName = null;
final String prefix = "public static void ";
int startName = prefix.length();
int endName = _entryPointMethodText.getText().lastIndexOf("(");
if(endName == -1) return "";
String entryMethod = _entryPointMethodText.getText().substring(startName, endName);
int lastDot = entryMethod.lastIndexOf(".");
if(lastDot != -1){
entryPointClassName = entryMethod.substring(0, lastDot);
}
Bundle bundle = MelangeHelper.getMelangeBundle(_languageCombo.getText());
if(entryPointClassName != null && bundle != null){
try {
Class<?> entryPointClass = bundle.loadClass(entryPointClassName);
for(Method m : entryPointClass.getMethods()){
// TODO find a better search mechanism (check signature, inheritance, aspects, etc)
if(m.isAnnotationPresent(fr.inria.diverse.k3.al.annotationprocessor.InitializeModel.class)){
return entryPointClassName+"."+m.getName();
}
}
} catch (ClassNotFoundException e) {}
}
return "";
}
/**
* caches the current model resource in order to avoid to reload it many times
* use {@link getModel()} in order to access it.
*/
private Resource currentModelResource;
private Resource getModel() {
URI modelURI = URI.createPlatformResourceURI(_modelLocationText.getText(), true);
if(currentModelResource == null || !currentModelResource.getURI().equals(modelURI)){
currentModelResource = PlainK3ExecutionEngine.loadModel(modelURI);
}
return currentModelResource;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration)
*/
@Override
public boolean isValid(ILaunchConfiguration config) {
setErrorMessage(null);
setMessage(null);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
String modelName = _modelLocationText.getText().trim();
if (modelName.length() > 0) {
IResource modelIResource = workspace.getRoot().findMember(modelName);
if (modelIResource == null || !modelIResource.exists()) {
setErrorMessage(NLS.bind(LauncherMessages.SequentialMainTab_model_doesnt_exist, new String[] {modelName}));
return false;
}
if (modelName.equals("/")) {
setErrorMessage(LauncherMessages.SequentialMainTab_Model_not_specified);
return false;
}
if (! (modelIResource instanceof IFile)) {
setErrorMessage(NLS.bind(LauncherMessages.SequentialMainTab_invalid_model_file, new String[] {modelName}));
return false;
}
}
if (modelName.length() == 0) {
setErrorMessage(LauncherMessages.SequentialMainTab_Model_not_specified);
return false;
}
String languageName = _languageCombo.getText().trim();
if (languageName.length() == 0) {
setErrorMessage(LauncherMessages.SequentialMainTab_Language_not_specified);
return false;
}
else if(MelangeHelper.getEntryPoints(languageName).isEmpty()){
setErrorMessage(LauncherMessages.SequentialMainTab_Language_main_methods_dont_exist);
return false;
}
String mainMethod = _entryPointMethodText.getText().trim();
if (mainMethod.length() == 0) {
setErrorMessage(LauncherMessages.SequentialMainTab_Language_main_method_not_selected);
return false;
}
String rootElement = _entryPointModelElementText.getText().trim();
if (rootElement.length() == 0) {
setErrorMessage(LauncherMessages.SequentialMainTab_Language_root_element_not_selected);
return false;
}
String[] params =MelangeHelper.getParametersType(mainMethod);
String firstParam = MelangeHelper.lastSegment(params[0]);
String rootEClass = getModel().getEObject(rootElement).eClass().getName();
if( !(params.length == 1 && firstParam.equals(rootEClass)) ){
setErrorMessage(LauncherMessages.SequentialMainTab_Language_incompatible_root_and_main);
return false;
}
return true;
}
/**
* Update _entryPointModelElement with pretty name
*/
private void updateMainElementName(){
try {
Resource model = getModel();
EObject mainElement = null;
if(model != null){
mainElement = model.getEObject(_entryPointModelElementText.getText());
}
if(mainElement != null){
org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider nameprovider = new DefaultDeclarativeQualifiedNameProvider();
QualifiedName qname = nameprovider.getFullyQualifiedName(mainElement);
String objectName = qname != null ? qname.toString(): mainElement.toString();
String prettyName = objectName+ " : "+mainElement.eClass().getName();
_entryPointModelElementLabel.setText(prettyName);
}
} catch (Exception e) { }
}
} |
package org.xwiki.gwt.wysiwyg.client.widget.wizard.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xwiki.gwt.user.client.ui.wizard.NavigationListener;
import org.xwiki.gwt.user.client.ui.wizard.NavigationListenerCollection;
import org.xwiki.gwt.user.client.ui.wizard.SourcesNavigationEvents;
import org.xwiki.gwt.user.client.ui.wizard.WizardStep;
import org.xwiki.gwt.wysiwyg.client.Strings;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TabPanel;
/**
* Wizard step used to aggregate a set of selectors for a file attached (file attachment or image) to a page in the
* wiki, and switch between the current page view and the entire wiki view.
*
* @param <T> the type of object edited by this wizard step
* @see AbstractSelectorWizardStep
* @version $Id$
*/
public abstract class AbstractSelectorAggregatorWizardStep<T> extends AbstractSelectorWizardStep<T> implements
SelectionHandler<Integer>, SourcesNavigationEvents, NavigationListener
{
/**
* Loading class for the time to load the step to which it has been toggled.
*/
private static final String STYLE_LOADING = "loading";
/**
* Loading class for the time to load the step to which it has been toggled.
*/
private static final String STYLE_ERROR = "errormessage";
/**
* The map of wizard step instances of the steps aggregated by this step.
*/
private Map<String, WizardStep> steps = new HashMap<String, WizardStep>();
/**
* The state of the initialization of the aggregated wizard steps.
*/
private Map<WizardStep, Boolean> initialized = new HashMap<WizardStep, Boolean>();
/**
* The tabbed panel of the wizard step.
*/
private final TabPanel tabPanel = new TabPanel();
/**
* The navigation listeners for this selector step, to pass further potential navigation events launched by
* aggregated steps.
*/
private NavigationListenerCollection listeners = new NavigationListenerCollection();
/**
* Creates a new aggregator selector wizard step.
*/
public AbstractSelectorAggregatorWizardStep()
{
tabPanel.addStyleName("xStepsTabs");
tabPanel.addSelectionHandler(this);
display().add(tabPanel);
display().addStyleName("xSelectorAggregatorStep");
}
/**
* @param name the name of the step to get
* @return the step for the passed name
*/
protected WizardStep getStep(String name)
{
if (steps.get(name) == null) {
// save it in the steps
WizardStep instance = getStepInstance(name);
steps.put(name, instance);
// add this as a listener, if it's the case, to pass further the navigation events
if (instance instanceof SourcesNavigationEvents) {
((SourcesNavigationEvents) instance).addNavigationListener(this);
}
// as uninitialized
initialized.put(instance, false);
}
return steps.get(name);
}
/**
* @param name the name of the step to initialize
* @return an instance of the step recognized by the passed name
*/
protected abstract WizardStep getStepInstance(String name);
/**
* @return the list of all step names
*/
protected abstract List<String> getStepNames();
/**
* @return the step which should be selected by default, the first step name by default
*/
protected String getDefaultStepName()
{
return getStepNames().get(0);
}
/**
* {@inheritDoc}
*
* @see SelectionHandler#onSelection(SelectionEvent)
*/
public void onSelection(SelectionEvent<Integer> event)
{
if (event.getSource() != tabPanel) {
return;
}
tabPanel.addStyleName(STYLE_LOADING);
// get the step to be prepared and shown
String stepName = tabPanel.getTabBar().getTabHTML(event.getSelectedItem());
final WizardStep stepToShow = getStep(stepName);
final FlowPanel stepPanel = (FlowPanel) tabPanel.getWidget(tabPanel.getDeckPanel().getVisibleWidget());
// hide its contents until after load
if (stepPanel.getWidgetCount() > 0) {
stepPanel.getWidget(0).setVisible(false);
}
// initialize only if it wasn't initialized before
lazyInitializeStep(stepToShow, new AsyncCallback<Object>()
{
public void onSuccess(Object result)
{
onStepInitialized(stepToShow, stepPanel);
}
public void onFailure(Throwable caught)
{
stepPanel.setVisible(true);
tabPanel.removeStyleName(STYLE_LOADING);
showError(Strings.INSTANCE.linkErrorLoadingData(), stepPanel);
}
});
}
/**
* Helper function to handle the success of the step initialization on tab select.
*
* @param step the step that just finished loading
* @param stepPanel the container panel of the tab where this widget is to be displayed
*/
private void onStepInitialized(WizardStep step, FlowPanel stepPanel)
{
// remove any existant error message
if (stepPanel.getWidgetCount() > 0 && stepPanel.getWidget(0).getStyleName().contains(STYLE_ERROR)) {
stepPanel.clear();
}
// add the UI of the step we switched to to the tabbed panel, if not already there
if (stepPanel.getWidgetCount() == 0) {
stepPanel.add(step.display());
}
stepPanel.getWidget(0).setVisible(true);
tabPanel.removeStyleName(STYLE_LOADING);
if (step instanceof AbstractSelectorWizardStep) {
((AbstractSelectorWizardStep< ? >) step).setActive();
}
}
/**
* Helper function to show an error in the passed panel.
*
* @param message the error message
* @param panel the panel in which the error is to be displayed
*/
private void showError(String message, Panel panel)
{
// remove all content before
panel.clear();
Label error = new Label(message);
error.addStyleName(STYLE_ERROR);
panel.add(error);
}
/**
* Selects the tab indicated by the passed name.
*
* @param tabName the name of the tab to select
*/
protected void selectTab(String tabName)
{
// searched for the specified tab and select it
for (int i = 0; i < tabPanel.getTabBar().getTabCount(); i++) {
if (tabPanel.getTabBar().getTabHTML(i).equals(tabName)) {
tabPanel.selectTab(i);
break;
}
}
}
/**
* @return the currently selected wizard step, or the default step if no selection is made
*/
private WizardStep getCurrentStep()
{
String selectedStepName = getSelectedStepName();
return getStep(selectedStepName == null ? getDefaultStepName() : selectedStepName);
}
/**
* @return the name of the currently selected wizard step, or {@code null} if no selection is made
*/
private String getSelectedStepName()
{
int selectedTab = tabPanel.getTabBar().getSelectedTab();
String currentStepName = null;
if (selectedTab > 0) {
currentStepName = tabPanel.getTabBar().getTabHTML(selectedTab);
}
return currentStepName;
}
/**
* {@inheritDoc}
*/
public String getDirectionName(NavigationDirection direction)
{
return getCurrentStep().getDirectionName(direction);
}
/**
* {@inheritDoc}
*/
public String getNextStep()
{
return getCurrentStep().getNextStep();
}
/**
* {@inheritDoc}
*/
public Object getResult()
{
return getCurrentStep().getResult();
}
/**
* {@inheritDoc}
*/
public void init(Object data, final AsyncCallback< ? > cb)
{
// Maybe initialize the tab bar.
if (tabPanel.getTabBar().getTabCount() == 0) {
// Fill the tab bar with the names of the aggregated wizard steps.
for (String stepName : getStepNames()) {
tabPanel.add(new FlowPanel(), stepName);
}
}
// Aggregated wizard steps have to be reinitialized.
for (WizardStep step : initialized.keySet()) {
initialized.put(step, false);
}
super.init(data, new AsyncCallback<Object>()
{
public void onSuccess(Object result)
{
dispatchInit(cb);
}
public void onFailure(Throwable caught)
{
cb.onFailure(caught);
}
});
}
/**
* Dispatches the initialization of the tabbed panel to the appropriate step, depending on the required step, the
* initialization of this aggregator and the current selected step, if any.
*
* @param cb the initialization callback
*/
private void dispatchInit(final AsyncCallback< ? > cb)
{
// pick the right tab to select
String stepName = getRequiredStep();
if (stepName == null) {
stepName = getSelectedStepName();
if (stepName == null) {
stepName = getDefaultStepName();
}
}
// select the chosen tab
selectTab(stepName);
// always return null, failure of aggregated step initialization will be handled inside this aggregator step,
// because one aggregated step failure should not prevent the others to be selected
cb.onSuccess(null);
}
/**
* Initializes the passed step only if it wasn't initialized yet (i.e. it's the first display of this step).
*
* @param step the step to initialize
* @param cb the call back to handle asynchronous load of the step
*/
private void lazyInitializeStep(final WizardStep step, final AsyncCallback< ? > cb)
{
if (!initialized.get(step)) {
step.init(getData(), new AsyncCallback<Object>()
{
public void onSuccess(Object result)
{
// only mark as initialized when init succeeded, so that a second retry is attempted and its panel
// is not used further if init fails to initialize it correctly
initialized.put(step, true);
if (cb != null) {
cb.onSuccess(null);
}
}
public void onFailure(Throwable caught)
{
if (cb != null) {
cb.onFailure(caught);
}
}
});
return;
}
// nothing to do, just signal success
cb.onSuccess(null);
}
/**
* @return the name of the step required to be loaded by the current created or edited element, if any, or null
* otherwise (if previous selection should be preserved). To be overwritten by subclasses to detect whether
* the data being handled requires the "all pages" step to be loaded or not.
*/
protected String getRequiredStep()
{
// by default, no requirement is made
return null;
}
/**
* {@inheritDoc}
*/
public void onCancel()
{
getCurrentStep().onCancel();
}
/**
* {@inheritDoc}
*/
public void onSubmit(AsyncCallback<Boolean> async)
{
getCurrentStep().onSubmit(async);
}
/**
* {@inheritDoc}
*/
public void addNavigationListener(NavigationListener listener)
{
// cannot delegate here because the steps shouldn't be initialized only to add listeners; only current step
// should fire navigation events.
listeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removeNavigationListener(NavigationListener listener)
{
listeners.remove(listener);
}
/**
* {@inheritDoc}
*/
public void onDirection(NavigationDirection direction)
{
// FIXME: at this point we assume that only the current step will send navigation event, or we relaunch the
// navigation events of all steps, regardless if they're active or not. This is a good enough assumption ftm,
// since navigation events are issued by user actions and right now only the current step is visible at a given
// moment.
listeners.fireNavigationEvent(direction);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.