answer
stringlengths 17
10.2M
|
|---|
package org.roaringbitmap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
/**
* Fast algorithms to aggregate many bitmaps.
*
* @author Daniel Lemire
*/
public final class FastAggregation {
/**
* Compute the AND aggregate.
*
* In practice, calls {#link naive_and}
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap and(Iterator<RoaringBitmap> bitmaps) {
return naive_and(bitmaps);
}
/**
* Compute the AND aggregate.
*
* In practice, calls {#link naive_and}
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap and(RoaringBitmap... bitmaps) {
return naive_and(bitmaps);
}
/**
* Calls naive_or.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
@Deprecated
public static RoaringBitmap horizontal_or(Iterator<RoaringBitmap> bitmaps) {
return naive_or(bitmaps);
}
/**
* Minimizes memory usage while computing the or aggregate on a moderate number of bitmaps.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #or(RoaringBitmap...)
*/
public static RoaringBitmap horizontal_or(List<RoaringBitmap> bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
if (bitmaps.isEmpty()) {
return answer;
}
PriorityQueue<ContainerPointer> pq = new PriorityQueue<>(bitmaps.size());
for (int k = 0; k < bitmaps.size(); ++k) {
ContainerPointer x = bitmaps.get(k).highLowContainer.getContainerPointer();
if (x.getContainer() != null) {
pq.add(x);
}
}
while (!pq.isEmpty()) {
ContainerPointer x1 = pq.poll();
if (pq.isEmpty() || (pq.peek().key() != x1.key())) {
answer.highLowContainer.append(x1.key(), x1.getContainer().clone());
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
continue;
}
ContainerPointer x2 = pq.poll();
Container newc = x1.getContainer().lazyOR(x2.getContainer());
while (!pq.isEmpty() && (pq.peek().key() == x1.key())) {
ContainerPointer x = pq.poll();
newc = newc.lazyIOR(x.getContainer());
x.advance();
if (x.getContainer() != null) {
pq.add(x);
} else if (pq.isEmpty()) {
break;
}
}
newc = newc.repairAfterLazy();
answer.highLowContainer.append(x1.key(), newc);
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
x2.advance();
if (x2.getContainer() != null) {
pq.add(x2);
}
}
return answer;
}
/**
* Minimizes memory usage while computing the or aggregate on a moderate number of bitmaps.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #or(RoaringBitmap...)
*/
public static RoaringBitmap horizontal_or(RoaringBitmap... bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
if (bitmaps.length == 0) {
return answer;
}
PriorityQueue<ContainerPointer> pq = new PriorityQueue<>(bitmaps.length);
for (int k = 0; k < bitmaps.length; ++k) {
ContainerPointer x = bitmaps[k].highLowContainer.getContainerPointer();
if (x.getContainer() != null) {
pq.add(x);
}
}
while (!pq.isEmpty()) {
ContainerPointer x1 = pq.poll();
if (pq.isEmpty() || (pq.peek().key() != x1.key())) {
answer.highLowContainer.append(x1.key(), x1.getContainer().clone());
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
continue;
}
ContainerPointer x2 = pq.poll();
Container newc = x1.getContainer().lazyOR(x2.getContainer());
while (!pq.isEmpty() && (pq.peek().key() == x1.key())) {
ContainerPointer x = pq.poll();
newc = newc.lazyIOR(x.getContainer());
x.advance();
if (x.getContainer() != null) {
pq.add(x);
} else if (pq.isEmpty()) {
break;
}
}
newc = newc.repairAfterLazy();
answer.highLowContainer.append(x1.key(), newc);
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
x2.advance();
if (x2.getContainer() != null) {
pq.add(x2);
}
}
return answer;
}
/**
* Minimizes memory usage while computing the xor aggregate on a moderate number of bitmaps.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #xor(RoaringBitmap...)
*/
public static RoaringBitmap horizontal_xor(RoaringBitmap... bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
if (bitmaps.length == 0) {
return answer;
}
PriorityQueue<ContainerPointer> pq = new PriorityQueue<>(bitmaps.length);
for (int k = 0; k < bitmaps.length; ++k) {
ContainerPointer x = bitmaps[k].highLowContainer.getContainerPointer();
if (x.getContainer() != null) {
pq.add(x);
}
}
while (!pq.isEmpty()) {
ContainerPointer x1 = pq.poll();
if (pq.isEmpty() || (pq.peek().key() != x1.key())) {
answer.highLowContainer.append(x1.key(), x1.getContainer().clone());
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
continue;
}
ContainerPointer x2 = pq.poll();
Container newc = x1.getContainer().xor(x2.getContainer());
while (!pq.isEmpty() && (pq.peek().key() == x1.key())) {
ContainerPointer x = pq.poll();
newc = newc.ixor(x.getContainer());
x.advance();
if (x.getContainer() != null) {
pq.add(x);
} else if (pq.isEmpty()) {
break;
}
}
answer.highLowContainer.append(x1.key(), newc);
x1.advance();
if (x1.getContainer() != null) {
pq.add(x1);
}
x2.advance();
if (x2.getContainer() != null) {
pq.add(x2);
}
}
return answer;
}
/**
* Compute overall AND between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_and(Iterator<RoaringBitmap> bitmaps) {
if (!bitmaps.hasNext()) {
return new RoaringBitmap();
}
RoaringBitmap answer = bitmaps.next().clone();
while (bitmaps.hasNext()) {
answer.and(bitmaps.next());
}
return answer;
}
/**
* Compute overall AND between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_and(RoaringBitmap... bitmaps) {
if (bitmaps.length == 0) {
return new RoaringBitmap();
}
RoaringBitmap answer = bitmaps[0].clone();
for (int k = 1; k < bitmaps.length; ++k) {
answer.and(bitmaps[k]);
}
return answer;
}
/**
* Compute overall OR between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_or(Iterator<RoaringBitmap> bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
while (bitmaps.hasNext()) {
answer.naivelazyor(bitmaps.next());
}
answer.repairAfterLazy();
return answer;
}
/**
* Compute overall OR between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_or(RoaringBitmap... bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
for (int k = 0; k < bitmaps.length; ++k) {
answer.naivelazyor(bitmaps[k]);
}
answer.repairAfterLazy();
return answer;
}
/**
* Compute overall XOR between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_xor(Iterator<RoaringBitmap> bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
while (bitmaps.hasNext()) {
answer.xor(bitmaps.next());
}
return answer;
}
/**
* Compute overall XOR between bitmaps two-by-two.
*
* This function runs in linear time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap naive_xor(RoaringBitmap... bitmaps) {
RoaringBitmap answer = new RoaringBitmap();
for (int k = 0; k < bitmaps.length; ++k) {
answer.xor(bitmaps[k]);
}
return answer;
}
/**
* Compute overall OR between bitmaps.
*
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap or(Iterator<RoaringBitmap> bitmaps) {
return naive_or(bitmaps);
}
/**
* Compute overall OR between bitmaps.
*
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap or(RoaringBitmap... bitmaps) {
return naive_or(bitmaps);
}
/**
* Uses a priority queue to compute the or aggregate.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #horizontal_or(RoaringBitmap...)
*/
public static RoaringBitmap priorityqueue_or(Iterator<RoaringBitmap> bitmaps) {
if (!bitmaps.hasNext()) {
return new RoaringBitmap();
}
// we buffer the call to getSizeInBytes(), hence the code complexity
ArrayList<RoaringBitmap> buffer = new ArrayList<>();
while (bitmaps.hasNext()) {
buffer.add(bitmaps.next());
}
final long[] sizes = new long[buffer.size()];
final boolean[] istmp = new boolean[buffer.size()];
for (int k = 0; k < sizes.length; ++k) {
sizes[k] = buffer.get(k).getLongSizeInBytes();
}
PriorityQueue<Integer> pq = new PriorityQueue<>(128, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return (int) (sizes[a] - sizes[b]);
}
});
for (int k = 0; k < sizes.length; ++k) {
pq.add(k);
}
while (pq.size() > 1) {
Integer x1 = pq.poll();
Integer x2 = pq.poll();
if (istmp[x2] && istmp[x1]) {
buffer.set(x1, RoaringBitmap.lazyorfromlazyinputs(buffer.get(x1), buffer.get(x2)));
sizes[x1] = buffer.get(x1).getLongSizeInBytes();
istmp[x1] = true;
pq.add(x1);
} else if (istmp[x2]) {
buffer.get(x2).lazyor(buffer.get(x1));
sizes[x2] = buffer.get(x2).getLongSizeInBytes();
pq.add(x2);
} else if (istmp[x1]) {
buffer.get(x1).lazyor(buffer.get(x2));
sizes[x1] = buffer.get(x1).getLongSizeInBytes();
pq.add(x1);
} else {
buffer.set(x1, RoaringBitmap.lazyor(buffer.get(x1), buffer.get(x2)));
sizes[x1] = buffer.get(x1).getLongSizeInBytes();
istmp[x1] = true;
pq.add(x1);
}
}
RoaringBitmap answer = buffer.get(pq.poll());
answer.repairAfterLazy();
return answer;
}
/**
* Uses a priority queue to compute the or aggregate.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #horizontal_or(RoaringBitmap...)
*/
public static RoaringBitmap priorityqueue_or(RoaringBitmap... bitmaps) {
if (bitmaps.length == 0) {
return new RoaringBitmap();
}
// we buffer the call to getSizeInBytes(), hence the code complexity
final RoaringBitmap[] buffer = Arrays.copyOf(bitmaps, bitmaps.length);
final long[] sizes = new long[buffer.length];
final boolean[] istmp = new boolean[buffer.length];
for (int k = 0; k < sizes.length; ++k) {
sizes[k] = buffer[k].getLongSizeInBytes();
}
PriorityQueue<Integer> pq = new PriorityQueue<>(128, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return (int) (sizes[a] - sizes[b]);
}
});
for (int k = 0; k < sizes.length; ++k) {
pq.add(k);
}
while (pq.size() > 1) {
Integer x1 = pq.poll();
Integer x2 = pq.poll();
if (istmp[x2] && istmp[x1]) {
buffer[x1] = RoaringBitmap.lazyorfromlazyinputs(buffer[x1], buffer[x2]);
sizes[x1] = buffer[x1].getLongSizeInBytes();
istmp[x1] = true;
pq.add(x1);
} else if (istmp[x2]) {
buffer[x2].lazyor(buffer[x1]);
sizes[x2] = buffer[x2].getLongSizeInBytes();
pq.add(x2);
} else if (istmp[x1]) {
buffer[x1].lazyor(buffer[x2]);
sizes[x1] = buffer[x1].getLongSizeInBytes();
pq.add(x1);
} else {
buffer[x1] = RoaringBitmap.lazyor(buffer[x1], buffer[x2]);
sizes[x1] = buffer[x1].getLongSizeInBytes();
istmp[x1] = true;
pq.add(x1);
}
}
RoaringBitmap answer = buffer[pq.poll()];
answer.repairAfterLazy();
return answer;
}
/**
* Uses a priority queue to compute the xor aggregate.
*
* This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps.
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
* @see #horizontal_xor(RoaringBitmap...)
*/
public static RoaringBitmap priorityqueue_xor(RoaringBitmap... bitmaps) {
// TODO: This code could be faster, see priorityqueue_or
if (bitmaps.length == 0) {
return new RoaringBitmap();
}
PriorityQueue<RoaringBitmap> pq =
new PriorityQueue<>(bitmaps.length, new Comparator<RoaringBitmap>() {
@Override
public int compare(RoaringBitmap a, RoaringBitmap b) {
return (int)(a.getLongSizeInBytes() - b.getLongSizeInBytes());
}
});
Collections.addAll(pq, bitmaps);
while (pq.size() > 1) {
RoaringBitmap x1 = pq.poll();
RoaringBitmap x2 = pq.poll();
pq.add(RoaringBitmap.xor(x1, x2));
}
return pq.poll();
}
/**
* Compute overall XOR between bitmaps.
*
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap xor(Iterator<RoaringBitmap> bitmaps) {
return naive_xor(bitmaps);
}
/**
* Compute overall XOR between bitmaps.
*
*
* @param bitmaps input bitmaps
* @return aggregated bitmap
*/
public static RoaringBitmap xor(RoaringBitmap... bitmaps) {
return naive_xor(bitmaps);
}
/**
* Private constructor to prevent instantiation of utility class
*/
private FastAggregation() {}
}
|
package org.spongepowered.api.world;
import org.spongepowered.api.block.Block;
import java.util.UUID;
/**
* A loaded Minecraft world
*/
public interface World {
/**
* Gets the unique id ({@link java.util.UUID} for this world.
*
* @return The unique id or UUID
*/
UUID getUniqueID();
/**
* Gets the name of the world.
*
* @return The world name
*/
String getName();
/**
* Gets an already-loaded {@link Chunk} by its x/z chunk coordinate, or
* null if it's not available
*
* @param cx X chunk coordinate
* @param cz Z chunk coordinate
* @return The chunk
*/
Chunk getChunk(int cx, int cz);
/**
* Loads and returns a {@link Chunk}. If the chunk does not
* exist, it will be generated unless `shouldGenerate` is false.
*
* @param cx X chunk coordinate
* @param cz Z chunk coordinate
* @param shouldGenerate Generate if new
* @return Chunk loaded/generated
*/
Chunk loadChunk(int cx, int cz, boolean shouldGenerate);
/**
* Gets a specific {@link org.spongepowered.api.block.Block} by its x/y/z block coordinate.
* @param x X block coordinate
* @param y Y block coordinate
* @param z Z block coordinate
* @return The block
*/
Block getBlock(int x, int y, int z);
}
|
package org.testng.internal;
import org.testng.IInvokedMethod;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import java.io.Serializable;
public class InvokedMethod implements Serializable, IInvokedMethod {
private static final long serialVersionUID = 2126127194102819222L;
transient private Object m_instance;
private ITestNGMethod m_testMethod;
private Object[] m_parameters;
private boolean m_isTest = true;
private boolean m_isConfigurationMethod = false;
private long m_date = System.currentTimeMillis();
private ITestResult m_testResult;
/**
* @param m_object
* @param m_method
* @param m_parameters
*/
public InvokedMethod(Object instance,
ITestNGMethod method,
Object[] parameters,
boolean isTest,
boolean isConfiguration,
long date,
ITestResult testResult) {
m_instance = instance;
m_testMethod = method;
m_parameters = parameters;
m_isTest = isTest;
m_isConfigurationMethod = isConfiguration;
m_date = date;
m_testResult = testResult;
}
/* (non-Javadoc)
* @see org.testng.internal.IInvokedMethod#isTestMethod()
*/
@Override
public boolean isTestMethod() {
return m_testMethod.isTest();
}
@Override
public String toString() {
StringBuffer result = new StringBuffer(m_testMethod.toString());
for (Object p : m_parameters) {
result.append(p).append(" ");
}
result.append(" ").append(m_instance != null ? m_instance.hashCode() : " <static>");
return result.toString();
}
/* (non-Javadoc)
* @see org.testng.internal.IInvokedMethod#isConfigurationMethod()
*/
@Override
public boolean isConfigurationMethod() {
return m_testMethod.isBeforeMethodConfiguration() ||
m_testMethod.isAfterMethodConfiguration() ||
m_testMethod.isBeforeTestConfiguration() ||
m_testMethod.isAfterTestConfiguration() ||
m_testMethod.isBeforeClassConfiguration() ||
m_testMethod.isAfterClassConfiguration() ||
m_testMethod.isBeforeSuiteConfiguration() ||
m_testMethod.isAfterSuiteConfiguration();
}
/* (non-Javadoc)
* @see org.testng.internal.IInvokedMethod#getTestMethod()
*/
@Override
public ITestNGMethod getTestMethod() {
return m_testMethod;
}
/* (non-Javadoc)
* @see org.testng.internal.IInvokedMethod#getDate()
*/
@Override
public long getDate() {
return m_date;
}
@Override
public ITestResult getTestResult() {
return m_testResult;
}
}
|
package org.web3j.quorum;
import java.math.BigInteger;
import java.util.Collections;
import java.util.concurrent.ScheduledExecutorService;
import org.web3j.protocol.Web3jService;
import org.web3j.protocol.core.JsonRpc2_0Web3j;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.VoidResponse;
import org.web3j.quorum.methods.request.*;
import org.web3j.quorum.methods.response.*;
import org.web3j.utils.Numeric;
/**
* Quorum JSON-RPC API implementation.
*/
public class JsonRpc2_0Quorum extends JsonRpc2_0Web3j implements Quorum {
public JsonRpc2_0Quorum(Web3jService web3jService) {
super(web3jService);
}
public JsonRpc2_0Quorum(
Web3jService web3jService, long pollingInterval,
ScheduledExecutorService scheduledExecutorService) {
super(web3jService, pollingInterval, scheduledExecutorService);
}
@Override
public Request<?, EthSendTransaction> ethSendTransaction(Transaction transaction) {
throw new UnsupportedOperationException("Quorum requires PrivateTransaction types");
}
@Override
public Request<?, EthSendTransaction> ethSendRawTransaction(
String signedTransactionData) {
throw new UnsupportedOperationException("Quorum requires PrivateTransaction types");
}
@Override
public Request<?, EthSendTransaction> ethSendTransaction(
PrivateTransaction transaction) {
return new Request<>(
"eth_sendTransaction",
Collections.singletonList(transaction),
ID,
web3jService,
EthSendTransaction.class);
}
@Override
public Request<?, QuorumNodeInfo> quorumNodeInfo() {
return new Request<>(
"quorum_nodeInfo",
Collections.<String>emptyList(),
ID,
web3jService,
QuorumNodeInfo.class);
}
@Override
public Request<?, CanonicalHash> quorumCanonicalHash(BigInteger blockHeight) {
return new Request<>(
"quorum_canonicalHash",
Collections.singletonList(Numeric.encodeQuantity(blockHeight)),
ID,
web3jService,
CanonicalHash.class);
}
@Override
public Request<?, Vote> quorumVote(String blockHash) {
return new Request<>(
"quorum_vote",
Collections.singletonList(blockHash),
ID,
web3jService,
Vote.class);
}
@Override
public Request<?, MakeBlock> quorumMakeBlock() {
return new Request<>(
"quorum_makeBlock",
Collections.<String>emptyList(),
ID,
web3jService,
MakeBlock.class);
}
@Override
public Request<?, VoidResponse> quorumPauseBlockMaker() {
return new Request<>(
"quorum_pauseBlockMaker",
Collections.<String>emptyList(),
ID,
web3jService,
VoidResponse.class);
}
@Override
public Request<?, VoidResponse> quorumResumeBlockMaker() {
return new Request<>(
"quorum_resumeBlockMaker",
Collections.<String>emptyList(),
ID,
web3jService,
VoidResponse.class);
}
@Override
public Request<?, BlockMaker> quorumIsBlockMaker(String address) {
return new Request<>(
"quorum_isBlockMaker",
Collections.singletonList(address),
ID,
web3jService,
BlockMaker.class);
}
@Override
public Request<?, Voter> quorumIsVoter(String address) {
return new Request<>(
"quorum_isVoter",
Collections.singletonList(address),
ID,
web3jService,
Voter.class);
}
}
|
package profilers;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.profile.ExternalProfiler;
import org.openjdk.jmh.results.AggregationPolicy;
import org.openjdk.jmh.results.Aggregator;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.Result;
import org.openjdk.jmh.results.ResultRole;
import org.openjdk.jmh.util.FileUtils;
// Effectively equivalent to passing jvm args to append for each benchmark. e.g.,
//@Fork(jvmArgsAppend =
//{"-XX:+UnlockCommercialFeatures",
// "-XX:+FlightRecorder",
// "-XX:StartFlightRecording=duration=60s,filename=./profiling-data.jfr,name=profile,settings=profile",
// "-XX:FlightRecorderOptions=settings=./openjdk/jdk1.8.0/jre/lib/jfr/profile.jfc,samplethreads=true"
/**
* The flight recording profiler enables flight recording for benchmarks and starts recording right away.
*/
public class FlightRecordingProfiler implements ExternalProfiler {
private String startFlightRecordingOptions = "duration=60s,name=profile,settings=profile,";
private String flightRecorderOptions = "samplethreads=true,";
/**
* Directory to contain all generated reports.
*/
private static final String SAVE_FLIGHT_OUTPUT_TO = System.getProperty("jmh.jfr.saveTo", ".");
/**
* Temporary location to record data
*/
private final String jfrData;
/**
* Holds whether recording is supported (checking the existence of the needed unlocking flag)
*/
private static final boolean IS_SUPPORTED;
static {
IS_SUPPORTED = ManagementFactory.getRuntimeMXBean().getInputArguments().contains("-XX:+UnlockCommercialFeatures");
}
public FlightRecordingProfiler() throws IOException {
jfrData = FileUtils.tempFile("jfrData").getAbsolutePath();
}
@Override
public Collection<String> addJVMInvokeOptions(BenchmarkParams params) {
return Collections.emptyList();
}
@Override
public Collection<String> addJVMOptions(BenchmarkParams params) {
startFlightRecordingOptions += "filename=" + jfrData;
String jfcPath = Paths.get(params.getJvm()).resolve("../../lib/jfr/profile.jfc").normalize().toAbsolutePath().toString();
flightRecorderOptions += ",settings=" + jfcPath;
return Arrays.asList(
"-XX:+FlightRecorder",
"-XX:StartFlightRecording=" + startFlightRecordingOptions,
"-XX:FlightRecorderOptions=" + flightRecorderOptions);
}
@Override
public void beforeTrial(BenchmarkParams benchmarkParams) {
}
static int currentId;
@Override
public Collection<? extends Result> afterTrial(BenchmarkResult benchmarkResult, long l, File stdOut, File stdErr) {
String target = Paths.get(SAVE_FLIGHT_OUTPUT_TO).resolve(benchmarkResult.getParams().getBenchmark() + "-" + currentId++ + ".jfr").toAbsolutePath().toString();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
FileUtils.copy(jfrData, target);
pw.println("Flight Recording output saved to " + target);
} catch (IOException e) {
e.printStackTrace();
pw.println("Unable to save flight output to " + target);
pw.println("Did you miss the system property: -Djmh.jfr.saveTo ?");
}
pw.flush();
pw.close();
NoResult r = new NoResult(sw.toString());
return Collections.singleton(r);
}
@Override
public boolean allowPrintOut() {
return true;
}
@Override
public boolean allowPrintErr() {
return false;
}
public boolean checkSupport(List<String> msgs) {
msgs.add("Commercial features of the JVM need to be enabled for this profiler.");
return IS_SUPPORTED;
}
public String label() {
return "jfr";
}
@Override
public String getDescription() {
return "Java Flight Recording profiler runs for every benchmark.";
}
private class NoResult extends Result<NoResult> {
private final String output;
public NoResult(String output) {
super(ResultRole.SECONDARY, "JFR", of(Double.NaN), "N/A", AggregationPolicy.SUM);
this.output = output;
}
@Override
protected Aggregator<NoResult> getThreadAggregator() {
return new NoResultAggregator();
}
@Override
protected Aggregator<NoResult> getIterationAggregator() {
return new NoResultAggregator();
}
@Override
public String extendedInfo() {
return "JFR Messages:\n
}
private class NoResultAggregator implements Aggregator<NoResult> {
@Override
public NoResult aggregate(Collection<NoResult> results) {
String output = "";
for (NoResult r : results) {
output += r.output;
}
return new NoResult(output);
}
}
}
}
|
package py.una.med.base.util;
import java.io.Serializable;
import py.una.med.base.business.ISIGHBaseLogic;
import py.una.med.base.dao.restrictions.Where;
import py.una.med.base.dao.search.ISearchParam;
import py.una.med.base.dao.search.SearchParam;
import py.una.med.base.dao.util.EntityExample;
public class PagingHelper<T, ID extends Serializable> {
private int rowsForPage = 10;
private int page = 0;
T example;
private Long currentCount;
private Long totalCount;
public PagingHelper(int rowsForPage) {
this.rowsForPage = rowsForPage;
}
public ISearchParam getISearchparam() {
SearchParam sp = new SearchParam();
sp.setOffset(page * rowsForPage);
sp.setLimit(rowsForPage);
return sp;
}
public void next() {
// boton siguiente
if (page + 1 > getMaxPage(currentCount)) {
return;
}
this.page++;
}
public void goMaxPage() {
this.page = getMaxPage(currentCount) - 1;
}
public void goInitPage() {
this.page = 0;
}
public void last() {
// TODO controlar que al llegar a la primera pagina se deshabilite el
// boton atras
if (page > 0) {
this.page
}
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public String getFormattedPage() {
Long firstRecord = Long.valueOf(page * rowsForPage + 1);
Long limit = Long.valueOf(page * rowsForPage + rowsForPage);
if (page + 1 == getMaxPage(currentCount)) {
limit = currentCount;
}
if (currentCount == 0) {
limit = 0L;
firstRecord = 0L;
}
String formattedPage = firstRecord + "-" + limit + " de "
+ currentCount;
return formattedPage;
}
private int getMaxPage(Long count) {
// TODO cambiar la forma de redondear hacia arriba, usar ceil
double total = totalCount;
double rowForPage = rowsForPage;
int maxPage = (int) (count / rowsForPage);
if (total / rowForPage > maxPage) {
maxPage++;
}
return maxPage;
}
public boolean hasNext() {
if (page + 1 == getMaxPage(currentCount)) {
return false;
} else {
return true;
}
}
public boolean hasLast() {
if (page == 0) {
return false;
} else {
return true;
}
}
public void calculate(ISIGHBaseLogic<T, ID> logic, Where<T> where) {
currentCount = logic.getCountByExample(new EntityExample<T>(example));
totalCount = logic.getCount();
}
}
|
package roart.hcutil;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import roart.model.ResultItem;
public class ResultItemSerializer implements StreamSerializer<ResultItem> {
@Override
public int getTypeId() {
return 4;
}
@Override
public void write( ObjectDataOutput out, ResultItem object ) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder( bos );
encoder.writeObject( object );
encoder.close();
out.write( bos.toByteArray() );
//System.out.println(bos.toString());
}
@Override
public ResultItem read( ObjectDataInput in ) throws IOException {
InputStream inputStream = (InputStream) in;
XMLDecoder decoder = new XMLDecoder( inputStream );
return (ResultItem) decoder.readObject();
}
@Override
public void destroy() {
}
}
|
package seedu.malitio.logic.parser;
import seedu.malitio.commons.exceptions.IllegalValueException;
import seedu.malitio.commons.util.StringUtil;
import seedu.malitio.logic.commands.*;
import static seedu.malitio.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.malitio.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>)[e|d|f|E|D|F]\\d+");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<name>[^/]+)"
+ "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags
private static final Pattern EDIT_DATA_ARGS_FORMAT =
Pattern.compile("(?<targetIndex>[e|d|f|E|D|F]\\d+)"
+ "(?<name>(?:\\s[^/]+)?)"
+ "(?<tagArguments>(?: t/[^/]+)*)");
private static final Pattern COMPLETE_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>[d|f|D|F]\\d+)");
private static final Set<String> TYPES_OF_TASKS = new HashSet<String>(Arrays.asList("f", "d", "e" ));
public static final String MESSAGE_MISSING_START_END = "Expecting start and end times\nExample: start thursday 0800 end thursday 0900";
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case CompleteCommand.COMMAND_WORD:
return prepareComplete(arguments);
case UncompleteCommand.COMMAND_WORD:
return prepareUncomplete(arguments);
case MarkCommand.COMMAND_WORD:
return prepareMark(arguments);
case UnmarkCommand.COMMAND_WORD:
return prepareUnmark(arguments);
case ClearCommand.COMMAND_WORD:
return prepareClear(arguments);
case ListAllCommand.COMMAND_WORD:
return new ListAllCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return prepareList(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case SaveCommand.COMMAND_WORD:
return prepareSave(arguments);
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
//@@author a0126633j
/**
* Parses arguments in the context of the clear command. Also checks validity of arguments
*/
private Command prepareClear(String arguments) {
if (!Arrays.asList(ClearCommand.VALID_ARGUMENTS).contains(arguments.trim().toLowerCase())) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ClearCommand.MESSAGE_USAGE));
}
return new ClearCommand(arguments.trim().toLowerCase());
}
/**
* Parses arguments in the context of the save command. Also ensure the argument is not empty
*/
private Command prepareSave(String arguments) {
if (arguments.trim().isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
return new SaveCommand(arguments.trim());
}
//@@author
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
* @@author A0153006W
*/
private Command prepareAdd(String args){
final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
boolean hasStart = false;
boolean hasEnd = false;
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
String name = matcher.group("name");
String deadline = getDeadlineFromArgs(StringUtil.removeTagsFromString(name));
String start = getStartFromArgs(StringUtil.removeTagsFromString(name));
if (!start.isEmpty()) {
name = name.substring(0, name.lastIndexOf("start")).trim();
hasStart = true;
}
String end = getEndFromArgs(StringUtil.removeTagsFromString(args));
if (!end.isEmpty()) {
hasEnd = true;
}
if (!deadline.isEmpty()) {
name = name.substring(0, name.lastIndexOf("by")).trim();
}
if (!deadline.isEmpty() && !hasStart && !hasEnd) {
return new AddCommand(
name,
deadline,
getTagsFromArgs(matcher.group("tagArguments"))
);
} else if (hasStart && hasEnd) {
return new AddCommand(
name,
start,
end,
getTagsFromArgs(matcher.group("tagArguments"))
);
} else if (hasStart ^ hasEnd) {
return new IncorrectCommand(MESSAGE_MISSING_START_END);
}
return new AddCommand(
name,
getTagsFromArgs(matcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
//@@author A0129595N
/**
* Parses arguments in the context of the edit task command.
*
* @param arguments
* @return the prepared command
*/
private Command prepareEdit(String args) {
final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
try {
String index = parseIndex(matcher.group("targetIndex"));
if (index.isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
String name = matcher.group("name");
if (name.equals("") && getTagsFromArgs(matcher.group("tagArguments")).isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
String deadline = getDeadlineFromArgs(name);
if (!deadline.isEmpty()) {
name = name.replaceAll(" by " + deadline, "");
}
String start = getStartFromArgs(name);
if (!start.isEmpty()) {
name = name.replaceAll(" start " + start, "");
}
String end = getEndFromArgs(name);
if (!end.isEmpty()) {
name = name.replaceAll(" end " + end, "");
}
name = name.trim();
return new EditCommand(
taskType,
taskNum,
name,
deadline,
start,
end,
getTagsFromArgs(matcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
//@@author A0122460W
/**
* Parses arguments in the context of the complete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareComplete(String args) {
final Matcher matcher = COMPLETE_INDEX_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE));
}
try {
String index = parseIndex(matcher.group("targetIndex"));
if (index.isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
return new CompleteCommand(taskType,taskNum);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses arguments in the context of the uncomplete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareUncomplete(String args) {
final Matcher matcher = COMPLETE_INDEX_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UncompleteCommand.MESSAGE_USAGE));
}
try {
String index = parseIndex(matcher.group("targetIndex"));
if (index.isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UncompleteCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
return new UncompleteCommand(taskType,taskNum);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
//@@author
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
String index = parseIndex(args);
if(index.isEmpty()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
return new DeleteCommand(Character.toString(taskType), taskNum);
}
/**
* Parses arguments in the context of the mark task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareMark(String args) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
String index = parseIndex(args);
if (index.isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
return new MarkCommand(taskType, taskNum);
}
/**
* Parses arguments in the context of the unmark task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareUnmark(String args) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE));
}
String index = parseIndex(args);
if (index.isEmpty()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE));
}
char taskType = index.charAt(0);
int taskNum = Integer.parseInt(index.substring(1));
return new UnmarkCommand(taskType, taskNum);
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
* @@author
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
String[] keywords = matcher.group("keywords").split("\\s+");
String typeOfTask = "";
if(TYPES_OF_TASKS.contains(keywords[0])) {
typeOfTask = keywords[0];
keywords = removeFirstFromArray(keywords);
}
if (keywords.length < 1) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(typeOfTask, keywordSet);
}
//@@author a0126633j
private String[] removeFirstFromArray(String[] arg) {
String[] result = new String[arg.length - 1];
for(int i = 1; i < arg.length; i++) {
result[i - 1] = arg[i];
}
return result;
}
/**
* Parses arguments in the context of the list task command.
*
* @param args full command args string
* @return the prepared command
* @@author A0153006W
*/
private Command prepareList(String args) {
if (args.isEmpty()) {
return new ListCommand();
}
try {
args = args.trim().toLowerCase();
return new ListCommand(args);
} catch (IllegalValueException ive) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
}
}
/**
* Returns the specified index as a String in the {@code command}
*/
private String parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return "";
}
String index = command.trim().toLowerCase();
return index;
}
/**
* Extracts the task's deadline from the command's arguments string.
*/
private static String getDeadlineFromArgs(String args) throws IllegalValueException {
int byIndex = args.lastIndexOf(" by ");
String deadline = "";
if(byIndex >= 0 && byIndex < args.length() - 4) {
deadline = args.substring(byIndex + 4);
}
return deadline;
}
/**
* Extracts the task's event start from the command's arguments string.
*/
private static String getStartFromArgs(String args) throws IllegalValueException {
int startIndex = args.lastIndexOf(" start ");
int endIndex = args.lastIndexOf(" end");
if (startIndex >= 0 && endIndex > 0) {
return args.substring(startIndex + 7, endIndex);
} else if (startIndex >= 0 && endIndex < 0) {
return args.substring(startIndex + 7);
} else {
return "";
}
}
/**
* Extracts the task's event end from the command's arguments string.
*/
private static String getEndFromArgs(String args) throws IllegalValueException {
int endIndex = args.lastIndexOf(" end ");
if (endIndex >= 0) {
return args.substring(endIndex + 5);
} else {
return "";
}
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
* @@author
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
}
|
package seedu.taskboss.ui;
import java.util.Date;
import java.util.logging.Logger;
import org.controlsfx.control.StatusBar;
import com.google.common.eventbus.Subscribe;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.taskboss.commons.core.LogsCenter;
import seedu.taskboss.commons.events.model.TaskBossChangedEvent;
import seedu.taskboss.commons.events.storage.TaskBossStorageChangedEvent;
import seedu.taskboss.commons.util.FxViewUtil;
/**
* A ui for the status bar that is displayed at the footer of the application.
*/
public class StatusBarFooter extends UiPart<Region> {
private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class);
@FXML
private StatusBar syncStatus;
@FXML
private StatusBar saveLocationStatus;
private static final String FXML = "StatusBarFooter.fxml";
public StatusBarFooter(AnchorPane placeHolder, String saveLocation) {
super(FXML);
addToPlaceholder(placeHolder);
setSyncStatus("Not updated yet in this session");
setSaveLocation(saveLocation);
registerAsAnEventHandler(this);
}
private void addToPlaceholder(AnchorPane placeHolder) {
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
placeHolder.getChildren().add(getRoot());
}
//@@author A0138961W
private void setSaveLocation(String location) {
this.saveLocationStatus.setText(location);
}
//@@author
private void setSyncStatus(String status) {
this.syncStatus.setText(status);
}
//@@author A0138961W
@Subscribe
public void handleTaskBossStorageChangedEvent(TaskBossStorageChangedEvent newFilePath) {
setSaveLocation(newFilePath.newPath);
}
//@@author
@Subscribe
public void handleTaskBossChangedEvent(TaskBossChangedEvent abce) {
String lastUpdated = (new Date()).toString();
logger.info(LogsCenter.getEventHandlingLogMessage(abce, "Setting last updated status to " + lastUpdated));
setSyncStatus("Last Updated: " + lastUpdated);
}
}
|
package seedu.taskell.model.task;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.taskell.commons.exceptions.IllegalValueException;
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
/**
* Represents a Task's date in the task manager.
* Guarantees: is valid as declared in {@link #isValidDate(String)}
*/
public class TaskDate {
public static final int JANUARY = 1;
public static final int FEBRUARY = 2;
public static final int MARCH = 3;
public static final int APRIL = 4;
public static final int MAY = 5;
public static final int JUNE = 6;
public static final int JULY = 7;
public static final int AUGUST = 8;
public static final int SEPTEMBER = 9;
public static final int OCTOBER = 10;
public static final int NOVEMBER = 11;
public static final int DECEMBER = 12;
public static final int NOT_A_VALID_MONTH = 0;
public static final int NOT_A_VALID_DAY_OF_THE_WEEK = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
public static final int SUNDAY = 7;
public static final int TODAY = 1;
public static final int TOMORROW = 2;
public static final int ONLY_CONTAIN_DAY_NAME_IN_WEEK = 3;
public static final int ONLY_CONTAIN_MONTH = 4;
public static final int ONLY_CONTAIN_DAY_AND_MONTH = 5;
public static final int ONLY_CONTAIN_MONTH_AND_YEAR = 6;
public static final int FULL_DATE_DISPLAY = 7; //NAME_OF_DAY_IN_WEEK, DAY MONTH YEAR
public static final int NUM_DAYS_IN_A_WEEK = 7;
public static final int NUM_MONTHS_IN_A_YEAR = 12;
public static final int FIRST_DAY_OF_THE_MONTH = 1;
public static final String DATE_DELIMITER = " .-/";
public static final int LENGTH_OF_KEYWORD_BY = 2+1;
public static final Pattern TASK_DATE_ARGS_FORMAT = Pattern
.compile("(?<day>(3[0-1]|2[0-9]|1[0-9]|[1-9]))" + "(-)(?<month>(1[0-2]|[1-9]))" + "(-)(?<year>([0-9]{4}))");
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("d M yyyy");
public static final String MESSAGE_TASK_DATE_CONSTRAINTS =
"Task dates should be separated by '-' or '.' or '/'"
+ "\nSpelling of month should be in full or 3-letters"
+ "\nYear should only be 4-digits";
public String taskDate;
public TaskDate(String dateToAdd) throws IllegalValueException {
if (isValidFullDate(dateToAdd)) {
setDateGivenFullDate(dateToAdd);
} else if (isValidDayAndMonth(dateToAdd)) {
setDateGivenDayMonth(dateToAdd);
} else if (isValidMonthAndYear(dateToAdd)) {
setDateGivenMonthYear(dateToAdd);
} else if (isValidMonth(dateToAdd)) {
setDateGivenMonth(dateToAdd);
} else if (isValidDayOfWeek(dateToAdd)) {
setDateGivenDayNameOfWeek(dateToAdd);
} else if (isValidToday(dateToAdd)) {
setDateGivenToday(dateToAdd);
} else if (isValidTomorrow(dateToAdd)) {
setDateGivenTomorrow(dateToAdd);
} else {
throw new IllegalValueException(MESSAGE_TASK_DATE_CONSTRAINTS);
}
}
private void setDateGivenFullDate(String dateToConvert) throws DateTimeException, IllegalValueException {
StringTokenizer st = new StringTokenizer(dateToConvert, DATE_DELIMITER);
String[] tokenArr = new String[3];
int i = 0;
while (st.hasMoreTokens()) {
tokenArr[i] = st.nextToken();
i++;
}
int day = Integer.valueOf(tokenArr[0]);
String monthStr = tokenArr[1];
int month;
try {
month = Integer.valueOf(tokenArr[1]);
} catch (NumberFormatException nfe) {
month = convertMonthIntoInteger(monthStr);
}
int year = Integer.valueOf(tokenArr[2]);
try {
setDate(day, month, year);
getYear();
} catch (IllegalValueException ive) {
throw ive;
}
}
private void setDateGivenDayMonth(String dateToConvert) throws IllegalValueException {
StringTokenizer st = new StringTokenizer(dateToConvert, DATE_DELIMITER);
String[] tokenArr = new String[3];
int i = 0;
while (st.hasMoreTokens()) {
tokenArr[i] = st.nextToken();
i++;
}
int day = Integer.valueOf(tokenArr[0]);
String monthStr = tokenArr[1];
int month;
try {
month = Integer.valueOf(tokenArr[1]);
} catch (NumberFormatException nfe) {
month = convertMonthIntoInteger(monthStr);
}
int year = Integer.valueOf(getThisYear());
try {
setDate(day, month, year);
getYear();
} catch (IllegalValueException ive) {
throw ive;
}
}
private void setDateGivenMonthYear(String dateToConvert) throws IllegalValueException {
StringTokenizer st = new StringTokenizer(dateToConvert, DATE_DELIMITER);
String[] tokenArr = new String[3];
int i = 0;
while (st.hasMoreTokens()) {
tokenArr[i] = st.nextToken();
i++;
}
int day = FIRST_DAY_OF_THE_MONTH;
String monthStr = tokenArr[0];
int month;
try {
month = Integer.valueOf(tokenArr[0]);
} catch (NumberFormatException nfe) {
month = convertMonthIntoInteger(monthStr);
}
int year = Integer.valueOf(tokenArr[1]);
try {
setDate(day, month, year);
getYear();
} catch (IllegalValueException ive) {
throw ive;
}
}
private void setDateGivenMonth(String monthToConvert) {
int day = FIRST_DAY_OF_THE_MONTH;
int month = convertMonthIntoInteger(monthToConvert);
int year = Integer.valueOf(getThisYear());
try {
setDate(day, month, year);
} catch (DateTimeException dte) {
throw dte;
}
}
private void setDateGivenDayNameOfWeek(String dayName) {
int day = convertDayOfWeekIntoInteger(dayName);
LocalDate today = LocalDate.now();
String todayDayNameInWeek = today.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US);
int todayDayInWeek = convertDayOfWeekIntoInteger(todayDayNameInWeek);
int daysToAdd = day - todayDayInWeek;
if (daysToAdd < 0) {
daysToAdd += NUM_DAYS_IN_A_WEEK;
}
LocalDate finalDate = today.plusDays(daysToAdd);
setDate(finalDate.getDayOfMonth(), finalDate.getMonthValue(), finalDate.getYear());
}
private void setDateGivenToday(String date) {
LocalDate today = LocalDate.now();
setDate(today.getDayOfMonth(), today.getMonthValue(), today.getYear());
}
private void setDateGivenTomorrow(String date) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
setDate(tomorrow.getDayOfMonth(), tomorrow.getMonthValue(), tomorrow.getYear());
}
/**
* Extract the different fields of a given valid date
* @throws DateTimeException
*/
public void setDate(int day, int month, int year) {
this.taskDate = convertToStandardFormat(day, month, year);
}
/**
* Convert this TaskDate to the format of
* DAY_MONTH-YEAR
*/
public String convertToStandardFormat(int day, int month, int year) {
return day + "-" + month + "-" + year;
}
/**
* Returns true if a given string is a valid task date.
*/
public static boolean isValidDate(String dateToValidate) {
if (dateToValidate == null || dateToValidate.isEmpty()) {
return false;
}
return isValidFullDate(dateToValidate) || isValidMonthAndYear(dateToValidate)
|| isValidDayAndMonth(dateToValidate) || isValidMonth(dateToValidate) || isValidToday(dateToValidate)
|| isValidTomorrow(dateToValidate) || isValidDayOfWeek(dateToValidate);
}
public static boolean isValidDayOfWeek(String dateToValidate) {
if (convertDayOfWeekIntoInteger(dateToValidate) == NOT_A_VALID_DAY_OF_THE_WEEK) {
return false;
}
return true;
}
public static boolean isValidMonthAndYear(String dateToValidate) {
if (isValidFormat(dateToValidate, "MMM yyyy") || isValidFormat(dateToValidate, "MMM-yyyy")
|| isValidFormat(dateToValidate, "MMM.yyyy")
|| isValidFormat(dateToValidate, "MMM/yyyy")) {
return true;
}
return false;
}
public static boolean isValidDayAndMonth(String dateToValidate) {
if (isValidFormat(dateToValidate, "d MMM") || isValidFormat(dateToValidate, "d-MMM")
|| isValidFormat(dateToValidate, "d.MMM")
|| isValidFormat(dateToValidate, "d/MMM")) {
return true;
}
return false;
}
public static boolean isValidFullDate(String dateToValidate) {
if (isValidFormat(dateToValidate, "d M yyyy") || isValidFormat(dateToValidate, "d MMM yyyy")
|| isValidFormat(dateToValidate, "d-M-yyyy") || isValidFormat(dateToValidate, "d-MMM-yyyy")
|| isValidFormat(dateToValidate, "d.M.yyyy") || isValidFormat(dateToValidate, "d.MMM.yyyy")
|| isValidFormat(dateToValidate, "d.M-yyyy") || isValidFormat(dateToValidate, "d.MMM-yyyy")
|| isValidFormat(dateToValidate, "d-M.yyyy") || isValidFormat(dateToValidate, "d-MMM.yyyy")
|| isValidFormat(dateToValidate, "d/M/yyyy") || isValidFormat(dateToValidate, "d/MMM/yyyy")
|| isValidFormat(dateToValidate, "d-M/yyyy") || isValidFormat(dateToValidate, "d-MMM/yyyy")
|| isValidFormat(dateToValidate, "d/M-yyyy") || isValidFormat(dateToValidate, "d/MMM-yyyy")
|| isValidFormat(dateToValidate, "d.M/yyyy") || isValidFormat(dateToValidate, "d.MMM/yyyy")
|| isValidFormat(dateToValidate, "d/M.yyyy") || isValidFormat(dateToValidate, "d/MMM.yyyy")) {
return true;
}
return false;
}
/**
* Returns true if a given string has a valid format supported by SimpleDateFormat.
*/
public static boolean isValidFormat(String dateToValidate, String acceptedFormat) {
if (dateToValidate == null) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(acceptedFormat);
sdf.setLenient(false);
try {
// if not valid, it will throw ParseException
Date date = sdf.parse(dateToValidate);
} catch (ParseException e) {
return false;
}
return true;
}
public static boolean isValidToday(String dateToValidate) {
assert (dateToValidate != null);
dateToValidate = dateToValidate.toLowerCase();
switch (dateToValidate) {
case "today":
// Fallthrough
case "tdy":
return true;
default:
return false;
}
}
public static boolean isValidTomorrow(String dateToValidate) {
assert (dateToValidate != null);
dateToValidate = dateToValidate.toLowerCase();
switch (dateToValidate) {
case "tomorrow":
// Fallthrough
case "tmr":
return true;
default:
return false;
}
}
public static boolean isValidMonth(String month) {
if (convertMonthIntoInteger(month) == NOT_A_VALID_MONTH) {
return false;
} else {
return true;
}
}
/**
* Returns an integer representing the day in a week
*/
private static int convertDayOfWeekIntoInteger(String day) {
assert (day != null);
day = day.toLowerCase();
switch (day) {
case "mon":
// Fallthrough
case "monday":
return MONDAY;
case "tue":
// Fallthrough
case "tues":
// Fallthrough
case "tuesday":
return TUESDAY;
case "wed":
// Fallthrough
case "wednesday":
return WEDNESDAY;
case "thu":
// Fallthrough
case "thur":
// Fallthrough
case "thurs":
// Fallthrough
case "thursday":
return THURSDAY;
case "fri":
// Fallthrough
case "friday":
return FRIDAY;
case "sat":
// Fallthrough
case "saturday":
return SATURDAY;
case "sun":
// Fallthrough
case "sunday":
return SUNDAY;
default:
return NOT_A_VALID_DAY_OF_THE_WEEK;
}
}
/**
* Returns an integer representing the month of a year.
*/
private static int convertMonthIntoInteger(String month) {
assert (month!= null);
if (Character.isLetter(month.charAt(0))) {
month = month.toLowerCase();
}
switch (month) {
case "jan":
// Fallthrough
case "january":
return JANUARY;
case "feb":
// Fallthrough
case "february":
return FEBRUARY;
case "mar":
// Fallthrough
case "march":
return MARCH;
case "apr":
// Fallthrough
case "april":
return APRIL;
case "may":
return MAY;
case "jun":
// Fallthrough
case "june":
return JUNE;
case "jul":
// Fallthrough
case "july":
return JULY;
case "aug":
// Fallthrough
case "august":
return AUGUST;
case "sep":
// Fallthrough
case "sept":
// Fallthrough
case "september":
return SEPTEMBER;
case "oct":
// Fallthrough
case "october":
return OCTOBER;
case "nov":
// Fallthrough
case "november":
return NOVEMBER;
case "dec":
// Fallthrough
case "december":
return DECEMBER;
default:
return NOT_A_VALID_MONTH;
}
}
/**
* Get today's date in the format of
* NAME_OF_DAY_IN_WEEK, DAY MONTH YEAR
*/
public static String getTodayDate() {
return LocalDate.now().format(dtf);
}
/**
* Get tomorrow's date in the format of
* NAME_OF_DAY_IN_WEEK, DAY MONTH YEAR
*/
public static String getTomorrowDate() {
return LocalDate.now().plusDays(1).format(dtf);
}
/**
* Returns a string representing the integer value of this year
*/
public static String getThisYear() {
return LocalDate.now().getYear() + "";
}
public String getDay() throws IllegalValueException {
assert taskDate != null;
final Matcher matcherFullArg = TASK_DATE_ARGS_FORMAT.matcher(taskDate.trim());
if (matcherFullArg.matches()) {
return matcherFullArg.group("day");
} else {
throw new IllegalValueException(MESSAGE_TASK_DATE_CONSTRAINTS);
}
}
public String getMonth() throws IllegalValueException {
assert taskDate != null;
final Matcher matcherFullArg = TASK_DATE_ARGS_FORMAT.matcher(taskDate.trim());
if (matcherFullArg.matches()) {
return matcherFullArg.group("month");
} else {
throw new IllegalValueException(MESSAGE_TASK_DATE_CONSTRAINTS);
}
}
public String getYear() throws IllegalValueException {
assert taskDate != null;
final Matcher matcherFullArg = TASK_DATE_ARGS_FORMAT.matcher(taskDate.trim());
if (matcherFullArg.matches()) {
return matcherFullArg.group("year");
} else {
throw new IllegalValueException(MESSAGE_TASK_DATE_CONSTRAINTS);
}
}
public String getDayNameInWeek() throws IllegalValueException {
try {
LocalDate localDate = LocalDate.of(Integer.valueOf(getYear()), Integer.valueOf(getMonth()), Integer.valueOf(getDay()));
String dayNameInWeek = localDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US);
return dayNameInWeek;
} catch (IllegalValueException ive) {
throw ive;
}
}
public String getMonthName() throws IllegalValueException {
try {
LocalDate localDate = LocalDate.of(Integer.valueOf(getYear()), Integer.valueOf(getMonth()), Integer.valueOf(getDay()));
String month = localDate.getMonth().getDisplayName(TextStyle.FULL, Locale.US);
return month;
} catch (IllegalValueException ive) {
throw ive;
}
}
public String getDisplayDate() throws IllegalValueException {
return getDayNameInWeek() + ", " + getDay() + " " + getMonthName() + " " + getYear();
}
/**
* Returns a string with the format of
* NAME_OF_DAY_IN_WEEK, DAY MONTH YEAR
*/
@Override
public String toString() {
return taskDate;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskDate // instanceof handles nulls
&& this.taskDate.equals(((TaskDate)other).taskDate));
}
@Override
public int hashCode() {
return taskDate.hashCode();
}
}
|
package sizebay.catalog.client;
import java.util.*;
import lombok.NonNull;
import sizebay.catalog.client.http.*;
import sizebay.catalog.client.model.*;
import sizebay.catalog.client.model.filters.*;
/**
* A Basic wrapper on generated Swagger client.
*
* @author Miere L. Teixeira
*/
public class CatalogAPI {
final static String
DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/",
ENDPOINT_BRAND = "/brands",
ENDPOINT_MODELING = "/modelings",
ENDPOINT_PRODUCT = "/products",
ENDPOINT_CATEGORIES = "/categories",
ENDPOINT_TENANTS = "/tenants/",
ENDPOINT_USER = "/user",
ENDPOINT_SIZE_STYLE = "/style",
ENDPOINT_DEVOLUTION = "/devolution",
ENDPOINT_IMPORTATION_ERROR = "/importations",
ENDPOINT_STRONG_CATEGORY_TYPE = "types",
ENDPOINT_STRONG_CATEGORY = "types/categories/strong",
ENDPOINT_STRONG_SUBCATEGORY = "types/categories/strong/sub",
ENDPOINT_STRONG_MODEL = "models/strong",
SEARCH_BY_TEXT = "/search/all?text=";
final RESTClient client;
/**
* Constructs the Catalog API.
*
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) {
this(DEFAULT_BASE_URL, applicationToken, securityToken);
}
/**
* Constructs the Catalog API.
*
* @param basePath
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) {
final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken );
final MimeType mimeType = new JSONMimeType();
client = new RESTClient( basePath, mimeType, authentication );
}
/**
* Starting user profile management
*/
public void insertUser (UserProfile userProfile) {
client.post(ENDPOINT_USER, userProfile);
}
public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){
return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class);
}
public UserProfile retrieveUser (String userId) {
return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class);
}
public UserProfile retrieveUserByFacebook(String facebookToken) {
return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class);
}
public UserProfile retrieveUserByGoogle(String googleToken) {
return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class);
}
public Profile retrieveProfile (long profileId) {
return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class);
}
public void updateUserFacebookToken(String userId, String facebookToken) {
client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken);
}
public void updateUserGoogleToken(String userId, String googleToken) {
client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken);
}
public void insertProfile (Profile profile) {
client.post(ENDPOINT_USER + "/profile", profile);
}
public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); }
/*
* End user profile management
*/
/*
* Starting size style management
*/
public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) {
return client.getList(ENDPOINT_SIZE_STYLE + "/search/all" + "?" + filter.createQuery(), SizeStyle.class);
}
public List<SizeStyle> getSizeStyle(long brandId, int typeId, char gender, int ageGroup) {
return client.getList(ENDPOINT_SIZE_STYLE + "/" + brandId + "/" + typeId + "/" + gender + "/" + ageGroup, SizeStyle.class);
}
public List<SizeStyle> getSizeStyle(long brandId, int typeId, char gender, int ageGroup, int categoryId) {
return client.getList(ENDPOINT_SIZE_STYLE + "/" + brandId + "/" + typeId + "/" + gender + "/" + ageGroup + "/" + categoryId, SizeStyle.class);
}
public List<SizeStyle> getSizeStyle(long brandId, int typeId, char gender, int ageGroup, int categoryId, int subcategoryId) {
return client.getList(ENDPOINT_SIZE_STYLE + "/" + brandId + "/" + typeId + "/" + gender + "/" + ageGroup + "/" + categoryId + "/" + subcategoryId, SizeStyle.class);
}
public SizeStyle getSingleSizeStyle(long id) {
return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class);
}
public long insertSizeStyle(SizeStyle sizeStyle) {
return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle);
}
public void updateWeightStyle(long id, SizeStyle sizeStyle) {
client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle);
}
public void bulkUpdateSizeStyles(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE, bulkUpdateSizeStyle);
}
public void deleteSizeStyle(long id) {
client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id);
}
public void deleteSizeStyles(List<Integer> ids) {
client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids);
}
/*
* End size style management
*/
/*
* Starting devolution management
*/
public List<DevolutionError> retrieveDevolutionErrors() {
return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class);
}
public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) {
return client.getList(ENDPOINT_DEVOLUTION + "/errors" + "?" + filter.createQuery(), DevolutionError.class);
}
public long insertDevolutionError(DevolutionError devolution) {
return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution);
}
public void deleteDevolutionErrors() {
client.delete(ENDPOINT_DEVOLUTION + "/errors");
}
public DevolutionSummary retrieveDevolutionSummaryLastBy() {
return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class);
}
public long insertDevolutionSummary(DevolutionSummary devolutionSummary) {
return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary);
}
public void deleteDevolutionSummary() {
client.delete(ENDPOINT_DEVOLUTION + "/summary");
}
/*
* End devolution management
*/
/*
* Starting user (MySizebay) management
*/
public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) {
return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class );
}
/*
* End user (MySizebay) management
*/
/*
* Starting product management
*/
public List<Product> getProducts(int page) {
return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class);
}
public List<Product> getProducts(ProductFilter filter) {
return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class);
}
public Product getProduct(long id) {
return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class);
}
public Long getProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink,
Long.class);
}
public Long getAvailableProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink
+ "&onlyAvailable=true",
Long.class);
}
public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id"
+ "/" + tenantId
+ "/" + feedProductId,
ProductIntegration.class);
}
public ProductBasicInformation retrieveProductByBarcode(Long barcode) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfo(long id){
return client.getSingle(ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info",
ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){
return client.getSingle( ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info-filter-sizes"
+ "?sizes=" + sizes,
ProductBasicInformation.class);
}
public long insertProduct(Product product) {
return client.post(ENDPOINT_PRODUCT + "/single", product);
}
public ProductIntegration insertProductIntegration(ProductIntegration product) {
return client.post(ENDPOINT_PRODUCT + "/single/integration", product, ProductIntegration.class);
}
public long insertMockedProduct(String permalink) {
return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class);
}
public void updateProduct(long id, Product product) {
client.put(ENDPOINT_PRODUCT + "/single/" + id, product);
}
public void bulkUpdateProducts(BulkUpdateProducts products) {
client.patch(ENDPOINT_PRODUCT, products);
}
public void deleteProducts() {
client.delete(ENDPOINT_PRODUCT);
}
public void deleteProduct(long id) {
client.delete(ENDPOINT_PRODUCT + "/single/" + id);
}
public void deleteProducts(List<Integer> ids) {
client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids);
}
/*
* End product management
*/
/*
* Starting brand management
*/
public List<Brand> searchForBrands(String text){
return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class);
}
public List<Brand> getBrands(int page) {
return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class);
}
public List<Brand> getBrands(int page, String name) {
return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class);
}
public Brand getBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class);
}
public long insertBrand(Brand brand) {
return client.post(ENDPOINT_BRAND + "/single", brand);
}
public void updateBrand(long id, Brand brand) {
client.put(ENDPOINT_BRAND + "/single/" + id, brand);
}
public void deleteBrands() {
client.delete(ENDPOINT_BRAND);
}
public void deleteBrand(long id) {
client.delete(ENDPOINT_BRAND + "/single/" + id);
}
public void deleteBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/bulk/some", ids);
}
/*
* End brand management
*/
/*
* Starting category management
*/
public List<Category> getCategories() {
return client.getList(ENDPOINT_CATEGORIES, Category.class);
}
public List<Category> getCategories(int page) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class);
}
public List<Category> getCategories(int page, String name) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class);
}
public List<Category> searchForCategories(String text){
return client.getList(ENDPOINT_CATEGORIES + SEARCH_BY_TEXT + text, Category.class);
}
public Category getCategory(long id) {
return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class);
}
public long insertCategory(Category brand) {
return client.post(ENDPOINT_CATEGORIES + "/single", brand);
}
public void updateCategory(long id, Category brand) {
client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand);
}
public void deleteCategories() {
client.delete(ENDPOINT_CATEGORIES);
}
public void deleteCategory(long id) {
client.delete(ENDPOINT_CATEGORIES + "/single/" + id);
}
public void deleteCategories(List<Integer> ids) {
client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids);
}
/*
* End category management
*/
/*
* Starting modeling management
*/
public List<Modeling> searchForModelings(long brandId, String gender) {
return searchForModelings(String.valueOf(brandId), gender);
}
public List<Modeling> searchForModelings(String brandId, String gender){
return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class);
}
public List<Modeling> getModelings(int page){
return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class);
}
public List<Modeling> getModelings(ModelingFilter filter) {
return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class);
}
public Modeling getModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class);
}
public long insertModeling(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single", modeling);
}
public void updateModeling(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id, modeling);
}
public void deleteModelings() {
client.delete(ENDPOINT_MODELING);
}
public void deleteModeling(long id) {
client.delete(ENDPOINT_MODELING + "/single/" + id);
}
public void deleteModelings(List<Integer> ids) {
client.delete(ENDPOINT_MODELING + "/bulk/some", ids);
}
/*
* End modeling management
*/
/*
* Starting importation error management
*/
public List<ImportationError> getImportationErrors(int page){
return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class);
}
public long insertImportationError(ImportationError importationError){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError);
}
public void deleteImportationErrors() {
client.delete(ENDPOINT_PRODUCT + "/importation-errors/all");
}
public ImportationSummary getImportationSummary(){
return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class);
}
public long insertImportationSummary(ImportationSummary importationSummary){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary);
}
public void deleteImportationSummary() {
client.delete(ENDPOINT_IMPORTATION_ERROR);
}
/*
* End importation error management
*/
/*
* Starting strong brand management
*/
public List<StrongBrand> getAllBrand(){
return client.getList(ENDPOINT_BRAND + "/strong", StrongBrand.class);
}
public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class);
}
public StrongBrand getSingleBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class);
}
public long insertStrongBrand(StrongBrand strongBrand){
return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand);
}
public void updateStrongBrand(long id, StrongBrand strongBrand) {
client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand);
}
public void deleteStrongBrand(long id) {
client.delete(ENDPOINT_BRAND + "/strong/single/" + id);
}
public void deleteStrongBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids);
}
/*
* End strong brand management
*/
/*
* Starting strong category management
*/
public List<StrongCategory> getAllStrongCategories(){
return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class);
}
public List<StrongCategory> getAllStrongCategories(int page, String categoryName, Long typeId){
String condition;
condition = categoryName == null ? "" : "&name=" + categoryName;
condition += typeId == null ? "" : "&typeId=" + typeId;
return client.getList(ENDPOINT_STRONG_CATEGORY + "/search/all?page=" + page + condition, StrongCategory.class);
}
public StrongCategory getSingleStrongCategory(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class);
}
public long insertStrongCategory(StrongCategory strongCategory){
return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory);
}
public void updateStrongCategory(long id, StrongCategory strongCategory) {
client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory);
}
public void deleteStrongCategory(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id);
}
/*
* End strong category management
*/
/*
* Starting strong subcategory management
*/
public List<StrongSubcategory> getAllStrongSubcategories(int page){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class);
}
public List<StrongSubcategory> getAllStrongSubcategories(int page, String subcategoryName){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page + "&name=" + subcategoryName, StrongSubcategory.class);
}
public StrongSubcategory getSingleStrongSubcategory(long id) {
return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class);
}
public long insertStrongSubcategory(StrongSubcategory strongSubcategory){
return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory);
}
public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) {
client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory);
}
public void deleteStrongSubcategory(long id) {
client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id);
}
/*
* End strong subcategory management
*/
/*
* Starting strong category type management
*/
public List<StrongCategoryType> getAllStrongCategoryTypes(int page){
return client.getList(ENDPOINT_STRONG_CATEGORY_TYPE + "?page=" + page, StrongCategoryType.class);
}
public List<StrongCategoryType> getAllStrongCategoryTypes(int page, String categoryTypeName){
return client.getList(ENDPOINT_STRONG_CATEGORY_TYPE + "?page=" + page + "&name=" + categoryTypeName, StrongCategoryType.class);
}
public StrongCategoryType getSingleStrongCategoryType(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id, StrongCategoryType.class);
}
public long insertStrongCategoryType(StrongCategoryType strongCategoryType){
return client.post(ENDPOINT_STRONG_CATEGORY_TYPE + "/single", strongCategoryType);
}
public void updateStrongCategoryType(long id, StrongCategoryType strongCategoryType) {
client.put(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id, strongCategoryType);
}
public void deleteStrongCategoryType(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY_TYPE + "/single/" + id);
}
/*
* End strong category type management
*/
/*
* Starting strong model management
*/
public List<StrongModel> getAllStrongModels(int page){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class);
}
public List<StrongModel> getAllStrongModels(int page, String modelName){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class);
}
public StrongModel getSingleStrongModel(long id) {
return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class);
}
public long insertStrongModel(StrongModel strongModel){
return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel);
}
public void updateStrongModel(long id, StrongModel strongModel) {
client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel);
}
public void deleteStrongModel(long id) {
client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id);
}
/*
* End strong model management
*/
public void updateHashXML(String hash) {
client.put(ENDPOINT_TENANTS + "hash", hash);
}
public List<Tenant> retrieveAllTenants(){
return client.getList( ENDPOINT_TENANTS, Tenant.class );
}
public Tenant getTenant( String appToken ){
return client.getSingle( ENDPOINT_TENANTS+ "single/" + appToken, Tenant.class );
}
@Deprecated
void saveUser( User user ){
client.post( "/users/", user );
}
public void insertTenant(Tenant tenant) {
client.post( ENDPOINT_TENANTS, tenant );
}
public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) {
client.post( "/importations/tenantId/"+tenantId, importationSummary );
}
public String retrieveImportRules(long id) {
return client.getSingle( ENDPOINT_TENANTS + id + "/rules", String.class );
}
public List<Tenant> searchTenants(TenantFilter filter) {
return client.getList( ENDPOINT_TENANTS + "search?monitored=" + filter.getMonitored(), Tenant.class);
}
public List<Tenant> searchAllTenants() {
return client.getList( ENDPOINT_TENANTS + "search/all", Tenant.class);
}
}
|
package tigase.muc.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.criteria.Criteria;
import tigase.criteria.ElementCriteria;
import tigase.muc.Affiliation;
import tigase.muc.DateUtil;
import tigase.muc.ElementWriter;
import tigase.muc.MucConfig;
import tigase.muc.Role;
import tigase.muc.Room;
import tigase.muc.RoomConfig;
import tigase.muc.RoomConfig.Anonymity;
import tigase.muc.exceptions.MUCException;
import tigase.muc.history.HistoryProvider;
import tigase.muc.logger.MucLogger;
import tigase.muc.modules.PresenceModule.DelayDeliveryThread.DelDeliverySend;
import tigase.muc.repository.IMucRepository;
import tigase.muc.repository.RepositoryException;
import tigase.server.Packet;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xml.XMLNodeIfc;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
/**
* @author bmalkow
*
*/
public class PresenceModule extends AbstractModule {
public static class DelayDeliveryThread extends Thread {
public static interface DelDeliverySend {
void sendDelayedPacket(Packet packet);
}
private final LinkedList<Element[]> items = new LinkedList<Element[]>();
private final DelDeliverySend sender;
public DelayDeliveryThread(DelDeliverySend component) {
this.sender = component;
}
/**
* @param elements
*/
public void put(Collection<Element> elements) {
if (elements != null && elements.size() > 0) {
items.push(elements.toArray(new Element[] {}));
}
}
public void put(Element element) {
items.add(new Element[] { element });
}
@Override
public void run() {
try {
do {
sleep(553);
if (items.size() > 0) {
Element[] toSend = items.poll();
if (toSend != null) {
for (Element element : toSend) {
try {
sender.sendDelayedPacket(Packet.packetInstance(element));
} catch (TigaseStringprepException ex) {
log.info("Packet addressing problem, stringprep failed: " + element);
}
}
}
}
} while (true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static final Criteria CRIT = ElementCriteria.name("presence");
protected static final Logger log = Logger.getLogger(PresenceModule.class.getName());
private static Role getDefaultRole(final RoomConfig config, final Affiliation affiliation) {
Role newRole;
if (config.isRoomModerated() && affiliation == Affiliation.none) {
newRole = Role.visitor;
} else {
switch (affiliation) {
case admin:
newRole = Role.moderator;
break;
case member:
newRole = Role.participant;
break;
case none:
newRole = Role.participant;
break;
case outcast:
newRole = Role.none;
break;
case owner:
newRole = Role.moderator;
break;
default:
newRole = Role.none;
break;
}
}
return newRole;
}
private static Integer toInteger(String v, Integer defaultValue) {
if (v == null)
return defaultValue;
try {
return Integer.parseInt(v);
} catch (Exception e) {
return defaultValue;
}
}
private final Set<Criteria> allowedElements = new HashSet<Criteria>();
private final Set<Criteria> disallowedElements = new HashSet<Criteria>();
private boolean filterEnabled = true;
private final HistoryProvider historyProvider;
private boolean lockNewRoom = true;
private final MucLogger mucLogger;
public PresenceModule(MucConfig config, ElementWriter writer, IMucRepository mucRepository,
HistoryProvider historyProvider, DelDeliverySend sender, MucLogger mucLogger) {
super(config, writer, mucRepository);
this.historyProvider = historyProvider;
this.mucLogger = mucLogger;
this.filterEnabled = config.isPresenceFilterEnabled();
allowedElements.add(ElementCriteria.name("show"));
allowedElements.add(ElementCriteria.name("status"));
allowedElements.add(ElementCriteria.name("priority"));
allowedElements.add(ElementCriteria.xmlns("http://jabber.org/protocol/caps"));
log.config("Filtering presence children is " + (filterEnabled ? "enabled" : "disabled"));
}
/**
* @param room
* @param date
* @param senderJID
* @param nickName
*/
private void addJoinToHistory(Room room, Date date, JID senderJID, String nickName) {
if (historyProvider != null)
historyProvider.addJoinEvent(room, date, senderJID, nickName);
if (mucLogger != null && room.getConfig().isLoggingEnabled()) {
mucLogger.addJoinEvent(room, date, senderJID, nickName);
}
}
/**
* @param room
* @param date
* @param senderJID
* @param nickName
*/
private void addLeaveToHistory(Room room, Date date, JID senderJID, String nickName) {
if (historyProvider != null)
historyProvider.addLeaveEvent(room, date, senderJID, nickName);
if (mucLogger != null && room.getConfig().isLoggingEnabled()) {
mucLogger.addLeaveEvent(room, date, senderJID, nickName);
}
}
protected Element clonePresence(Element element) {
Element presence = new Element(element);
if (filterEnabled) {
List<Element> cc = element.getChildren();
if (cc != null) {
List<XMLNodeIfc> children = new ArrayList<XMLNodeIfc>();
for (Element c : cc) {
for (Criteria crit : allowedElements) {
if (crit.match(c)) {
children.add(c);
break;
}
}
}
presence.setChildren(children);
}
}
Element toRemove = presence.getChild("x", "http://jabber.org/protocol/muc");
if (toRemove != null)
presence.removeChild(toRemove);
return presence;
}
@Override
public String[] getFeatures() {
return null;
}
@Override
public Criteria getModuleCriteria() {
return CRIT;
}
public boolean isLockNewRoom() {
return lockNewRoom;
}
private Element preparePresence(JID occupantJid, final Element presence, Room room, BareJID roomJID, String nickName,
Affiliation affiliation, Role role, JID senderJID, boolean newRoomCreated, String newNickName) {
Anonymity anonymity = room.getConfig().getRoomAnonymity();
final Affiliation occupantAffiliation = room.getAffiliation(occupantJid.getBareJID());
try {
presence.setAttribute("from", JID.jidInstance(roomJID, nickName).toString());
} catch (TigaseStringprepException e) {
presence.setAttribute("from", roomJID + "/" + nickName);
}
presence.setAttribute("to", occupantJid.toString());
Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" });
Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] { affiliation.name(),
role.name(), nickName });
if (senderJID.equals(occupantJid)) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "110" }));
if (anonymity == Anonymity.nonanonymous) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "100" }));
}
if (room.getConfig().isLoggingEnabled()) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "170" }));
}
}
if (newRoomCreated) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "201" }));
}
if (anonymity == Anonymity.nonanonymous
|| (anonymity == Anonymity.semianonymous && occupantAffiliation.isViewOccupantsJid())) {
item.setAttribute("jid", senderJID.toString());
}
if (newNickName != null) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "303" }));
item.setAttribute("nick", newNickName);
}
x.addChild(item);
presence.addChild(x);
return presence;
}
private void preparePresenceToAllOccupants(final Element $presence, Room room, BareJID roomJID, String nickName,
Affiliation affiliation, Role role, JID senderJID, boolean newRoomCreated, String newNickName)
throws TigaseStringprepException {
for (String occupantNickname : room.getOccupantsNicknames()) {
for (JID occupantJid : room.getOccupantsJidsByNickname(occupantNickname)) {
Element presence = preparePresence(occupantJid, $presence.clone(), room, roomJID, nickName, affiliation, role,
senderJID, newRoomCreated, newNickName);
writer.write(Packet.packetInstance(presence));
}
}
}
private void preparePresenceToAllOccupants(Room room, BareJID roomJID, String nickName, Affiliation affiliation, Role role,
JID senderJID, boolean newRoomCreated, String newNickName) throws TigaseStringprepException {
Element presence;
if (newNickName != null) {
presence = new Element("presence");
presence.setAttribute("type", "unavailable");
} else if (room.getOccupantsNickname(senderJID) == null) {
presence = new Element("presence");
presence.setAttribute("type", "unavailable");
} else {
presence = room.getLastPresenceCopyByJid(senderJID.getBareJID());
}
preparePresenceToAllOccupants(presence, room, roomJID, nickName, affiliation, role, senderJID, newRoomCreated,
newNickName);
}
@Override
public void process(Packet element) throws MUCException, TigaseStringprepException {
final JID senderJID = JID.jidInstance(element.getAttribute("from"));
final BareJID roomJID = BareJID.bareJIDInstance(element.getAttribute("to"));
final String nickName = getNicknameFromJid(JID.jidInstance(element.getAttribute("to")));
final String presenceType = element.getAttribute("type");
if (presenceType != null && "error".equals(presenceType)) {
if (log.isLoggable(Level.FINER))
log.finer("Ignoring presence with type='" + presenceType + "' from " + senderJID);
return;
}
if (nickName == null) {
throw new MUCException(Authorization.JID_MALFORMED);
}
try {
Room room = repository.getRoom(roomJID);
if (presenceType != null && "unavailable".equals(presenceType)) {
processExit(room, element.getElement(), senderJID);
return;
}
final String knownNickname;
final boolean roomCreated;
if (room == null) {
log.info("Creating new room '" + roomJID + "' by user " + nickName + "' <" + senderJID.toString() + ">");
room = repository.createNewRoom(roomJID, senderJID);
room.addAffiliationByJid(senderJID.getBareJID(), Affiliation.owner);
room.setRoomLocked(this.lockNewRoom);
roomCreated = true;
knownNickname = null;
} else {
roomCreated = false;
knownNickname = room.getOccupantsNickname(senderJID);
}
final boolean probablyReEnter = element.getElement().getChild("x", "http://jabber.org/protocol/muc") != null;
if (probablyReEnter || knownNickname == null) {
processEntering(room, roomCreated, element.getElement(), senderJID, nickName);
} else if (knownNickname.equals(nickName)) {
processChangeAvailabilityStatus(room, element.getElement(), senderJID, knownNickname);
} else if (!knownNickname.equals(nickName)) {
processChangeNickname(room, element.getElement(), senderJID, knownNickname, nickName);
}
} catch (MUCException e) {
throw e;
} catch (TigaseStringprepException e) {
throw e;
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
protected void processChangeAvailabilityStatus(final Room room, final Element presenceElement, final JID senderJID,
final String nickname) throws TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + presenceElement.toString());
room.updatePresenceByJid(null, clonePresence(presenceElement));
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Role role = room.getRole(nickname);
Element pe = room.getLastPresenceCopyByJid(senderJID.getBareJID());
preparePresenceToAllOccupants(pe, room, room.getRoomJID(), nickname, affiliation, role, senderJID, false, null);
}
protected void processChangeNickname(final Room room, final Element element, final JID senderJID,
final String senderNickname, final String newNickName) throws TigaseStringprepException, MUCException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + element.toString());
throw new MUCException(Authorization.FEATURE_NOT_IMPLEMENTED, "Will me done soon");
// TODO Example 23. Service Denies Room Join Because Roomnicks Are
// Locked Down (???)
}
protected void processEntering(final Room room, final boolean roomCreated, final Element element, final JID senderJID,
final String nickname) throws MUCException, TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + element.toString());
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Anonymity anonymity = room.getConfig().getRoomAnonymity();
final Element xElement = element.getChild("x", "http://jabber.org/protocol/muc");
final Element password = xElement == null ? null : xElement.getChild("password");
if (room.getConfig().isPasswordProtectedRoom()) {
final String psw = password == null ? null : password.getCData();
final String roomPassword = room.getConfig().getPassword();
if (psw == null || !psw.equals(roomPassword)) {
// Service Denies Access Because No Password Provided
log.finest("Password '" + psw + "' is not match to room password '" + roomPassword + "' ");
throw new MUCException(Authorization.NOT_AUTHORIZED);
}
}
if (room.isRoomLocked() && affiliation != Affiliation.owner) {
// Service Denies Access Because Room Does Not (Yet) Exist
throw new MUCException(Authorization.ITEM_NOT_FOUND);
}
if (!affiliation.isEnterOpenRoom()) {
// Service Denies Access Because User is Banned
log.info("User " + nickname + "' <" + senderJID.toString() + "> is on rooms '" + room.getRoomJID() + "' blacklist");
throw new MUCException(Authorization.FORBIDDEN);
} else if (room.getConfig().isRoomMembersOnly() && !affiliation.isEnterMembersOnlyRoom()) {
// Service Denies Access Because User Is Not on Member List
log.info("User " + nickname + "' <" + senderJID.toString() + "> is NOT on rooms '" + room.getRoomJID()
+ "' member list.");
throw new MUCException(Authorization.REGISTRATION_REQUIRED);
}
final BareJID currentOccupantJid = room.getOccupantsJidByNickname(nickname);
if (currentOccupantJid != null && !currentOccupantJid.equals(senderJID.getBareJID())) {
// Service Denies Access Because of Nick Conflict
throw new MUCException(Authorization.CONFLICT);
}
// TODO Service Informs User that Room Occupant Limit Has Been Reached
// Service Sends Presence from Existing Occupants to New Occupant
for (String occupantNickname : room.getOccupantsNicknames()) {
final Affiliation occupantAffiliation = room.getAffiliation(occupantNickname);
final Role occupantRole = room.getRole(occupantNickname);
final BareJID occupantJid = room.getOccupantsJidByNickname(occupantNickname);
Element presence = room.getLastPresenceCopyByJid(occupantJid);
presence.setAttribute("from", room.getRoomJID() + "/" + occupantNickname);
presence.setAttribute("to", senderJID.toString());
Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" });
Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] {
occupantAffiliation.name(), occupantRole.name(), occupantNickname });
if (anonymity == Anonymity.nonanonymous
|| (anonymity == Anonymity.semianonymous && (affiliation == Affiliation.admin || affiliation == Affiliation.owner))) {
item.setAttribute("jid", occupantJid.toString());
}
x.addChild(item);
presence.addChild(x);
writer.write(Packet.packetInstance(presence));
}
final Role newRole = getDefaultRole(room.getConfig(), affiliation);
log.finest("Occupant '" + nickname + "' <" + senderJID.toString() + "> is entering room " + room.getRoomJID()
+ " as role=" + newRole.name() + ", affiliation=" + affiliation.name());
room.addOccupantByJid(senderJID, nickname, newRole);
Element pe = clonePresence(element);
room.updatePresenceByJid(null, pe);
if (currentOccupantJid == null) {
// Service Sends New Occupant's Presence to All Occupants
// Service Sends New Occupant's Presence to New Occupant
preparePresenceToAllOccupants(room, room.getRoomJID(), nickname, affiliation, newRole, senderJID, roomCreated, null);
} else {
// Service Sends New Occupant's Presence to New Occupant
Element p = preparePresence(senderJID, pe, room, room.getRoomJID(), nickname, affiliation, newRole, senderJID,
roomCreated, null);
writer.writeElement(p);
}
Integer maxchars = null;
Integer maxstanzas = null;
Integer seconds = null;
Date since = null;
Element hist = xElement.getChild("history");
if (hist != null) {
maxchars = toInteger(hist.getAttribute("maxchars"), null);
maxstanzas = toInteger(hist.getAttribute("maxstanzas"), null);
seconds = toInteger(hist.getAttribute("seconds"), null);
since = DateUtil.parse(hist.getAttribute("since"));
}
sendHistoryToUser(room, senderJID, maxchars, maxstanzas, seconds, since, writer);
if (room.getSubject() != null && room.getSubjectChangerNick() != null && room.getSubjectChangeDate() != null) {
Element message = new Element("message", new String[] { "type", "from", "to" }, new String[] { "groupchat",
room.getRoomJID() + "/" + room.getSubjectChangerNick(), senderJID.toString() });
message.addChild(new Element("subject", room.getSubject()));
String stamp = DateUtil.formatDatetime(room.getSubjectChangeDate());
Element delay = new Element("delay", new String[] { "xmlns", "stamp" }, new String[] { "urn:xmpp:delay", stamp });
delay.setAttribute("jid", room.getRoomJID() + "/" + room.getSubjectChangerNick());
Element x = new Element("x", new String[] { "xmlns", "stamp" }, new String[] { "jabber:x:delay",
DateUtil.formatOld(room.getSubjectChangeDate()) });
message.addChild(delay);
message.addChild(x);
writer.writeElement(message);
}
if (room.isRoomLocked()) {
sendMucMessage(room, room.getOccupantsNickname(senderJID), "Room is locked. Please configure.");
}
if (roomCreated) {
StringBuilder sb = new StringBuilder();
sb.append("Welcome! You created new Multi User Chat Room.");
if (room.isRoomLocked())
sb.append(" Room is locked now. Configure it please!");
else
sb.append(" Room is unlocked and ready for occupants!");
sendMucMessage(room, room.getOccupantsNickname(senderJID), sb.toString());
}
if (room.getConfig().isLoggingEnabled()) {
addJoinToHistory(room, new Date(), senderJID, nickname);
}
}
protected void processExit(final Room room, final Element presenceElement, final JID senderJID) throws MUCException,
TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + presenceElement.toString());
if (room == null)
throw new MUCException(Authorization.ITEM_NOT_FOUND, "Unkown room");
final String nickname = room.getOccupantsNickname(senderJID);
if (nickname == null)
throw new MUCException(Authorization.ITEM_NOT_FOUND, "Unkown occupant");
final Element pe = clonePresence(presenceElement);
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Role role = room.getRole(nickname);
final Element selfPresence = preparePresence(senderJID, pe, room, room.getRoomJID(), nickname, affiliation, role,
senderJID, false, null);
boolean nicknameGone = room.removeOccupant(senderJID);
room.updatePresenceByJid(senderJID, pe);
writer.writeElement(selfPresence);
// TODO if highest priority is gone, then send current highest priority
// to occupants
if (nicknameGone) {
preparePresenceToAllOccupants(pe, room, room.getRoomJID(), nickname, affiliation, role, senderJID, false, null);
if (room.getConfig().isLoggingEnabled()) {
addLeaveToHistory(room, new Date(), senderJID, nickname);
}
}
}
/**
* @param room
* @param senderJID
* @param maxchars
* @param maxstanzas
* @param seconds
* @param since
*/
private void sendHistoryToUser(final Room room, final JID senderJID, final Integer maxchars, final Integer maxstanzas,
final Integer seconds, final Date since, final ElementWriter writer) {
if (historyProvider != null)
historyProvider.getHistoryMessages(room, senderJID, maxchars, maxstanzas, seconds, since, writer);
}
public void setLockNewRoom(boolean lockNewRoom) {
this.lockNewRoom = lockNewRoom;
}
}
|
package wasdev.sample.servlet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.google.gson.stream.JsonReader;
import com.ibm.watson.developer_cloud.personality_insights.v2.PersonalityInsights;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Content;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.ProfileOptions;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.ProfileOptions.Language;
import com.ibm.watson.developer_cloud.util.GsonSingleton;
/**
* Servlet implementation class JsonServlet
*/
@WebServlet("/JsonServlet")
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JsonServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Inside Servlet doGet");
//PersonalityInsights personalityInsight=new PersonalityInsights();
response.setContentType("text/html");
// PrintWriter out =response.getWriter();
BufferedReader reader = null;
String weather="";
String urlString="https://2c435666-86e9-4041-8c17-46c807cf59fc:7lnNFiTeLZ@twcservice.mybluemix.net:443/api/weather/v2/location/point?postalKey=30339%3AUS&language=en-US";
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//conn.setRequestProperty("username", "fcb61d2d-3a6d-4c39-9b75-70172d3df53d");
//conn.setRequestProperty("password", "vlX9X7iVGd");
conn.setRequestProperty("Accept", "application/json");
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
weather=buffer.toString()+"::"+buffer;
System.out.println("Weather: "+ weather);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("weather", weather);
request.getRequestDispatcher("/jsp/Response.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Inside Servlet doPost");
String baseURL = "https://gateway-s.watsonplatform.net/personality-insights/api";
String username = "46235a77-79d7-44ed-81a4-63468124a3b0";
String password = "w3cQvZxjFKu0";
String text="Ashok Malik, Journalist "
+" Perhaps he knew it all along. On Independence Day, Prime Minister Narendra Modi delivered a 100-minute long speech, but the resultant coverage and debate has centred on his reference to troubled regions that are in Pakistani control but disputed internationally, or part of Pakistan but with a contested sovereignty domestically. There were three proper nouns Modi used and it is important to understand the context of each."
+" First, he spoke of Pakistan-Occupied Kashmir, a part of Kashmir in Pakistani control since 1947. Following the accession of the kingdom of Jammu and Kashmir in October 1947, it belongs to India. Indian maps show it as such. Since 1965, successive Indian governments have been willing to write off Pakistan-Occupied Kashmir and convert the line dividing it and the Kashmir Valley (the Line of Control) into an international border - whether a hard border or, as has been suggested over the past 10-15 years, a soft border permitting trade and movement of peoples."
+" Second, Modi referred to Gilgit or, to be more correct, Gilgit-Baltistan, also known as the Northern Areas. Modi was both right and wrong in distinguishing Gilgit-Baltistan from Pakistan-Occupied Kashmir. He was right because this is ethnically and geographically not part of the Kashmir region. Given its strategic import and proximity to Central Asia, the Pakistan government has spun off Gilgit-Baltistan into a separate territory, distinct from Pakistan-occupied Kashmir or the so-called Azad Kashmir."
+" Yet, Modi was also wrong. While not part of the cultural and social expanse of Kashmir and so not part of Pakistan-Occupied Kashmir in that narrow reckoning, the Northern Areas were a part of Hari Singh's kingdom and legally acceded to India in 1947. As such, Gilgit-Baltistan is a segment of Pakistan-occupied portions of the former kingdom (or the current Indian state) of Jammu and Kashmir."
+" Third, Balochistan is in a class by itself. In 1947, it existed as a frontier region comprising a clutch of kingdoms and some territory under the suzerainty of Oman, an Arab kingdom that was an ally of the British Raj. The biggest Baloch kingdom was the Khanate of Kalat. While it acceded to Pakistan, allegedly following promises by Mohammad Ali Jinnah that were never kept, Kalat had never quite been part of British India. Its position vis-à-vis the Raj was not very different from that of Nepal. As such, if Nepal is not part of India, there is logic to suggest that Kalat should not be part of Pakistan."
+" Certainly the former royal family of Kalat, members of which live in London, still fancy their claims. Another princely state was Las Bela, with its capital city, Bela, famous for not having had a European visitor between Alexander the Great and the British in the 19th century. Alexander visited Balochistan on his way home from India and is believed to have boarded a ship from the Makran Coast, near today's Gwadar. ";
try {
URI profileURI = new URI(baseURL + "/v2/profile").normalize();
Request profileRequest = Request.Post(profileURI)
.addHeader("Accept", "application/json")
.addHeader("Content-Language", "en")
.bodyString(text, ContentType.TEXT_PLAIN);
Executor executor = Executor.newInstance().auth(username, password);
Response responsefromAPI = executor.execute(profileRequest);
// HttpResponse httpResponse = responsefromAPI.returnResponse();
//response.setStatus(httpResponse.getStatusLine().getStatusCode());
/*
ServletOutputStream servletOutputStream = response.getOutputStream();
httpResponse.getEntity().writeTo(servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();*/
String jsonResponse= responsefromAPI.returnContent().asString();
System.out.println("JsonResponse: "+jsonResponse);
request.setAttribute("weather", jsonResponse);
} catch (Exception e) {
System.out.println("Service error: " + e.getMessage());
// resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
}
request.getRequestDispatcher("/jsp/Response.jsp").forward(request, response);
/*
*
*
* CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(postUrl);
postRequest.addHeader("accept", "application/json");
postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
URI profileURI = new URI(baseURL + "/v2/profile").normalize();
Request profileRequest = Request.Post(profileURI)
.addHeader("Accept", "application/json")
.addHeader("Content-Language", language)
.bodyString(text, ContentType.TEXT_PLAIN);
Executor executor = Executor.newInstance().auth(username, password);
Response response = executor.execute(profileRequest);
HttpResponse httpResponse = response.returnResponse();
resp.setStatus(httpResponse.getStatusLine().getStatusCode());
ServletOutputStream servletOutputStream = resp.getOutputStream();
httpResponse.getEntity().writeTo(servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
System.out.println( e.getMessage().toString());
//resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
}*/
}
}
|
package org.testng.reporters;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.log4testng.Logger;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Reported designed to render self-contained HTML top down view of a testing
* suite.
*
* @author Paul Mendelson
* @since 5.2
* @version $Revision$
*/
public class EmailableReporter implements IReporter {
Logger m_logger = Logger.getLogger(EmailableReporter.class);
private PrintWriter m_out;
int m_row;
private int m_method_ptr;
private int m_row_total;
/** Creates summary of the run */
public void generateReport(List<XmlSuite> xml, List<ISuite> suites,
String outdir) {
try {
m_out = new PrintWriter(new FileWriter(new File(outdir,
"emailable-report.html")));
} catch (IOException e) {
m_logger.error("output file", e);
return;
}
startHtml(m_out);
summarize(suites);
m_method_ptr = 0;
for (ISuite suite : suites) {
m_out.println("<a id=\"summary\"></a>");
Map<String, ISuiteResult> r = suite.getResults();
startResultSummaryTable("passed");
for (ISuiteResult r2 : r.values()) {
ITestContext test = r2.getTestContext();
resultSummary(test.getFailedTests(), test.getName(), "failed");
resultSummary(test.getSkippedTests(), test.getName(), "skipped");
resultSummary(test.getPassedTests(), test.getName(), "passed");
}
}
m_out.println("</table>");
m_method_ptr = 0;
for (ISuite suite : suites) {
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
if (r.values().size() > 0) {
m_out.println("<h1>" + r2.getTestContext().getName() + "</h1>");
}
resultDetail(r2.getTestContext().getFailedTests(), "failed");
resultDetail(r2.getTestContext().getSkippedTests(), "skipped");
resultDetail(r2.getTestContext().getPassedTests(), "passed");
}
}
endHtml(m_out);
m_out.close();
}
/**
* @param tests
*/
private void resultSummary(IResultMap tests, String testname, String style) {
if (tests.getAllResults().size() > 0) {
StringBuffer buff = new StringBuffer();
String lastc = "";
int mq = 0;
int cq = 0;
for (ITestNGMethod method : getMethodSet(tests)) {
m_row += 1;
m_method_ptr += 1;
String cname = method.getTestClass().getName();
if (mq == 0) {
titleRow(testname + " — " + style, 4);
}
if (!cname.equalsIgnoreCase(lastc)) {
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")
+ "\">" + "<td rowspan=\"" + mq + "\">" + lastc + buff);
}
mq = 0;
buff.setLength(0);
lastc = cname;
}
Set<ITestResult> result_set = tests.getResults(method);
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
for (ITestResult ans : tests.getResults(method)) {
if (ans.getEndMillis() > end) {
end = ans.getEndMillis();
}
if (ans.getStartMillis() < start) {
start = ans.getStartMillis();
}
}
mq += 1;
if (mq > 1) {
buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even")
+ "\">");
}
buff.append("<td><a href=\"#m" + m_method_ptr + "\">"
+ qualifiedName(method) + "</a></td>" + "<td class=\"numi\">"
+ result_set.size() + "</td><td class=\"numi\">" + (end - start)
+ "</td></tr>");
}
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")
+ "\">" + "<td rowspan=\"" + mq + "\">" + lastc + buff);
}
}
}
/** Starts and defines columns result summary table */
private void startResultSummaryTable(String style) {
tableStart(style);
m_out
.println("<tr><th>Class</th>"
+ "<th>Method</th><th># of<br/>Scenarios</th><th>Time<br/>(Msecs)</th></tr>");
m_row = 0;
}
private String qualifiedName(ITestNGMethod method) {
String addon = "";
if (method.getGroups().length > 0
&& !"basic".equalsIgnoreCase(method.getGroups()[0])) {
addon = " (" + method.getGroups()[0] + ")";
}
return method.getMethodName() + addon;
}
private void resultDetail(IResultMap tests, final String style) {
if (tests.getAllResults().size() > 0) {
int row = 0;
StringBuffer buff = new StringBuffer();
for (ITestNGMethod method : getMethodSet(tests)) {
row += 1;
m_method_ptr += 1;
String cname = method.getTestClass().getName();
m_out.println("<a id=\"m" + m_method_ptr + "\"></a><h2>" + cname + ":"
+ method.getMethodName() + "</h2>");
int rq = 0;
Set<ITestResult> result_set = tests.getResults(method);
for (ITestResult ans : result_set) {
rq += 1;
Object[] pset = ans.getParameters();
String output_tag=null;
if (pset.length > 0) {
if (rq == 1) {
tableStart("param");
m_out.print("<tr>");
for (int x = 1; x <= pset.length; x++) {
m_out
.print("<th style=\"padding-left:1em;padding-right:1em\">Parameter
+ x + "</th>");
}
m_out.println("</tr>");
}
m_out.print("<tr>");
for (Object p : pset) {
m_out.println("<td style=\"padding-left:.5em;padding-right:2em\">"
+ p + "</td>");
}
m_out.println("</tr>");
}
List<String> msgs = Reporter.getOutput(ans);
if (msgs.size() > 0) {
String indent=" style=\"padding-left:3em\"";
if (pset.length > 0) {
m_out.println("<tr><td"+indent+" colspan=\""+pset.length+"\">");
} else {
m_out.println("<div"+indent+">");
}
for (String line : msgs) {
m_out.println(line + "<br/>");
}
if (pset.length > 0) {
m_out.println("</td></tr>");
} else {
m_out.println("</div>");
}
}
if (pset.length > 0) {
if (rq == result_set.size()) {
m_out.println("</table>");
}
}
}
m_out
.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");
}
}
}
/**
* @param tests
* @return
*/
private Collection<ITestNGMethod> getMethodSet(IResultMap tests) {
Set r = new TreeSet<ITestNGMethod>(new TestSorter<ITestNGMethod>());
r.addAll(tests.getAllMethods());
return r;
}
private void summarize(List<ISuite> suites) {
tableStart("param");
m_out.print("<tr><th>Test</th>");
tableColumnStart("Methods<br/>Passed");
tableColumnStart("Scenarios<br/>Passed");
tableColumnStart("# skipped");
tableColumnStart("# failed");
tableColumnStart("Total<br/>Time");
tableColumnStart("Included<br/>Groups");
tableColumnStart("Excluded<br/>Groups");
m_out.println("</tr>");
NumberFormat formatter = new DecimalFormat("
int qty_tests = 0;
int qty_pass_m = 0;
int qty_pass_s = 0;
int qty_skip = 0;
int qty_fail = 0;
long time_start = Long.MAX_VALUE;
long time_end = Long.MIN_VALUE;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 7);
}
Map<String, ISuiteResult> tests = suite.getResults();
for (ISuiteResult r : tests.values()) {
qty_tests += 1;
ITestContext overview = r.getTestContext();
startSummaryRow(overview.getName());
int q = getMethodSet(overview.getPassedTests()).size();
qty_pass_m += q;
summaryCell(q);
q = overview.getPassedTests().size();
qty_pass_s += q;
summaryCell(q);
q = getMethodSet(overview.getSkippedTests()).size();
qty_skip += q;
summaryCell(q);
q = getMethodSet(overview.getFailedTests()).size();
qty_fail += q;
summaryCell(q);
time_start = Math.min(overview.getStartDate().getTime(), time_start);
time_end = Math.max(overview.getEndDate().getTime(), time_end);
summaryCell(formatter
.format((overview.getEndDate().getTime() - overview.getStartDate()
.getTime()) / 1000.)
+ " seconds");
summaryCell(overview.getIncludedGroups());
summaryCell(overview.getExcludedGroups());
m_out.println("</tr>");
}
}
if (qty_tests > 1) {
m_out.println("<tr class=\"total\"><td>Total</td>");
summaryCell(qty_pass_m);
summaryCell(qty_pass_s);
summaryCell(qty_skip);
summaryCell(qty_fail);
summaryCell(formatter.format((time_end - time_start) / 1000.)
+ " seconds");
m_out.println("<td colspan=\"2\"> </td></tr>");
m_out.println("</table>");
}
}
private void summaryCell(String[] val) {
StringBuffer b = new StringBuffer();
for (String v : val)
b.append(v + " ");
summaryCell(b.toString());
}
private void summaryCell(String v) {
m_out.print("<td class=\"numi\">" + v + "</td>");
}
private void startSummaryRow(String label) {
m_row += 1;
m_out
.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td style=\"text-align:left;padding-right:2em\">" + label
+ "</td>");
}
private void summaryCell(int v) {
summaryCell(String.valueOf(v));
m_row_total += v;
}
private void tableStart(String cssclass) {
m_out.println("<table cellspacing=0 cellpadding=0"
+ (cssclass != null ? " class=\"" + cssclass + "\""
: " style=\"padding-bottom:2em\"") + ">");
m_row = 0;
}
private void tableStart(String cssclass, String title) {
tableStart(cssclass);
m_out.println("<caption>" + title + "</caption>");
m_row += 1;
}
private void tableColumnStart(String label) {
m_out.print("<th class=\"numi\">" + label + "</th>");
}
private void titleRow(String label, int cq) {
m_out.println("<tr><th colspan=\"" + cq + "\">" + label + "</th></tr>");
m_row = 0;
}
/** Starts HTML stream */
protected void startHtml(PrintWriter out) {
out
.println("<!DOCTYPE html PUBLIC \"-
out.println("<html xmlns=\"http:
out.println("<head>");
out.println("<title>TestNG: Unit Test</title>");
out.println("<style type=\"text/css\">");
out
.println("table caption,table.info_table,table.param,table.passed,table.failed {margin-bottom:10px;border:1px solid #000099;border-collapse:collapse;empty-cells:show;}");
out
.println("table.info_table td,table.info_table th,table.param td,table.param th,table.passed td,table.passed th,table.failed td,table.failed th {");
out.println("border:1px solid #000099;padding:.25em .5em .25em .5em");
out.println("}");
out.println("table.param th {vertical-align:bottom}");
out.println("td.numi,th.numi {");
out.println("text-align:right");
out.println("}");
out.println("tr.total td {font-weight:bold}");
out.println("table caption {");
out.println("text-align:center;font-weight:bold;");
out.println("}");
out
.println("table.passed tr.stripe td,table tr.passedodd td {background-color: #00AA00;}");
out
.println("table.passed td,table tr.passedeven td {background-color: #33FF33;}");
out
.println("table.passed tr.stripe td,table tr.skippedodd td {background-color: #cccccc;}");
out
.println("table.passed td,table tr.skippedodd td {background-color: #dddddd;}");
out
.println("table.failed tr.stripe td,table tr.failedodd td {background-color: #FF3333;}");
out
.println("table.failed td,table tr.failedeven td {background-color: #DD0000;}");
out.println("tr.stripe td,tr.stripe th {background-color: #E6EBF9;}");
out
.println("p.totop {font-size:85%;text-align:center;border-bottom:2px black solid}");
out.println("div.shootout {padding:2em;border:3px #4854A8 solid}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
}
/** Finishes HTML stream */
protected void endHtml(PrintWriter out) {
out.println("</body></html>");
}
/** Arranges methods by classname and method name */
private class TestSorter<T extends ITestNGMethod> implements Comparator {
/** Arranges methods by classname and method name */
public int compare(Object o1, Object o2) {
int r = ((T) o1).getTestClass().getName().compareTo(
((T) o2).getTestClass().getName());
if (r == 0) {
r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());
}
return r;
}
}
}
|
// File: ChipperTest.java
// Description: Java test/example app for ossimjni Info class.
// Usage: java -Djava.library.path=<path_to_libossimjni-swig> -cp <path_to_ossimjni.jar> org.ossim.jni.test.ChipperTest <image>
// Example:
// $ java -Djava.library.path=$HOME/code/osgeo_ossim/trunk/ossimjni/java/build/lib -cp $HOME/code/osgeo_ossim/trunk/ossimjni/java/build/lib/ossimjni.jar org.ossim.jni.test.ChipperTest
// $Id: ChipperTest.java 22320 2013-07-19 15:21:03Z dburken $
package org.ossim.oms.apps;
import joms.oms.Chipper;
import joms.oms.ImageData;
import joms.oms.Init;
import joms.oms.Keywordlist;
import joms.oms.KeywordlistIterator;
import joms.oms.StringPair;
import java.io.File;
public class ChipperTest
{
static
{
System.loadLibrary( "ossimjni-swig" );
}
/**
* @param args
*/
public static void main( String[] args )
{
// Copy the args with app name for c++ initialize.
String[] newArgs = new String[args.length + 1];
newArgs[0] = "org.ossim.oms.apps.ChipperTest";
System.arraycopy(args, 0, newArgs, 1, args.length);
// Initialize ossim stuff:
int argc = Init.instance().initialize(newArgs.length, newArgs);
if ( argc == 3 )
{
try
{
String outputFile = newArgs[1];
String optionsFile = newArgs[2];
System.out.println( "outputFile: " + outputFile );
System.out.println( "optionsFile: " + optionsFile );
joms.oms.Chipper chipper = new joms.oms.Chipper();
joms.oms.ImageData chip = new joms.oms.ImageData();
joms.oms.Keywordlist kwl = new joms.oms.Keywordlist();
kwl.addFile( optionsFile );
if ( chipper.initialize( kwl ) )
{
String str;
str = kwl.findKey("cut_width");
int width = Integer.parseInt(str);
str = kwl.findKey("cut_height");
int height = Integer.parseInt(str);
int numbands = 3;
byte[] buffer = new byte[width*height*numbands];
// Return status:
// OSSIM_STATUS_UNKNOWN = 0,
// OSSIM_NULL = 1, not initialized
// OSSIM_EMPTY = 2, initialized but blank or empty
// OSSIM_PARTIAL = 3, contains some null/invalid values
// OSSIM_FULL = 4 all valid data
int status = chipper.getChip( buffer, buffer.length, false );
if ( ( status == 3 ) || ( status == 4 ) )
{
System.out.println( "No problems" );
}
else
{
System.err.println("Chipper::getChip failed!");
String statusString = null;
if ( status == 0)
{
statusString = "unknown";
}
else if ( status == 1 )
{
statusString = "null";
}
else if ( status == 2 )
{
statusString = "empty";
}
System.err.println("Return status: " + statusString);
}
}
else
{
System.err.println("Chipper::initialize failed!");
}
}
catch( Exception e )
{
System.err.println("Caught Exception: " + e.getMessage());
}
}
else
{
System.out.println( "Usage: org.ossim.oms.apps.ChipperTest <outputFile> <options.kwl>");
}
} // End of main:
} // Matches: public class ChipperTest
|
package cpw.mods.fml.common;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.logging.Level;
import org.objectweb.asm.Type;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
/**
* @author cpw
*
*/
public class ProxyInjector
{
public static void inject(ModContainer mod, ASMDataTable data, Side side)
{
FMLLog.fine("Attempting to inject @SidedProxy classes into %s", mod.getModId());
Set<ASMData> targets = data.getAnnotationsFor(mod).get(SidedProxy.class.getName());
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.severe("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
Object proxy=Class.forName(targetType, true, mcl).newInstance();
if ((target.getModifiers() & Modifier.STATIC) == 0 )
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
target.set(null, proxy);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An error occured trying to load a proxy into %s.%s", targ.getAnnotationInfo(), targ.getClassName(), targ.getObjectName());
throw new LoaderException(e);
}
}
}
}
|
package ca.firstvoices.operations;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
@Operation(id = FVGetPendingUserRegistrations.ID, category = Constants.CAT_USERS_GROUPS, label = "Get user registrations.",
description = "Get registrations for specific dialect or when input is ALL (*) for the system. \n prune action can be 'ignore', 'approved' or 'accepted'\n.")
public class FVGetPendingUserRegistrations
{
public static final String ID = "FVGetPendingUserRegistrations";
private static final Log log = LogFactory.getLog(FVGetPendingUserRegistrations.class);
public static final String IGNORE = "ignore";
public static final String APPROVED = "approved";
public static final String ACCEPTED = "accepted";
@Context
protected CoreSession session;
@Param(name = "dialectID")
protected String dialectID;
@Param(name = "pruneAction", required = false, values = { IGNORE, APPROVED, ACCEPTED})
protected String pruneAction = IGNORE;
@OperationMethod
public DocumentModelList run()
{
DocumentModelList registrations = null;
try
{
// prune all items which are not part of the specific dialect
if( !(dialectID.toLowerCase().equals("all") || dialectID.toLowerCase().equals("*")) )
{
registrations = session.query(String.format("Select * from Document where ecm:mixinType = 'UserRegistration' and %s = '%s'", "docinfo:documentId", dialectID));
}
else
{
registrations = session.query("Select * from Document where ecm:mixinType = 'UserRegistration'");
}
if( !registrations.isEmpty()) {
registrations = pruneRegistrationList(registrations, pruneAction);
}
} catch (Exception e) {
log.warn(e);
}
return registrations;
}
private DocumentModelList pruneRegistrationList( DocumentModelList registrations, String pruneAction )
{
if( !pruneAction.equals(IGNORE))
{
DocumentModelList prunned = new DocumentModelListImpl();
for (DocumentModel uReg : registrations)
{
if (pruneAction.equals(APPROVED) && uReg.getCurrentLifeCycleState().equals(APPROVED))
prunned.add(uReg);
else if (pruneAction.equals(ACCEPTED) && uReg.getCurrentLifeCycleState().equals(ACCEPTED))
prunned.add(uReg);
}
if( prunned.isEmpty() ) registrations.clear();
else registrations = prunned;
}
return registrations;
}
}
|
package io.spine.validate.option;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.ImmutableTypeParameter;
import com.google.protobuf.DescriptorProtos.FieldOptions;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.GeneratedMessage.GeneratedExtension;
import io.spine.code.proto.FieldContext;
import io.spine.code.proto.FieldOption;
import io.spine.validate.ExternalConstraintOptions;
import java.util.Optional;
import static java.lang.String.format;
/**
* An option that validates a field.
*
* <p>Validating options impose constraint on fields that they are applied to.
*
* @param <T>
* type of value held by this option
*/
@Immutable
public abstract class FieldValidatingOption<@ImmutableTypeParameter T>
extends FieldOption<T>
implements ValidatingOption<T, FieldContext, FieldDescriptor> {
/** Specifies the extension that corresponds to this option. */
protected FieldValidatingOption(GeneratedExtension<FieldOptions, T> optionExtension) {
super(optionExtension);
}
/**
* Returns a value of the option.
*
* @apiNote Should only be called by subclasses in circumstances that assume presence of
* the option. For all other cases please refer to
* {@link #valueFrom(FieldContext)}.
*/
protected T optionValue(FieldContext field) throws IllegalStateException {
Optional<T> option = valueFrom(field);
return option.orElseThrow(() -> {
FieldDescriptor descriptor = extension().getDescriptor();
String fieldName = field.targetDeclaration()
.name()
.value();
String containingTypeName = descriptor.getContainingType()
.getName();
return couldNotGetOptionValueFrom(fieldName, containingTypeName);
});
}
private IllegalStateException couldNotGetOptionValueFrom(String fieldName,
String containingTypeName) {
String optionName = extension().getDescriptor()
.getName();
String message = format("Could not get value of option %s from field %s in message %s.",
optionName,
fieldName,
containingTypeName);
return new IllegalStateException(message);
}
/**
* Takes the value of the option from the given descriptor, given the specified context.
*
* <p>The value is firstly obtained from the external constraint and if an external constraint
* is not present, the value is obtained from the actual field constraint.
*
* @param context
* context of the field
* @return an {@code Optional} with an option value if such exists, otherwise an empty
* {@code Optional}
* @apiNote Use this in favour of {@link
* FieldOption#optionsFrom(com.google.protobuf.Descriptors.FieldDescriptor)
* optionsFrom(FieldDescriptor)} when {@code FieldContext} matters, e.g. when handling
* {@code (constraint_for)} options.
*/
public Optional<T> valueFrom(FieldContext context) {
Optional<T> externalConstraint =
ExternalConstraintOptions.getOptionValue(context, extension());
return externalConstraint.isPresent()
? externalConstraint
: valueFrom(context.target());
}
/**
* Returns {@code true} if this option exists for the specified field, {@code false} otherwise.
*
* @param context
* the value to be validated
*/
public boolean shouldValidate(FieldContext context) {
return valueFrom(context).isPresent();
}
}
|
package org.intermine.bio.web.displayer;
import java.util.Arrays;
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 javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.results.ResultElement;
import org.intermine.api.util.PathUtil;
import org.intermine.model.bio.DataSet;
import org.intermine.model.bio.Gene;
import org.intermine.model.bio.Homologue;
import org.intermine.model.bio.Organism;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathException;
import org.intermine.web.displayer.CustomDisplayer;
import org.intermine.web.logic.config.ReportDisplayerConfig;
import org.intermine.web.logic.results.ReportObject;
public class HomologueDisplayer extends CustomDisplayer {
private static final List<String> SPECIES = Arrays.asList(new String[] {"grimshawi", "virilis",
"mojavensis", "willistoni", "persimilis", "pseudoobscura", "ananassae", "erecta",
"yakuba", "melanogaster", "sechellia", "simulans"});
private static final String HOMOLOGY_DATASET = "Drosophila 12 Genomes Consortium homology";
protected static final Logger LOG = Logger.getLogger(OverlappingFeaturesDisplayer.class);
public HomologueDisplayer(ReportDisplayerConfig config, InterMineAPI im) {
super(config, im);
}
@Override
public void display(HttpServletRequest request, ReportObject reportObject) {
request.setAttribute("parameters", config.getParameterString());
Map<String, Set<ResultElement>> homologues =
new TreeMap<String, Set<ResultElement>>();
Map<String, String> organismIds = new HashMap<String, String>();
Path symbolPath = null;
Path primaryIdentifierPath = null;
try {
symbolPath = new Path(im.getModel(), "Gene.symbol");
primaryIdentifierPath = new Path(im.getModel(), "Gene.primaryIdentifier");
} catch (PathException e) {
return;
}
Gene gene = (Gene) reportObject.getObject();
for (Homologue homologue : gene.getHomologues()) {
for (DataSet dataSet : homologue.getDataSets()) {
if (!HOMOLOGY_DATASET.equals(dataSet.getName())) {
Organism org = homologue.getHomologue().getOrganism();
organismIds.put(org.getSpecies(), org.getId().toString());
try {
if (PathUtil.resolvePath(symbolPath, homologue.getHomologue()) != null) {
ResultElement re = new ResultElement(homologue.getHomologue(),
symbolPath, true);
addToMap(homologues, org.getShortName(), re);
} else {
ResultElement re = new ResultElement(homologue.getHomologue(),
primaryIdentifierPath, true);
addToMap(homologues, org.getShortName(), re);
}
} catch (PathException e) {
LOG.error("Failed to resolved path: " + symbolPath + " for gene: " + gene);
}
}
}
}
request.setAttribute("organismIds", organismIds);
request.setAttribute("homologues", homologues);
}
private Map<String, Set<ResultElement>> initMap() {
Map homologues = new ListOrderedMap();
for (String species : SPECIES) {
addToMap(homologues, species, null);
}
return homologues;
}
private void addToMap(Map<String, Set<ResultElement>> homologues, String species,
ResultElement re) {
Set<ResultElement> speciesHomologues = homologues.get(species);
if (speciesHomologues == null) {
speciesHomologues = new HashSet<ResultElement>();
homologues.put(species, speciesHomologues);
}
if (re != null) {
speciesHomologues.add(re);
}
}
}
|
package io.bootique.bom.job;
import io.bootique.command.CommandOutcome;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JobAppIT {
private JobApp app;
private ExecutorService executor;
@Before
public void before() {
this.app = new JobApp();
this.executor = Executors.newSingleThreadExecutor();
}
@After
public void after() throws InterruptedException {
executor.shutdownNow();
executor.awaitTermination(3, TimeUnit.SECONDS);
}
@Test
public void testRun_Help() {
CommandOutcome outcome = app.run("--help");
assertEquals(0, outcome.getExitCode());
String help = app.getStdout();
assertTrue(help.contains("--exec"));
assertTrue(help.contains("--list"));
assertTrue(help.contains("--schedule"));
assertTrue(help.contains("--help"));
assertTrue(help.contains("--config"));
assertTrue(help.contains("--job"));
}
@Test
public void testList() {
CommandOutcome outcome = app.run("--list");
assertEquals(0, outcome.getExitCode());
String stdout = app.getStdout();
assertTrue(stdout.contains("- bom"));
}
@Test
public void testExec() {
BomJob.COUNTER.set(0);
CommandOutcome outcome = app.run("--exec", "--job=bom");
assertEquals(0, outcome.getExitCode());
assertEquals(1l, BomJob.COUNTER.get());
}
@Test
public void testSchedule() throws InterruptedException, ExecutionException, TimeoutException {
BomJob.COUNTER.set(0);
BomParameterizedJob.COUNTER.set(0);
// since ScheduleCommand main thread blocks, run the server in a
// separate thread...
Future<CommandOutcome> result = executor.submit(() -> {
return app.run("--config=classpath:io/bootique/bom/job/test.yml", "--schedule");
});
// wait for scheduler to start and run some jobs...
Thread.sleep(3000);
// since we exited via interrupt, the result of the --schedule command
// will look like a failure
executor.shutdownNow();
CommandOutcome outcome = result.get(3, TimeUnit.SECONDS);
assertEquals(0, outcome.getExitCode());
assertTrue(BomJob.COUNTER.get() > 3);
assertTrue(BomParameterizedJob.COUNTER.get() > 17 * 3);
assertEquals(0, BomParameterizedJob.COUNTER.get() % 17);
}
}
|
package il.ac.technion.ie.experiments.threads;
import com.google.common.base.Joiner;
import il.ac.technion.ie.experiments.exception.OSNotSupportedException;
import il.ac.technion.ie.experiments.model.ConvexBPContext;
import il.ac.technion.ie.experiments.utils.ExperimentUtils;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class ApacheExecutor implements IConvexBPExecutor {
private final int WAIT_TIMEOUT_MINUTES = 45;
static final Logger logger = Logger.getLogger(ApacheExecutor.class);
@Override
public File execute(ConvexBPContext context) throws OSNotSupportedException, IOException, ExecutionException, InterruptedException {
ExperimentUtils.checkOS();
CommandLine commandLine = buildCommandLine(context);
long startTime = System.nanoTime();
Future<Long> longFuture = ProcessExecutor.runProcess(commandLine, TimeUnit.MINUTES.toMillis(WAIT_TIMEOUT_MINUTES),
new IProcessOutputHandler() {
@Override
public void onStandardOutput(String msg) {
logger.info(msg);
}
@Override
public void onStandardError(String msg) {
logger.error(msg);
}
});
//wait till execution has finished
Long exitValue = longFuture.get();
long endTime = System.nanoTime();
logger.info(String.format("Total execution time of convexBP: %d seconds", TimeUnit.NANOSECONDS.toSeconds(endTime - startTime)));
logger.info(String.format("Execution of convexBP has finished with status: %d", exitValue));
return new File(context.getPathToOutputFile());
}
private CommandLine buildCommandLine(ConvexBPContext context) {
String commandWithArguments = context.getCommand();
String pathToExecute = StringUtils.substringBetween(commandWithArguments, "\"");
String commandArguments = StringUtils.substringAfterLast(commandWithArguments, "\"");
CommandLine commandLine = new CommandLine(pathToExecute);
commandLine.addArguments(commandArguments, false);
String log = commandLine.getExecutable() + Joiner.on(' ').join(commandLine.getArguments());
logger.debug("About to run: " + log);
return commandLine;
}
}
|
package com.easymargining.replication.ccg.calc;
import com.easymargining.replication.ccg.market.ClassFileItem;
import com.easymargining.replication.ccg.market.MarketDataEnvironment;
import com.easymargining.replication.ccg.market.MarketDataFileResolver;
import com.easymargining.replication.ccg.trade.CcgMarsMarginTradeItem;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
public class CcgMarsReplicationCalculator {
public void computeFuturesSpreadMargin(LocalDate s_valuationDate, List<CcgMarsMarginTradeItem> marginTradeItems){
// Use file resolver utility to discover data from CCG directory structure
MarketDataFileResolver fileResolver = new MarketDataFileResolver("marketData", s_valuationDate);
MarketDataEnvironment marketDataEnv = new MarketDataEnvironment();
marketDataEnv.loadMarketData(fileResolver);
// 1- Update position "List<CcgMarsMarginTradeItem>" records with underlying information
// class file must be used to acquire the Class Group and Product group for each
List<ClassFileItem> classFileItems = marketDataEnv.getClassFileItems();
Map<String, ClassFileItem> classFileMap = classFileItems
.stream()
.collect(Collectors.toMap(
p -> p.getSymbol() + "#" + p.getClassType(), // Unique Key = Symbol + Class Type
p -> p,
(oldValue, newValue) -> oldValue)
);
System.out.println(classFileMap);
// Build MarginPosition from marginTradeItem and
marginTradeItems.forEach( marginTradeItem -> {
MarginPositions marginPosition = new MarginPositions();
ClassFileItem classFileItem = classFileMap.get(
marginTradeItem.getSymbol() + "#" + marginTradeItem.getClassType().getShortName());
marginPosition.setClassGroup(classFileItem.getClassGroup());
marginPosition.setProductGroup(classFileItem.getProductGroup());
});
// Group by Symbol
//Map<String, ClassFileItem> classFileMap = classFileItems
// .stream()
// .collect(Collectors.groupingsBy(p -> p.getSymbol(), p -> p));
}
public void computeMarktoMarketMargin() {
}
public void premiumMargin() {
}
public void computeAdditionalMargin () {
}
}
|
package jade.core;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ArrayList;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.ACLCodec;
import jade.lang.acl.StringACLCodec;
import jade.mtp.MTP;
import jade.mtp.TransportAddress;
import jade.domain.FIPAAgentManagement.Envelope;
/**
Standard <em>Agent Communication Channel</em>. This class implements
<em><b>FIPA</b></em> <em>ACC</em> service. <b>JADE</b> applications
cannot use this class directly, but interact with it transparently
when using <em>ACL</em> message passing.
@author Giovanni Rimassa - Universita` di Parma
@version $Date$ $Revision$
*/
class acc implements MTP.Dispatcher {
public static class NoMoreAddressesException extends NotFoundException {
NoMoreAddressesException(String msg) {
super(msg);
}
}
private Map messageEncodings = new TreeMap(String.CASE_INSENSITIVE_ORDER);
private Map localMTPs = new TreeMap(String.CASE_INSENSITIVE_ORDER);
private RoutingTable routes = new RoutingTable();
private List addresses = new LinkedList();
private List localAddresses = new LinkedList();
private AgentContainerImpl myContainer;
public acc(AgentContainerImpl ac) {
ACLCodec stringCodec = new StringACLCodec();
messageEncodings.put(stringCodec.getName().toLowerCase(), stringCodec);
myContainer = ac;
}
/*
* This method is called by ACCProxy before preparing the Envelope of an outgoing message.
* It checks for all the AIDs present in the message and adds the addresses, if not present
**/
public void addPlatformAddresses(AID id) {
Iterator it = addresses.iterator();
while(it.hasNext()) {
String addr = (String)it.next();
id.addAddresses(addr);
}
}
public void prepareEnvelope(ACLMessage msg, AID receiver) {
Envelope env = msg.getEnvelope();
if(env == null) {
msg.setDefaultEnvelope();
env = msg.getEnvelope();
}
// If no 'to' slot is present, copy the 'to' slot from the
// 'receiver' slot of the ACL message
Iterator itTo = env.getAllTo();
if(!itTo.hasNext()) {
Iterator itReceiver = msg.getAllReceiver();
while(itReceiver.hasNext())
env.addTo((AID)itReceiver.next());
}
// If no 'from' slot is present, copy the 'from' slot from the
// 'sender' slot of the ACL message
AID from = env.getFrom();
if(from == null)
env.setFrom(msg.getSender());
// Set the 'date' slot to 'now' if not present already
Date d = env.getDate();
if(d == null)
env.setDate(new Date());
// If no ACL representation is found, then default to String
// representation
String rep = env.getAclRepresentation();
if(rep == null)
env.setAclRepresentation(StringACLCodec.NAME);
// Write 'intended-receiver' slot as per 'FIPA Agent Message
// Transport Service Specification': this ACC splits all
// multicasts, since JADE has already split them in the
// handleSend() method
env.clearAllIntendedReceiver();
env.addIntendedReceiver(receiver);
String comments = env.getComments();
if(comments == null)
env.setComments("");
String aclRepresentation = env.getAclRepresentation();
if(aclRepresentation == null)
env.setAclRepresentation("");
String payloadLength = env.getPayloadLength();
if(payloadLength == null)
env.setPayloadLength("-1");
String payloadEncoding = env.getPayloadEncoding();
if(payloadEncoding == null)
env.setPayloadEncoding("");
}
public byte[] encodeMessage(ACLMessage msg) throws NotFoundException {
Envelope env = msg.getEnvelope();
String enc = env.getAclRepresentation();
ACLCodec codec = (ACLCodec)messageEncodings.get(enc.toLowerCase());
if(codec == null)
throw new NotFoundException("Unknown ACL encoding: " + enc + ".");
return codec.encode(msg);
}
public void forwardMessage(Envelope env, byte[] payload, String address) throws MTP.MTPException {
boolean ok = routeMessage(env, payload, address);
if(!ok) { // Try to find another container who can route the outgoing message
String proto = extractProto(address);
if(proto == null)
throw new MTP.MTPException("Missing protocol delimiter");
AgentContainer ac = routes.lookup(proto);
if(ac == null)
throw new MTP.MTPException("MTP not available in this platform");
try {
ac.route(env, payload, address);
}
catch(java.rmi.RemoteException re) {
throw new MTP.MTPException("Container unreachable during routing");
}
catch(NotFoundException nfe) {
throw new MTP.MTPException("MTP not available in this platform [after routing]");
}
}
}
// This method returns true when a local MTP is found and the
// message is delivered.
public boolean routeMessage(Object o, byte[] payload, String address) {
String proto = extractProto(address);
if(proto == null)
return false;
MTP outGoing = (MTP)localMTPs.get(proto);
if(outGoing != null) { // A suitable MTP is installed in this container.
try {
TransportAddress ta = outGoing.strToAddr(address);
Envelope env = (Envelope)o;
outGoing.deliver(ta, env, payload);
return true;
}
catch(MTP.MTPException mtpe) {
return false;
}
}
else
return false;
}
public AgentProxy getProxy(AID agentID) throws NotFoundException {
return new ACCProxy(agentID, this);
}
public TransportAddress addMTP(MTP proto, String address) throws MTP.MTPException {
if(address == null) { // Let the protocol choose the address
localMTPs.put(proto.getName(), proto);
if(proto.getName().equalsIgnoreCase("iiop")) {
localMTPs.put("ior", proto);
localMTPs.put("corbaloc", proto);
localMTPs.put("corbaname", proto);
}
if(proto.getName().equalsIgnoreCase("ior")) {
localMTPs.put("iiop", proto);
localMTPs.put("corbaloc", proto);
localMTPs.put("corbaname", proto);
}
if(proto.getName().equalsIgnoreCase("corbaloc")) {
localMTPs.put("ior", proto);
localMTPs.put("iiop", proto);
localMTPs.put("corbaname", proto);
}
if(proto.getName().equalsIgnoreCase("corbaname")) {
localMTPs.put("ior", proto);
localMTPs.put("iiop", proto);
localMTPs.put("corbaloc", proto);
}
TransportAddress ta = proto.activate(this);
localAddresses.add(proto.addrToStr(ta));
return ta;
}
else { // Convert the given string into a TransportAddress object and use it
TransportAddress ta = proto.strToAddr(address);
localMTPs.put(ta.getProto(), proto);
if(ta.getProto().equalsIgnoreCase("iiop")) {
localMTPs.put("ior", proto);
localMTPs.put("corbaloc", proto);
localMTPs.put("corbaname", proto);
}
if(ta.getProto().equalsIgnoreCase("ior")) {
localMTPs.put("iiop", proto);
localMTPs.put("corbaloc", proto);
localMTPs.put("corbaname", proto);
}
if(ta.getProto().equalsIgnoreCase("corbaloc")) {
localMTPs.put("ior", proto);
localMTPs.put("iiop", proto);
localMTPs.put("corbaname", proto);
}
if(ta.getProto().equalsIgnoreCase("corbaname")) {
localMTPs.put("ior", proto);
localMTPs.put("iiop", proto);
localMTPs.put("corbaloc", proto);
}
proto.activate(this, ta);
return ta;
}
}
public List getLocalAddresses() {
return localAddresses;
}
public void addRoute(String address, AgentContainer ac) {
String proto = extractProto(address);
routes.addMTP(proto, ac);
addresses.add(address);
}
public void removeRoute(String address, AgentContainer ac) {
String proto = extractProto(address);
routes.removeMTP(proto, ac);
addresses.remove(address);
}
public void shutdown() {
// FIXME: To be implemented
}
public void dispatchMessage(Envelope env, byte[] payload) {
// Decode the message, according to the 'acl-representation' slot
String aclRepresentation = env.getAclRepresentation();
// Default to String representation
if(aclRepresentation == null)
aclRepresentation = StringACLCodec.NAME;
ACLCodec codec = (ACLCodec)messageEncodings.get(aclRepresentation.toLowerCase());
if(codec == null) {
System.out.println("Unknown ACL codec: " + aclRepresentation);
return;
}
try {
ACLMessage msg = codec.decode(payload);
// If the 'sender' AID has no addresses, replace it with the
// 'from' envelope slot
AID sender = msg.getSender();
Iterator itSender = sender.getAllAddresses();
if(!itSender.hasNext())
msg.setSender(env.getFrom());
Iterator it = env.getAllIntendedReceiver();
// If no 'intended-receiver' is present, use the 'to' slot (but
// this should not happen).
if(!it.hasNext())
it = env.getAllTo();
while(it.hasNext()) {
AID receiver = (AID)it.next();
myContainer.unicastPostMessage(msg, receiver);
}
}
catch(ACLCodec.CodecException ce) {
ce.printStackTrace();
}
}
private String extractProto(String address) {
int colonPos = address.indexOf(':');
if(colonPos == -1)
return null;
return address.substring(0, colonPos);
}
}
|
package simpledb.systemtest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.junit.Ignore;
import org.junit.Test;
import simpledb.BufferPool;
import simpledb.Database;
import simpledb.DbException;
import simpledb.HeapFile;
import simpledb.HeapFileEncoder;
import simpledb.Parser;
import simpledb.TableStats;
import simpledb.Transaction;
import simpledb.TransactionAbortedException;
import simpledb.Utility;
public class QueryTest {
/**
* Given a matrix of tuples from SystemTestUtil.createRandomHeapFile, create an identical HeapFile table
* @param tuples Tuples to create a HeapFile from
* @param columns Each entry in tuples[] must have "columns == tuples.get(i).size()"
* @param colPrefix String to prefix to the column names (the columns are named after their column number by default)
* @return a new HeapFile containing the specified tuples
* @throws IOException if a temporary file can't be created to hand to HeapFile to open and read its data
*/
public static HeapFile createDuplicateHeapFile(ArrayList<ArrayList<Integer>> tuples, int columns, String colPrefix) throws IOException {
File temp = File.createTempFile("table", ".dat");
temp.deleteOnExit();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
HeapFileEncoder.convert(tuples, out, BufferPool.getPageSize(), columns);
return Utility.openHeapFile(columns, colPrefix, temp);
}
@Test(timeout=20000) public void queryTest() throws IOException, DbException, TransactionAbortedException {
// This test is intended to approximate the join described in the
// "Query Planning" section of 2009 Quiz 1,
// though with some minor variation due to limitations in simpledb
// and to only test your integer-heuristic code rather than
// string-heuristic code.
final int IO_COST = 101;
// HashMap<String, TableStats> stats = new HashMap<String, TableStats>();
// Create all of the tables, and add them to the catalog
ArrayList<ArrayList<Integer>> empTuples = new ArrayList<ArrayList<Integer>>();
HeapFile emp = SystemTestUtil.createRandomHeapFile(6, 100000, null, empTuples, "c");
Database.getCatalog().addTable(emp, "emp");
ArrayList<ArrayList<Integer>> deptTuples = new ArrayList<ArrayList<Integer>>();
HeapFile dept = SystemTestUtil.createRandomHeapFile(3, 1000, null, deptTuples, "c");
Database.getCatalog().addTable(dept, "dept");
ArrayList<ArrayList<Integer>> hobbyTuples = new ArrayList<ArrayList<Integer>>();
HeapFile hobby = SystemTestUtil.createRandomHeapFile(6, 1000, null, hobbyTuples, "c");
Database.getCatalog().addTable(hobby, "hobby");
ArrayList<ArrayList<Integer>> hobbiesTuples = new ArrayList<ArrayList<Integer>>();
HeapFile hobbies = SystemTestUtil.createRandomHeapFile(2, 200000, null, hobbiesTuples, "c");
Database.getCatalog().addTable(hobbies, "hobbies");
// Get TableStats objects for each of the tables that we just generated.
TableStats.setTableStats("emp", new TableStats(Database.getCatalog().getTableId("emp"), IO_COST));
TableStats.setTableStats("dept", new TableStats(Database.getCatalog().getTableId("dept"), IO_COST));
TableStats.setTableStats("hobby", new TableStats(Database.getCatalog().getTableId("hobby"), IO_COST));
TableStats.setTableStats("hobbies", new TableStats(Database.getCatalog().getTableId("hobbies"), IO_COST));
// Parser.setStatsMap(stats);
Transaction t = new Transaction();
t.start();
Parser p = new Parser();
p.setTransaction(t);
// Each of these should return around 20,000
// This Parser implementation currently just dumps to stdout, so checking that isn't terribly clean.
// So, don't bother for now; future TODO.
// Regardless, each of the following should be optimized to run quickly,
// even though the worst case takes a very long time.
p.processNextStatement("SELECT * FROM emp,dept,hobbies,hobby WHERE emp.c1 = dept.c0 AND hobbies.c0 = emp.c2 AND hobbies.c1 = hobby.c0 AND emp.c3 < 1000;");
}
/**
* Build a large series of tables; then run the command-line query code and execute a query.
* The number of tables is large enough that the query will only succeed within the
* specified time if a join method faster than nested-loops join is available.
* The tables are also too big for a query to be successful if its query plan isn't reasonably efficient,
* and there are too many tables for a brute-force search of all possible query plans.
*/
// Not required for Lab 4
@Ignore
@Test(timeout=600000) public void largeJoinTest() throws IOException, DbException, TransactionAbortedException {
final int IO_COST = 103;
ArrayList<ArrayList<Integer>> smallHeapFileTuples = new ArrayList<ArrayList<Integer>>();
HeapFile smallHeapFileA = SystemTestUtil.createRandomHeapFile(2, 100, Integer.MAX_VALUE, null, smallHeapFileTuples, "c");
HeapFile smallHeapFileB = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileC = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileD = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileE = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileF = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileG = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileH = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileI = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileJ = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileK = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileL = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileM = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileN = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileO = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileP = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileQ = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileR = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileS = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
HeapFile smallHeapFileT = createDuplicateHeapFile(smallHeapFileTuples, 2, "c");
ArrayList<ArrayList<Integer>> bigHeapFileTuples = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 1000; i++) {
bigHeapFileTuples.add( smallHeapFileTuples.get( i%100 ) );
}
HeapFile bigHeapFile = createDuplicateHeapFile(bigHeapFileTuples, 2, "c");
Database.getCatalog().addTable(bigHeapFile, "bigTable");
// We want a bunch of these guys
Database.getCatalog().addTable(smallHeapFileA, "a");
Database.getCatalog().addTable(smallHeapFileB, "b");
Database.getCatalog().addTable(smallHeapFileC, "c");
Database.getCatalog().addTable(smallHeapFileD, "d");
Database.getCatalog().addTable(smallHeapFileE, "e");
Database.getCatalog().addTable(smallHeapFileF, "f");
Database.getCatalog().addTable(smallHeapFileG, "g");
Database.getCatalog().addTable(smallHeapFileH, "h");
Database.getCatalog().addTable(smallHeapFileI, "i");
Database.getCatalog().addTable(smallHeapFileJ, "j");
Database.getCatalog().addTable(smallHeapFileK, "k");
Database.getCatalog().addTable(smallHeapFileL, "l");
Database.getCatalog().addTable(smallHeapFileM, "m");
Database.getCatalog().addTable(smallHeapFileN, "n");
Database.getCatalog().addTable(smallHeapFileO, "o");
Database.getCatalog().addTable(smallHeapFileP, "p");
Database.getCatalog().addTable(smallHeapFileQ, "q");
Database.getCatalog().addTable(smallHeapFileR, "r");
Database.getCatalog().addTable(smallHeapFileS, "s");
Database.getCatalog().addTable(smallHeapFileT, "t");
TableStats.setTableStats("bigTable", new TableStats(bigHeapFile.getId(), IO_COST));
TableStats.setTableStats("a", new TableStats(smallHeapFileA.getId(), IO_COST));
TableStats.setTableStats("b", new TableStats(smallHeapFileB.getId(), IO_COST));
TableStats.setTableStats("c", new TableStats(smallHeapFileC.getId(), IO_COST));
TableStats.setTableStats("d", new TableStats(smallHeapFileD.getId(), IO_COST));
TableStats.setTableStats("e", new TableStats(smallHeapFileE.getId(), IO_COST));
TableStats.setTableStats("f", new TableStats(smallHeapFileF.getId(), IO_COST));
TableStats.setTableStats("g", new TableStats(smallHeapFileG.getId(), IO_COST));
TableStats.setTableStats("h", new TableStats(smallHeapFileH.getId(), IO_COST));
TableStats.setTableStats("i", new TableStats(smallHeapFileI.getId(), IO_COST));
TableStats.setTableStats("j", new TableStats(smallHeapFileJ.getId(), IO_COST));
TableStats.setTableStats("k", new TableStats(smallHeapFileK.getId(), IO_COST));
TableStats.setTableStats("l", new TableStats(smallHeapFileL.getId(), IO_COST));
TableStats.setTableStats("m", new TableStats(smallHeapFileM.getId(), IO_COST));
TableStats.setTableStats("n", new TableStats(smallHeapFileN.getId(), IO_COST));
TableStats.setTableStats("o", new TableStats(smallHeapFileO.getId(), IO_COST));
TableStats.setTableStats("p", new TableStats(smallHeapFileP.getId(), IO_COST));
TableStats.setTableStats("q", new TableStats(smallHeapFileQ.getId(), IO_COST));
TableStats.setTableStats("r", new TableStats(smallHeapFileR.getId(), IO_COST));
TableStats.setTableStats("s", new TableStats(smallHeapFileS.getId(), IO_COST));
TableStats.setTableStats("t", new TableStats(smallHeapFileT.getId(), IO_COST));
Parser p = new Parser();
Transaction t = new Transaction();
t.start();
p.setTransaction(t);
// Each of these should return around 20,000
// This Parser implementation currently just dumps to stdout, so checking that isn't terribly clean.
// So, don't bother for now; future TODO.
// Regardless, each of the following should be optimized to run quickly,
// even though the worst case takes a very long time.
p.processNextStatement("SELECT COUNT(a.c0) FROM bigTable, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t WHERE bigTable.c0 = n.c0 AND a.c1 = b.c1 AND b.c0 = c.c0 AND c.c1 = d.c1 AND d.c0 = e.c0 AND e.c1 = f.c1 AND f.c0 = g.c0 AND g.c1 = h.c1 AND h.c0 = i.c0 AND i.c1 = j.c1 AND j.c0 = k.c0 AND k.c1 = l.c1 AND l.c0 = m.c0 AND m.c1 = n.c1 AND n.c0 = o.c0 AND o.c1 = p.c1 AND p.c1 = q.c1 AND q.c0 = r.c0 AND r.c1 = s.c1 AND s.c0 = t.c0;");
}
}
|
package dijkstra;
/**
* Project: NASA Path in conjunction with University of Maryland University
* College
*
* @author jadovan
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DijkstraPaths {
private List<Node> nodes;
private List<Edge> edges;
CreateNodes cn = new CreateNodes();
// This method processes the Dijkstra Algorithm for the three shortest paths
public void ExecutePaths(String source, String destination) {
cn.createS0LabHandHoldNodeList();
int sourceIndex = cn.s0LabHandHoldNodeIndexList.indexOf(source);
int destinationIndex = cn.s0LabHandHoldNodeIndexList.indexOf(destination);
Graph graph1 = new Graph(pathNodes(), pathOneEdges());
Dijkstra dijkstra1 = new Dijkstra(graph1);
dijkstra1.execute(nodes.get(sourceIndex));
LinkedList<Node> path1 = dijkstra1.getPath(nodes.get(destinationIndex));
System.out.println("1st path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path1 != null) {
path1.forEach((node1) -> {
System.out.println(node1.getNodeId());
});
} else {
System.out.println("1st path could not be determined between these nodes.");
}
Graph graph2 = new Graph(pathNodes(), pathTwoEdges());
Dijkstra dijkstra2 = new Dijkstra(graph2);
dijkstra2.execute(nodes.get(sourceIndex));
LinkedList<Node> path2 = dijkstra2.getPath(nodes.get(destinationIndex));
System.out.println("\n2nd path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path2 != null) {
path2.forEach((node2) -> {
System.out.println(node2.getNodeId());
});
} else {
System.out.println("2nd path could not be determined between these nodes.");
}
Graph graph3 = new Graph(pathNodes(), pathThreeEdges());
Dijkstra dijkstra3 = new Dijkstra(graph3);
dijkstra3.execute(nodes.get(sourceIndex));
LinkedList<Node> path3 = dijkstra3.getPath(nodes.get(destinationIndex));
System.out.println("\n3rd path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path3 != null) {
path3.forEach((node3) -> {
System.out.println(node3.getNodeId());
});
} else {
System.out.println("3rd path could not be determined between these nodes.");
}
}
// This method is used for creating the Edge lanes to be processed by the Dijkstra Algorithm
private void addLane(String laneId, int sourceLocNo, int destLocNo,
double duration) {
Edge lane = new Edge(laneId, nodes.get(sourceLocNo), nodes.get(destLocNo), duration);
edges.add(lane);
}
// This method adds node locations for the shortest paths
private List pathNodes() {
nodes = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
// These for loops add lanes to the s0 and lab nodes for the shortest paths
for (int i = 0; i < cn.s0LabHandHoldNodeList.size(); i++) {
Node location = new Node(cn.s0LabHandHoldNodeList.get(i).getNodeId());
nodes.add(location);
}
return nodes;
}
// This method adds lanes for the first shortest path
private List pathOneEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 54) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
// This method adds lanes for the second shortest path
private List pathTwoEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 62) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
// This method adds lanes for the third shortest path
private List pathThreeEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 70) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
}
|
package ru.job4j.set.setonalinkedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SimpleSet<E> implements Iterable<E>{
private Node<E> last;
private Node<E> first;
private int size = 0;
public void add(E el) {
final Node<E> lt = last;
if (!contains(el)) {
final Node<E> newNode = new Node<>(lt, el, null);
this.last = newNode;
if (lt == null)
first = newNode;
else
lt.next = newNode;
size++;
}
}
public boolean contains(E el) {
Iterator it = this.iterator();
while (it.hasNext()) {
if (it.next().equals(el)) {
return true;
}
}
return false;
}
@Override
public Iterator<E> iterator() {
return new Iter();
}
private static class Node<E>{
Node<E> next;
Node<E> prev;
E item;
int count = 0;
public Node(Node<E> prev, E item, Node<E> next) {
this.prev = prev;
this.item = item;
this.next = next;
}
}
public class Iter implements Iterator<E> {
private SimpleSet.Node<E> next;
private int nextIndex;
@Override
public boolean hasNext() {
return nextIndex < size;
}
@Override
public E next() {
if (!hasNext())
throw new NoSuchElementException();
if (nextIndex == 0)
next = first;
else
next = next.next;
nextIndex++;
return next.item;
}
}
}
|
package ru.stqa.javacourse.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
public class HelperBase {
protected WebDriver wd;
public HelperBase(WebDriver wd) {
this.wd=wd;
}
protected void click(By locator) {
wd.findElement(locator).click();
}
protected void type(By locator, String text) {
click(locator);
if (text!=null) {
String existingText =wd.findElement(locator).getAttribute("value");
if (! text.equals(existingText)) {
wd.findElement(locator).clear();
wd.findElement(locator).sendKeys(text);
}
}
}
public boolean isAlertPresent() {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
|
package pylos.test;
import pylos.ai.State;
import pylos.model.Model;
import pylos.model.Position;
public class AITest extends PylosTestCase {
// public void testAI() {
// MainTest.gameSample();
// /**
// * ooo.
// * ooo. o..
// * ..o. ...
// * .... ...
// */
// for (int i = 0; i < 8; i++) {
// AlphaBeta.AI();
// public void testEval() {
// MainTest.gameSample();
// State s = new State();
// // System.out.println(s.evaluate());
public void testEval2() {
Model.currentPlayer.putBallOnBoard(Position.at(0, 0, 0));
Model.currentPlayer.putBallOnBoard(Position.at(2, 1, 0));
Model.currentPlayer.putBallOnBoard(Position.at(0, 2, 0));
Model.currentPlayer.putBallOnBoard(Position.at(1, 2, 0));
Model.currentPlayer.putBallOnBoard(Position.at(0, 3, 0));
Model.otherPlayer().putBallOnBoard(Position.at(3, 0, 0));
Model.otherPlayer().putBallOnBoard(Position.at(1, 1, 0));
Model.otherPlayer().putBallOnBoard(Position.at(1, 3, 0));
Model.otherPlayer().putBallOnBoard(Position.at(2, 3, 0));
Model.otherPlayer().putBallOnBoard(Position.at(0, 2, 1));
/**
* o..x
* .xo. ...
* oo.. ...
* oxx. x..
*/
State s = new State();
System.out.println(s.evaluate());
}
// public void testGetLines() {
// State s = new State();
// assertEquals(18, s.getLines().size());
// assertEquals(13, s.getSquare().size());
// public void testCountPoint() {
// MainTest.gameSample();
// /**
// * ooo.
// * ooo. o..
// * ..o. ...
// * .... ...
// */
// State s = new State();
// assertEquals(70, s.anyLinesOrSquarePoint(s.currentPlayer));
// assertEquals(2, s.evaluate());
public void testEval() {
MainTest.gameSample();
State s = new State();
System.out.println(s.evaluate());
}
}
|
package model.dao;
import java.util.ArrayList;
import exceptions.ExceptionSearchId;
import model.entity.AssignProductToOrder;
import model.entity.Order;
import model.entity.Product;
import model.entity.State;
public class OrderManager {
private ArrayList<Order> orderList;
private ArrayList<AssignProductToOrder> productsOfTheOrder;
private ArrayList<Product> shoppingCarList;
public OrderManager() {
this.orderList = new ArrayList<>();
this.productsOfTheOrder = new ArrayList<>();
shoppingCarList = new ArrayList<>();
}
public void addShoppingCarList(Product product) {
shoppingCarList.add(product);
}
public void removeProducOfShoppingCarList(Product product) {
shoppingCarList.remove(product);
}
public ArrayList<Product> getShoppingCarList() {
return shoppingCarList;
}
public void removeAllProductOfShoppingCarList() {
shoppingCarList.clear();
}
public static Order createOrder(int id, String direction) {
return new Order(id, direction);
}
public void addOrder(Order order) {
orderList.add(order);
}
public Product searchProductMyCar(int id) throws ExceptionSearchId {
for (Product product : shoppingCarList) {
if (product.getId() == id) {
return product;
}
}
throw new ExceptionSearchId();
}
public Order searchOrder(int id) throws ExceptionSearchId {
for (Order order : orderList) {
if (order.getId() == id) {
return order;
}
}
throw new ExceptionSearchId();
}
public void deleteOrder(Order order) {
orderList.remove(order);
}
public void editOwner(Order order, int id) {
orderList.set(id, order);
}
public boolean isToSend() {
for (AssignProductToOrder assignProductToOrder : productsOfTheOrder) {
if (assignProductToOrder.getProduct().getState().equals(State.TO_SEND)) {
return true;
}
}
return false;
}
public boolean isSend() {
for (AssignProductToOrder assignProductToOrder : productsOfTheOrder) {
if (!assignProductToOrder.getProduct().getState().equals(State.SEND)) {
return false;
}
}
return true;
}
public boolean isRecived() {
for (AssignProductToOrder assignProductToOrder : productsOfTheOrder) {
if (assignProductToOrder.getProduct().getState().equals(State.RECEIVED)) {
return false;
}
}
return true;
}
public boolean isProductToOrder(Product product) {
for (AssignProductToOrder assignProductToOrder : productsOfTheOrder) {
if (assignProductToOrder.getProduct().equals(assignProductToOrder)) {
return true;
}
}
return false;
}
public State getState(Order order) {
if (isToSend()) {
order.setState(State.TO_SEND);
}
if (isRecived()) {
order.setState(State.RECEIVED);
} else {
order.setState(State.RECEIVED);
}
return order.getState();
}
public ArrayList<Product> searchProductByName(String name) {
ArrayList<Product> productsFounds = new ArrayList<>();
for (Product product : productsFounds) {
if (product.getName().equalsIgnoreCase(name)) {
productsFounds.add(product);
}
}
return productsFounds;
}
public static AssignProductToOrder createAssignProductToOrder(Order order, Product product) {
return new AssignProductToOrder(order, product);
}
public void addAssignProductoToOrder(AssignProductToOrder assignProductToOrder) {
productsOfTheOrder.add(assignProductToOrder);
}
public ArrayList<Product> searchAssignProductToOrder(int id) throws ExceptionSearchId {
ArrayList<Product> products = new ArrayList<>();
for (AssignProductToOrder assignProductToOrder : productsOfTheOrder) {
if (assignProductToOrder.getOrder().getId() == id) {
products.add(assignProductToOrder.getProduct());
}
}
return products;
}
public void deleteAssignProductToOrder(AssignProductToOrder assignProductToOrder) {
productsOfTheOrder.remove(assignProductToOrder);
}
}
|
package controllers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.SqlUpdate;
import com.fasterxml.jackson.databind.JsonNode;
import models.Alert;
import models.AssignableArk;
import models.BlCollectionSubset;
import models.Book;
import models.Document;
import models.DocumentFilter;
import models.FlashMessage;
import models.Journal;
import models.JournalTitle;
import models.Portal;
import models.Target;
import models.User;
import models.WatchedTarget;
import play.Logger;
import play.data.Form;
import play.data.validation.ValidationError;
import play.libs.F.Function;
import play.libs.F.Function0;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.ws.WS;
import play.libs.ws.WSRequestHolder;
import play.libs.ws.WSResponse;
import play.libs.XPath;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.mvc.Security;
import play.Play;
import org.apache.commons.lang3.StringUtils;
import org.apache.tika.io.IOUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import uk.bl.Const;
import uk.bl.configurable.BlCollectionSubsetList;
import uk.bl.documents.DocumentAnalyser;
import views.html.documents.compare;
import views.html.documents.edit;
import views.html.documents.list;
@Security.Authenticated(SecuredController.class)
public class Documents extends AbstractController {
public static BlCollectionSubsetList blCollectionSubsetList = new BlCollectionSubsetList();
private static String saveDir = Play.application().configuration().getString("dls.documents.sip.dir");
public static Result view(Long id) {
return render(id, false);
}
public static Result edit(Long id) {
return render(id, true);
}
private static Result render(Long id, boolean editable) {
Logger.debug("Documents.render()");
Document document = getDocumentFromDB(id);
if (document == null) return ok("Document not found: The requested document is no longer available.");
if (document.status == Document.Status.SUBMITTED) editable = false;
User user = User.findByEmail(request().username());
if (!document.isEditableFor(user))
editable = false;
Form<Document> documentForm = Form.form(Document.class).fill(document);
setRelatedEntitiesOfView(documentForm, document);
return ok(edit.render("Document" + id, document, documentForm,
user, editable));
}
public static Result continueEdit() {
Logger.debug("Documents.continueEdit()");
if (flash("journalTitle") != null)
session("journal.journalTitleId", flash("journalTitle"));
Form<Document> documentForm = Form.form(Document.class).bind(session());
documentForm.discardErrors();
return ok(edit.render("Document", Document.find.byId(new Long(session("id"))), documentForm,
User.findByEmail(request().username()), true));
}
public static Result save(Long id) {
Logger.debug("Documents.save()");
String journalTitle = getFormParam("journalTitle");
Form<Document> documentForm = Form.form(Document.class).bindFromRequest();
if (journalTitle != null) {
session().putAll(documentForm.data());
return redirect(routes.JournalTitles.addJournalTitle(
new Long(documentForm.apply("watchedTarget.id").value()), true));
}
Logger.debug("Errors: " + documentForm.hasErrors());
for (String key : documentForm.errors().keySet()) {
Logger.debug("Key: " + key);
for (ValidationError error : documentForm.errors().get(key)) {
for (String message : error.messages()) {
Logger.debug("Message: " + message);
}
}
}
if (documentForm.hasErrors()) {
Logger.debug("Show errors in html");
FlashMessage.validationWarning.send();
return status(303, edit.render("Document",
Document.find.byId(new Long(documentForm.field("id").value())), documentForm,
User.findByEmail(request().username()), true));
}
Logger.debug("Glob Errors: " + documentForm.hasGlobalErrors());
Document document = documentForm.get();
document.clearImproperFields();
setRelatedEntitiesOfModel(document, documentForm);
Ebean.update(document);
if (document.publicationDate == null) {
Ebean.createUpdate(Document.class, "update document SET publication_date=null where id=:id")
.setParameter("id", document.id).execute();
}
if (!document.isBookOrBookChapter() && document.book.id != null) {
Book book = Ebean.find(Book.class, document.book.id);
Ebean.delete(book);
}
if (!document.isJournalArticleOrIssue() && document.journal.id != null) {
Journal journal = Ebean.find(Journal.class, document.journal.id);
Ebean.delete(journal);
}
if (document.isBookOrBookChapter()) {
document.book.document = document;
if (document.book.id == null) {
Ebean.save(document.book);
} else {
Ebean.update(document.book);
}
} else if (document.isJournalArticleOrIssue()) {
document.journal.document = document;
document.journal.journalTitle = Ebean.find(JournalTitle.class, document.journal.journalTitleId);
if (document.journal.id == null) {
Ebean.save(document.journal);
} else {
Ebean.update(document.journal);
}
}
FlashMessage.updateSuccess.send();
return redirect(routes.Documents.view(document.id));
}
private static String getAnARK() {
List<AssignableArk> assignableArks = AssignableArk.find.all();
if (assignableArks.isEmpty()) {
requestNewArks();
assignableArks = AssignableArk.find.all();
if (assignableArks.isEmpty()) {
FlashMessage arkError = new FlashMessage(FlashMessage.Type.ERROR,
"Submission failed! It was not possible to get an ARK identifier.");
arkError.send();
return null;
}
}
String ark = assignableArks.get(0).ark;
Ebean.delete(assignableArks.get(0));
return ark;
}
public static Result submit(final Long id) {
// Find the document:
Document document = Document.find.byId(id);
// Mint an ARK for the document:
if( StringUtils.isEmpty(document.ark) ) {
document.ark = getAnARK();
}
// Check it worked:
if( document.ark == null ) {
return redirect(routes.Documents.view(id));
} else {
Ebean.save(document);
}
// Download it to a local file.
String url = routes.DocumentSIPController.sip(id).absoluteURL(request());
Logger.info("Downloading "+url);
final Promise<File> filePromise = WS.url(url).get().map(
new Function<WSResponse, File>() {
@Override
public File apply(WSResponse response) throws Throwable {
String fileName = "_sip_"+id+".xml";
final File file = new File(saveDir, fileName);
try {
IOUtils.copy(response.getBodyAsStream(), new FileOutputStream(file));
} catch (IOException e) {
Logger.error("Exception while downloading file: "+e.getMessage(),e);
return null;
}
return file;
}
});
// Wait for the file to download, up to thirty seconds:
File file = filePromise.get(30, TimeUnit.SECONDS);
// Check it's good:
if (file != null && file.exists() && file.isFile() && file.length()!= 0){
String newFileName = "sip_"+id+".xml";
file.renameTo(new File(saveDir, newFileName));
} else {
if( file.exists()) {
file.delete();
}
FlashMessage downloadError = new FlashMessage(FlashMessage.Type.ERROR,
"SIP XML could not be downloaded for submission!");
downloadError.send();
}
// Record success:
document.setStatus(Document.Status.SUBMITTED);
Ebean.save(document);
// And tell:
FlashMessage submitSuccess = new FlashMessage(FlashMessage.Type.SUCCESS,
"The document has been submitted.");
submitSuccess.send();
return redirect(routes.Documents.view(id));
}
public static Result compare(Long id1, Long id2) {
Document d1 = Document.find.byId(id1);
Document d2 = Document.find.byId(id2);
return ok(compare.render(d1, d2, User.findByEmail(request().username())));
}
private static void requestNewArks() {
String piiUrl = Play.application().configuration().getString("pii_url");
WSRequestHolder holder = WS.url(piiUrl);
Promise<List<AssignableArk>> arksPromise = holder.post("").map(
new Function<WSResponse, List<AssignableArk>>() {
@Override
public List<AssignableArk> apply(WSResponse response) {
Logger.debug("PII XML-Response: " + response.getBody());
List<AssignableArk> arks = new ArrayList<>();
try {
org.w3c.dom.Document xml = response.asXml();
if (xml != null) {
NodeList nodes = XPath.selectNodes("/pii/results/arkList/ark", xml);
for (int i=0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
arks.add(new AssignableArk(node.getTextContent()));
}
}
} catch (Exception e) {
Logger.error("Can't get ARKs from the PII server: " + e.getMessage());
}
return arks;
}
}
);
List<AssignableArk> arks = arksPromise.get(5000);
Ebean.save(arks);
}
public static Result ignore(Long id, DocumentFilter documentFilter, int pageNo,
String sortBy, String order, String filter, boolean filters) {
Document document = Document.find.byId(id);
if (documentFilter.status == Document.Status.NEW)
document.setStatus(Document.Status.IGNORED);
else
document.setStatus(Document.Status.NEW);
Ebean.save(document);
if (filters)
return redirect(routes.Documents.list(documentFilter, pageNo, sortBy, order, filter));
else
return redirect(routes.Documents.overview(pageNo, sortBy, "asc"));
}
public static Result ignoreAll(DocumentFilter documentFilter, String filter, boolean filters) {
Query<Document> query = Document.query(documentFilter, "title", "asc", filter);
Document.Status status;
if (documentFilter.status == Document.Status.NEW)
status = Document.Status.IGNORED;
else
status = Document.Status.NEW;
for (Document document : query.findList()) {
document.setStatus(status);
Ebean.save(document);
}
if (filters)
return redirect(routes.Documents.list(documentFilter, 0, "title", "asc", filter));
else
return redirect(routes.Documents.overview(0, "title", "asc"));
}
@BodyParser.Of(value = BodyParser.Json.class, maxLength = 1024 * 1024)
public static Result importJson() {
Logger.info("documents are imported");
JsonNode json = request().body().asJson();
List<Document> documents = new ArrayList<>();
for (JsonNode objNode : json) {
// Parse:
try {
Document document = parseDocumentJson(objNode);
// And save and add if not null:
if( document != null) {
// Attempt to extract critical data:
DocumentAnalyser da = new DocumentAnalyser();
da.extractMetadata(document);
// Look for other documents with the same non-empty hash:
boolean unique = true;
if( StringUtils.isNoneEmpty(document.sha256Hash)) {
for (Document doc2 : document.watchedTarget.documents ) {
if( document.sha256Hash.equals( doc2.sha256Hash)) {
Logger.warn("Already seen this document at "+doc2.documentUrl);
unique = false;
break;
}
}
}
// Record unique documents:
if( unique ) {
// Allow unset titles:
if( document.title == null){
document.title = "";
}
Logger.info("Saving document metadata.");
Ebean.save(document);
if( document.book != null ) {
Ebean.save(document.book);
}
// Add to list for post-import checks:
documents.add(document);
} else {
Logger.warn("Dropping document from " + document.documentUrl + " based on SHA-256 hash being identical to an existing document on this target.");
}
}
} catch( Exception ex ) {
ex.printStackTrace();
return badRequest("Problem during import: "+ex);
}
}
if( documents.size() > 0 ) {
Promise.promise(new DocumentAnalyser.SimilarityFunction(documents));
return ok("Documents added");
} else {
return ok("No new documents added");
}
}
protected static Document parseDocumentJson(JsonNode objNode) throws Exception {
Document document = new Document();
Long targetId = objNode.get("target_id").longValue();
Logger.info("TargetID: "+targetId);
Target target = Target.find.byId(targetId);
if( target == null ) {
throw new Exception("No Target with ID "+targetId);
}
Logger.info("Target: "+target.title);
document.watchedTarget = target.watchedTarget;
Logger.info("WatchedTarget: "+document.watchedTarget);
document.waybackTimestamp = objNode.get("wayback_timestamp").textValue();
Logger.info("Comparing "+document.watchedTarget.waybackTimestamp+" to "+document.waybackTimestamp);
if (document.watchedTarget.waybackTimestamp == null ||
document.waybackTimestamp.compareTo(document.watchedTarget.waybackTimestamp) > 0) {
document.watchedTarget.waybackTimestamp = document.waybackTimestamp;
Ebean.save(document.watchedTarget);
}
document.landingPageUrl = objNode.get("landing_page_url").textValue().replace("'", "%27");
document.documentUrl = objNode.get("document_url").textValue().replace("'", "%27");
document.filename = objNode.get("filename").textValue();
document.size = objNode.get("size").longValue();
document.setStatus(Document.Status.NEW);
document.fastSubjects = target.watchedTarget.fastSubjects;
if( documentAlreadyKnown(document)) {
Logger.warn("This Document is already known to the system.");
return null;
} else {
Logger.debug("attempting to add document " + document);
}
// Optional fields
// Title:
if(objNode.get("title") != null) {
document.title = objNode.get("title").textValue();
}
// Publisher:
if( objNode.get("publisher") != null) {
if( document.book == null) document.book = new Book(document);
document.book.publisher = objNode.get("publisher").textValue();
}
// Publication Date (in yyyy-MM-dd format):
if( objNode.get("publication_date") != null ) {
String ymd = objNode.get("publication_date").textValue();
try {
document.publicationDate = new SimpleDateFormat("yyyy-MM-dd").parse(ymd);
Calendar calendar = Calendar.getInstance();
calendar.setTime(document.publicationDate);
document.publicationYear = calendar.get(Calendar.YEAR);
} catch( ParseException e ) {
throw new Exception("Could not parse publication date (should be yyyy-MM-dd format"+ymd);
}
}
// Authors array processing:
if( objNode.get("authors") != null ) {
List<String> authors = new ArrayList<String>();
Iterator<JsonNode> it = objNode.get("authors").elements();
while( it.hasNext()) {
JsonNode val = it.next();
authors.add(val.textValue());
}
if (authors.size() >= 1) {
String[] a = authors.get(0).trim().split("\\s+", 2);
document.author1Fn = a[0];
document.author1Ln = a[1];
}
if (authors.size() >= 2) {
String[] a = authors.get(1).trim().split("\\s+", 2);
document.author2Fn = a[0];
document.author2Ln = a[1];
}
if (authors.size() >= 3) {
String[] a = authors.get(2).trim().split("\\s+", 2);
document.author3Fn = a[0];
document.author3Ln = a[1];
}
}
// ISBN
if( objNode.get("isbn") != null ) {
if( document.book == null) document.book = new Book(document);
document.book.isbn = objNode.get("isbn").textValue();
}
// DOI
if( objNode.get("doi") != null ) {
if( document.book == null) document.book = new Book(document);
document.doi = objNode.get("doi").textValue();
}
return document;
}
private static boolean documentAlreadyKnown(Document document) {
String urlWithoutSchema = document.documentUrl.replaceFirst("^.*:
if (Document.find.where().eq("regexp_replace(document_url,'^.*://','')", urlWithoutSchema).findRowCount() == 0) {
return false;
} else {
return true;
}
}
public static List<Document> filterNew(List<Document> documentList) {
List<Document> newDocumentList = new ArrayList<>();
for (Document document : documentList) {
if (! documentAlreadyKnown(document))
newDocumentList.add(document);
}
return newDocumentList;
}
public static Result export(DocumentFilter documentFilter, String sortBy,
String order, String filter) {
Query<Document> query = Document.query(documentFilter, sortBy, order, filter);
StringBuilder builder = new StringBuilder();
builder.append(
"id" + Const.CSV_SEPARATOR +
"id_target" + Const.CSV_SEPARATOR +
"title" + Const.CSV_SEPARATOR +
"landing_page_url" + Const.CSV_SEPARATOR +
"document_url" + Const.CSV_SEPARATOR +
"wayback_timestamp" + Const.CSV_LINE_END
);
for (Document document : query.findList()) {
builder.append(
document.id + Const.CSV_SEPARATOR +
document.watchedTarget.target.id + Const.CSV_SEPARATOR +
document.title + Const.CSV_SEPARATOR +
document.landingPageUrl + Const.CSV_SEPARATOR +
document.documentUrl + Const.CSV_SEPARATOR +
document.waybackTimestamp + Const.CSV_LINE_END
);
}
response().setContentType("text/csv; charset=utf-8");
response().setHeader("Content-Disposition","attachment; filename=\"document-export.csv");
return ok(builder.toString());
}
public static void addHashes(Document document) {
File file = Play.application().getFile("conf/converter/" + document.id + ".sha256");
try {
Scanner scanner = new Scanner(file);
document.sha256Hash = scanner.next();
scanner.close();
file.delete();
} catch (Exception e) {
Logger.warn("can't read sha256 hash: " + e.getMessage());
}
file = Play.application().getFile("conf/converter/" + document.id + ".ctp");
try {
Scanner scanner = new Scanner(file);
document.ctpHash = scanner.next();
scanner.close();
file.delete();
} catch (Exception e) {
Logger.warn("can't read ctp hash: " + e.getMessage());
}
Ebean.save(document);
}
public static void addDuplicateAlert(String ctphFile) {
File file = Play.application().getFile("conf/converter/" + ctphFile + ".out");
try {
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[\r\n]+");
while (scanner.hasNext()) {
String line = scanner.next();
String[] parts = line.split("[ :]");
if (parts.length == 6) {
int similarity = Integer.parseInt(parts[5].replace("(", "").replace(")", ""));
if (similarity >= 98 && similarity < 100) {
long docId1 = Long.parseLong(parts[1].split("\\.")[0]);
long docId2 = Long.parseLong(parts[4].split("\\.")[0]);
Document doc1 = Document.find.byId(docId1);
Document doc2 = Document.find.byId(docId2);
Alert alert = new Alert();
alert.user = doc1.watchedTarget.target.authorUser;
alert.text = "possible duplicate found: " + Alert.link(doc1) + " matches " +
Alert.link(doc2) + " with " + similarity + "% " +
"(" + Alert.compareLink(doc1, doc2) + ")";
Ebean.save(alert);
}
}
}
scanner.close();
file.delete();
} catch (Exception e) {
Logger.warn("can't read ctph matches:", e);
}
}
public static Document getDocumentFromDB(long id) {
Document document = Ebean.find(Document.class, id);
if (document == null) return null;
if (document.type == null) document.type = "";
if (document.journal != null)
document.journal.journalTitleId = document.journal.journalTitle.id;
return document;
}
public static Map<String, String> getJournalTitles(Form<Document> form) {
WatchedTarget watchedTarget = WatchedTarget.find.byId(new Long(form.apply("watchedTarget.id").value()));
Map<String, String> titles = new LinkedHashMap<>();
titles.put("","");
for (JournalTitle journalTitle : watchedTarget.journalTitles)
titles.put(""+journalTitle.id, journalTitle.title);
return titles;
}
private static void setRelatedEntitiesOfModel(Document document, Form<Document> documentForm) {
document.fastSubjects = FastSubjects.getFastSubjects(documentForm);
document.portals = Portals.getPortals(documentForm);
if (document.isBookOrBookChapter())
for (BlCollectionSubset blCollectionSubset : blCollectionSubsetList.getList())
if (documentForm.apply("blCollectionSubset_" + blCollectionSubset.id).value() != null)
document.book.blCollectionSubsets.add(blCollectionSubset);
}
private static void setRelatedEntitiesOfView(Form<Document> documentForm, Document document) {
documentForm.data().putAll(FastSubjects.getFormData(document.fastSubjects));
documentForm.data().putAll(Portals.getFormData(document.portals));
if (document.isBookOrBookChapter())
for (BlCollectionSubset portal : document.book.blCollectionSubsets)
documentForm.data().put("blCollectionSubset_" + portal.id, "true");
}
public static List<String> getPortalsSelection() {
List<Portal> portals = Portals.portalList.getList();
List<String> portalTitles = new ArrayList<>();
portalTitles.add("All");
for (Portal portal : portals)
portalTitles.add(portal.title);
return portalTitles;
}
/**
* Display the paginated list of Documents.
*
* @param page Current page number (starts from 0)
* @param sortBy Column to be sorted
* @param order Sort order (either asc or desc)
* @param filter Filter applied on Documents
*/
public static Result list(DocumentFilter documentFilter,
int pageNo, String sortBy, String order, String filter) {
if (documentFilter.status == Document.Status.IGNORED)
changeStatusOfIgnoredDocuments();
return renderList(documentFilter, pageNo, sortBy, order, filter, true);
}
private static void changeStatusOfIgnoredDocuments() {
SqlUpdate su = Ebean.createSqlUpdate("update document" +
" set status=" + Document.Status.DELETED.ordinal() +
" where status=" + Document.Status.IGNORED.ordinal() +
" and age(current_status_set) >= interval '1 month'");
Ebean.execute(su);
Promise.promise(new Function0<Boolean>() {
@Override
public Boolean apply() {
List<Document> documents = Document.find.where().eq("status", Document.Status.DELETED.ordinal()).findList();
for (Document document : documents)
deleteHtmlFile(document.htmlFilename());
return true;
}
});
}
public static Result overview(int pageNo, String sortBy, String order) {
DocumentFilter documentFilter = new DocumentFilter(User.findByEmail(request().username()).id);
return renderList(documentFilter, pageNo, sortBy, order, "", false);
}
public static Result renderList(DocumentFilter documentFilter,
int pageNo, String sortBy, String order, String filter, boolean filters) {
Logger.debug("Documents.list()");
Form<DocumentFilter> filterForm = Form.form(DocumentFilter.class).fill(documentFilter);
for (String fastSubject : documentFilter.fastSubjects)
filterForm.data().put(fastSubject, "true");
return ok(
list.render(
User.findByEmail(request().username()),
filterForm,
filter,
Document.page(documentFilter, pageNo, 20, sortBy, order, filter),
sortBy,
order,
filters)
);
}
public static Result filterByJson(String title) {
JsonNode jsonData = null;
if (title != null) {
List<Document> documents = Document.find.where().icontains("title", title).findList();
jsonData = Json.toJson(documents);
}
return ok(jsonData);
}
public static Result html(String encodedFilename) {
try {
String filename = URLDecoder.decode(encodedFilename, "UTF-8");
File file = Play.application().getFile("../html/" + filename);
return ok(file, filename);
} catch (Exception e) {
return ok("This file was not found on the system.");
}
}
public static void deleteHtmlFiles(WatchedTarget watchedTarget) {
for (Document document : watchedTarget.documents)
deleteHtmlFile(document.htmlFilename());
}
public static void deleteHtmlFile(String filename) {
File file = Play.application().getFile("../html/" + filename);
file.delete();
}
public static List<Long> stringToLongList(String subject) {
List<Long> subjectIds = new ArrayList<Long>();
if (subject != null && !subject.isEmpty()) {
String[] subjects = subject.split(", ");
for (String sId : subjects) {
Long subjectId = Long.valueOf(sId);
subjectIds.add(subjectId);
}
}
return subjectIds;
}
public static String longListToString(List<Long> subjectIds) {
return StringUtils.join(subjectIds, ", ");
}
}
|
package controllers;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.typesafe.config.ConfigFactory;
import config.KuratorConfig;
import config.KuratorConfigFactory;
import config.ParameterConfig;
import forms.FormDefinition;
import forms.input.*;
import models.*;
import org.apache.commons.io.FileUtils;
import org.kurator.akka.WorkflowConfig;
import org.kurator.akka.WorkflowRunner;
import org.kurator.akka.YamlStreamWorkflowRunner;
import org.restflow.yaml.spring.YamlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import play.Play;
import play.libs.Json;
import play.mvc.*;
import java.io.*;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import util.AsyncWorkflowRunnable;
import util.ClasspathStreamHandler;
import util.ConfigurableStreamHandlerFactory;
import views.html.*;
import javax.inject.Singleton;
/**
* This controller deals with actions related to running a workflow, uploading files, checking the status of a run, and
* obtaining artifacts produced by the run.
*
*/
@Singleton
public class Workflows extends Controller {
private static final String WORKFLOWS_PATH = "workflows";
static {
try {
URL.setURLStreamHandlerFactory(new ConfigurableStreamHandlerFactory("classpath",
new ClasspathStreamHandler()));
} catch (Error e) {
// if the stream handler was already set ignore the "factory already defined" error
}
}
/**
* Start the workflow run asynchronously.
*
* @param name The name of the workflow
* @return json response containing id
*/
@Security.Authenticated(Secured.class)
public Result runWorkflow(String name) {
FormDefinition form = formDefinitionForWorkflow(name);
// Process file upload first if present in form data
Http.MultipartFormData body = request().body().asMultipartFormData();
for (Object obj : body.getFiles()) {
Http.MultipartFormData.FilePart filePart = (Http.MultipartFormData.FilePart) obj;
UserUpload userUpload = uploadFile(filePart);
BasicField fileInputField = form.getField(filePart.getKey());
fileInputField.setValue(userUpload);
}
// Set the form definition field values from the request data
Map<String, String[]> data = body.asFormUrlEncoded();
for (String key : data.keySet()) {
BasicField field = form.getField(key);
field.setValue(data.get(key));
}
// Transfer form field data to workflow settings map
Map<String, Object> settings = new HashMap<>();
for (BasicField field : form.fields) {
settings.put(field.name, field.value());
}
settings.putAll(settingsFromConfig( form));
// Update the workflow model object and persist to the db
Workflow workflow = Workflow.find.where().eq("name", form.name).findUnique();
if (workflow == null) {
workflow = new Workflow();
}
workflow.name = form.name;
workflow.title = form.title;
workflow.yamlFile = form.yamlFile;
workflow.save();
// Run the workflow
ObjectNode response = runYamlWorkflow(form.yamlFile, workflow, settings);
return redirect(
routes.Application.index()
);
}
/**
* Helper method for running yaml workflows using an instance of WorkflowRunner.
*
* @param yamlFile The workflow yaml file
* @param workflow Workflow definition object
* @param settings A map of the settings provided as input to the runner
* @return json containing the id of this run
*/
private static ObjectNode runYamlWorkflow(String yamlFile, Workflow workflow, Map<String, Object> settings) {
InputStream yamlStream = null;
try {
yamlStream = loadYamlStream(yamlFile);
} catch (Exception e) {
throw new RuntimeException("Could not load workflow from yaml file.", e);
}
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
// This instance of runnable will be executed at the end of a workflow run
AsyncWorkflowRunnable runnable = new AsyncWorkflowRunnable();
try {
// Get jython home and path variables from application.conf and set them in workflow runner global config
String jythonPath = ConfigFactory.defaultApplication().getString("jython.path");
String jythonHome = ConfigFactory.defaultApplication().getString("jython.home");
Map<String, Object> config = new HashMap<String, Object>();
config.put("jython_home", jythonHome);
config.put("jython_path", jythonPath);
// Initialize and run the yaml workflow
WorkflowRunner runner = new YamlStreamWorkflowRunner()
.yamlStream(yamlStream).configure(config);
runnable.init(workflow, runner, errStream, outStream);
runner.apply(settings)
.outputStream(new PrintStream(outStream))
.errorStream(new PrintStream(errStream))
.runAsync(runnable);
} catch (Exception e) {
e.printStackTrace();
// Log exceptions as part of the workflow error log
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String errorText = writer.toString();
String outputText = new String(outStream.toByteArray());
runnable.error(errorText, outputText);
}
// The response json contains the workflow run id for later reference
ObjectNode response = Json.newObject();
WorkflowRun run = runnable.getWorkflowRun();
response.put("runId", run.id);
return response;
}
private static InputStream loadYamlStream(String yamlFile) throws IOException {
URL url = new URL(yamlFile);
return url.openConnection().getInputStream();
}
/**
* Generic workflow input form page.
*
* @param name workflow name
*/
@Security.Authenticated(Secured.class)
public Result workflow(String name) {
FormDefinition form = formDefinitionForWorkflow(name);
if (form != null) {
return ok(
workflow.render(form)
);
} else {
return notFound("No workflow found for name " + name);
}
}
/**
* Return the result archive containing artifacts produced by the workflow run.
*
* @param workflowRunId identifies the workflow run by id
* @return the zip archive
*/
@Security.Authenticated(Secured.class)
public Result resultArchive(long workflowRunId) {
WorkflowRun run = WorkflowRun.find.byId(workflowRunId);
return ok(new File(run.result.archivePath));
}
/**
* Return the workflow run error log as a text file.
*
* @param workflowRunId identifies the workflow run by id
* @return error log as text file
*/
@Security.Authenticated(Secured.class)
public Result errorLog(long workflowRunId) {
response().setHeader("Content-Disposition", "attachment; filename=error_log.txt");
response().setContentType("text/plain");
WorkflowRun run = WorkflowRun.find.byId(workflowRunId);
if (run != null) {
return ok(run.result.errorText);
} else {
return notFound("No error log found for workflow run with id " + workflowRunId);
}
}
/**
* Return the workflow output log as a text file.
*
* @param workflowRunId identifies the workflow run by id
* @return output log as text file
*/
@Security.Authenticated(Secured.class)
public Result outputLog(long workflowRunId) {
response().setHeader("Content-Disposition", "attachment; filename=output_log.txt");
response().setContentType("text/plain");
WorkflowRun run = WorkflowRun.find.byId(workflowRunId);
if (run != null) {
return ok(run.result.outputText);
} else {
return notFound("No output log found for workflow run with id " + workflowRunId);
}
}
/**
* REST endpoint returns a json array containing metadata about the currently logged in user's uploaded files.
*
* @return json containing file upload ids and filenames
*/
public Result listUploads() {
List<UserUpload> uploadList = UserUpload.findUploadsByUserId(Application.getCurrentUserId());
ObjectNode response = Json.newObject();
ArrayNode uploads = response.putArray("uploads");
for (UserUpload userUpload : uploadList) {
ObjectNode upload = Json.newObject();
upload.put("id", userUpload.id);
upload.put("filename", userUpload.fileName);
uploads.add(upload);
}
return ok(uploads);
}
public Result removeRun(long workflowRunId) {
WorkflowRun run = WorkflowRun.find.byId(workflowRunId);
if (run != null) {
run.delete();
WorkflowResult result = run.result;
if (run.result != null) {
List<ResultFile> resultFiles = result.resultFiles;
for (ResultFile resultFile : resultFiles) {
resultFile.delete();
}
result.delete();
}
}
return ok();
}
/** REST endopint returns a json object with metadata about the status of all of a current users workflow runs.
*
* @param uid
* @return
*/
public Result status(String uid) {
List<WorkflowRun> workflowRuns = WorkflowRun.find.where().eq("user.id", uid).findList();
ArrayNode response = Json.newArray();
for (WorkflowRun run : workflowRuns) {
ObjectNode runJson = Json.newObject();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
runJson.put("id", run.id);
runJson.put("workflow", run.workflow.title);
runJson.put("startTime", dateFormat.format(run.startTime));
runJson.put("endTime", run.endTime != null ? dateFormat.format(run.endTime) : null);
runJson.put("status", run.status);
runJson.put("hasResult", run.result != null);
if (run.result != null) {
runJson.put("hasOutput", !run.result.outputText.equals(""));
runJson.put("hasErrors", !run.result.errorText.equals(""));
} else {
runJson.put("hasOutput", false);
runJson.put("hasErrors", false);
}
response.add(runJson);
}
return ok(response);
}
/**
* Private helper method obtains an instance of FormDefinition from the workflow name.
*
* @param name workflow name
* @return the form definition object
*/
private static FormDefinition formDefinitionForWorkflow(String name) {
List<FormDefinition> formDefs = loadWorkflowFormDefinitions();
FormDefinition form = null;
for (FormDefinition formDef : formDefs) {
if (formDef.name.equals(name)) {
form = formDef;
}
}
return form;
}
/**
* Utility method loads all of the workflow form definitions from yaml files contained in the workflow
* directory.
*
* @return
*/
public static List<FormDefinition> loadWorkflowFormDefinitions() {
// List<FormDefinition> formDefs = new ArrayList<>();
// URL path = Play.application().classloader().getResource(WORKFLOWS_PATH);
// try {
// File dir = new File(path.toURI());
// File[] workflows = dir.listFiles(new FilenameFilter() {
// public boolean accept(File dir, String name) {
// return name.toLowerCase().endsWith(".yaml");
// for (File file : workflows) {
// formDefs.add(loadFormDefinition(file.getAbsolutePath()));
// } catch (URISyntaxException e) { /* Should not occur */ }
List<FormDefinition> formDefs = new ArrayList<>();
KuratorConfig config = KuratorConfigFactory.load();
Collection<config.WorkflowConfig> workflows = config.getAllWorkflows();
for (config.WorkflowConfig workflow : workflows) {
FormDefinition formDef = new FormDefinition();
formDef.name = workflow.getName();
formDef.title = workflow.getTitle();
formDef.yamlFile = workflow.getYaml();
formDef.documentation = workflow.getDocumentation();
formDef.instructions = workflow.getInstructions();
formDef.summary = workflow.getSummary();
for (ParameterConfig parameter : workflow.getParameters()) {
if (parameter.isTyped()) {
String type = parameter.getType();
switch (type) {
case "text":
TextField textField = new TextField();
textField.name = parameter.getName();
textField.label = parameter.getLabel();
textField.tooltip = parameter.getDescription();
formDef.addField(textField);
break;
case "select":
SelectField selectField = new SelectField();
selectField.name = parameter.getName();
selectField.label = parameter.getLabel();
selectField.options = parameter.getOptions();
selectField.tooltip = parameter.getDescription();
formDef.addField(selectField);
break;
case "upload":
FileInput fileInput = new FileInput();
fileInput.name = parameter.getName();
fileInput.label = parameter.getLabel();
fileInput.tooltip = parameter.getDescription();
formDef.addField(fileInput);
break;
}
}
}
formDefs.add(formDef);
}
return formDefs;
}
/**
* Private helper method loads data from the yaml file specified and creates an instance of FormDefinition
*
* @param yamlFile
* @return
*/
// private static FormDefinition loadFormDefinition(String yamlFile) {
// try {
// GenericApplicationContext springContext = new GenericApplicationContext();
// YamlBeanDefinitionReader yamlBeanReader = new YamlBeanDefinitionReader(springContext);
// yamlBeanReader.loadBeanDefinitions(new FileInputStream(yamlFile), "-");
// springContext.refresh();
// FormDefinition formDefinition = springContext.getBean(FormDefinition.class);
// formDefinition.yamlFile = yamlFile;
// return formDefinition;
// } catch (Exception e) {
// throw new RuntimeException(e);
/**
* Helper method creates a temp file from the multipart form data and persists the upload file metadata to the
* database
*
* @param filePart data from the form submission
* @return an instance of UploadFile that has been persisted to the db
*/
private static UserUpload uploadFile(Http.MultipartFormData.FilePart filePart) {
File src = (File) filePart.getFile();
File file = null;
try {
file = File.createTempFile(filePart.getFilename() + "-", ".csv");
FileUtils.copyFile(src, file);
} catch (IOException e) {
throw new RuntimeException("Could not create temp file for upload", e);
}
UserUpload uploadFile = new UserUpload();
uploadFile.absolutePath = file.getAbsolutePath();
uploadFile.fileName = filePart.getFilename();
uploadFile.user = Application.getCurrentUser();
uploadFile.save();
return uploadFile;
}
/**
* Obtains the currently uploaded file from the session variable.
*
* @return uploaded file
* @throws FileNotFoundException
*/
private static File getCurrentUpload() throws FileNotFoundException {
String uploadFileId = session().get("uploadFileId");
UserUpload uploadFile = UserUpload.find.byId(Long.parseLong(uploadFileId));
File file = new File(uploadFile.absolutePath);
if (!file.exists()) {
throw new FileNotFoundException("Could not load input from file.");
}
return file;
}
/**
* Will load additional settings from the web app config. Creates a map object that contains
* workflow parameters to be provided as input to the runner
*
* @param form form definition of the workflow being run
* @return a map of the settings
*/
private static Map<String, String> settingsFromConfig(FormDefinition form) {
try {
Map<String, String> settings = new HashMap<String, String>();
// Get the workspace basedir from application.conf
String workspace = ConfigFactory.defaultApplication().getString("jython.workspace");
// Load workflow yaml file to check parameters
GenericApplicationContext springContext = new GenericApplicationContext();
YamlBeanDefinitionReader yamlBeanReader = new YamlBeanDefinitionReader(springContext);
yamlBeanReader.loadBeanDefinitions(loadYamlStream(form.yamlFile), "-");
springContext.refresh();
WorkflowConfig workflowConfig = springContext.getBean(WorkflowConfig.class);
// Create a workspace
Path path = Paths.get(workspace, "workspace_" + UUID.randomUUID());
path.toFile().mkdir();
// If the "workspace" parameter is present in the workflow set it to the path defined in the config
if (workflowConfig.getParameters().containsKey("workspace")) {
settings.put("workspace", path.toString());
}
return settings;
} catch (IOException e) {
throw new RuntimeException("Error creating workspace directory.", e);
} catch (Exception e) {
throw new RuntimeException("Error reading yaml file for parameters.", e);
}
}
}
|
package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import java.io.File;
import java.io.IOException;
public class Controller {
private Downloader con = new Downloader(this);
private Launcher launch = new Launcher(this);
@FXML
private TextField installLoc;
@FXML
private Button launchButton;
@FXML
private TabPane tabView;
@FXML
private TextArea output;
@FXML
private Button patchButton;
@FXML
private TextField serverAddress;
@FXML
private ProgressBar progressBar;
@FXML
private Button openButton;
@FXML
private void launchHandle(){
launchMinecraft();
}
private void launchMinecraft() {
launchButton.setDisable(true);
launchButton.setText("Launching...");
Runnable task1 = () -> launch.launchMinecraft(installLoc.getText());
new Thread(task1).start();
}
@FXML
private void dirHandle(){
DirectoryChooser chooser = new DirectoryChooser();
File chosen = new File(installLoc.getText());
if(chosen.exists()) chooser.setInitialDirectory(new File(installLoc.getText()));
chooser.setTitle("Choose Minecraft install location");
File location = chooser.showDialog(installLoc.getScene().getWindow());
if (location!=null) installLoc.setText(location.getAbsolutePath());
else System.out.println("Please select a correct location.");
}
@FXML
private void patchHandle(){
output.clear();
con.patch(installLoc.getText(),serverAddress.getText());
}
@FXML
protected void initialize(){
//set install location to appdata/.minecraft
installLoc.setText(System.getenv("Appdata")+"\\.minecraft");
}
@FXML
private void openHandle(){
try {
Runtime.getRuntime().exec("explorer.exe \"" + installLoc.getText()+"\"");
} catch (IOException e) {
e.printStackTrace();
printOutput("Cannot open chosen directory.",true);
}
}
void launchFailed() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
printOutput("launcher.jar not found, please install minecraft",true);
Platform.runLater(()->launchButton.setDisable(false));
Platform.runLater(()->launchButton.setText("Launch"));
}
void printOutput(String value, boolean fancy){
if (fancy) Platform.runLater(()->output.appendText("=== "+value+" ===\n"));
else Platform.runLater(()->output.appendText(value+"\n"));
}
void updateProgress(double value){
Platform.runLater(()->progressBar.setProgress(value));
}
}
|
package jme3test.helloworld;
import com.jme3.app.SimpleApplication;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import com.jme3.texture.Texture;
import com.jme3.util.TangentBinormalGenerator;
/** Sample 6 - how to give an object's surface a material and texture.
* How to make objects transparent, or let colors "leak" through partially
* transparent textures. How to make bumpy and shiny surfaces. */
public class HelloMaterial extends SimpleApplication {
public static void main(String[] args) {
HelloMaterial app = new HelloMaterial();
app.start();
}
@Override
public void simpleInitApp() {
/** A simple textured cube -- in good MIP map quality. */
Box box1Mesh = new Box(1f,1f,1f);
Geometry cubePlainGeo = new Geometry("My Textured Box", box1Mesh);
Material stlMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
Texture monkeyTex = assetManager.loadTexture("Interface/Logo/Monkey.jpg");
stlMat.setTexture("ColorMap", monkeyTex);
cubePlainGeo.setMaterial(stlMat);
cubePlainGeo.move(new Vector3f(-3f,1.1f,0f));
rootNode.attachChild(cubePlainGeo);
/** A translucent/transparent texture, similar to a window frame. */
Box box3Mesh = new Box(1f,1f,0.01f);
Geometry windowGeo = new Geometry("window frame", box3Mesh);
Material ttMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
ttMat.setTexture("ColorMap", assetManager.loadTexture("Textures/ColoredTex/Monkey.png"));
ttMat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); // activate transparency
windowGeo.setQueueBucket(Bucket.Transparent);
windowGeo.setMaterial(ttMat);
rootNode.attachChild(windowGeo);
/** A cube with its base color "bleeding" through a partially transparent texture */
Box box4Mesh = new Box(1f,1f,1f);
Geometry bleedCubeGeo = new Geometry("bleed-through colored cube", box4Mesh);
Material tlMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
tlMat.setTexture("ColorMap", assetManager.loadTexture("Textures/ColoredTex/Monkey.png"));
tlMat.setColor("Color", new ColorRGBA(1f,0f,1f, 1f)); // purple
bleedCubeGeo.setMaterial(tlMat);
bleedCubeGeo.move(new Vector3f(3f,-1f,0f));
rootNode.attachChild(bleedCubeGeo);
//bleedCubeGeo.setMaterial((Material) assetManager.loadAsset( "Materials/BleedThrough.j3m"));
/** A bumpy rock with a shiny light effect. To make bumpy objects you must create a NormalMap. */
Sphere sphereMesh = new Sphere(32,32, 2f);
Geometry shinyRockGeo = new Geometry("Shiny rock", sphereMesh);
sphereMesh.setTextureMode(Sphere.TextureMode.Projected); // better quality on spheres
TangentBinormalGenerator.generate(sphereMesh); // for lighting effect
Material litMat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
litMat.setTexture("DiffuseMap", assetManager.loadTexture("Textures/Terrain/Pond/Pond.jpg"));
litMat.setTexture("NormalMap", assetManager.loadTexture("Textures/Terrain/Pond/Pond_normal.png"));
litMat.setBoolean("UseMaterialColors",true);
litMat.setColor("Specular",ColorRGBA.White);
litMat.setColor("Diffuse",ColorRGBA.White);
litMat.setFloat("Shininess", 64f); // [0,128]
shinyRockGeo.setMaterial(litMat);
shinyRockGeo.setLocalTranslation(0,2,-2); // Move it a bit
shinyRockGeo.rotate(1.6f, 0, 0); // Rotate it a bit
rootNode.attachChild(shinyRockGeo);
/** Must add a light to make the lit object visible! */
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(1,0,-2).normalizeLocal());
sun.setColor(ColorRGBA.White);
rootNode.addLight(sun);
}
}
|
package jme3test.helloworld;
import com.jme3.app.SimpleApplication;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
import com.jme3.texture.Texture;
import com.jme3.util.TangentBinormalGenerator;
/** Sample 6 - how to give an object's surface a material and texture.
* How to make objects transparent. How to make bumpy and shiny surfaces. */
public class HelloMaterial extends SimpleApplication {
public static void main(String[] args) {
HelloMaterial app = new HelloMaterial();
app.start();
}
@Override
public void simpleInitApp() {
/** A simple textured cube -- in good MIP map quality. */
Box cube1Mesh = new Box( 1f,1f,1f);
Geometry cube1Geo = new Geometry("My Textured Box", cube1Mesh);
cube1Geo.setLocalTranslation(new Vector3f(-3f,1.1f,0f));
Material cube1Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
Texture cube1Tex = assetManager.loadTexture("Interface/Logo/Monkey.jpg");
cube1Mat.setTexture("ColorMap", cube1Tex);
cube1Geo.setMaterial(cube1Mat);
rootNode.attachChild(cube1Geo);
/** A translucent/transparent texture, similar to a window frame. */
Box cube2Mesh = new Box( 1f,1f,0.01f);
Geometry cube2Geo = new Geometry("window frame", cube2Mesh);
Material cube2Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
cube2Mat.setTexture("ColorMap", assetManager.loadTexture("Textures/ColoredTex/Monkey.png"));
cube2Mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); // activate transparency
cube2Geo.setQueueBucket(Bucket.Transparent);
cube2Geo.setMaterial(cube2Mat);
rootNode.attachChild(cube2Geo);
/** A bumpy rock with a shiny light effect. To make bumpy objects you must create a NormalMap. */
Sphere sphereMesh = new Sphere(32,32, 2f);
Geometry sphereGeo = new Geometry("Shiny rock", sphereMesh);
sphereMesh.setTextureMode(Sphere.TextureMode.Projected); // better quality on spheres
TangentBinormalGenerator.generate(sphereMesh); // for lighting effect
Material sphereMat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
sphereMat.setTexture("DiffuseMap", assetManager.loadTexture("Textures/Terrain/Pond/Pond.jpg"));
sphereMat.setTexture("NormalMap", assetManager.loadTexture("Textures/Terrain/Pond/Pond_normal.png"));
sphereMat.setBoolean("UseMaterialColors",true);
sphereMat.setColor("Diffuse",ColorRGBA.White);
sphereMat.setColor("Specular",ColorRGBA.White);
sphereMat.setFloat("Shininess", 64f); // [0,128]
sphereGeo.setMaterial(sphereMat);
//sphereGeo.setMaterial((Material) assetManager.loadMaterial("Materials/MyCustomMaterial.j3m"));
sphereGeo.setLocalTranslation(0,2,-2); // Move it a bit
sphereGeo.rotate(1.6f, 0, 0); // Rotate it a bit
rootNode.attachChild(sphereGeo);
/** Must add a light to make the lit object visible! */
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(1,0,-2).normalizeLocal());
sun.setColor(ColorRGBA.White);
rootNode.addLight(sun);
}
}
|
package seph.lang.compiler;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import seph.lang.*;
import seph.lang.ast.*;
import seph.lang.persistent.*;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import static org.objectweb.asm.Opcodes.*;
import static seph.lang.compiler.CompilationHelpers.*;
import java.dyn.MethodHandle;
/**
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class AbstractionCompiler {
private final static Object[] EMPTY = new Object[0];
private final static org.objectweb.asm.MethodHandle basicSephBootstrap = new org.objectweb.asm.MethodHandle(MH_INVOKESTATIC, "seph/lang/compiler/Bootstrap", "basicSephBootstrap", Bootstrap.BOOTSTRAP_SIGNATURE_DESC);
private final static AtomicInteger compiledCount = new AtomicInteger(0);
private final Message code;
private final LexicalScope capture;
private LiteralEntry[] literals = new LiteralEntry[4];
private int literalsFill = 0;
private Class<?> abstractionClass;
private final ClassWriter cw;
private MethodVisitor mv_act;
private final String className;
private AbstractionCompiler(Message code, LexicalScope capture) {
this.code = code;
this.capture = capture;
this.className = "seph$gen$abstraction$" + compiledCount.getAndIncrement();
this.cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
}
private void generateAbstractionClass() {
cw.visit(V1_7, ACC_PUBLIC, p(className), null, p(SimpleSephObject.class), new String[0]);
activateWithMethod();
abstractionFields();
constructor(SimpleSephObject.class);
cw.visitEnd();
abstractionClass = seph.lang.Runtime.LOADER.defineClass(className, cw.toByteArray());
}
private SephObject instantiateAbstraction() {
try {
return (SephObject)abstractionClass.getConstructor(getSignature()).newInstance(getArguments());
} catch(Exception e) {
System.err.println(e);
e.printStackTrace();
throw new CompilationAborted("An error was encountered during compilation");
}
}
private void abstractionFields() {
cw.visitField(ACC_FINAL, "fullMsg", c(Message.class), null, null);
cw.visitField(ACC_FINAL, "capture", c(LexicalScope.class), null, null);
}
private void constructor(Class<?> superClass) {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", sig(void.class, getSignature()), null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0); // [recv]
mv.visitInsn(DUP); // [recv, recv]
mv.visitFieldInsn(GETSTATIC, p(PersistentArrayMap.class), "EMPTY", c(PersistentArrayMap.class)); // [recv, recv, EMPTY]
mv.visitFieldInsn(GETSTATIC, p(SimpleSephObject.class), "activatable", c(Symbol.class)); // [recv, recv, EMPTY, act]
mv.visitFieldInsn(GETSTATIC, p(seph.lang.Runtime.class), "TRUE", c(SephObject.class)); // [recv, recv, EMPTY, act, true]
mv.visitMethodInsn(INVOKEVIRTUAL, p(PersistentArrayMap.class), "associate", sig(IPersistentMap.class, Object.class, Object.class)); // [recv, recv, map]
mv.visitMethodInsn(INVOKESPECIAL, p(superClass), "<init>", sig(void.class, IPersistentMap.class)); // [recv]
mv.visitInsn(DUP); // [recv, recv]
mv.visitVarInsn(ALOAD, 1); // [recv, code]
mv.visitFieldInsn(PUTFIELD, p(className), "fullMsg", c(Message.class));
for(int i = 0; i<literalsFill; i++) {
LiteralEntry le = literals[i];
mv.visitVarInsn(ALOAD, 0); // [recv]
mv.visitVarInsn(ALOAD, 3 + le.position); // [recv, literal1]
mv.visitFieldInsn(PUTFIELD, p(className), le.name, c(SephObject.class));
}
mv.visitVarInsn(ALOAD, 0); // [recv]
mv.visitVarInsn(ALOAD, 2); // [recv, scope]
mv.visitFieldInsn(PUTFIELD, p(className), "capture", c(LexicalScope.class));
mv.visitInsn(RETURN);
mv.visitMaxs(0,0);
mv.visitEnd();
}
private void compileLiteral(Message current) {
int position = literalsFill;
LiteralEntry le = new LiteralEntry("literal" + position, current, position);
if(position >= literals.length) {
LiteralEntry[] newLiterals = new LiteralEntry[literals.length * 2];
System.arraycopy(literals, 0, newLiterals, 0, literals.length);
literals = newLiterals;
}
literals[position] = le;
literalsFill++;
cw.visitField(ACC_FINAL, le.name, c(SephObject.class), null, null);
mv_act.visitInsn(POP);
mv_act.visitVarInsn(ALOAD, 0);
mv_act.visitFieldInsn(GETFIELD, className, le.name, c(SephObject.class));
}
private void compileTerminator(Message current) {
if(current.next() != null && !(current.next() instanceof Terminator)) {
mv_act.visitInsn(POP);
mv_act.visitVarInsn(ALOAD, 3);
}
}
private void compileMessageSend(Message current) {
if(current.arguments().seq() == null) {
mv_act.visitVarInsn(ALOAD, 1);
mv_act.visitInsn(SWAP);
mv_act.visitVarInsn(ALOAD, 0);
mv_act.visitFieldInsn(GETFIELD, className, "capture", c(LexicalScope.class));
mv_act.visitInsn(SWAP);
compileInvocation(current);
} else {
throw new CompilationAborted("No support for method calls with arguments");
}
}
private void activateWithMethod() {
mv_act = cw.visitMethod(ACC_PUBLIC, "activateWith", sig(SephObject.class, SThread.class, LexicalScope.class, SephObject.class, IPersistentList.class), null, null);
mv_act.visitCode();
Message current = code;
mv_act.visitVarInsn(ALOAD, 3);
while(current != null) {
if(current.isLiteral()) {
compileLiteral(current);
} else if(current instanceof Terminator) {
compileTerminator(current);
} else {
compileMessageSend(current);
}
current = current.next();
}
mv_act.visitInsn(ARETURN);
mv_act.visitMaxs(0,0);
mv_act.visitEnd();
}
private void compileInvocation(Message code) {
mv_act.visitInvokeDynamicInsn(code.name(), sig(SephObject.class, SThread.class, LexicalScope.class, SephObject.class), basicSephBootstrap, EMPTY);
}
private Class[] getSignature() {
Class[] params = new Class[literals.length + 2];
Arrays.fill(params, SephObject.class);
params[0] = Message.class;
params[1] = LexicalScope.class;
return params;
}
private Object[] getArguments() {
Object[] args = new Object[literals.length + 2];
args[0] = code;
args[1] = capture;
for(int i = 0; i < literalsFill; i++) {
args[i+2] = literals[i].code.literal();
}
return args;
}
public static SephObject compile(Message code, LexicalScope capture) {
AbstractionCompiler c = new AbstractionCompiler(code, capture);
c.generateAbstractionClass();
return c.instantiateAbstraction();
}
public static SephObject compile(ISeq argumentsAndCode, LexicalScope capture) {
if(RT.next(argumentsAndCode) == null) { // Only compile methods that take no arguments for now
return compile((Message)RT.first(argumentsAndCode), capture);
} else {
throw new CompilationAborted("No support for compiling abstractions with arguments");
}
}
private static class LiteralEntry {
public final String name;
public final Message code;
public final int position;
public LiteralEntry(String name, Message code, int position) {
this.name = name;
this.code = code;
this.position = position;
}
}
}// AbstractionCompiler
|
package tb.common.itemblock;
import tb.common.block.BlockTBLog;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBlockTBLogs extends ItemBlock{
public ItemBlockTBLogs(Block b) {
super(b);
this.setHasSubtypes(true);
}
public String getUnlocalizedName(ItemStack stk)
{
return "tile."+BlockTBLog.names[Math.max(BlockTBLog.names.length,stk.getItemDamage()%4)];
}
public int getMetadata(int meta)
{
return meta;
}
}
|
package net.domesdaybook.parser.tree;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import net.domesdaybook.parser.ParseException;
import net.domesdaybook.util.bytes.ByteUtilities;
/**
* A utility class of static helper methods to use when parsing expressions.
*
* @author Matt Palmer
*/
public final class ParseTreeUtils {
public static final String TYPE_ERROR = "Parse tree type id [&d] with description [%s] is not supported by the parser.";
public static final String QUOTE = "\'";
private ParseTreeUtils() {
}
/**
* Returns a byte from its hexadecimal string representation.
*
* @param hexByte
* a hexadecimal representation of a byte.
* @return the byte encoded by the hex representation.
* @throws ParseException if the string cannot be parsed as a hex byte, or is null or empty.
*/
public static byte parseHexByte(final String hexByte) throws ParseException {
try {
final int value = Integer.parseInt(hexByte, 16);
if (value < 0 || value > 255) {
throw new ParseException("The hex string [" + hexByte +
"] is not a byte value between 0 and 255 inclusive: "
+ value);
}
return (byte) value;
} catch (NumberFormatException nfe) {
throw new ParseException("Could not parse into a hex byte: [" + hexByte + "]");
}
}
public static ParseTree getFirstChild(final ParseTree node) throws ParseException {
final List<ParseTree> children = node.getChildren();
if (children.size() > 0) {
return children.get(0);
}
throw new ParseException("No children exist for node type: " +
node.getParseTreeType().name());
}
public static int getFirstRangeValue(final ParseTree rangeNode) throws ParseException {
return getRangeValue(rangeNode, 0);
}
public static int getSecondRangeValue(final ParseTree rangeNode) throws ParseException {
return getRangeValue(rangeNode, 1);
}
private static int getRangeValue(final ParseTree rangeNode, final int valueIndex) throws ParseException {
final List<ParseTree> rangeChildren = rangeNode.getChildren();
if (rangeChildren.size() != 2) {
throw new ParseException("Ranges must have two integer values as child nodes." +
"Actual number of children was: " + rangeChildren.size());
}
final int rangeValue = rangeChildren.get(0).getIntValue();
if (rangeValue < 0 || rangeValue > 255) {
throw new ParseException("Range values must be between 0 and 255." +
"Actual value was: " + rangeValue);
}
return rangeValue;
}
public static int getFirstRepeatValue(final ParseTree repeatNode) throws ParseException {
return getRepeatValue(repeatNode, 0);
}
public static int getSecondRepeatValue(final ParseTree repeatNode) throws ParseException {
return getRepeatValue(repeatNode, 1);
}
public static ParseTree getNodeToRepeat(final ParseTree repeatNode) throws ParseException {
final List<ParseTree> repeatChildren = repeatNode.getChildren();
if (repeatChildren.size() != 3) {
throw new ParseException("Repeats must have three child nodes. " +
"Actual number of children was: " + repeatChildren.size());
}
return repeatChildren.get(2);
}
private static int getRepeatValue(final ParseTree repeatNode, final int valueIndex) throws ParseException {
final List<ParseTree> repeatChildren = repeatNode.getChildren();
if (repeatChildren.size() != 3) {
throw new ParseException("Repeats must have three child nodes. " +
"Actual number of children was: " +repeatChildren.size());
}
final ParseTree repeatValue = repeatChildren.get(valueIndex);
if (repeatValue.getParseTreeType() == ParseTreeType.INTEGER) {
final int intValue = repeatValue.getIntValue();
if (intValue < 1) {
throw new ParseException("Repeat integer values must be at least one. " +
"Actual value was: " + intValue);
}
return intValue;
}
return -1; //FIXME: need to test for MANY node, which doesn't exist at the moment...
// But this function should return a negative number for a many node,
// and throw a ParseException if the node isn't an integer or a many node.
}
public static Collection<Byte> getRangeValues(final ParseTree range) throws ParseException {
final int range1 = getFirstRangeValue(range);
final int range2 = getSecondRangeValue(range);
final Set<Byte> values = new LinkedHashSet<Byte>(64);
ByteUtilities.addBytesInRange(range1, range2, values);
return values;
}
public static Collection<Byte> getAllBitmaskValues(final ParseTree allBitmask) throws ParseException {
return ByteUtilities.getBytesMatchingAllBitMask(allBitmask.getByteValue());
}
public static Collection<Byte> getAnyBitmaskValues(final ParseTree anyBitmask) throws ParseException {
return ByteUtilities.getBytesMatchingAnyBitMask(anyBitmask.getByteValue());
}
public static Collection<Byte> getStringAsSet(final ParseTree string) throws ParseException {
final Set<Byte> values = new LinkedHashSet<Byte>();
try {
final byte[] utf8Value = string.getTextValue().getBytes("US-ASCII");
ByteUtilities.addAll(utf8Value, values);
return values;
} catch (UnsupportedEncodingException e) {
throw new ParseException(e);
}
}
public static Collection<Byte> getCaseInsensitiveStringAsSet(final ParseTree caseInsensitive) throws ParseException {
final Set<Byte> values = new LinkedHashSet<Byte>();
final String stringValue = caseInsensitive.getTextValue();
for (int charIndex = 0; charIndex < stringValue.length(); charIndex++) {
final char charAt = stringValue.charAt(charIndex);
if (charAt >= 'a' && charAt <= 'z') {
values.add((byte) Character.toUpperCase(charAt));
} else if (charAt >= 'A' && charAt <= 'A') {
values.add((byte) Character.toLowerCase(charAt));
}
values.add((byte) charAt);
}
return values;
}
public static Set<Byte> calculateSetValues(final ParseTree set) throws ParseException {
final Set<Byte> setValues = getSetValues(set);
if (set.isValueInverted()) {
return ByteUtilities.invertedSet(setValues);
}
return setValues;
}
/**
* Calculates a value of a set given the parent set node (or inverted set
* node) Sets can contain bytes, strings (case sensitive & insensitive),
* ranges, other sets nested inside them (both normal and inverted) and
* bitmasks.
* <p>
* This method does not invert the set bytes returned if the root set node is inverted.
* It preserves the bytes as-defined in the set, leaving the question of whether to
* invert the bytes defined in the set passed in to any clients of the code.
*
* This can be recursive procedure if sets are nested within one another.
*
* @param node
* The set node to calculate a set of byte values for.
* @return A set of byte values defined by the node.
* @throws ParseException
* If a problem occurs parsing the node.
*/
public static Set<Byte> getSetValues(final ParseTree set)
throws ParseException {
final Set<Byte> setValues = new LinkedHashSet<Byte>(192);
for (final ParseTree child : set.getChildren()) {
switch (child.getParseTreeType()) {
case SEQUENCE: // Drop through: treat all possible types of node which may hold
case ALTERNATIVES: // byte value bearing children as just containers of those values.
case SET: // The idea is you can pass any regular expression node into this
case ZERO_TO_MANY: // function, and get the set of all byte values which *could* be
case ONE_TO_MANY: // matched by that expression.
case OPTIONAL: setValues.addAll(calculateSetValues(child)); break;
case REPEAT: setValues.addAll(calculateSetValues(getNodeToRepeat(child))); break;
case BYTE: setValues.add(child.getByteValue()); break;
case RANGE: setValues.addAll(getRangeValues(child)); break;
case ALL_BITMASK: setValues.addAll(getAllBitmaskValues(child)); break;
case ANY_BITMASK: setValues.addAll(getAnyBitmaskValues(child)); break;
case STRING: setValues.addAll(getStringAsSet(child)); break;
case CASE_INSENSITIVE_STRING: setValues.addAll(getCaseInsensitiveStringAsSet(child)); break;
default: throw new ParseException(getTypeError(child));
}
}
return setValues;
}
private static String getTypeError(final ParseTree node) {
final ParseTreeType type = node.getParseTreeType();
return String.format(TYPE_ERROR, type, type.getDescription());
}
}
|
package com.bbn.bue.common.files;
import com.bbn.bue.common.StringUtils;
import com.bbn.bue.common.TextGroupImmutable;
import com.bbn.bue.common.collections.KeyValueSink;
import com.bbn.bue.common.collections.MapUtils;
import com.bbn.bue.common.io.GZIPByteSink;
import com.bbn.bue.common.io.GZIPByteSource;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.bue.common.symbols.SymbolUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.Collections2;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import com.google.common.primitives.Ints;
import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import static com.bbn.bue.common.StringUtils.startsWith;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.skip;
import static com.google.common.collect.Iterables.transform;
import static java.nio.file.Files.walkFileTree;
@Value.Enclosing
public final class FileUtils {
private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
private FileUtils() {
throw new UnsupportedOperationException();
}
/**
* Create the parent directories of the given file, if needed.
*/
public static void ensureParentDirectoryExists(File f) throws IOException {
final File parent = f.getParentFile();
if (parent != null) {
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Could not create parent directories for " + f.getAbsolutePath());
}
}
}
/**
* Takes a file with filenames listed one per line and returns a list of the corresponding File
* objects. Ignores blank lines and lines with a "#" in the first column position. Treats the
* file as UTF-8 encoded.
*/
public static ImmutableList<File> loadFileList(final File fileList) throws IOException {
return loadFileList(Files.asCharSource(fileList, Charsets.UTF_8));
}
/**
* Takes a {@link com.google.common.io.CharSource} with filenames listed one per line and returns
* a list of the corresponding File objects. Ignores blank lines and lines with a "#" in the
* first column position.
*/
public static ImmutableList<File> loadFileList(final CharSource source) throws IOException {
final ImmutableList.Builder<File> ret = ImmutableList.builder();
for (final String filename : source.readLines()) {
if (!filename.isEmpty() && !filename.startsWith("
ret.add(new File(filename.trim()));
}
}
return ret.build();
}
/**
* takes a List of fileNames and returns a list of files, ignoring any empty entries white space
* at the end of a name
*/
public static ImmutableList<File> loadFileList(final Iterable<String> fileNames)
throws IOException {
final ImmutableList.Builder<File> ret = ImmutableList.builder();
for (String filename : fileNames) {
if (!filename.isEmpty()) {
ret.add(new File(filename.trim()));
}
}
return ret.build();
}
/**
* Writes the absolutes paths of the given files in iteration order, one-per-line. Each line
* will end with a Unix newline.
*/
public static void writeFileList(Iterable<File> files, CharSink sink) throws IOException {
writeUnixLines(FluentIterable.from(files)
.transform(toAbsolutePathFunction()), sink);
}
/**
* Like {@link #loadFileList(java.io.File)}, except if the file name ends in ".gz" or ".tgz" it is
* treated as GZIP compressed. This is often convenient for loading e.g. document lists which
* benefit from being compressed for large corpora.
*/
public static ImmutableList<File> loadPossiblyCompressedFileList(File fileList)
throws IOException {
final CharSource source;
if (fileList.getName().endsWith(".gz") || fileList.getName().endsWith(".tgz")) {
source = GZIPByteSource.fromCompressed(fileList).asCharSource(Charsets.UTF_8);
} else {
source = Files.asCharSource(fileList, Charsets.UTF_8);
}
return loadFileList(source);
}
/**
* Takes a file with relative pathnames listed one per line and returns a list of the
* corresponding {@link java.io.File} objects, resolved against the provided base path using the
* {@link java.io.File#File(java.io.File, String)} constructor. Ignores blank lines and lines with
* a "#" in the first column position.
*/
public static ImmutableList<File> loadFileListRelativeTo(File fileList, File basePath)
throws IOException {
checkNotNull(basePath);
final ImmutableList.Builder<File> ret = ImmutableList.builder();
for (final String filename : Files.readLines(fileList, Charsets.UTF_8)) {
if (!filename.isEmpty() && !filename.startsWith("
ret.add(new File(basePath, filename.trim()));
}
}
return ret.build();
}
/**
* Returns another file just like the input but with a different extension. If the input file has
* an extension (a suffix beginning with "."), everything after the . is replaced with
* newExtension. Otherwise, a newExtension is appended to the filename and a new File is returned.
* Note that unless you want double .s, newExtension should not begin with a .
*/
public static File swapExtension(final File f, final String newExtension) {
checkNotNull(f);
checkNotNull(newExtension);
Preconditions.checkArgument(!f.isDirectory());
final String absolutePath = f.getAbsolutePath();
final int dotIndex = absolutePath.lastIndexOf(".");
String basePath;
if (dotIndex >= 0) {
basePath = absolutePath.substring(0, dotIndex);
} else {
basePath = absolutePath;
}
return new File(String.format("%s.%s", basePath, newExtension));
}
/**
* Derives one {@link File} from another by adding the provided extension.
* The extension will be separated from the base file name by a ".".
*/
public static File addExtension(final File f, final String extension) {
checkNotNull(f);
checkNotNull(extension);
Preconditions.checkArgument(!extension.isEmpty());
Preconditions.checkArgument(!f.isDirectory());
final String absolutePath = f.getAbsolutePath();
return new File(absolutePath + "." + extension);
}
/**
* @deprecated Prefer {@link CharSink#writeLines(Iterable, String)} or {@link
* FileUtils#writeUnixLines(Iterable, CharSink)}.
*/
@Deprecated
public static void writeLines(final File f, final Iterable<String> data, final Charset charSet)
throws IOException {
final FileOutputStream fin = new FileOutputStream(f);
final BufferedOutputStream bout = new BufferedOutputStream(fin);
final PrintStream out = new PrintStream(bout);
boolean threw = true;
try {
for (final String s : data) {
out.println(s);
}
threw = false;
} finally {
Closeables.close(out, threw);
}
}
public static ImmutableMap<Symbol, File> loadSymbolToFileMap(
final File f) throws IOException {
return loadSymbolToFileMap(Files.asCharSource(f, Charsets.UTF_8));
}
public static ImmutableMap<Symbol, File> loadSymbolToFileMap(
final CharSource source) throws IOException {
return loadMap(source, SymbolUtils.symbolizeFunction(), FileFunction.INSTANCE);
}
public static ImmutableListMultimap<Symbol, File> loadSymbolToFileListMultimap(
final CharSource source) throws IOException {
return loadMultimap(source, SymbolUtils.symbolizeFunction(), FileFunction.INSTANCE);
}
/**
* Writes a map from symbols to file absolute paths to a file. Each line has a mapping with the key and value
* separated by a single tab. The file will have a trailing newline.
*/
public static void writeSymbolToFileMap(Map<Symbol, File> symbolToFileMap, CharSink sink) throws IOException {
writeSymbolToFileEntries(symbolToFileMap.entrySet(), sink);
}
private static final Function<Map.Entry<Symbol, String>, String>
TO_TAB_SEPARATED_ENTRY = MapUtils.toStringWithKeyValueSeparator("\t");
/**
* Writes map entries from symbols to file absolute paths to a file. Each line has a mapping with
* the key and value separated by a single tab. The file will have a trailing newline. Note that
* the same "key" may appear in the file with multiple mappings.
*/
public static void writeSymbolToFileEntries(final Iterable<Map.Entry<Symbol, File>> entries,
final CharSink sink) throws IOException {
writeUnixLines(
transform(
MapUtils.transformValues(entries, toAbsolutePathFunction()),
TO_TAB_SEPARATED_ENTRY),
sink);
}
public static Map<Symbol, CharSource> loadSymbolToFileCharSourceMap(CharSource source)
throws IOException {
return Maps.transformValues(loadSymbolToFileMap(source),
FileUtils.asUTF8CharSourceFunction());
}
public static Map<String, File> loadStringToFileMap(final File f) throws IOException {
return loadStringToFileMap(Files.asCharSource(f, Charsets.UTF_8));
}
public static Map<String, File> loadStringToFileMap(final CharSource source) throws IOException {
return loadMap(source, Functions.<String>identity(), FileFunction.INSTANCE);
}
public static ImmutableListMultimap<String, File> loadStringToFileListMultimap(
final CharSource source) throws IOException {
return loadMultimap(source, Functions.<String>identity(), FileFunction.INSTANCE);
}
public static <K, V> ImmutableMap<K, V> loadMap(final CharSource source,
final Function<String, K> keyFunction, final Function<String, V> valueFunction)
throws IOException {
final ImmutableMap.Builder<K, V> ret = ImmutableMap.builder();
loadMapToSink(source, MapUtils.asMapSink(ret), keyFunction, valueFunction);
return ret.build();
}
public static <K, V> ImmutableMap<K, V> loadMap(final File file,
final Function<String, K> keyFunction, final Function<String, V> valueFunction)
throws IOException {
return loadMap(Files.asCharSource(file, Charsets.UTF_8), keyFunction, valueFunction);
}
public static <K, V> ImmutableListMultimap<K, V> loadMultimap(final CharSource source,
final Function<String, K> keyFunction, final Function<String, V> valueFunction)
throws IOException {
final ImmutableListMultimap.Builder<K, V> ret = ImmutableListMultimap.builder();
loadMapToSink(source, MapUtils.asMapSink(ret), keyFunction, valueFunction);
return ret.build();
}
public static <K, V> ImmutableListMultimap<K, V> loadMultimap(final File file,
final Function<String, K> keyFunction, final Function<String, V> valueFunction)
throws IOException {
return loadMultimap(Files.asCharSource(file, Charsets.UTF_8), keyFunction, valueFunction);
}
private static <K, V> void loadMapToSink(final CharSource source,
final KeyValueSink<K, V> mapSink, final Function<String, K> keyFunction,
final Function<String, V> valueFunction)
throws IOException {
// Using a LineProcessor saves memory by not loading the whole file into memory. This can matter
// for multi-gigabyte Gigaword-scale maps.
final MapLineProcessor<K, V> processor =
new MapLineProcessor<>(mapSink, keyFunction, valueFunction, Splitter.on("\t").trimResults());
source.readLines(processor);
}
/**
* Writes a single integer to the beginning of a file, overwriting what was there originally but
* leaving the rest of the file intact. This is useful when you are writing a long binary file
* with a size header, but don't know how many elements are there until the end.
*/
public static void writeIntegerToStart(final File f, final int num) throws IOException {
final RandomAccessFile fixupFile = new RandomAccessFile(f, "rw");
fixupFile.writeInt(num);
fixupFile.close();
}
public static int[] loadBinaryIntArray(final ByteSource inSup,
final boolean compressed) throws IOException {
InputStream in = inSup.openStream();
if (compressed) {
try {
in = new GZIPInputStream(in);
} catch (final IOException e) {
in.close();
throw e;
}
}
final DataInputStream dis = new DataInputStream(in);
try {
final int size = dis.readInt();
final int[] ret = new int[size];
for (int i = 0; i < size; ++i) {
ret[i] = dis.readInt();
}
return ret;
} finally {
dis.close();
}
}
public static int[] loadTextIntArray(final File f) throws NumberFormatException, IOException {
final List<Integer> ret = Lists.newArrayList();
for (final String line : Files.readLines(f, Charsets.UTF_8)) {
ret.add(Integer.parseInt(line));
}
return Ints.toArray(ret);
}
public static void writeBinaryIntArray(final int[] arr,
final ByteSink outSup) throws IOException {
final OutputStream out = outSup.openBufferedStream();
final DataOutputStream dos = new DataOutputStream(out);
try {
dos.writeInt(arr.length);
for (final int x : arr) {
dos.writeInt(x);
}
} finally {
dos.close();
}
}
public static void backup(final File f) throws IOException {
new BackupRequest.Builder()
.fileToBackup(f)
.build().doBackup();
}
public static void backup(final File f, final String extension) throws IOException {
new BackupRequest.Builder()
.fileToBackup(f)
.extension(extension)
.build().doBackup();;
}
/**
* A request to backup a file. This request is executed by calling {@link #doBackup()}.
*/
@TextGroupImmutable
@Value.Immutable
public static abstract class BackupRequest {
public abstract File fileToBackup();
/**
* The name of the type of object being backed up (e.g. "geonames database"). If this is
* provided, a message is logged.
*/
public abstract Optional<String> nameOfThingToBackup();
/**
* The logger to write a log message to. If not specified, defaults to the logger of
* {@link FileUtils}
*/
@Value.Default
public Logger logger() {
return FileUtils.log;
}
/**
* The extension to append to the backup file. A "." is automatically inserted. Defaults to "bak"
*/
@Value.Default
public String extension() {
return "bak";
}
/**
* Whether to delete the file being backed up.
*/
@Value.Default
public boolean deleteOriginal() {
return false;
}
@Value.Check
protected void check() {
checkArgument(!extension().isEmpty(), "Backup extension may not be empty");
}
/**
* Execute the backup request.
*/
public final void doBackup() throws IOException {
if (fileToBackup().isFile()) {
final File backupFile = addExtension(fileToBackup(), extension());
final String operationMessage;
if (deleteOriginal()) {
operationMessage = "Moved";
java.nio.file.Files.move(fileToBackup().toPath(),
backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
operationMessage = "Copied";
java.nio.file.Files.copy(fileToBackup().toPath(),
backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
if (nameOfThingToBackup().isPresent()) {
logger().info("{} existing {} from {} to {}", operationMessage, nameOfThingToBackup().get(),
fileToBackup().getAbsolutePath(), backupFile.getAbsolutePath());
}
}
}
public static class Builder extends ImmutableFileUtils.BackupRequest.Builder {}
}
/**
* Given a file, returns a File representing a sibling directory with the specified name.
*
* @param f If f is the filesystem root, a runtime exeption will be thrown.
* @param siblingDirName The non-empty name of the sibling directory.
*/
public static File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName);
} else {
throw new RuntimeException(String
.format("Cannot create sibling directory %s of %s because the latter has no parent.",
siblingDirName, f));
}
}
public static BufferedReader optionallyCompressedBufferedReader(final File f,
final boolean compressed) throws IOException {
InputStream stream = new BufferedInputStream(new FileInputStream(f));
if (compressed) {
try {
stream = new GZIPInputStream(stream);
} catch (final IOException e) {
stream.close();
throw e;
}
}
return new BufferedReader(new InputStreamReader(stream));
}
public static ImmutableList<Symbol> loadSymbolList(final File symbolListFile) throws IOException {
return loadSymbolList(Files.asCharSource(symbolListFile, Charsets.UTF_8));
}
/**
* Loads a list of {@link Symbol}s from a file, one-per-line, skipping lines starting with "#" as
* comments.
*/
public static ImmutableList<Symbol> loadSymbolList(final CharSource source) throws IOException {
return SymbolUtils.listFrom(loadStringList(source));
}
/**
* @deprecated Prefer {@link #toNameFunction()}
*/
@Deprecated
public static final Function<File, String> ToName = ToNameEnum.INSTANCE;
public static Function<File, String> toNameFunction() {
return ToNameEnum.INSTANCE;
}
private enum ToNameEnum implements Function<File, String> {
INSTANCE;
@Override
public String apply(final File f) {
return f.getName();
}
}
public static final Function<File, String> toAbsolutePathFunction() {
return ToAbsolutePathFunction.INSTANCE;
}
private enum ToAbsolutePathFunction implements Function<File, String> {
INSTANCE;
@Override
public String apply(final File input) {
return input.getAbsolutePath();
}
}
public static boolean isEmptyDirectory(final File directory) {
if (directory.exists() && directory.isDirectory()) {
return directory.listFiles().length == 0;
}
return false;
}
/**
* Make a predicate to test files for ending with the specified suffix.
*
* @param suffix May not be null or empty.
*/
public static Predicate<File> EndsWith(final String suffix) {
checkArgument(!suffix.isEmpty());
return new Predicate<File>() {
@Override
public boolean apply(final File f) {
return f.getName().endsWith(suffix);
}
};
}
/**
* Loads a file in the format {@code key value1 value2 value3} (tab-separated) into a {@link
* com.google.common.collect.Multimap} of {@code String} to {@code String}. Each key should only
* appear on one line, and there should be no duplicate values. Each key and value has whitespace
* trimmed off. Skips empty lines and allows comment-lines with {@code #} in the first position.
* If a key has no values, it will not show up in the keySet of the returned multimap.
*/
public static ImmutableMultimap<String, String> loadStringMultimap(CharSource multimapSource)
throws IOException {
final ImmutableMultimap.Builder<String, String> ret = ImmutableMultimap.builder();
int count = 0;
for (final String line : multimapSource.readLines()) {
++count;
if (line.startsWith("
continue;
}
final List<String> parts = multimapSplitter.splitToList(line);
if (parts.isEmpty()) {
continue;
}
ret.putAll(parts.get(0), skip(parts, 1));
}
return ret.build();
}
/**
* Deprecated in favor of version with {@link com.google.common.io.CharSource} argument.
*
* @deprecated
*/
@Deprecated
public static ImmutableMultimap<String, String> loadStringMultimap(File multimapFile)
throws IOException {
return loadStringMultimap(Files.asCharSource(multimapFile, Charsets.UTF_8));
}
/**
* Deprecated in favor of the CharSource version to force the user to define their encoding. If
* you call this, it will use UTF_8 encoding.
*
* @deprecated
*/
@Deprecated
public static ImmutableMultimap<Symbol, Symbol> loadSymbolMultimap(File multimapFile)
throws IOException {
return loadSymbolMultimap(Files.asCharSource(multimapFile, Charsets.UTF_8));
}
/**
* Loads a file in the format {@code key value1 value2 value3} (tab-separated) into a {@link
* com.google.common.collect.Multimap} of {@link com.bbn.bue.common.symbols.Symbol} to Symbol.
* Each key should only appear on one line, and there should be no duplicate values. Each key and
* value has whitespace trimmed off. Skips empty lines and allows comment-lines with {@code #} in
* the first position. If a key has no values, it will not show up in the keySet of the returned
* multimap.
*/
public static ImmutableMultimap<Symbol, Symbol> loadSymbolMultimap(CharSource multimapSource)
throws IOException {
final ImmutableMultimap<String, String> stringMM = loadStringMultimap(multimapSource);
final ImmutableMultimap.Builder<Symbol, Symbol> ret = ImmutableMultimap.builder();
for (final Map.Entry<String, Collection<String>> entry : stringMM.asMap().entrySet()) {
ret.putAll(Symbol.from(entry.getKey()),
Collections2.transform(entry.getValue(), Symbol.FromString));
}
return ret.build();
}
private static final Splitter MAP_SPLITTER =
Splitter.on("\t").trimResults().omitEmptyStrings().limit(2);
/**
* Loads a file in the format {@code key value1} (tab-separated) into a {@link
* com.google.common.collect.ImmutableMap} of {@link String}s. Each key should only appear on one
* line, and there should be no duplicate values. Each key and value has whitespace trimmed off.
* Skips empty lines and allows comment-lines with {@code #} in the first position.
*/
public static ImmutableMap<String, String> loadStringMap(CharSource source) throws IOException {
return loadStringMap(source, false);
}
/**
* Like {@link #loadStringMap(CharSource)}, but differs in that lines can contain only
* a key and no value and will be treated as having a value of empty string in the resulting
* map. This is useful for specifying absent values for a specific key.
*
* @see FileUtils#loadStringMap(CharSource)
*/
public static ImmutableMap<String, String> loadStringMapAllowingEmptyValues(CharSource source)
throws IOException {
return loadStringMap(source, true);
}
private static ImmutableMap<String, String> loadStringMap(CharSource source,
final boolean allowEmptyValues) throws IOException {
final ImmutableMap.Builder<String, String> ret = ImmutableMap.builder();
int count = 0;
for (final String line : source.readLines()) {
++count;
if (line.startsWith("
continue;
}
final List<String> parts = MAP_SPLITTER.splitToList(line);
if (parts.isEmpty()) {
continue;
}
if (parts.size() == 2) {
ret.put(parts.get(0), parts.get(1));
} else if (allowEmptyValues && parts.size() == 1) {
ret.put(parts.get(0), "");
} else {
throw new RuntimeException(
"When reading a map from " + source + ", line " + count + " is invalid: "
+ line);
}
}
return ret.build();
}
/**
* Loads a file in the format {@code key value1} (tab-separated) into a {@link
* com.google.common.collect.ImmutableMap} of {@link String}s. Each key should only appear on one
* line, and there should be no duplicate values. Each key and value has whitespace trimmed off.
* Skips empty lines and allows comment-lines with {@code #} in the first position.
*/
public static ImmutableMap<Symbol, Symbol> loadSymbolMap(CharSource source) throws IOException {
final ImmutableMap.Builder<Symbol, Symbol> ret = ImmutableMap.builder();
for (ImmutableMap.Entry<String, String> row : loadStringMap(source).entrySet()) {
ret.put(Symbol.from(row.getKey()), Symbol.from(row.getValue()));
}
return ret.build();
}
public static void writeSymbolMultimap(Multimap<Symbol, Symbol> mm, CharSink charSink)
throws IOException {
final Joiner tabJoiner = Joiner.on('\t');
writeUnixLines(transform(mm.asMap().entrySet(),
new Function<Map.Entry<Symbol, Collection<Symbol>>, String>() {
@Override
public String apply(Map.Entry<Symbol, Collection<Symbol>> input) {
return input.getKey() + "\t" + tabJoiner.join(input.getValue());
}
}), charSink);
}
public static ImmutableTable<Symbol, Symbol, Symbol> loadSymbolTable(CharSource input)
throws IOException {
final ImmutableTable.Builder<Symbol, Symbol, Symbol> ret = ImmutableTable.builder();
int lineNo = 0;
for (final String line : input.readLines()) {
final List<String> parts = StringUtils.onTabs().splitToList(line);
if (parts.size() != 3) {
throw new IOException(String.format("Invalid line %d when reading symbol table: %s",
lineNo, line));
}
ret.put(Symbol.from(parts.get(0)), Symbol.from(parts.get(1)), Symbol.from(parts.get(2)));
++lineNo;
}
return ret.build();
}
private static final Splitter multimapSplitter =
Splitter.on("\t").trimResults().omitEmptyStrings();
private enum AsUTF8CharSource implements Function<File, CharSource> {
INSTANCE;
public CharSource apply(File f) {
return Files.asCharSource(f, Charsets.UTF_8);
}
}
/**
* Transforms a file to a {@link com.google.common.io.CharSource} with UTF-8 encoding.
*/
public static Function<File, CharSource> asUTF8CharSourceFunction() {
return AsUTF8CharSource.INSTANCE;
}
/**
* Throws an {@link java.io.IOException} if the supplied directory either does not exist or is not
* a directory.
*/
public static void assertDirectoryExists(File directory) throws IOException {
if (!directory.isDirectory()) {
throw new IOException(directory + " does not exist or is not a directory");
}
}
/**
* Just like {@link Files#asByteSource(java.io.File)}, but decompresses the incoming data using
* GZIP.
*/
public static ByteSource asCompressedByteSource(File f) throws IOException {
return GZIPByteSource.fromCompressed(Files.asByteSource(f));
}
/**
* Just like {@link Files#asByteSink(java.io.File, com.google.common.io.FileWriteMode...)}, but
* decompresses the incoming data using GZIP.
*/
public static ByteSink asCompressedByteSink(File f) throws IOException {
return GZIPByteSink.gzipCompress(Files.asByteSink(f));
}
/**
* Just like {@link Files#asCharSource(java.io.File, java.nio.charset.Charset)}, but decompresses
* the incoming data using GZIP.
*/
public static CharSource asCompressedCharSource(File f, Charset charSet) throws IOException {
return asCompressedByteSource(f).asCharSource(charSet);
}
/**
* Just like {@link Files#asCharSink(java.io.File, java.nio.charset.Charset,
* com.google.common.io.FileWriteMode...)}, but decompresses the incoming data using GZIP.
*/
public static CharSink asCompressedCharSink(File f, Charset charSet) throws IOException {
return asCompressedByteSink(f).asCharSink(charSet);
}
// Guava predicates and functions
public static Predicate<File> isDirectoryPredicate() {
return new Predicate<File>() {
@Override
public boolean apply(final File input) {
return input.isDirectory();
}
};
}
/**
* wraps any IOException and throws a RuntimeException
*/
public static Function<File, Iterable<String>> toLinesFunction(final Charset charset) {
return new Function<File, Iterable<String>>() {
@Override
public Iterable<String> apply(final File input) {
try {
return Files.readLines(input, charset);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
};
}
/**
* Loads a list of {@link Symbol}s from a file, one-per-line, skipping lines starting with "#"
* as comments.
*/
public static ImmutableSet<Symbol> loadSymbolSet(final CharSource source) throws IOException {
return ImmutableSet.copyOf(loadSymbolList(source));
}
/**
* Returns a {@link List} consisting of the lines of the provided {@link CharSource} in the
* order given.
*/
public static ImmutableList<String> loadStringList(final CharSource source) throws IOException {
return FluentIterable.from(source.readLines())
.filter(not(startsWith("
.toList();
}
/**
* Loads a list of {@link String}s from a file, one-per-line, skipping lines starting with "#"
* as comments.
*/
public static ImmutableSet<String> loadStringSet(final CharSource source) throws IOException {
return ImmutableSet.copyOf(loadStringList(source));
}
/**
* Recursively delete this directory and all its contents.
*/
public static void recursivelyDeleteDirectory(File directory) throws IOException {
if (!directory.exists()) {
return;
}
checkArgument(directory.isDirectory(), "Cannot recursively delete a non-directory");
walkFileTree(directory.toPath(), new DeletionFileVisitor());
}
private static class DeletionFileVisitor implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
throws IOException {
java.nio.file.Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
throws IOException {
java.nio.file.Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
/**
* Calls {@link #recursivelyDeleteDirectory(File)} on JVM exit.
*/
public static void recursivelyDeleteDirectoryOnExit(final File directory) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
recursivelyDeleteDirectory(directory);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Recursively copies a directory.
*
* @param sourceDir the source directory
* @param destDir the destination directory, which does not need to already exist
* @param copyOption options to be used for copying files
*/
public static void recursivelyCopyDirectory(final File sourceDir, final File destDir,
final StandardCopyOption copyOption)
throws IOException {
checkNotNull(sourceDir);
checkNotNull(destDir);
checkArgument(sourceDir.isDirectory(), "Source directory does not exist");
destDir.mkdirs();
walkFileTree(sourceDir.toPath(), new CopyFileVisitor(sourceDir.toPath(), destDir.toPath(),
copyOption));
}
private static class CopyFileVisitor implements FileVisitor<Path> {
private final Path sourcePath;
private final Path destPath;
private final StandardCopyOption copyOption;
private CopyFileVisitor(Path sourcePath, Path destPath, final StandardCopyOption copyOption) {
this.sourcePath = checkNotNull(sourcePath);
this.destPath = checkNotNull(destPath);
this.copyOption = checkNotNull(copyOption);
}
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
throws IOException {
final Path newPath = destPath.resolve(sourcePath.relativize(dir));
if (!java.nio.file.Files.exists(newPath)) {
java.nio.file.Files.createDirectory(newPath);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
throws IOException {
final Path newPath = destPath.resolve(sourcePath.relativize(file));
java.nio.file.Files.copy(file, newPath, copyOption);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException exc)
throws IOException {
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
}
/**
* @deprecated See {@link #toAbsolutePathFunction()}.
*/
@Deprecated
public static final Function<File, String> ToAbsolutePath = new Function<File, String>() {
@Override
public String apply(final File f) {
return f.getAbsolutePath();
}
};
/**
* Generally we want to avoid {@link CharSink#writeLines(Iterable)} because it uses the OS default
* line separator, but our code always works with Unix line endings regardless of platform. This
* is just like {@link CharSink#writeLines(Iterable)}, but always uses Unix endings.
*/
public static void writeUnixLines(Iterable<? extends CharSequence> lines, CharSink sink)
throws IOException {
sink.writeLines(lines, "\n");
}
/**
* Creates a {@link File} from a {@link String} using the {@link File} constructor.
*/
public Function<String, File> asFileFunction() {
return FileFunction.INSTANCE;
}
private enum FileFunction implements Function<String, File> {
INSTANCE;
@Override
public File apply(final String input) {
return new File(checkNotNull(input));
}
}
private static class MapLineProcessor<K, V> implements LineProcessor<Void> {
private int lineNo;
private final KeyValueSink<K, V> mapSink;
private final Function<String, K> keyFunction;
private final Function<String, V> valueFunction;
private final Splitter splitter;
private MapLineProcessor(final KeyValueSink<K, V> mapSink,
final Function<String, K> keyFunction, final Function<String, V> valueFunction,
final Splitter splitter) {
this.mapSink = checkNotNull(mapSink);
this.keyFunction = checkNotNull(keyFunction);
this.valueFunction = checkNotNull(valueFunction);
this.splitter = checkNotNull(splitter);
}
@Override
public boolean processLine(final String line) throws IOException {
++lineNo;
if (line.isEmpty()) {
// Skip this line and go to the next one
return true;
}
final Iterator<String> parts = splitter.split(line).iterator();
final String key;
final String value;
boolean good = true;
if (parts.hasNext()) {
key = parts.next();
} else {
key = null;
good = false;
}
if (parts.hasNext()) {
value = parts.next();
} else {
value = null;
good = false;
}
if (!good || parts.hasNext()) {
throw new RuntimeException(String.format("Corrupt line #%d: %s", lineNo, line));
}
try {
mapSink.put(keyFunction.apply(key), valueFunction.apply(value));
} catch (IllegalArgumentException iae) {
throw new IOException(String.format("Error processing line %d of file map: %s",
lineNo, line), iae);
}
// all lines should be processed
return true;
}
@Override
public Void getResult() {
// We don't produce a result; we just write to mapSink as a side-effect
return null;
}
}
}
|
package nl.fotnys.epic.core.triggers;
/**
*
* @author Jan Kerkenhoff <jan.kerkenhoff@gmail.com>
*/
public interface TriggerManager {
<Type extends Trigger> void register(Class<Type> triggerClass);
<Type extends Trigger> void unregister(Class<Type> triggerClass);
void handle(Triggerable t) throws TriggerException;
}
|
package opendap.semantics.IRISail;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.*;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Vector;
public class RepositoryUtility {
private static Logger log = LoggerFactory.getLogger(RepositoryUtility.class);
public static final String internalStartingPoint = "http://iridl.ldeo.columbia.edu/ontologies/rdfcache.owl";
public static final String rdfCacheNamespace = internalStartingPoint+"
public static void dropStartingPoints(SailRepository repo, Vector<String> startingPointUrls) {
RepositoryConnection con = null;
ValueFactory valueFactory;
try {
con = repo.getConnection();
valueFactory = repo.getValueFactory();
RepositoryUtility.dropStartingPoints(con, valueFactory, startingPointUrls);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
}
/**
* Set addStartingPoints statement for the importURI in the repository.
*
*/
public static void dropStartingPoints(RepositoryConnection con, ValueFactory valueFactory, Vector<String> startingPointUrls) {
String pred = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
URI startingPointValue = null;
URI isa = valueFactory.createURI(pred);
URI context = valueFactory.createURI(rdfCacheNamespace+"startingPoints");
URI startingPointType = valueFactory.createURI(rdfCacheNamespace+"StartingPoint");
URL url;
try {
for (String importURL : startingPointUrls) {
url = new URL(importURL);
startingPointValue = valueFactory.createURI(importURL);
con.remove((Resource) startingPointValue, isa, (Value) startingPointType, (Resource) context);
log.info("Removed starting point " + importURL + " from the repository. (N-Triple: <" + startingPointValue + "> <" + isa
+ "> " + "<" + startingPointType + "> " + "<" + context + "> )");
}
} catch (RepositoryException e) {
log.error("In addStartingPoints, caught an RepositoryException! Msg: "
+ e.getMessage());
} catch (MalformedURLException e) {
log.error("In addStartingPoints, caught an MalformedURLException! Msg: "
+ e.getMessage());
//} catch (RDFParseException e) {
// log.error("In addStartingPoints, caught an RDFParseException! Msg: "
// + e.getMessage());
} catch (IOException e) {
log.error("In addStartingPoints, caught an IOException! Msg: "
+ e.getMessage());
}
}
public static void addStartingPoints(SailRepository repo, Vector<String> startingPointUrls) {
RepositoryConnection con = null;
ValueFactory valueFactory;
try {
con = repo.getConnection();
valueFactory = repo.getValueFactory();
addStartingPoints(con, valueFactory, startingPointUrls);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
}
/**
* Adds the passed list of starting points to the repository.
*
*
* @param con
* @param startingPointUrls
*/
public static void addStartingPoints(RepositoryConnection con, ValueFactory valueFactory, Vector<String> startingPointUrls) {
for (String importURL : startingPointUrls) {
addStartingPoint(con, valueFactory, importURL);
}
}
private static boolean startingPointExists( RepositoryConnection con, String staringPointUrl){
return false;
}
private static void addInternalStartingPoint(RepositoryConnection con, ValueFactory valueFactory){
if(!startingPointExists(con,internalStartingPoint)){
addStartingPoint(con, valueFactory, internalStartingPoint);
}
}
public static void addStartingPoint(SailRepository repo, String startingPointUrl) {
RepositoryConnection con = null;
ValueFactory valueFactory;
try {
con = repo.getConnection();
valueFactory = repo.getValueFactory();
addStartingPoint(con, valueFactory, startingPointUrl);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
}
/**
* Adds the passed starting point to the repository.
*
* @param con
* @param importURL
*/
public static void addStartingPoint(RepositoryConnection con, ValueFactory valueFactory, String importURL) {
String pred = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
URI s = valueFactory.createURI(importURL);
URI isa = valueFactory.createURI(pred);
URI cont = valueFactory.createURI("http://iridl.ldeo.columbia.edu/ontologies/rdfcache.owl#startingPoints");
URI o = valueFactory.createURI("http://iridl.ldeo.columbia.edu/ontologies/rdfcache.owl#StartingPoint");
URL url;
try {
addInternalStartingPoint(con, valueFactory);
if (importURL.startsWith("http://")) { //make sure an url and read it in
url = new URL(importURL);
s = valueFactory.createURI(importURL);
con.add((Resource) s, isa, (Value) o, (Resource) cont);
log.info("Added to the repository <" + s + "> <" + isa
+ "> " + "<" + o + "> " + "<" + cont + "> ");
}
} catch (RepositoryException e) {
log.error("In addStartingPoints, caught an RepositoryException! Msg: "
+ e.getMessage());
} catch (MalformedURLException e) {
log.error("In addStartingPoints, caught an MalformedURLException! Msg: "
+ e.getMessage());
//} catch (RDFParseException e) {
// log.error("In addStartingPoints, caught an RDFParseException! Msg: "
// + e.getMessage());
} catch (IOException e) {
log.error("In addStartingPoints, caught an IOException! Msg: "
+ e.getMessage());
}
}
public static Vector<String> findChangedStartingPoints(SailRepository repo, Vector<String> startingPointUrls) {
RepositoryConnection con = null;
try {
con = repo.getConnection();
return findChangedStartingPoints(con, startingPointUrls);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
return new Vector<String>();
}
/*
* Add the old StartingPoint that is no longer a StartingPoint in this
* update to the drop-list
*/
public static Vector<String> findChangedStartingPoints(RepositoryConnection con, Vector<String> startingPointsUrls) {
Vector<String> result = null;
Vector<String> changedStartingPoints = new Vector<String> ();
log.debug("Checking if the old StartingPoint is still a StartingPoint ...");
try {
result = findAllStartingPoints(con);
for (String startpoint : result) {
//log.debug("StartingPoints: " + startpoint);
if (!startingPointsUrls.contains(startpoint)
&& !startpoint.equals(RepositoryUtility.internalStartingPoint)) {
changedStartingPoints.add(startpoint);
log.debug("Adding to droplist: " + startpoint);
}
}
} catch (QueryEvaluationException e) {
log.error("Caught an QueryEvaluationException! Msg: "
+ e.getMessage());
} catch (RepositoryException e) {
log.error("Caught RepositoryException! Msg: " + e.getMessage());
} catch (MalformedQueryException e) {
log.error("Caught MalformedQueryException! Msg: " + e.getMessage());
}
log.info("Located " + changedStartingPoints.size()+" starting points that have been changed.");
return changedStartingPoints;
}
public static Vector<String> findNewStartingPoints(SailRepository repo, Vector<String> startingPointUrls) {
RepositoryConnection con = null;
try {
con = repo.getConnection();
return findNewStartingPoints(con, startingPointUrls);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
return new Vector<String>();
}
/*
* Find new StartingPoints in the input file but not in the repository yet
*
*/
public static Vector<String> findNewStartingPoints(RepositoryConnection con, Vector<String> startingPointUrls) {
Vector<String> result = null;
Vector<String> newStartingPoints = new Vector<String> ();
log.debug("Checking for new starting points...");
try {
result = findAllStartingPoints(con);
for (String startpoint : startingPointUrls) {
//log.debug("StartingPoints: " + startpoint);
if (!result.contains(startpoint)
&& !startpoint.equals(RepositoryUtility.internalStartingPoint)) {
newStartingPoints.add(startpoint);
log.debug("Adding to New StartingPints list: " + startpoint);
}
}
} catch (QueryEvaluationException e) {
log.error("Caught an QueryEvaluationException! Msg: "
+ e.getMessage());
} catch (RepositoryException e) {
log.error("Caught RepositoryException! Msg: " + e.getMessage());
} catch (MalformedQueryException e) {
log.error("Caught MalformedQueryException! Msg: " + e.getMessage());
}
log.info("Number of new StartingPoints: " + newStartingPoints.size());
return newStartingPoints;
}
public static Vector<String> findAllStartingPoints(SailRepository repo) throws MalformedQueryException, QueryEvaluationException {
RepositoryConnection con = null;
try {
con = repo.getConnection();
return findAllStartingPoints(con);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
return new Vector<String>();
}
/*
* Find all starting points in the repository
*
*/
public static Vector<String> findAllStartingPoints(RepositoryConnection con) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
Vector<String> startingPoints = new Vector <String> ();
TupleQueryResult result = queryForStartingPoints(con);
if (result != null) {
if (!result.hasNext()) {
log.debug("NEW repository!");
}
while (result.hasNext()) {
BindingSet bindingSet = (BindingSet) result.next();
Value firstValue = bindingSet.getValue("doc");
String startpoint = firstValue.stringValue();
//log.debug("StartingPoints: " + startpoint);
if (!startpoint.equals(RepositoryUtility.internalStartingPoint)) {
startingPoints.add(startpoint);
//log.debug("Starting point in the repository: " + startpoint);
}
}
} else {
log.debug("No query result!");
}
return startingPoints;
}
public static boolean isNewRepository(SailRepository repo) {
RepositoryConnection con = null;
try {
con = repo.getConnection();
return isNewRepository(con);
}
catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to open repository connection. Msg: "
+ e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
return true;
}
public static boolean isNewRepository(RepositoryConnection con){
try{
TupleQueryResult result = queryForStartingPoints(con);
if (result != null && !result.hasNext()) {
return true;
}
} catch (RepositoryException e) {
log.error("Caught RepositoryException! Msg: " + e.getMessage());
} catch (QueryEvaluationException e) {
log.error("Caught QueryEvaluationException! Msg: " + e.getMessage());
} catch (MalformedQueryException e) {
log.error("Caught MalformedQueryException! Msg: " + e.getMessage());
}
return false;
}
private static TupleQueryResult queryForStartingPoints(RepositoryConnection con) throws QueryEvaluationException, MalformedQueryException, RepositoryException {
TupleQueryResult result = null;
List<String> bindingNames;
Vector<String> startingPoints = new Vector <String> ();
log.debug("Finding StartingPoints in the repository ...");
String queryString = "SELECT doc "
+ "FROM {doc} rdf:type {rdfcache:StartingPoint} "
+ "USING NAMESPACE "
+ "rdfcache = <"+ RepositoryUtility.rdfCacheNamespace+">";
log.debug("queryStartingPoints: " + queryString);
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,queryString);
result = tupleQuery.evaluate();
return result;
}
}
|
package org.aikodi.chameleon.core.document;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.element.ElementImpl;
import org.aikodi.chameleon.core.language.Language;
import org.aikodi.chameleon.core.lookup.LookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.namespacedeclaration.NamespaceDeclaration;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.exception.ChameleonProgrammerException;
import org.aikodi.chameleon.util.association.Multi;
import org.aikodi.chameleon.workspace.DocumentLoader;
import org.aikodi.chameleon.workspace.FakeDocumentLoader;
import org.aikodi.chameleon.workspace.FakeDocumentScanner;
import org.aikodi.chameleon.workspace.ProjectException;
import org.aikodi.chameleon.workspace.View;
import org.aikodi.contract.Contracts;
import be.kuleuven.cs.distrinet.rejuse.association.SingleAssociation;
/**
* <p>
* A document represents an artefact in which elements of the program/model are
* defined. This will often correspond to a file.
* </p>
*
* <p>
* A document does not directly contain the source code elements. It contains
* the namespace declarations ({@link NamespaceDeclaration}) that contain the
* elements and associate them with a namespace. Namespace declarations can be
* nested. If a language does not explicitly mention a general namespace (such
* as Eiffel), a namespace declaration should be used that puts its contents in
* the root namespace.
* </p>
*
* <p>
* Each document is linked to the {@link DocumentLoader} that is responsible for
* populating the document. The document only connects itself to a project after
* invoking ({@link #activate()})! This should be done automatically by the
* {@link DocumentLoader} when a document is loaded by the lookup mechanism and
* when it is reparsed.
* </p>
*
* @author Marko van Dooren
*/
public class Document extends ElementImpl {
// private CreationStackTrace _trace = new CreationStackTrace();
/**
* Create a new empty document. The document is not activated.
*/
/*@
@ public behavior
@
@ post children().isEmpty();
@*/
public Document() {
}
/**
* Create a new compilation unit with the given namespace declaration. The
* document is not activated.
*
* @param namespaceDeclaration
* The namespace declaration that is added.
*/
/*@
@ public behavior
@
@ post children().size() == 1;
@ post children().contains(namespaceDeclaration);
@*/
public Document(NamespaceDeclaration namespaceDeclaration) {
add(namespaceDeclaration);
}
/**
* Activate this document by letting all child namespace declarations activate
* themselves. This adds the contents of this document to the logical
* namespace structure of the project.
*/
public void activate() {
for (NamespaceDeclaration part : namespaceDeclarations()) {
part.activate();
}
}
/**
* Return the namespace declarations in this document.
*/
public List<NamespaceDeclaration> namespaceDeclarations() {
return _subNamespaceParts.getOtherEnds();
}
/**
* @param index
* @return
*/
public NamespaceDeclaration namespaceDeclaration(int index) {
return _subNamespaceParts.elementAt(index);
}
/**
* Add the given namespace declaration to this document.
*
* @param namespaceDeclaration
* The namespace declaration to be added.
*/
/*@
@ public behavior
@
@ ! \old(namespaceDeclarations().contains(namespaceDeclaration)) ==>
@ namespaceDeclaration(namespaceDeclarations().size()) == namespaceDeclaration;
@ ! \old(namespaceDeclarations().contains(namespaceDeclaration) ==>
@ namespaceDeclarations().size() == \old(namespaceDeclarations().size()) + 1;
@*/
public void add(NamespaceDeclaration namespaceDeclaration) {
add(_subNamespaceParts, namespaceDeclaration);
}
/**
* Remove the given namespace declaration to this document.
*
* @param namespaceDeclaration
* The namespace declaration to be added.
*/
/*
@ public behavior
@
@ ! namespaceDeclarations().contains(namespaceDeclaration);
@ ! \old(namespaceDeclarations().contains(namespaceDeclaration) ==>
@ namespaceDeclarations().size() == \old(namespaceDeclarations().size()) - 1;
*/
public void remove(NamespaceDeclaration namespaceDeclaration) {
remove(_subNamespaceParts, namespaceDeclaration);
}
private Multi<NamespaceDeclaration> _subNamespaceParts = new Multi<NamespaceDeclaration>(this);
/**
* <p>
* Always throws a {@link LookupException}. A document should not be involved
* in the lookup process. The child namespace declarations should redirect the
* lookup towards the general namespace.
* </p>
*/
@Override
public LookupContext lookupContext(Element child) throws LookupException {
throw new ChameleonProgrammerException("A document should not be involved in the lookup");
}
/**
* {@inheritDoc}
*
* @return The language of the view of the loader.
*/
@Override
public Language language() {
return loader().scanner().view().language();
}
@Override
protected Document cloneSelf() {
return new Document();
}
/**
* <p>Copy this document to the given view and activate it.</p>
*
* <p>The result is a clone of this document. All elements in the
* clone will have the corresponding element in the descendant tree
* of this document as their {@link Element#origin()}. All namespaces
* that are populated by namespace declarations in this document
* will be created if necessary. The document is activated.</p>
*
* @param view The view to which this document must be copied.
*
* @return A clone of the document in the given view.
*/
@Deprecated
public Document cloneTo(View view) {
Contracts.notNull(view);
Document clone = (Document) clone((e1,e2) -> {e2.setOrigin(e1);}, Element.class);
// Document clone = (Document) clone();
FakeDocumentScanner pl = new FakeDocumentScanner();
DocumentLoader is = new FakeDocumentLoader(clone, pl);
for (NamespaceDeclaration decl : descendants(NamespaceDeclaration.class)) {
view.namespace().getOrCreateNamespace(decl.namespace().fullyQualifiedName());
}
try {
view.addSource(pl);
} catch (ProjectException e) {
throw new ChameleonProgrammerException(e);
}
clone.activate();
return clone;
}
/**
* @return The association object that links this document to its loader.
*/
public SingleAssociation<Document, DocumentLoader> loaderLink() {
return _loader;
}
/**
* @return the document loader that is responsible for loading the contents of
* this document.
*/
public DocumentLoader loader() {
return _loader.getOtherEnd();
}
protected SingleAssociation<Document, DocumentLoader> _loader = new SingleAssociation<Document, DocumentLoader>(this);
/**
* @return The view of a document is the view to which its document loader is
* connected.
*/
/*@
@ public behavior
@
@ post \result == documentLoader().view();
@*/
@Override
public View view() {
return loader().view();
}
}
|
package org.apache.xerces.parsers;
import org.apache.xerces.dom.AttrImpl;
import org.apache.xerces.dom.DeferredDocumentImpl;
import org.apache.xerces.dom.CoreDocumentImpl;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.DocumentTypeImpl;
import org.apache.xerces.dom.ElementDefinitionImpl;
import org.apache.xerces.dom.ElementImpl;
import org.apache.xerces.dom.EntityImpl;
import org.apache.xerces.dom.EntityReferenceImpl;
import org.apache.xerces.dom.NodeImpl;
import org.apache.xerces.dom.NotationImpl;
import org.apache.xerces.dom.ProcessingInstructionImpl;
import org.apache.xerces.dom.PSVIAttrNSImpl;
import org.apache.xerces.dom.PSVIElementNSImpl;
import org.apache.xerces.dom.TextImpl;
import org.apache.xerces.impl.Constants;
// id types
import org.apache.xerces.xni.psvi.AttributePSVI;
import org.apache.xerces.impl.xs.psvi.XSAttributeDeclaration;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.psvi.AttributePSVI;
import org.apache.xerces.xni.psvi.ElementPSVI;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.w3c.dom.ls.DOMBuilderFilter;
import org.w3c.dom.traversal.NodeFilter;
import java.util.Stack;
/**
* This is the base class of all DOM parsers. It implements the XNI
* callback methods to create the DOM tree. After a successful parse of
* an XML document, the DOM Document object can be queried using the
* <code>getDocument</code> method. The actual pipeline is defined in
* parser configuration.
*
* @author Arnaud Le Hors, IBM
* @author Andy Clark, IBM
* @author Elena Litani, IBM
*
* @version $Id$
*/
public class AbstractDOMParser extends AbstractXMLDocumentParser{
// Constants
// feature ids
/** Feature id: namespace. */
protected static final String NAMESPACES =
Constants.SAX_FEATURE_PREFIX+Constants.NAMESPACES_FEATURE;
/** Feature id: create entity ref nodes. */
protected static final String CREATE_ENTITY_REF_NODES =
Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_ENTITY_REF_NODES_FEATURE;
/** Feature id: include comments. */
protected static final String INCLUDE_COMMENTS_FEATURE =
Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_COMMENTS_FEATURE;
/** Feature id: create cdata nodes. */
protected static final String CREATE_CDATA_NODES_FEATURE =
Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_CDATA_NODES_FEATURE;
/** Feature id: include ignorable whitespace. */
protected static final String INCLUDE_IGNORABLE_WHITESPACE =
Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_IGNORABLE_WHITESPACE;
/** Feature id: defer node expansion. */
protected static final String DEFER_NODE_EXPANSION =
Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE;
/** Expose XML Schema normalize value */
protected static final String NORMALIZE_DATA =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE;
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
NAMESPACES,
CREATE_ENTITY_REF_NODES,
INCLUDE_COMMENTS_FEATURE,
CREATE_CDATA_NODES_FEATURE,
INCLUDE_IGNORABLE_WHITESPACE,
DEFER_NODE_EXPANSION,
NORMALIZE_DATA,
};
// property ids
/** Property id: document class name. */
protected static final String DOCUMENT_CLASS_NAME =
Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_CLASS_NAME_PROPERTY;
protected static final String CURRENT_ELEMENT_NODE=
Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY;
// protected static final String GRAMMAR_POOL =
// Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
DOCUMENT_CLASS_NAME,
CURRENT_ELEMENT_NODE,
};
// other
/** Default document class name. */
protected static final String DEFAULT_DOCUMENT_CLASS_NAME =
"org.apache.xerces.dom.DocumentImpl";
protected static final String CORE_DOCUMENT_CLASS_NAME =
"org.apache.xerces.dom.CoreDocumentImpl";
protected static final String PSVI_DOCUMENT_CLASS_NAME =
"org.apache.xerces.dom.PSVIDocumentImpl";
// debugging
private static final boolean DEBUG_EVENTS = false;
private static final boolean DEBUG_BASEURI = false;
// Data
/** True if inside DTD. */
protected boolean fInDTD;
// features
/** Create entity reference nodes. */
protected boolean fCreateEntityRefNodes;
/** Include ignorable whitespace. */
protected boolean fIncludeIgnorableWhitespace;
/** Include Comments. */
protected boolean fIncludeComments;
/** Create cdata nodes. */
protected boolean fCreateCDATANodes;
/** Expose XML Schema schema_normalize_values via DOM*/
protected boolean fNormalizeData = true;
// dom information
/** The document. */
protected Document fDocument;
/** The default Xerces document implementation, if used. */
protected CoreDocumentImpl fDocumentImpl;
/** Whether to store PSVI information in DOM tree. */
protected boolean fStorePSVI;
/** The document class name to use. */
protected String fDocumentClassName;
/** The document type node. */
protected DocumentType fDocumentType;
/** Current node. */
protected Node fCurrentNode;
protected CDATASection fCurrentCDATASection;
protected EntityImpl fCurrentEntityDecl;
protected int fDeferredEntityDecl;
/** Character buffer */
protected final StringBuffer fStringBuffer = new StringBuffer(50);
// internal subset
/** Internal subset buffer. */
protected StringBuffer fInternalSubset;
// deferred expansion data
protected boolean fDeferNodeExpansion;
protected boolean fNamespaceAware;
protected DeferredDocumentImpl fDeferredDocumentImpl;
protected int fDocumentIndex;
protected int fDocumentTypeIndex;
protected int fCurrentNodeIndex;
protected int fCurrentCDATASectionIndex;
// state
/** True if inside DTD external subset. */
protected boolean fInDTDExternalSubset;
/** True if inside document. */
protected boolean fInDocument;
/** True if inside CDATA section. */
protected boolean fInCDATASection;
/** True if saw the first chunk of characters*/
protected boolean fFirstChunk = false;
/** DOMBuilderFilter: specifies that element with given QNAME and all its children
must be rejected */
protected boolean fFilterReject = false;
// data
/** Base uri stack*/
protected Stack fBaseURIStack = new Stack();
/** DOMBuilderFilter: the QNAME of rejected element*/
protected final QName fRejectedElement = new QName();
/** DOMBuilderFilter: store qnames of skipped elements*/
protected Stack fSkippedElemStack = null;
/** Attribute QName. */
private QName fAttrQName = new QName();
// handlers
protected DOMBuilderFilter fDOMFilter = null;
// Constructors
/** Default constructor. */
protected AbstractDOMParser(XMLParserConfiguration config) {
super(config);
// add recognized features
fConfiguration.addRecognizedFeatures(RECOGNIZED_FEATURES);
// set default values
fConfiguration.setFeature(CREATE_ENTITY_REF_NODES, true);
fConfiguration.setFeature(INCLUDE_IGNORABLE_WHITESPACE, true);
fConfiguration.setFeature(DEFER_NODE_EXPANSION, true);
fConfiguration.setFeature(INCLUDE_COMMENTS_FEATURE, true);
fConfiguration.setFeature(CREATE_CDATA_NODES_FEATURE, true);
// add recognized properties
fConfiguration.addRecognizedProperties(RECOGNIZED_PROPERTIES);
// set default values
fConfiguration.setProperty(DOCUMENT_CLASS_NAME,
DEFAULT_DOCUMENT_CLASS_NAME);
} // <init>(XMLParserConfiguration)
/**
* This method retreives the name of current document class.
*/
protected String getDocumentClassName() {
return fDocumentClassName;
}
/**
* This method allows the programmer to decide which document
* factory to use when constructing the DOM tree. However, doing
* so will lose the functionality of the default factory. Also,
* a document class other than the default will lose the ability
* to defer node expansion on the DOM tree produced.
*
* @param documentClassName The fully qualified class name of the
* document factory to use when constructing
* the DOM tree.
*
* @see #getDocumentClassName
* @see #DEFAULT_DOCUMENT_CLASS_NAME
*/
protected void setDocumentClassName(String documentClassName) {
// normalize class name
if (documentClassName == null) {
documentClassName = DEFAULT_DOCUMENT_CLASS_NAME;
}
// verify that this class exists and is of the right type
try {
Class _class = Class.forName(documentClassName);
//if (!_class.isAssignableFrom(Document.class)) {
if (!Document.class.isAssignableFrom(_class)) {
// REVISIT: message
throw new IllegalArgumentException("PAR002 Class, \"" +
documentClassName +
"\", is not of type org.w3c.dom.Document.\n" +
documentClassName);
}
}
catch (ClassNotFoundException e) {
// REVISIT: message
throw new IllegalArgumentException("PAR003 Class, \"" +
documentClassName +
"\", not found.\n" +
documentClassName);
}
// set document class name
fDocumentClassName = documentClassName;
if (!documentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME)) {
fDeferNodeExpansion = false;
}
} // setDocumentClassName(String)
// Public methods
/** Returns the DOM document object. */
public Document getDocument() {
return fDocument;
} // getDocument():Document
// XMLDocumentParser methods
/**
* Resets the parser state.
*
* @throws SAXException Thrown on initialization error.
*/
public void reset() throws XNIException {
super.reset();
// get feature state
fCreateEntityRefNodes =
fConfiguration.getFeature(CREATE_ENTITY_REF_NODES);
fIncludeIgnorableWhitespace =
fConfiguration.getFeature(INCLUDE_IGNORABLE_WHITESPACE);
fDeferNodeExpansion =
fConfiguration.getFeature(DEFER_NODE_EXPANSION);
fNamespaceAware = fConfiguration.getFeature(NAMESPACES);
fIncludeComments = fConfiguration.getFeature(INCLUDE_COMMENTS_FEATURE);
fCreateCDATANodes = fConfiguration.getFeature(CREATE_CDATA_NODES_FEATURE);
try {
fNormalizeData = fConfiguration.getFeature(NORMALIZE_DATA);
} catch (XMLConfigurationException x) {
fNormalizeData = false;
}
// get property
setDocumentClassName((String)
fConfiguration.getProperty(DOCUMENT_CLASS_NAME));
// reset dom information
fDocument = null;
fDocumentImpl = null;
fStorePSVI = false;
fDocumentType = null;
fDocumentTypeIndex = -1;
fDeferredDocumentImpl = null;
fCurrentNode = null;
// reset string buffer
fStringBuffer.setLength(0);
// reset state information
fInDocument = false;
fInDTD = false;
fInDTDExternalSubset = false;
fInCDATASection = false;
fFirstChunk = false;
fCurrentCDATASection = null;
fCurrentCDATASectionIndex = -1;
fBaseURIStack.clear();
} // reset()
// XMLDocumentHandler methods
/**
* This method notifies the start of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the general entity.
* @param identifier The resource identifier.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException Thrown by handler to signal an error.
*/
public void startGeneralEntity(String name,
XMLResourceIdentifier identifier,
String encoding, Augmentations augs)
throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>startGeneralEntity ("+name+")");
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId( **baseURI): "+identifier.getExpandedSystemId());
System.out.println(" baseURI:"+ identifier.getBaseSystemId());
}
}
// Always create entity reference nodes to be able to recreate
// entity as a part of doctype
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
setCharacterData(true);
EntityReference er = fDocument.createEntityReference(name);
if (fDocumentImpl != null) {
// REVISIT: baseURI/actualEncoding
// remove dependency on our implementation when DOM L3 is REC
EntityReferenceImpl erImpl =(EntityReferenceImpl)er;
// set base uri
erImpl.setBaseURI(identifier.getExpandedSystemId());
if (fDocumentType != null) {
// set actual encoding
NamedNodeMap entities = fDocumentType.getEntities();
fCurrentEntityDecl = (EntityImpl) entities.getNamedItem(name);
if (fCurrentEntityDecl != null) {
fCurrentEntityDecl.setActualEncoding(encoding);
}
}
// we don't need synchronization now, because entity ref will be
// expanded anyway. Synch only needed when user creates entityRef node
erImpl.needsSyncChildren(false);
}
fCurrentNode.appendChild(er);
fCurrentNode = er;
}
else {
int er =
fDeferredDocumentImpl.createDeferredEntityReference(name, identifier.getExpandedSystemId());
if (fDocumentTypeIndex != -1) {
// find corresponding Entity decl
int node = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (node != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(node, false);
if (nodeType == Node.ENTITY_NODE) {
String nodeName =
fDeferredDocumentImpl.getNodeName(node, false);
if (nodeName.equals(name)) {
fDeferredEntityDecl = node;
fDeferredDocumentImpl.setActualEncoding(node, encoding);
break;
}
}
node = fDeferredDocumentImpl.getRealPrevSibling(node, false);
}
}
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, er);
fCurrentNodeIndex = er;
}
} // startGeneralEntity(String,XMLResourceIdentifier, Augmentations)
/**
* Notifies of the presence of a TextDecl line in an entity. If present,
* this method will be called immediately following the startEntity call.
* <p>
* <strong>Note:</strong> This method will never be called for the
* document entity; it is only called for external general entities
* referenced in document content.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param version The XML version, or null if not specified.
* @param encoding The IANA encoding name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void textDecl(String version, String encoding, Augmentations augs) throws XNIException {
if (!fDeferNodeExpansion) {
if (fCurrentEntityDecl != null && !fFilterReject) {
fCurrentEntityDecl.setEncoding(encoding);
fCurrentEntityDecl.setVersion(version);
}
}
else {
if (fDeferredEntityDecl !=-1) {
fDeferredDocumentImpl.setEntityInfo(fDeferredEntityDecl, version, encoding);
}
}
} // textDecl(String,String)
/**
* A comment.
*
* @param text The text in the comment.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text, Augmentations augs) throws XNIException {
if (fInDTD) {
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!
fInternalSubset.append(text.toString());
fInternalSubset.append("
}
return;
}
if (!fIncludeComments || fFilterReject) {
return;
}
if (!fDeferNodeExpansion) {
Comment comment = fDocument.createComment(text.toString());
setCharacterData(false);
fCurrentNode.appendChild(comment);
if (fDOMFilter !=null &&
(fDOMFilter.getWhatToShow() & NodeFilter.SHOW_COMMENT)!= 0) {
short code = fDOMFilter.acceptNode(comment);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
// REVISIT: the constant FILTER_REJECT should be changed when new
// DOM LS specs gets published
// fall through to SKIP since comment has no children.
}
case NodeFilter.FILTER_SKIP: {
// REVISIT: the constant FILTER_SKIP should be changed when new
// DOM LS specs gets published
fCurrentNode.removeChild(comment);
// make sure we don't loose chars if next event is characters()
fFirstChunk = true;
return;
}
default: {
// accept node
}
}
}
}
else {
int comment =
fDeferredDocumentImpl.createDeferredComment(text.toString());
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, comment);
}
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
if (fInDTD) {
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<?");
fInternalSubset.append(target.toString());
fInternalSubset.append(' ');
fInternalSubset.append(data.toString());
fInternalSubset.append("?>");
}
return;
}
if (DEBUG_EVENTS) {
System.out.println("==>processingInstruction ("+target+")");
}
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
ProcessingInstruction pi =
fDocument.createProcessingInstruction(target, data.toString());
setCharacterData(false);
fCurrentNode.appendChild(pi);
if (fDOMFilter !=null &&
(fDOMFilter.getWhatToShow() & NodeFilter.SHOW_PROCESSING_INSTRUCTION)!= 0) {
short code = fDOMFilter.acceptNode(pi);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
// fall through to SKIP since PI has no children.
}
case NodeFilter.FILTER_SKIP: {
fCurrentNode.removeChild(pi);
// fFirstChunk must be set to true so that data
// won't be lost in the case where the child before PI is
// a text node and the next event is characters.
fFirstChunk = true;
return;
}
default: {
}
}
}
}
else {
int pi = fDeferredDocumentImpl.
createDeferredProcessingInstruction(target, data.toString());
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, pi);
}
} // processingInstruction(String,XMLString)
/**
* The start of the document.
*
* @param locator The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
fInDocument = true;
if (!fDeferNodeExpansion) {
if (fDocumentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME)) {
fDocument = new DocumentImpl();
fDocumentImpl = (CoreDocumentImpl)fDocument;
// REVISIT: when DOM Level 3 is REC rely on Document.support
// instead of specific class
// set DOM error checking off
fDocumentImpl.setStrictErrorChecking(false);
// set actual encoding
fDocumentImpl.setActualEncoding(encoding);
// set documentURI
fDocumentImpl.setDocumentURI(locator.getExpandedSystemId());
}
else {
// use specified document class
try {
Class documentClass = Class.forName(fDocumentClassName);
fDocument = (Document)documentClass.newInstance();
// if subclass of our own class that's cool too
Class defaultDocClass =
Class.forName(CORE_DOCUMENT_CLASS_NAME);
if (defaultDocClass.isAssignableFrom(documentClass)) {
fDocumentImpl = (CoreDocumentImpl)fDocument;
Class psviDocClass = Class.forName(PSVI_DOCUMENT_CLASS_NAME);
if (psviDocClass.isAssignableFrom(documentClass)) {
fStorePSVI = true;
}
// REVISIT: when DOM Level 3 is REC rely on
// Document.support instead of specific class
// set DOM error checking off
fDocumentImpl.setStrictErrorChecking(false);
// set actual encoding
fDocumentImpl.setActualEncoding(encoding);
// set documentURI
if (locator != null) {
fDocumentImpl.setDocumentURI(locator.getExpandedSystemId());
}
}
}
catch (ClassNotFoundException e) {
// won't happen we already checked that earlier
}
catch (Exception e) {
// REVISIT: Localize this message.
throw new RuntimeException(
"Failed to create document object of class: "
+ fDocumentClassName);
}
}
fCurrentNode = fDocument;
}
else {
fDeferredDocumentImpl = new DeferredDocumentImpl(fNamespaceAware);
fDocument = fDeferredDocumentImpl;
fDocumentIndex = fDeferredDocumentImpl.createDeferredDocument();
// REVISIT: strict error checking is not implemented in deferred dom.
// Document.support instead of specific class
// set actual encoding
fDeferredDocumentImpl.setActualEncoding(encoding);
// set documentURI
fDeferredDocumentImpl.setDocumentURI(locator.getExpandedSystemId());
fCurrentNodeIndex = fDocumentIndex;
}
} // startDocument(String,String)
/**
* Notifies of the presence of an XMLDecl line in the document. If
* present, this method will be called immediately following the
* startDocument call.
*
* @param version The XML version.
* @param encoding The IANA encoding name of the document, or null if
* not specified.
* @param standalone The standalone value, or null if not specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void xmlDecl(String version, String encoding, String standalone,
Augmentations augs)
throws XNIException {
if (!fDeferNodeExpansion) {
// REVISIT: when DOM Level 3 is REC rely on Document.support
// instead of specific class
if (fDocumentImpl != null) {
fDocumentImpl.setVersion(version);
fDocumentImpl.setEncoding(encoding);
fDocumentImpl.setStandalone("true".equals(standalone));
}
}
else {
fDeferredDocumentImpl.setVersion(version);
fDeferredDocumentImpl.setEncoding(encoding);
fDeferredDocumentImpl.setStandalone("true".equals(standalone));
}
} // xmlDecl(String,String,String)
/**
* Notifies of the presence of the DOCTYPE line in the document.
*
* @param rootElement The name of the root element.
* @param publicId The public identifier if an external DTD or null
* if the external DTD is specified using SYSTEM.
* @param systemId The system identifier if an external DTD, null
* otherwise.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void doctypeDecl(String rootElement,
String publicId, String systemId, Augmentations augs)
throws XNIException {
if (!fDeferNodeExpansion) {
if (fDocumentImpl != null) {
fDocumentType = fDocumentImpl.createDocumentType(
rootElement, publicId, systemId);
fCurrentNode.appendChild(fDocumentType);
}
}
else {
fDocumentTypeIndex = fDeferredDocumentImpl.
createDeferredDocumentType(rootElement, publicId, systemId);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, fDocumentTypeIndex);
}
} // doctypeDecl(String,String,String)
/**
* The start of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param uri The URI bound to the prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
} // startPrefixMapping(String,String)
/**
* The end of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException {
} // endPrefixMapping(String)
/**
* The start of an element. If the document specifies the start element
* by using an empty tag, then the startElement method will immediately
* be followed by the endElement method, with no intervening methods.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>startElement ("+element.rawname+")");
}
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
Element el = createElementNode(element);
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount; i++) {
attributes.getName(i, fAttrQName);
Attr attr = createAttrNode(fAttrQName);
String attrValue = attributes.getValue(i);
// REVISIT: consider moving this code to the XML Schema validator.
// When PSVI and XML Schema component interfaces are finalized
// remove dependancy on *Impl class.
AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI);
if (fStorePSVI && attrPSVI != null) {
((PSVIAttrNSImpl)attr).setPSVI(attrPSVI);
}
if (fNormalizeData) {
// If validation is not attempted, the SchemaNormalizedValue will be null.
// We shouldn't take the normalized value in this case.
if (attrPSVI != null && attrPSVI.getValidationAttempted() == AttributePSVI.VALIDATION_FULL) {
attrValue = attrPSVI.getSchemaNormalizedValue();
}
}
attr.setValue(attrValue);
el.setAttributeNode(attr);
// NOTE: The specified value MUST be set after you set
// the node value because that turns the "specified"
// flag to "true" which may overwrite a "false"
// value from the attribute list. -Ac
if (fDocumentImpl != null) {
AttrImpl attrImpl = (AttrImpl)attr;
boolean specified = attributes.isSpecified(i);
attrImpl.setSpecified(specified);
// Identifier registration
// REVISIT: try to retrieve XML Schema attribute declaration
// we should try to modify psvi API to allows to
// check if id type
XSAttributeDeclaration xsDecl = (XSAttributeDeclaration)((attrPSVI!=null)?attrPSVI.getAttributeDeclaration():null);
if (attributes.getType(i).equals("ID") ||
(xsDecl !=null && ((XSSimpleType)xsDecl.getTypeDefinition()).isIDType())) {
((ElementImpl) el).setIdAttributeNode(attr);
}
}
// REVISIT: Handle entities in attribute value.
}
setCharacterData(false);
// filter nodes
if (fDOMFilter != null) {
short code = fDOMFilter.startContainer(el);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
fFilterReject = true;
fRejectedElement.setValues(element);
return;
}
case NodeFilter.FILTER_SKIP: {
fSkippedElemStack.push(element);
return;
}
default: {
}
}
}
fCurrentNode.appendChild(el);
fCurrentNode = el;
}
else {
int el =
fDeferredDocumentImpl.createDeferredElement(fNamespaceAware ?
element.uri : null,
element.rawname);
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount; i++) {
String attrValue = attributes.getValue(i);
// REVISIT: consider moving this code to the XML Schema validator.
// When PSVI and XML Schema component interfaces are finalized
// remove dependancy on *Impl class.
AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI);
if (fNormalizeData) {
// If validation is not attempted, the SchemaNormalizedValue will be null.
// We shouldn't take the normalized value in this case.
if (attrPSVI != null && attrPSVI.getValidationAttempted() == AttributePSVI.VALIDATION_FULL) {
attrValue = attrPSVI.getSchemaNormalizedValue();
}
}
int attr = fDeferredDocumentImpl.setDeferredAttribute(el,
attributes.getQName(i),
attributes.getURI(i),
attrValue,
attributes.isSpecified(i));
// identifier registration
// REVISIT: try to retrieve XML Schema attribute declaration
// we should try to modify psvi API to allows to
// check if id type
XSAttributeDeclaration xsDecl = (XSAttributeDeclaration)((attrPSVI!=null)?attrPSVI.getAttributeDeclaration():null);
if (attributes.getType(i).equals("ID") ||
(xsDecl !=null && ((XSSimpleType)xsDecl.getTypeDefinition()).isIDType())) {
fDeferredDocumentImpl.setIdAttributeNode(el, attr);
}
}
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, el);
fCurrentNodeIndex = el;
}
} // startElement(QName,XMLAttributes)
/**
* An empty element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
startElement(element, attributes, augs);
endElement(element, augs);
} // emptyElement(QName,XMLAttributes)
/**
* Character content.
*
* @param text The content.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void characters(XMLString text, Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>characters(): "+text.toString());
}
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
if (fInCDATASection && fCreateCDATANodes) {
if (fCurrentCDATASection == null) {
fCurrentCDATASection =
fDocument.createCDATASection(text.toString());
fCurrentNode.appendChild(fCurrentCDATASection);
fCurrentNode = fCurrentCDATASection;
}
else {
fCurrentCDATASection.appendData(text.toString());
}
}
else if (!fInDTD) {
// if type is union (XML Schema) it is possible that we receive
// character call with empty data
if (text.length == 0) {
return;
}
String value = null;
// normalized value for element is stored in schema_normalize_value property
// of PSVI element.
if (fNormalizeData && augs != null) {
ElementPSVI elemPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI);
if (elemPSVI != null) {
value = elemPSVI.getSchemaNormalizedValue();
}
}
if (value == null) {
value = text.toString();
}
Node child = fCurrentNode.getLastChild();
if (child != null && child.getNodeType() == Node.TEXT_NODE) {
// collect all the data into the string buffer.
if (fFirstChunk) {
if (fDocumentImpl != null) {
fStringBuffer.append(((TextImpl)child).removeData());
} else {
fStringBuffer.append(((Text)child).getData());
((Text)child).setNodeValue(null);
}
fFirstChunk = false;
}
fStringBuffer.append(value);
}
else {
fFirstChunk = true;
Text textNode = fDocument.createTextNode(value);
fCurrentNode.appendChild(textNode);
}
}
}
else {
// The Text and CDATASection normalization is taken care of within
// the DOM in the deferred case.
if (fInCDATASection && fCreateCDATANodes) {
if (fCurrentCDATASectionIndex == -1) {
int cs = fDeferredDocumentImpl.
createDeferredCDATASection(text.toString());
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, cs);
fCurrentCDATASectionIndex = cs;
fCurrentNodeIndex = cs;
}
else {
int txt = fDeferredDocumentImpl.
createDeferredTextNode(text.toString(), false);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt);
}
} else if (!fInDTD) {
// if type is union (XML Schema) it is possible that we receive
// character call with empty data
if (text.length == 0) {
return;
}
String value = null;
// normalized value for element is stored in schema_normalize_value property
// of PSVI element.
if (fNormalizeData && augs != null) {
ElementPSVI elemPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI);
if (elemPSVI != null) {
value = elemPSVI.getSchemaNormalizedValue();
}
}
if (value == null) {
value = text.toString();
}
int txt = fDeferredDocumentImpl.
createDeferredTextNode(value, false);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt);
}
}
} // characters(XMLString)
/**
* Ignorable whitespace. For this method to be called, the document
* source must have some way of determining that the text containing
* only whitespace characters should be considered ignorable. For
* example, the validator can determine if a length of whitespace
* characters in the document are ignorable based on the element
* content model.
*
* @param text The ignorable whitespace.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
if (!fIncludeIgnorableWhitespace || fFilterReject) {
return;
}
if (!fDeferNodeExpansion) {
Node child = fCurrentNode.getLastChild();
if (child != null && child.getNodeType() == Node.TEXT_NODE) {
Text textNode = (Text)child;
textNode.appendData(text.toString());
}
else {
Text textNode = fDocument.createTextNode(text.toString());
if (fDocumentImpl != null) {
TextImpl textNodeImpl = (TextImpl)textNode;
textNodeImpl.setIgnorableWhitespace(true);
}
fCurrentNode.appendChild(textNode);
}
}
else {
// The Text normalization is taken care of within the DOM in the
// deferred case.
int txt = fDeferredDocumentImpl.
createDeferredTextNode(text.toString(), true);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt);
}
} // ignorableWhitespace(XMLString)
/**
* The end of an element.
*
* @param element The name of the element.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element, Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>endElement ("+element.rawname+")");
}
if (!fDeferNodeExpansion) {
// REVISIT: Should this happen after we call the filter?
if (fStorePSVI && augs != null) {
ElementPSVI elementPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI);
if (elementPSVI != null) {
((PSVIElementNSImpl)fCurrentNode).setPSVI(elementPSVI);
}
}
if (fDOMFilter != null) {
if (fFilterReject) {
if (element.equals(fRejectedElement)) {
fFilterReject = false;
}
return;
}
if (!fSkippedElemStack.isEmpty()) {
if (fSkippedElemStack.peek().equals(element)) {
fSkippedElemStack.pop();
return;
}
}
setCharacterData(false);
if ((fDOMFilter.getWhatToShow() & NodeFilter.SHOW_ELEMENT)!=0) {
short code = fDOMFilter.acceptNode(fCurrentNode);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
Node parent = fCurrentNode.getParentNode();
parent.removeChild(fCurrentNode);
fCurrentNode = parent;
return;
}
case NodeFilter.FILTER_SKIP: {
// make sure that if any char data is available
// the fFirstChunk is true, so that if the next event
// is characters(), and the last node is text, we will copy
// the value already in the text node to fStringBuffer
// (not to loose it).
fFirstChunk = true;
// replace children
Node parent = fCurrentNode.getParentNode();
NodeList ls = fCurrentNode.getChildNodes();
int length = ls.getLength();
for (int i=0;i<length;i++) {
parent.appendChild(ls.item(0));
}
parent.removeChild(fCurrentNode);
fCurrentNode = parent;
return;
}
default: { }
}
}
fCurrentNode = fCurrentNode.getParentNode();
} // end-if DOMFilter
else {
setCharacterData(false);
fCurrentNode = fCurrentNode.getParentNode();
}
}
else {
fCurrentNodeIndex =
fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false);
}
} // endElement(QName)
/**
* The start of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA(Augmentations augs) throws XNIException {
fInCDATASection = true;
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
setCharacterData(false);
}
} // startCDATA()
/**
* The end of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA(Augmentations augs) throws XNIException {
fInCDATASection = false;
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
if (fCurrentCDATASection !=null) {
if (fDOMFilter !=null &&
(fDOMFilter.getWhatToShow() & NodeFilter.SHOW_CDATA_SECTION)!= 0) {
short code = fDOMFilter.acceptNode(fCurrentCDATASection);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
// fall through to SKIP since CDATA section has no children.
}
case NodeFilter.FILTER_SKIP: {
Node parent = fCurrentNode.getParentNode();
parent.removeChild(fCurrentCDATASection);
fCurrentNode = parent;
return;
}
default: {
// accept node
}
}
}
fCurrentNode = fCurrentNode.getParentNode();
fCurrentCDATASection = null;
}
}
else {
if (fCurrentCDATASectionIndex !=-1) {
fCurrentNodeIndex =
fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false);
fCurrentCDATASectionIndex = -1;
}
}
} // endCDATA()
/**
* The end of the document.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDocument(Augmentations augs) throws XNIException {
fInDocument = false;
if (!fDeferNodeExpansion) {
// REVISIT: when DOM Level 3 is REC rely on Document.support
// instead of specific class
// set DOM error checking back on
if (fDocumentImpl != null) {
fDocumentImpl.setStrictErrorChecking(true);
}
fCurrentNode = null;
}
else {
fCurrentNodeIndex = -1;
}
} // endDocument()
/**
* This method notifies the end of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException
* Thrown by handler to signal an error.
*/
public void endGeneralEntity(String name, Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>endGeneralEntity: ("+name+")");
}
if (!fDeferNodeExpansion) {
if (fFilterReject) {
return;
}
setCharacterData(true);
if (fDocumentType != null) {
// get current entity declaration
NamedNodeMap entities = fDocumentType.getEntities();
fCurrentEntityDecl = (EntityImpl) entities.getNamedItem(name);
if (fCurrentEntityDecl != null) {
if (fCurrentEntityDecl != null && fCurrentEntityDecl.getFirstChild() == null) {
fCurrentEntityDecl.setReadOnly(false, true);
Node child = fCurrentNode.getFirstChild();
while (child != null) {
Node copy = child.cloneNode(true);
fCurrentEntityDecl.appendChild(copy);
child = child.getNextSibling();
}
fCurrentEntityDecl.setReadOnly(true, true);
//entities.setNamedItem(fCurrentEntityDecl);
}
fCurrentEntityDecl = null;
}
}
boolean removeEntityRef = false;
if (fCreateEntityRefNodes) {
if (fDocumentImpl != null) {
// Make entity ref node read only
((NodeImpl)fCurrentNode).setReadOnly(true, true);
}
if (fDOMFilter !=null &&
(fDOMFilter.getWhatToShow() & NodeFilter.SHOW_ENTITY_REFERENCE)!= 0) {
short code = fDOMFilter.acceptNode(fCurrentNode);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
Node parent = fCurrentNode.getParentNode();
parent.removeChild(fCurrentNode);
fCurrentNode = parent;
return;
}
case NodeFilter.FILTER_SKIP: {
// make sure we don't loose chars if next event is characters()
fFirstChunk = true;
removeEntityRef = true;
break;
}
default: {
fCurrentNode = fCurrentNode.getParentNode();
}
}
} else {
fCurrentNode = fCurrentNode.getParentNode();
}
}
if (!fCreateEntityRefNodes || removeEntityRef) {
// move entity reference children to the list of
// siblings of its parent and remove entity reference
NodeList children = fCurrentNode.getChildNodes();
Node parent = fCurrentNode.getParentNode();
int length = children.getLength();
// get previous sibling of the entity reference
Node node = fCurrentNode.getPreviousSibling();
// normalize text nodes
Node child = children.item(0);
if (node != null && node.getNodeType() == Node.TEXT_NODE &&
child.getNodeType() == Node.TEXT_NODE) {
((Text)node).appendData(child.getNodeValue());
fCurrentNode.removeChild(child);
} else {
node = parent.insertBefore(child, fCurrentNode);
handleBaseURI(node);
}
for (int i=1;i <length;i++) {
node = parent.insertBefore(children.item(0), fCurrentNode);
handleBaseURI(node);
}
parent.removeChild(fCurrentNode);
fCurrentNode = parent;
}
}
else {
if (fDocumentTypeIndex != -1) {
// find corresponding Entity decl
int node = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (node != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(node, false);
if (nodeType == Node.ENTITY_NODE) {
String nodeName =
fDeferredDocumentImpl.getNodeName(node, false);
if (nodeName.equals(name)) {
fDeferredEntityDecl = node;
break;
}
}
node = fDeferredDocumentImpl.getRealPrevSibling(node, false);
}
}
if (fDeferredEntityDecl != -1) {
int prevIndex = -1;
int childIndex = fDeferredDocumentImpl.getLastChild(fCurrentNodeIndex, false);
while (childIndex != -1) {
int cloneIndex = fDeferredDocumentImpl.cloneNode(childIndex, true);
fDeferredDocumentImpl.insertBefore(fDeferredEntityDecl, cloneIndex, prevIndex);
prevIndex = cloneIndex;
childIndex = fDeferredDocumentImpl.getRealPrevSibling(childIndex, false);
}
}
if (fCreateEntityRefNodes) {
fCurrentNodeIndex =
fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex,
false);
} else { //!fCreateEntityRefNodes
// move children of entity ref before the entity ref.
// remove entity ref.
// holds a child of entity ref
int childIndex = fDeferredDocumentImpl.getLastChild(fCurrentNodeIndex, false);
int parentIndex =
fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex,
false);
int prevIndex = fCurrentNodeIndex;
int lastChild = childIndex;
int sibling = -1;
while (childIndex != -1) {
handleBaseURI(childIndex);
sibling = fDeferredDocumentImpl.getRealPrevSibling(childIndex, false);
fDeferredDocumentImpl.insertBefore(parentIndex, childIndex, prevIndex);
prevIndex = childIndex;
childIndex = sibling;
}
fDeferredDocumentImpl.setAsLastChild(parentIndex, lastChild);
fCurrentNodeIndex = parentIndex;
}
fDeferredEntityDecl = -1;
}
} // endGeneralEntity(String, Augmentations)
/**
* Record baseURI information for the Element (by adding xml:base attribute)
* or for the ProcessingInstruction (by setting a baseURI field)
* Non deferred DOM.
*
* @param node
*/
protected void handleBaseURI (Node node){
if (fDocumentImpl != null) {
// REVISIT: remove dependency on our implementation when
// DOM L3 becomes REC
String baseURI = null;
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE) {
// if an element already has xml:base attribute
// do nothing
if (fNamespaceAware && (((Element)node).getAttributeNodeNS("http:
return;
} else if (((Element)node).getAttributeNode("xml:base") != null) {
return;
}
// retrive the baseURI from the entity reference
baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI();
if (baseURI !=null && !baseURI.equals(fDocumentImpl.getDocumentURI())) {
if (fNamespaceAware) {
((Element)node).setAttributeNS("http:
} else {
((Element)node).setAttribute("xml:base", baseURI);
}
}
}
else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE) {
baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI();
((ProcessingInstructionImpl)node).setBaseURI(baseURI);
}
}
}
/**
*
* Record baseURI information for the Element (by adding xml:base attribute)
* or for the ProcessingInstruction (by setting a baseURI field)
* Deferred DOM.
*
* @param node
*/
protected void handleBaseURI (int node){
short nodeType = fDeferredDocumentImpl.getNodeType(node, false);
if (nodeType == Node.ELEMENT_NODE) {
String baseURI = fDeferredDocumentImpl.getNodeValueString(fCurrentNodeIndex, false);
if (baseURI == null) {
baseURI = fDeferredDocumentImpl.getDeferredEntityBaseURI(fDeferredEntityDecl);
}
if (baseURI !=null && !baseURI.equals(fDeferredDocumentImpl.getDocumentURI())) {
fDeferredDocumentImpl.setDeferredAttribute(node,
"xml:base",
"http:
baseURI,
true);
}
}
else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE) {
// retrieve baseURI from the entity reference
String baseURI = fDeferredDocumentImpl.getNodeValueString(fCurrentNodeIndex, false);
if (baseURI == null) {
// try baseURI of the entity declaration
baseURI = fDeferredDocumentImpl.getDeferredEntityBaseURI(fDeferredEntityDecl);
}
fDeferredDocumentImpl.setDeferredPIBaseURI(node, baseURI);
}
}
// XMLDTDHandler methods
/**
* The start of the DTD.
*
* @param locator The document locator, or null if the document
* location cannot be reported during the parsing of
* the document DTD. However, it is <em>strongly</em>
* recommended that a locator be supplied that can
* at least report the base system identifier of the
* DTD.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDTD(XMLLocator locator, Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>startDTD");
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId: "+locator.getExpandedSystemId());
System.out.println(" baseURI:"+ locator.getBaseSystemId());
}
}
fInDTD = true;
fBaseURIStack.push(locator.getBaseSystemId());
if (fDeferNodeExpansion || fDocumentImpl != null) {
fInternalSubset = new StringBuffer(1024);
}
} // startDTD(XMLLocator)
/**
* The end of the DTD.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDTD(Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>endDTD()");
}
fInDTD = false;
fBaseURIStack.pop();
String internalSubset = fInternalSubset != null && fInternalSubset.length() > 0
? fInternalSubset.toString() : null;
if (fDeferNodeExpansion) {
if (internalSubset != null) {
fDeferredDocumentImpl.setInternalSubset(fDocumentTypeIndex, internalSubset);
}
}
else if (fDocumentImpl != null) {
if (internalSubset != null) {
((DocumentTypeImpl)fDocumentType).setInternalSubset(internalSubset);
}
}
} // endDTD()
/**
* The start of a conditional section.
*
* @param type The type of the conditional section. This value will
* either be CONDITIONAL_INCLUDE or CONDITIONAL_IGNORE.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #CONDITIONAL_INCLUDE
* @see #CONDITIONAL_IGNORE
*/
public void startConditional(short type, Augmentations augs) throws XNIException {
} // startConditional(short)
/**
* The end of a conditional section.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endConditional(Augmentations augs) throws XNIException {
} // endConditional()
/**
* The start of the DTD external subset.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startExternalSubset(XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>startExternalSubset");
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId: "+identifier.getExpandedSystemId());
System.out.println(" baseURI:"+ identifier.getBaseSystemId());
}
}
fBaseURIStack.push(identifier.getBaseSystemId());
fInDTDExternalSubset = true;
} // startExternalSubset(Augmentations)
/**
* The end of the DTD external subset.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endExternalSubset(Augmentations augs) throws XNIException {
fInDTDExternalSubset = false;
fBaseURIStack.pop();
} // endExternalSubset(Augmentations)
/**
* An internal entity declaration.
*
* @param name The name of the entity. Parameter entity names start with
* '%', whereas the name of a general entity is just the
* entity name.
* @param text The value of the entity.
* @param nonNormalizedText The non-normalized value of the entity. This
* value contains the same sequence of characters that was in
* the internal entity declaration, without any entity
* references expanded.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void internalEntityDecl(String name, XMLString text,
XMLString nonNormalizedText,
Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>internalEntityDecl: "+name);
if (DEBUG_BASEURI) {
System.out.println(" baseURI:"+ (String)fBaseURIStack.peek());
}
}
// internal subset string
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!ENTITY ");
if (name.startsWith("%")) {
fInternalSubset.append("% ");
fInternalSubset.append(name.substring(1));
}
else {
fInternalSubset.append(name);
}
fInternalSubset.append(' ');
String value = nonNormalizedText.toString();
boolean singleQuote = value.indexOf('\'') == -1;
fInternalSubset.append(singleQuote ? '\'' : '"');
fInternalSubset.append(value);
fInternalSubset.append(singleQuote ? '\'' : '"');
fInternalSubset.append(">\n");
}
// NOTE: We only know how to create these nodes for the Xerces
// DOM implementation because DOM Level 2 does not specify
// that functionality. -Ac
// create full node
// don't add parameter entities!
if(name.startsWith("%"))
return;
if (fDocumentType != null) {
NamedNodeMap entities = fDocumentType.getEntities();
EntityImpl entity = (EntityImpl)entities.getNamedItem(name);
if (entity == null) {
entity = (EntityImpl)fDocumentImpl.createEntity(name);
entity.setBaseURI((String)fBaseURIStack.peek());
entities.setNamedItem(entity);
}
}
// create deferred node
if (fDocumentTypeIndex != -1) {
boolean found = false;
int node = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (node != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(node, false);
if (nodeType == Node.ENTITY_NODE) {
String nodeName = fDeferredDocumentImpl.getNodeName(node, false);
if (nodeName.equals(name)) {
found = true;
break;
}
}
node = fDeferredDocumentImpl.getRealPrevSibling(node, false);
}
if (!found) {
int entityIndex =
fDeferredDocumentImpl.createDeferredEntity(name, null, null, null, (String)fBaseURIStack.peek());
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex);
}
}
} // internalEntityDecl(String,XMLString,XMLString)
/**
* An external entity declaration.
*
* @param name The name of the entity. Parameter entity names start
* with '%', whereas the name of a general entity is just
* the entity name.
* @param identifier An object containing all location information
* pertinent to this notation.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void externalEntityDecl(String name, XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>externalEntityDecl: "+name);
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId:"+ identifier.getExpandedSystemId());
System.out.println(" baseURI:"+ identifier.getBaseSystemId());
}
}
// internal subset string
String publicId = identifier.getPublicId();
String literalSystemId = identifier.getLiteralSystemId();
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!ENTITY ");
if (name.startsWith("%")) {
fInternalSubset.append("% ");
fInternalSubset.append(name.substring(1));
}
else {
fInternalSubset.append(name);
}
fInternalSubset.append(' ');
if (publicId != null) {
fInternalSubset.append("PUBLIC '");
fInternalSubset.append(publicId);
fInternalSubset.append("' '");
}
else {
fInternalSubset.append("SYSTEM '");
}
fInternalSubset.append(literalSystemId);
fInternalSubset.append("'>\n");
}
// NOTE: We only know how to create these nodes for the Xerces
// DOM implementation because DOM Level 2 does not specify
// that functionality. -Ac
// create full node
// don't add parameter entities!
if(name.startsWith("%"))
return;
if (fDocumentType != null) {
NamedNodeMap entities = fDocumentType.getEntities();
EntityImpl entity = (EntityImpl)entities.getNamedItem(name);
if (entity == null) {
entity = (EntityImpl)fDocumentImpl.createEntity(name);
entity.setPublicId(publicId);
entity.setSystemId(literalSystemId);
entity.setBaseURI(identifier.getBaseSystemId());
entities.setNamedItem(entity);
}
}
// create deferred node
if (fDocumentTypeIndex != -1) {
boolean found = false;
int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (nodeIndex != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false);
if (nodeType == Node.ENTITY_NODE) {
String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false);
if (nodeName.equals(name)) {
found = true;
break;
}
}
nodeIndex = fDeferredDocumentImpl.getRealPrevSibling(nodeIndex, false);
}
if (!found) {
int entityIndex = fDeferredDocumentImpl.createDeferredEntity(
name, publicId, literalSystemId, null, identifier.getBaseSystemId());
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex);
}
}
} // externalEntityDecl(String,XMLResourceIdentifier, Augmentations)
/**
* This method notifies of the start of a parameter entity. The parameter
* entity name start with a '%' character.
*
* @param name The name of the parameter entity.
* @param identifier The resource identifier.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal parameter entities).
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startParameterEntity(String name,
XMLResourceIdentifier identifier,
String encoding,
Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>startParameterEntity: "+name);
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId: "+identifier.getExpandedSystemId());
System.out.println(" baseURI:"+ identifier.getBaseSystemId());
}
}
fBaseURIStack.push(identifier.getExpandedSystemId());
}
/**
* This method notifies the end of a parameter entity. Parameter entity
* names begin with a '%' character.
*
* @param name The name of the parameter entity.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endParameterEntity(String name, Augmentations augs) throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>endParameterEntity: "+name);
}
fBaseURIStack.pop();
}
/**
* An unparsed entity declaration.
*
* @param name The name of the entity.
* @param identifier An object containing all location information
* pertinent to this entity.
* @param notation The name of the notation.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void unparsedEntityDecl(String name, XMLResourceIdentifier identifier,
String notation, Augmentations augs)
throws XNIException {
if (DEBUG_EVENTS) {
System.out.println("==>unparsedEntityDecl: "+name);
if (DEBUG_BASEURI) {
System.out.println(" expandedSystemId:"+ identifier.getExpandedSystemId());
System.out.println(" baseURI:"+ identifier.getBaseSystemId());
}
}
// internal subset string
String publicId = identifier.getPublicId();
String literalSystemId = identifier.getLiteralSystemId();
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!ENTITY ");
fInternalSubset.append(name);
fInternalSubset.append(' ');
if (publicId != null) {
fInternalSubset.append("PUBLIC '");
fInternalSubset.append(publicId);
if (literalSystemId != null) {
fInternalSubset.append("' '");
fInternalSubset.append(literalSystemId);
}
}
else {
fInternalSubset.append("SYSTEM '");
fInternalSubset.append(literalSystemId);
}
fInternalSubset.append("' NDATA ");
fInternalSubset.append(notation);
fInternalSubset.append(">\n");
}
// NOTE: We only know how to create these nodes for the Xerces
// DOM implementation because DOM Level 2 does not specify
// that functionality. -Ac
// create full node
if (fDocumentType != null) {
NamedNodeMap entities = fDocumentType.getEntities();
EntityImpl entity = (EntityImpl)entities.getNamedItem(name);
if (entity == null) {
entity = (EntityImpl)fDocumentImpl.createEntity(name);
entity.setPublicId(publicId);
entity.setSystemId(literalSystemId);
entity.setNotationName(notation);
entity.setBaseURI(identifier.getBaseSystemId());
entities.setNamedItem(entity);
}
}
// create deferred node
if (fDocumentTypeIndex != -1) {
boolean found = false;
int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (nodeIndex != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false);
if (nodeType == Node.ENTITY_NODE) {
String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false);
if (nodeName.equals(name)) {
found = true;
break;
}
}
nodeIndex = fDeferredDocumentImpl.getRealPrevSibling(nodeIndex, false);
}
if (!found) {
int entityIndex = fDeferredDocumentImpl.createDeferredEntity(
name, publicId, literalSystemId, notation, identifier.getBaseSystemId());
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex);
}
}
} // unparsedEntityDecl(String,XMLResourceIdentifier, String, Augmentations)
/**
* A notation declaration
*
* @param name The name of the notation.
* @param identifier An object containing all location information
* pertinent to this notation.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void notationDecl(String name, XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
// internal subset string
String publicId = identifier.getPublicId();
String literalSystemId = identifier.getLiteralSystemId();
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!NOTATION ");
fInternalSubset.append(name);
if (publicId != null) {
fInternalSubset.append(" PUBLIC '");
fInternalSubset.append(publicId);
if (literalSystemId != null) {
fInternalSubset.append("' '");
fInternalSubset.append(literalSystemId);
}
}
else {
fInternalSubset.append(" SYSTEM '");
fInternalSubset.append(literalSystemId);
}
fInternalSubset.append("'>\n");
}
// NOTE: We only know how to create these nodes for the Xerces
// DOM implementation because DOM Level 2 does not specify
// that functionality. -Ac
// create full node
if (fDocumentImpl !=null && fDocumentType != null) {
NamedNodeMap notations = fDocumentType.getNotations();
if (notations.getNamedItem(name) == null) {
NotationImpl notation = (NotationImpl)fDocumentImpl.createNotation(name);
notation.setPublicId(publicId);
notation.setSystemId(literalSystemId);
notation.setBaseURI(identifier.getBaseSystemId());
notations.setNamedItem(notation);
}
}
// create deferred node
if (fDocumentTypeIndex != -1) {
boolean found = false;
int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (nodeIndex != -1) {
short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false);
if (nodeType == Node.NOTATION_NODE) {
String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false);
if (nodeName.equals(name)) {
found = true;
break;
}
}
nodeIndex = fDeferredDocumentImpl.getPrevSibling(nodeIndex, false);
}
if (!found) {
int notationIndex = fDeferredDocumentImpl.createDeferredNotation(
name, publicId, literalSystemId, identifier.getBaseSystemId());
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, notationIndex);
}
}
} // notationDecl(String,XMLResourceIdentifier, Augmentations)
/**
* Characters within an IGNORE conditional section.
*
* @param text The ignored text.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignoredCharacters(XMLString text, Augmentations augs) throws XNIException {
} // ignoredCharacters(XMLString, Augmentations)
/**
* An element declaration.
*
* @param name The name of the element.
* @param contentModel The element content model.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void elementDecl(String name, String contentModel, Augmentations augs)
throws XNIException {
// internal subset string
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!ELEMENT ");
fInternalSubset.append(name);
fInternalSubset.append(' ');
fInternalSubset.append(contentModel);
fInternalSubset.append(">\n");
}
} // elementDecl(String,String)
/**
* An attribute declaration.
*
* @param elementName The name of the element that this attribute
* is associated with.
* @param attributeName The name of the attribute.
* @param type The attribute type. This value will be one of
* the following: "CDATA", "ENTITY", "ENTITIES",
* "ENUMERATION", "ID", "IDREF", "IDREFS",
* "NMTOKEN", "NMTOKENS", or "NOTATION".
* @param enumeration If the type has the value "ENUMERATION" or
* "NOTATION", this array holds the allowed attribute
* values; otherwise, this array is null.
* @param defaultType The attribute default type. This value will be
* one of the following: "#FIXED", "#IMPLIED",
* "#REQUIRED", or null.
* @param defaultValue The attribute default value, or null if no
* default value is specified.
* @param nonNormalizedDefaultValue The attribute default value with no normalization
* performed, or null if no default value is specified.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void attributeDecl(String elementName, String attributeName,
String type, String[] enumeration,
String defaultType, XMLString defaultValue,
XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException {
// internal subset string
if (fInternalSubset != null && !fInDTDExternalSubset) {
fInternalSubset.append("<!ATTLIST ");
fInternalSubset.append(elementName);
fInternalSubset.append(' ');
fInternalSubset.append(attributeName);
fInternalSubset.append(' ');
if (type.equals("ENUMERATION")) {
fInternalSubset.append('(');
for (int i = 0; i < enumeration.length; i++) {
if (i > 0) {
fInternalSubset.append('|');
}
fInternalSubset.append(enumeration[i]);
}
fInternalSubset.append(')');
}
else {
fInternalSubset.append(type);
}
if (defaultType != null) {
fInternalSubset.append(' ');
fInternalSubset.append(defaultType);
}
if (defaultValue != null) {
fInternalSubset.append(" '");
for (int i = 0; i < defaultValue.length; i++) {
char c = defaultValue.ch[defaultValue.offset + i];
if (c == '\'') {
fInternalSubset.append("'");
}
else {
fInternalSubset.append(c);
}
}
fInternalSubset.append('\'');
}
fInternalSubset.append(">\n");
}
// deferred expansion
if (fDeferredDocumentImpl != null) {
// get the default value
if (defaultValue != null) {
// get element definition
int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition(elementName);
// create element definition if not already there
if (elementDefIndex == -1) {
elementDefIndex = fDeferredDocumentImpl.createDeferredElementDefinition(elementName);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, elementDefIndex);
}
// add default attribute
int attrIndex = fDeferredDocumentImpl.createDeferredAttribute(
attributeName, defaultValue.toString(), false);
if (type.equals("ID")) {
fDeferredDocumentImpl.setIdAttribute(attrIndex);
}
// REVISIT: set ID type correctly
fDeferredDocumentImpl.appendChild(elementDefIndex, attrIndex);
}
} // if deferred
// full expansion
else if (fDocumentImpl != null) {
// get the default value
if (defaultValue != null) {
// get element definition node
NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements();
ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem(elementName);
if (elementDef == null) {
elementDef = fDocumentImpl.createElementDefinition(elementName);
((DocumentTypeImpl)fDocumentType).getElements().setNamedItem(elementDef);
}
// REVISIT: Check for uniqueness of element name? -Ac
// create attribute and set properties
boolean nsEnabled = fNamespaceAware;
AttrImpl attr;
if (nsEnabled) {
String namespaceURI = null;
// DOM Level 2 wants all namespace declaration attributes
// So as long as the XML parser doesn't do it, it needs to
// done here.
if (attributeName.startsWith("xmlns:") ||
attributeName.equals("xmlns")) {
namespaceURI = NamespaceContext.XMLNS_URI;
}
attr = (AttrImpl)fDocumentImpl.createAttributeNS(namespaceURI,
attributeName);
}
else {
attr = (AttrImpl)fDocumentImpl.createAttribute(attributeName);
}
attr.setValue(defaultValue.toString());
attr.setSpecified(false);
attr.setIdAttribute(type.equals("ID"));
// add default attribute to element definition
if (nsEnabled){
elementDef.getAttributes().setNamedItemNS(attr);
}
else {
elementDef.getAttributes().setNamedItem(attr);
}
}
} // if NOT defer-node-expansion
} // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations)
/**
* The start of an attribute list.
*
* @param elementName The name of the element that this attribute
* list is associated with.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startAttlist(String elementName, Augmentations augs) throws XNIException {
} // startAttlist(String)
/**
* The end of an attribute list.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endAttlist(Augmentations augs) throws XNIException {
} // endAttlist()
// method to create an element node.
// subclasses can override this method to create element nodes in other ways.
protected Element createElementNode(QName element) {
Element el = null;
if (fNamespaceAware) {
// if we are using xerces DOM implementation, call our
// own constructor to reuse the strings we have here.
if (fDocumentImpl != null) {
el = fDocumentImpl.createElementNS(element.uri, element.rawname,
element.localpart);
}
else {
el = fDocument.createElementNS(element.uri, element.rawname);
}
}
else {
el = fDocument.createElement(element.rawname);
}
return el;
}
// method to create an attribute node.
// subclasses can override this method to create attribute nodes in other ways.
protected Attr createAttrNode(QName attrQName) {
Attr attr = null;
if (fNamespaceAware) {
if (fDocumentImpl != null) {
// if we are using xerces DOM implementation, call our
// own constructor to reuse the strings we have here.
attr = fDocumentImpl.createAttributeNS(attrQName.uri,
attrQName.rawname,
attrQName.localpart);
}
else {
attr = fDocument.createAttributeNS(attrQName.uri,
attrQName.rawname);
}
}
else {
attr = fDocument.createAttribute(attrQName.rawname);
}
return attr;
}
/*
* When the first characters() call is received, the data is stored in
* a new Text node. If right after the first characters() we receive another chunk of data,
* the data from the Text node, following the new characters are appended
* to the fStringBuffer and the text node data is set to empty.
*
* This function is called when the state is changed and the
* data must be appended to the current node.
*
* Note: if DOMFilter is set, you must make sure that if Node is skipped,
* or removed fFistChunk must be set to true, otherwise some data can be lost.
*
*/
protected void setCharacterData(boolean sawChars){
// handle character data
fFirstChunk = sawChars;
// if we have data in the buffer we must have created
// a text node already.
Node child = fCurrentNode.getLastChild();
if (child != null) {
if (fStringBuffer.length() > 0) {
// REVISIT: should this check be performed?
if (child.getNodeType() == Node.TEXT_NODE) {
if (fDocumentImpl != null) {
((TextImpl)child).replaceData(fStringBuffer.toString());
}
else {
((Text)child).setData(fStringBuffer.toString());
}
}
// reset string buffer
fStringBuffer.setLength(0);
}
if (fDOMFilter !=null) {
if ((fDOMFilter.getWhatToShow() & NodeFilter.SHOW_TEXT)!= 0) {
short code = fDOMFilter.acceptNode(child);
switch (code) {
case DOMBuilderFilter.FILTER_INTERRUPT:{
throw new RuntimeException("The normal processing of the document was interrupted.");
}
case NodeFilter.FILTER_REJECT:{
// fall through to SKIP since Comment has no children.
}
case NodeFilter.FILTER_SKIP: {
fCurrentNode.removeChild(child);
return;
}
default: {
// accept node -- do nothing
}
}
}
} // end-if fDOMFilter !=null
} // end-if child !=null
}
} // class AbstractDOMParser
|
package beginner;
import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
public class AboutBitwiseOperators {
@Koan
public void fullAnd() {
int i = 1;
if (true & (++i < 8)) i = i + 1;
assertEquals(i, 3);
}
@Koan
public void shortCircuitAnd() {
int i = 1;
if (true && (i < -28)) i = i + 1;
assertEquals(i, 1);
}
@Koan
public void aboutXOR() {
int i = 1;
int a = 6;
if ((a < 9) ^ false) i = i + 1;
assertEquals(i, 2);
}
@Koan
public void dontMistakeEqualsForEqualsEquals() {
int i = 1;
boolean a = false;
if (a = true) i++;
assertEquals(a, true);
assertEquals(i, 2);
// How could you write the condition 'with a twist' to avoid this trap?
}
@Koan
public void aboutBitShiftingRightShift() {
int rightShift = 8;
rightShift = rightShift >> 1;
assertEquals(rightShift, 4);
}
@Koan
public void aboutBitShiftingLeftShift() {
int leftShift = 0x80000000; // Is this number positive or negative?
leftShift = leftShift << 1;
assertEquals(leftShift, 0);
}
@Koan
public void aboutBitShiftingRightUnsigned() {
int rightShiftNegativeStaysNegative = 0x80000000;
rightShiftNegativeStaysNegative = rightShiftNegativeStaysNegative >> 4;
assertEquals(rightShiftNegativeStaysNegative, -134217728);
int unsignedRightShift = 0x80000000; // always fills with 0
unsignedRightShift >>>= 4; // Just like +=
assertEquals(unsignedRightShift, 134217728);
}
}
|
//FILE: MMStudio.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager;
import bsh.EvalError;
import bsh.Interpreter;
import com.google.common.eventbus.Subscribe;
import com.swtdesigner.SwingResourceManager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.prefs.Preferences;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.StrVector;
import mmcorej.TaggedImage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.acquisition.*;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DataProcessor;
import org.micromanager.api.IAcquisitionEngine2010;
import org.micromanager.api.ImageCache;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.api.MMTags;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.SequenceSettings;
import org.micromanager.api.events.ExposureChangedEvent;
import org.micromanager.api.events.PropertiesChangedEvent;
import org.micromanager.conf2.MMConfigFileException;
import org.micromanager.conf2.MicroscopeModel;
import org.micromanager.dialogs.AcqControlDlg;
import org.micromanager.dialogs.CalibrationListDlg;
import org.micromanager.dialogs.MMIntroDlg;
import org.micromanager.dialogs.RegistrationDlg;
import org.micromanager.events.EventManager;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.graph.HistogramSettings;
import org.micromanager.imagedisplay.DisplayWindow;
import org.micromanager.imagedisplay.MetadataPanel;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.logging.LogFileManager;
import org.micromanager.menus.FileMenu;
import org.micromanager.menus.HelpMenu;
import org.micromanager.menus.ToolsMenu;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.pipelineinterface.PipelineFrame;
import org.micromanager.pluginmanagement.PluginManager;
import org.micromanager.positionlist.PositionListDlg;
import org.micromanager.script.ScriptPanel;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.UIMonitor;
import org.micromanager.utils.WaitDialog;
/*
* Implements the ScriptInterface (i.e. primary API) and does various other
* tasks that should probably be refactored out at some point.
*/
public class MMStudio implements ScriptInterface {
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_SAVE_METHOD = "saveMethod";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings";
private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
private static final String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private static final String DEFAULT_CONFIG_FILE_PROPERTY = "org.micromanager.default.config.file";
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry";
// GUI components
private MMOptions options_;
private boolean amRunningAsPlugin_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private PluginManager pluginManager_;
private final SnapLiveManager snapLiveManager_;
private final ToolsMenu toolsMenu_;
private List<Component> MMFrames_
= Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private GraphData lineProfileData_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
private Preferences exposurePrefs_;
private Preferences contrastPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionWrapperEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean isProgramRunning_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private ScriptPanel scriptPanel_;
private PipelineFrame pipelineFrame_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private boolean liveModeSuspended_;
public static final FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudio studio_;
// Our primary window.
private static MainFrame frame_;
// Callback
private CoreEventCallback coreCallback_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private final JMenuBar menuBar_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
public static final FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread acquisitionEngine2010LoadingThread_ = null;
private Class<?> acquisitionEngine2010Class_ = null;
private IAcquisitionEngine2010 acquisitionEngine2010_ = null;
private final StaticInfo staticInfo_;
/**
* Main procedure for stand alone operation.
* @param args
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudio mmStudio = new MMStudio(false);
} catch (ClassNotFoundException e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
} catch (IllegalAccessException e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
} catch (InstantiationException e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
} catch (UnsupportedLookAndFeelException e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
/**
* MMStudio constructor
* @param shouldRunAsPlugin Indicates if we're running from "within" ImageJ,
* which governs our behavior when we are closed.
*/
@SuppressWarnings("LeakingThisInConstructor")
public MMStudio(boolean shouldRunAsPlugin) {
org.micromanager.diagnostics.ThreadExceptionLogger.setUp();
// Set up event handling early, so following code can subscribe/publish
// events as needed.
EventManager manager = new EventManager();
EventManager.register(this);
prepAcquisitionEngine();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
UIMonitor.enable(options_.debugLogEnabled_);
guiColors_ = new GUIColors();
studio_ = this;
amRunningAsPlugin_ = shouldRunAsPlugin;
isProgramRunning_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = new File(DEFAULT_CONFIG_FILE_NAME).getAbsolutePath();
sysConfigFile_ = System.getProperty(DEFAULT_CONFIG_FILE_PROPERTY,
sysConfigFile_);
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = new File(options_.startupScript_).getAbsolutePath();
} else {
startupScriptFile_ = "";
}
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
EXPOSURE_SETTINGS_NODE);
contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
CONTRAST_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
showRegistrationDialogMaybe();
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex,
"Failed to load the MMCoreJ_wrap native library");
}
core_.enableStderrLog(true);
snapLiveManager_ = new SnapLiveManager(studio_, core_);
frame_ = new MainFrame(this, core_, snapLiveManager_, mainPrefs_);
frame_.setIconImage(SwingResourceManager.getImage(MMStudio.class,
"icons/microscope.gif"));
frame_.loadApplicationPrefs(mainPrefs_, options_.closeOnExit_);
ReportingUtils.SetContainingFrame(frame_);
// move ImageJ window to place where it last was if possible
// or else (150,150) if not
if (IJ.getInstance() != null) {
Point ijWinLoc = IJ.getInstance().getLocation();
if (GUIUtils.getGraphicsConfigurationContaining(ijWinLoc.x, ijWinLoc.y) == null) {
// only reach this code if the pref coordinates are off screen
IJ.getInstance().setLocation(150, 150);
}
}
staticInfo_ = new StaticInfo(core_, frame_);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
try {
ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName()) ) );
} catch (ClassNotFoundException ex) {
ReportingUtils.logError(ex, "Class not found error. Should never happen");
}
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
frame_.setBackground(getBackgroundColor());
menuBar_ = new JMenuBar();
frame_.setJMenuBar(menuBar_);
FileMenu fileMenu = new FileMenu(studio_);
fileMenu.initializeFileMenu(menuBar_);
toolsMenu_ = new ToolsMenu(studio_, core_, options_);
toolsMenu_.initializeToolsMenu(menuBar_, mainPrefs_);
HelpMenu helpMenu = new HelpMenu(studio_, core_);
initializationSequence();
helpMenu.initializeHelpMenu(menuBar_, systemPrefs_);
}
/**
* Initialize the program.
*/
private void initializationSequence() {
if (core_ == null) {
// Give up.
return;
}
// Initialize hardware.
String logFileName = LogFileManager.makeLogFileNameForCurrentSession();
new File(logFileName).getParentFile().mkdirs();
try {
core_.setPrimaryLogFile(logFileName);
}
catch (Exception ignore) {
// The Core will have logged the error to stderr, so do nothing.
}
core_.enableDebugLog(options_.debugLogEnabled_);
if (options_.deleteOldCoreLogs_) {
LogFileManager.deleteLogFilesDaysOld(
options_.deleteCoreLogAfterDays_, logFileName);
}
ReportingUtils.setCore(core_);
logStartupProperties();
engine_ = new AcquisitionWrapperEngine(acqMgr_);
// This entity is a class property to avoid garbage collection.
coreCallback_ = new CoreEventCallback(core_, engine_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
engine_.setParentGUI(studio_);
loadMRUConfigFiles();
afMgr_ = new AutofocusManager(studio_);
pluginManager_ = new PluginManager(studio_, menuBar_);
Thread pluginInitializer = pluginManager_.initializePlugins();
frame_.paintToFront();
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Ditto with the image pipeline panel.
createPipelinePanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
if (!options_.doNotAskForConfigFile_) {
// Ask the user for a configuration file.
MMIntroDlg introDlg = new MMIntroDlg(
MMVersion.VERSION_STRING, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(getBackgroundColor());
introDlg.setVisible(true);
introDlg.toFront();
if (!introDlg.okChosen()) {
// User aborted; close the program down.
closeSequence(false);
return;
}
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
// before loading the system configuration, we need to wait
// until the plugins are loaded
final WaitDialog waitDlg = new WaitDialog(
"Loading plugins, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
try {
pluginInitializer.join(15000);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex,
"Interrupted while waiting for plugin loading thread");
}
if (pluginInitializer.isAlive()) {
ReportingUtils.logMessage("Warning: Plugin loading did not finish within 15 seconds; continuing anyway");
}
else {
ReportingUtils.logMessage("Finished waiting for plugins to load");
}
waitDlg.closeDialog();
// if an error occurred during config loading, do not display more
// errors than needed
if (!loadSystemConfiguration()) {
ReportingUtils.showErrorOn(false);
}
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the
// "ChannelGroup" based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_,
studio_, options_);
addMMBackgroundListener(acqControlWin_);
frame_.initializeConfigPad();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException ex) {
// this error should never happen
ReportingUtils.showError(ex);
}
}
centerAndDragListener_ = new CenterAndDragListener(studio_);
zWheelListener_ = new ZWheelListener(core_, studio_);
snapLiveManager_.addLiveModeListener(zWheelListener_);
xyzKeyListener_ = new XYZKeyListener(core_, studio_);
snapLiveManager_.addLiveModeListener(xyzKeyListener_);
// switch error reporting back on
ReportingUtils.showErrorOn(true);
org.micromanager.diagnostics.gui.ProblemReportController.startIfInterruptedOnExit();
}
public void showPipelinePanel() {
pipelineFrame_.setVisible(true);
}
public void showScriptPanel() {
scriptPanel_.setVisible(true);
}
private void handleError(String message) {
snapLiveManager_.setLiveMode(false);
JOptionPane.showMessageDialog(frame_, message);
core_.logMessage(message);
}
public void saveChannelColor(String chName, int rgb) {
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor) {
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException {
ImageCache ic = display.getImageCache();
int channels = ic.getSummaryMetadata().getInt("Channels");
for (int i = 0; i < channels; i++) {
// Make a copy of the image we get, so we don't interfere with
// the Live mode version.
TaggedImage image = ic.getImage(i, 0, 0, 0);
JSONArray names = image.tags.names();
String[] keys = new String[names.length()];
for (int j = 0; j < names.length(); ++j) {
keys[j] = names.getString(j);
}
TaggedImage newImage = new TaggedImage(image.pix,
new JSONObject(image.tags, keys));
addToAlbum(newImage, ic.getDisplayAndComments());
}
}
private void showRegistrationDialogMaybe() {
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
}
/**
* Spawn a new thread to load the acquisition engine jar, because this
* takes significant time (or so Mark claims).
*/
private void prepAcquisitionEngine() {
acquisitionEngine2010LoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
acquisitionEngine2010Class_ = Class.forName("org.micromanager.AcquisitionEngine2010");
} catch (ClassNotFoundException ex) {
ReportingUtils.logError(ex);
acquisitionEngine2010Class_ = null;
}
}
};
acquisitionEngine2010LoadingThread_.setContextClassLoader(getClass().getClassLoader());
acquisitionEngine2010LoadingThread_.start();
}
public void toggleAutoShutter() {
try {
if (frame_.getAutoShutterChecked()) {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
frame_.toggleAutoShutter(false);
} else {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
frame_.toggleAutoShutter(true);
}
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
/**
* Shows images as they appear in the default display window. Uses
* the default processor stack to process images as they arrive on
* the rawImageQueue.
* @param rawImageQueue
* @param displayImageRoutine
*/
public void runDisplayThread(BlockingQueue<TaggedImage> rawImageQueue,
final DisplayImageRoutine displayImageRoutine) {
final BlockingQueue<TaggedImage> processedImageQueue =
ProcessorStack.run(rawImageQueue,
getAcquisitionEngine().getImageProcessors());
new Thread("Display thread") {
@Override
public void run() {
try {
TaggedImage image;
do {
image = processedImageQueue.take();
if (image != TaggedImageQueue.POISON) {
displayImageRoutine.show(image);
}
} while (image != TaggedImageQueue.POISON);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
}.start();
}
public interface DisplayImageRoutine {
public void show(TaggedImage image);
}
/**
* used to store contrast settings to be later used for initialization of contrast of new windows.
* Shouldn't be called by loaded data sets, only
* ones that have been acquired
* @param channelGroup
* @param channel
* @param mda
* @param settings
*/
public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda,
HistogramSettings settings) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_);
contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_);
contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_);
contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_);
contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_);
}
public HistogramSettings loadStoredChannelHistogramSettings(String channelGroup, String channel, boolean mda) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
return new HistogramSettings(
contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0),
contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536),
contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0),
contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1),
contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) );
}
public void setExposure(double exposureTime) {
// This is synchronized with the shutdown lock primarily so that
// the exposure-time field in MainFrame won't cause issues when it loses
// focus during shutdown.
synchronized(shutdownLock_) {
if (core_ == null) {
// Just give up.
return;
}
snapLiveManager_.safeSetCoreExposure(exposureTime);
// Display the new exposure time
double exposure;
try {
exposure = core_.getExposure();
frame_.setDisplayedExposureTime(exposure);
// update current channel in MDA window with this exposure
String channelGroup = core_.getChannelGroup();
String channel = core_.getCurrentConfigFromCache(channelGroup);
if (!channel.equals("") ) {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (options_.syncExposureMainAndMDA_) {
getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure);
}
}
}
catch (Exception e) {
ReportingUtils.logError(e, "Couldn't set exposure time.");
}
} // End synchronization check
}
public double getPreferredWindowMag() {
return options_.windowMag_;
}
public boolean getMetadataFileWithMultipageTiff() {
return options_.mpTiffMetadataFile_;
}
public boolean getSeparateFilesForPositionsMPTiff() {
return options_.mpTiffSeparateFilesForPositions_;
}
@Override
public boolean getHideMDADisplayOption() {
return options_.hideMDADisplay_;
}
public void updateLineProfile() {
if (WindowManager.getCurrentWindow() == null || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
profileWin_.setData(lineProfileData_);
}
public void openLineProfileWindow() {
if (WindowManager.getCurrentWindow() == null ||
WindowManager.getCurrentWindow().isClosed()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(getBackgroundColor());
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
@Override
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBounds();
// If the image has ROI info attached to it, correct for the offsets.
// Otherwise, assume the image was taken with the current camera ROI
// (which is a horrendously buggy way to do things, but that was the
// old behavior and I'm leaving it in case there are cases where it is
// necessary).
Rectangle originalROI = null;
VirtualAcquisitionDisplay virtAcq =
VirtualAcquisitionDisplay.getDisplay(curImage);
JSONObject tags = virtAcq.getCurrentMetadata();
try {
originalROI = MDUtils.getROI(tags);
}
catch (JSONException e) {
}
catch (MMScriptException e) {
}
if (originalROI == null) {
originalROI = getROI();
}
r.x += originalROI.x;
r.y += originalROI.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (MMScriptException e) {
ReportingUtils.showError(e);
}
}
public void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
staticInfo_.refreshValues();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
/**
* Returns instance of the core uManager object;
*/
@Override
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudio
* @return singleton instance of MMStudio
*/
public static MMStudio getInstance() {
return studio_;
}
/**
* Returns singleton instance of MainFrame. You should ideally not need
* to use this function.
* @return singleton instance of the mainFrame
*/
public static MainFrame getFrame() {
return frame_;
}
public MetadataPanel getMetadataPanel() {
return frame_.getMetadataPanel();
}
@Override
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(frame_,
"Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
frame_.setConfigSaveButtonStatus(configChanged_);
frame_.updateTitle(sysConfigFile_);
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
/**
* Get currently used configuration file
* @return - Path to currently used configuration file
*/
public String getSysConfigFile() {
return sysConfigFile_;
}
public void setSysConfigFile(String newFile) {
sysConfigFile_ = newFile;
configChanged_ = false;
frame_.setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
* @param inRAM whether or not to keep data in RAM
*/
public void promptForAcquisitionToOpen(boolean inRAM) {
File f = FileDialogs.openDir(frame_,
"Please select an image data set", MM_DATA_SET);
if (f == null) {
return;
}
String path = f.getParent();
if (f.isDirectory()) {
path = f.getAbsolutePath();
}
try {
openAcquisitionData(path, inRAM);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
@Override
public String openAcquisitionData(String dir, boolean inRAM, boolean show)
throws MMScriptException {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1));
name = acqMgr_.getUniqueAcquisitionName(name);
acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true);
try {
getAcquisition(name).initialize();
} catch (MMScriptException mex) {
acqMgr_.closeAcquisition(name);
throw (mex);
}
return name;
}
/**
* Opens an existing data set. Shows the acquisition in a window.
* @param dir location of data set
* @param inRam whether not to open completely in RAM
* @return The acquisition object.
* @throws org.micromanager.utils.MMScriptException
*/
@Override
public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException {
return openAcquisitionData(dir, inRam, true);
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
String item = frame_.getBinMode();
if (item != null) {
core_.setProperty(StaticInfo.cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item);
}
}
staticInfo_.refreshValues();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(studio_);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
public void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(studio_);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, studio_);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(studio_);
scriptPanel_.setBackground(getBackgroundColor());
addMMBackgroundListener(scriptPanel_);
}
}
private void createPipelinePanel() {
if (pipelineFrame_ == null) {
pipelineFrame_ = new PipelineFrame(studio_, engine_);
pipelineFrame_.setBackground(getBackgroundColor());
addMMBackgroundListener(pipelineFrame_);
}
}
public void updateXYPos(double x, double y) {
staticInfo_.updateXYPos(x, y);
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.updateXYPosRelative(x, y);
}
public void updateZPos(double z) {
staticInfo_.updateZPos(z);
}
public void updateZPosRelative(double z) {
staticInfo_.updateZPosRelative(z);
}
public void updateXYStagePosition() {
staticInfo_.getNewXYStagePosition();
}
public void toggleShutter() {
frame_.toggleShutter();
}
public void updateCenterAndDragListener() {
if (toolsMenu_.getIsCenterAndDragChecked()) {
centerAndDragListener_.start();
} else {
centerAndDragListener_.stop();
}
}
// Ensure that the "XY list..." dialog exists.
private void checkPosListDlg() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, studio_, posList_,
acqControlWin_,options_);
GUIUtils.recallPosition(posListDlg_);
posListDlg_.setBackground(getBackgroundColor());
studio_.addMMBackgroundListener(posListDlg_);
posListDlg_.addListeners();
}
}
// public interface available for scripting access
@Override
public void snapSingleImage() {
doSnap();
}
private boolean isCameraAvailable() {
return StaticInfo.cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
@Override
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
@Override
@Deprecated
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
@Override
@Deprecated
public PositionListDlg getXYPosListDlg() {
checkPosListDlg();
return posListDlg_;
}
@Override
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
@Override
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = MMVersion.VERSION_STRING.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (NumberFormatException ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
@Override
public boolean isLiveModeOn() {
return snapLiveManager_.getIsLiveModeOn();
}
public boolean displayImage(final Object pixels) {
if (pixels instanceof TaggedImage) {
return displayTaggedImage((TaggedImage) pixels, true);
} else {
return displayImage(pixels, true);
}
}
public boolean displayImage(final Object pixels, boolean wait) {
return snapLiveManager_.displayImage(pixels);
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
boolean ret = displayImage(pixels);
snapLiveManager_.setStatusLine(statusLine);
return ret;
}
public void displayStatusLine(String statusLine) {
ImagePlus ip = WindowManager.getCurrentImage();
if (!(ip.getWindow() instanceof DisplayWindow)) {
return;
}
VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine);
}
private boolean isCurrentImageFormatSupported() {
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
return true;
}
return false;
}
public void doSnap() {
doSnap(false);
}
public void doSnap(final boolean shouldAddToAlbum) {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
BlockingQueue<TaggedImage> snapImageQueue =
new LinkedBlockingQueue<TaggedImage>();
try {
core_.snapImage();
long c = core_.getNumberOfCameraChannels();
runDisplayThread(snapImageQueue, new DisplayImageRoutine() {
@Override
public void show(final TaggedImage image) {
if (shouldAddToAlbum) {
try {
addToAlbum(image);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
} else {
displayImage(image);
}
}
});
for (int i = 0; i < c; ++i) {
TaggedImage img = core_.getTaggedImage(i);
MDUtils.setNumChannels(img.tags, (int) c);
snapImageQueue.put(img);
}
snapImageQueue.put(TaggedImageQueue.POISON);
snapLiveManager_.moveDisplayToFront();
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
/**
* Is this function still needed? It does some magic with tags. I found
* it to do harmful thing with tags when a Multi-Camera device is
* present (that issue is now fixed).
* @param ti
*/
public void normalizeTags(TaggedImage ti) {
if (ti != TaggedImageQueue.POISON) {
int channel = 0;
try {
if (ti.tags.has("ChannelIndex")) {
channel = MDUtils.getChannelIndex(ti.tags);
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setPositionIndex(ti.tags, 0);
MDUtils.setSliceIndex(ti.tags, 0);
MDUtils.setFrameIndex(ti.tags, 0);
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
}
}
private boolean displayTaggedImage(TaggedImage ti, boolean update) {
try {
frame_.setCursor(new Cursor(Cursor.WAIT_CURSOR));
// Ensure that the acquisition is ready before we add the image.
snapLiveManager_.validateDisplayAndAcquisition(ti);
MDUtils.setSummary(ti.tags, getAcquisitionWithName(SnapLiveManager.SIMPLE_ACQ).getSummaryMetadata());
staticInfo_.addStagePositionToTags(ti);
addImage(SnapLiveManager.SIMPLE_ACQ, ti, update, true);
} catch (JSONException ex) {
ReportingUtils.logError(ex);
return false;
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
return false;
}
if (update) {
frame_.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
updateLineProfile();
}
return true;
}
private void configureBinningCombo() throws Exception {
if (StaticInfo.cameraLabel_.length() > 0) {
frame_.configureBinningComboForCamera(StaticInfo.cameraLabel_);
}
}
public void initializeGUI() {
try {
staticInfo_.refreshValues();
engine_.setZStageDevice(StaticInfo.zStageLabel_);
configureBinningCombo();
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
frame_.initializeShutterGUI(items);
}
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
frame_.updateAutofocusButtons(afMgr_.getDevice() != null);
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
@Subscribe
public void onPropertiesChanged(PropertiesChangedEvent event) {
updateGUI(true);
}
@Subscribe
public void onExposureChanged(ExposureChangedEvent event) {
if (event.getCameraName().equals(StaticInfo.cameraLabel_)) {
frame_.setDisplayedExposureTime(event.getNewExposureTime());
}
}
public void updateGUI(boolean updateConfigPadStructure) {
updateGUI(updateConfigPadStructure, false);
}
public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) {
ReportingUtils.logMessage("Updating GUI; config pad = " +
updateConfigPadStructure + "; from cache = " + fromCache);
try {
staticInfo_.refreshValues();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
frame_.setDisplayedExposureTime(exp);
configureBinningCombo();
String binSize;
if (fromCache) {
binSize = core_.getPropertyFromCache(StaticInfo.cameraLabel_, MMCoreJ.getG_Keyword_Binning());
} else {
binSize = core_.getProperty(StaticInfo.cameraLabel_, MMCoreJ.getG_Keyword_Binning());
}
frame_.setBinSize(binSize);
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
frame_.setShutterComboSelection(
activeShutter != null ? activeShutter : "");
}
// Set AutoShutterCheckBox
frame_.setAutoShutterSelected(core_.getAutoShutter());
// Set Shutter button
frame_.setShutterButton(core_.getShutterOpen());
if (snapLiveManager_.getIsLiveModeOn()) {
frame_.setToggleShutterButtonEnabled(!core_.getAutoShutter());
}
ConfigGroupPad pad = frame_.getConfigPad();
// state devices
if (updateConfigPadStructure && (pad != null)) {
pad.refreshStructure(fromCache);
// Needed to update read-only properties. May slow things down...
if (!fromCache) {
core_.updateSystemStateCache();
}
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
// update list of pixel sizes in pixel size configuration window
if (calibrationListDlg_ != null) {
calibrationListDlg_.refreshCalibrations();
}
if (propertyBrowser_ != null) {
propertyBrowser_.refresh();
}
ReportingUtils.logMessage("Finished updating GUI");
} catch (Exception e) {
ReportingUtils.logError(e);
}
frame_.updateTitle(sysConfigFile_);
}
// Cancel acquisitions and stop live mode.
public void stopAllActivity() {
if (acquisitionEngine2010_ != null) {
acquisitionEngine2010_.stop();
}
enableLiveMode(false);
}
/**
* Cleans up resources while shutting down
*
* @param calledByImageJ
* @return Whether or not cleanup was successful. Shutdown should abort
* on failure.
*/
private boolean cleanupOnClose(boolean calledByImageJ) {
// Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
// if the configChanged_ flag did not become false, the user
// must have cancelled the configuration saving and we should cancel
// quitting as well
if (configChanged_) {
return false;
}
}
}
snapLiveManager_.setLiveMode(false);
// check needed to avoid deadlock
if (!calledByImageJ) {
if (!WindowManager.closeAllWindows()) {
core_.logMessage("Failed to close some windows");
}
}
if (posListDlg_ != null) {
removeMMBackgroundListener(posListDlg_);
posListDlg_.getToolkit().getSystemEventQueue().postEvent(
new WindowEvent(posListDlg_, WindowEvent.WINDOW_CLOSING));
posListDlg_.dispose();
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (pipelineFrame_ != null) {
removeMMBackgroundListener(pipelineFrame_);
pipelineFrame_.dispose();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.getToolkit().getSystemEventQueue().postEvent(
new WindowEvent(propertyBrowser_, WindowEvent.WINDOW_CLOSING));
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
if (engine_ != null) {
engine_.shutdown();
engine_.disposeProcessors();
}
pluginManager_.disposePlugins();
synchronized (shutdownLock_) {
try {
if (core_ != null) {
ReportingUtils.setCore(null);
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
return true;
}
private void saveSettings() {
frame_.savePrefs(mainPrefs_);
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
mainPrefs_.put(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
public synchronized boolean closeSequence(boolean calledByImageJ) {
if (!getIsProgramRunning()) {
if (core_ != null) {
core_.logMessage("MMStudio::closeSequence called while isProgramRunning_ is false");
}
return true;
}
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(frame_,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return false;
}
}
stopAllActivity();
try {
// Close all image windows associated with MM. Canceling saving of
// any of these should abort shutdown
if (!acqMgr_.closeAllImageWindows()) {
return false;
}
} catch (MMScriptException ex) {
// Not sure what to do here...
}
if (!cleanupOnClose(calledByImageJ)) {
return false;
}
isProgramRunning_ = false;
saveSettings();
try {
frame_.getConfigPad().saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
logError(e);
}
if (options_.closeOnExit_) {
if (!amRunningAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
} else {
frame_.dispose();
}
return true;
}
//TODO: Deprecated @Override
// Last I checked, this is only used by the SlideExplorer plugin.
public ContrastSettings getContrastSettings() {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null )
return null;
return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0);
}
public boolean getIsProgramRunning() {
return isProgramRunning_;
}
/**
* Executes the beanShell script.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, studio_);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.logError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.logError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
* @return true when successful
*/
public boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
frame_.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
coreCallback_.setIgnoring(true);
core_.loadSystemConfiguration(sysConfigFile_);
coreCallback_.setIgnoring(false);
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
waitDlg.closeDialog(); // Prevent from obscuring error alert
ReportingUtils.showError(err,
"Failed to load hardware configuation",
null);
result = false;
} finally {
waitDlg.closeDialog();
}
frame_.setEnabled(true);
initializeGUI();
toolsMenu_.updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg);
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
public List<String> getMRUConfigFiles() {
return MRUConfigFiles_;
}
/**
* Load the most recently used config file(s) to help the user when
* selecting which one to use.
*/
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (sysConfigFile_.length() > 0) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
public void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, studio_, options_);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
public void updateChannelCombos() {
if (acqControlWin_ != null) {
acqControlWin_.updateChannelAndGroupCombo();
}
}
public void autofocusNow() {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if (lmo) {
enableLiveMode(false);
}
afMgr_.getDevice().fullFocus();
if (lmo) {
enableLiveMode(true);
}
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start();
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
// Script interface
@Override
public String getVersion() {
return MMVersion.VERSION_STRING;
}
/**
* Inserts version info for various components in the Corelog
*/
@Override
public void logStartupProperties() {
core_.logMessage("User: " + System.getProperty("user.name"));
String hostname;
try {
hostname = java.net.InetAddress.getLocalHost().getHostName();
}
catch (java.net.UnknownHostException e) {
hostname = "unknown";
}
core_.logMessage("Host: " + hostname);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") +
" (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version"));
core_.logMessage("JVM: " + System.getProperty("java.vm.name") +
", version " + System.getProperty("java.version") + ", " +
System.getProperty("sun.arch.data.model") + "-bit");
}
@Override
public void makeActive() {
frame_.toFront();
}
@Override
public boolean displayImage(TaggedImage ti) {
normalizeTags(ti);
return displayTaggedImage(ti, true);
}
/**
* Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
checkPosListDlg();
posListDlg_.setVisible(true);
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
frame_.setConfigSaveButtonStatus(configChanged_);
}
public boolean getIsConfigChanged() {
return configChanged_;
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated.
* TODO: should we set the background color here as well? Currently there's
* a lot of duplicated code where, every time someone calls this method,
* they also have to manually set their background color for the first time.
* @param comp
*/
@Override
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
* @param comp
*/
@Override
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
/**
* Returns exposure time for the desired preset in the given channelgroup
* Acquires its info from the preferences
* Same thing is used in MDA window, but this class keeps its own copy
*
* @param channelGroup
* @param channel -
* @param defaultExp - default value
* @return exposure time
*/
@Override
public double getChannelExposureTime(String channelGroup, String channel,
double defaultExp) {
return exposurePrefs_.getDouble("Exposure_" + channelGroup
+ "_" + channel, defaultExp);
}
/**
* Updates the exposure time in the given preset
* Will also update current exposure if it the given channel and channelgroup
* are the current one
*
* @param channelGroup -
*
* @param channel - preset for which to change exposure time
* @param exposure - desired exposure time
*/
@Override
public void setChannelExposureTime(String channelGroup, String channel,
double exposure) {
try {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) {
if (channel != null && !channel.equals("") &&
channel.equals(core_.getCurrentConfigFromCache(channelGroup))) {
setExposure(exposure);
}
}
} catch (Exception ex) {
ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: "
+ channelGroup + ", channel: " + channel + ", exposure: " + exposure);
}
}
@Override
public void enableRoiButtons(final boolean enabled) {
frame_.enableRoiButtons(enabled);
}
/**
* Returns the current background color
* @return current background color
*/
@Override
public final Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
frame_.setBackground(guiColors_.background.get((backgroundType)));
frame_.paint(frame_.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
@Override
public ImageWindow getSnapLiveWin() {
return snapLiveManager_.getSnapLiveWindow();
}
@Override
public ImageCache getCacheForWindow(ImageWindow window) throws IllegalArgumentException {
VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(window.getImagePlus());
if (display == null) {
throw new IllegalArgumentException("No matching Micro-Manager display for this window");
}
return display.getImageCache();
}
@Override
public String runAcquisition() throws MMScriptException {
if (SwingUtilities.isEventDispatchThread()) {
throw new MMScriptException("Acquisition can not be run from this (EDT) thread");
}
testForAbortRequests();
if (acqControlWin_ != null) {
String name = acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return name;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String acqName = acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
// ensure that the acquisition has finished.
// This does not seem to work, needs something better
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
boolean finished = false;
while (!finished) {
ImageCache imCache = acq.getImageCache();
if (imCache != null) {
if (imCache.isFinished()) {
finished = true;
} else {
Thread.sleep(100);
}
}
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return acqName;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
/**
* Loads acquisition settings from file
* @param path file containing previously saved acquisition settings
* @throws MMScriptException
*/
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
try {
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(path);
}
} catch (MMScriptException ex) {
throw new MMScriptException(ex.getMessage());
}
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null)
posListDlg_.setPositionList(posList_);
if (engine_ != null)
engine_.setPositionList(posList_);
if (acqControlWin_ != null)
acqControlWin_.updateGUIContents();
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, show, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0,
show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, save);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0,
show, virtual);
}
@Override
@Deprecated
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) {
return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff);
}
/**
* Call initializeAcquisition with values extracted from the provided
* JSONObject.
*/
private void initializeAcquisitionFromTags(String name, JSONObject tags) throws JSONException, MMScriptException {
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int byteDepth = MDUtils.getDepth(tags);
int bitDepth = byteDepth * 8;
if (MDUtils.hasBitDepth(tags)) {
bitDepth = MDUtils.getBitDepth(tags);
}
initializeAcquisition(name, width, height, byteDepth, bitDepth);
}
@Override
public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
//number of multi-cam cameras is set to 1 here for backwards compatibility
//might want to change this later
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getBitDepth();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getByteDepth();
}
@Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getMultiCameraNumChannels();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {
acqMgr_.closeImageWindow(acquisitionName);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
@Override
public void refreshGUIFromCache() {
updateGUI(true, true);
}
@Override
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
@Override
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
@Override
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
@Override
public void enableLiveMode(boolean enable) {
if (core_ == null) {
return;
}
snapLiveManager_.setLiveMode(enable);
}
@Override
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
addToAlbum(taggedImg, null);
}
public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {
normalizeTags(taggedImg);
acqMgr_.addToAlbum(taggedImg,displaySettings);
}
/**
* The basic method for adding images to an existing data set.
* If the acquisition was not previously initialized, it will attempt to
* initialize it from the available image data
* @param frame
* @param channel
* @param slice
* @param position
* @throws org.micromanager.utils.MMScriptException
*/
@Override
public void addImageToAcquisition(String name,
int frame,
int channel,
int slice,
int position,
TaggedImage taggedImg) throws MMScriptException {
// TODO: complete the tag set and initialize the acquisition
MMAcquisition acq = acqMgr_.getAcquisition(name);
// check position, for multi-position data set the number of declared positions should be at least 2
if (acq.getPositions() <= 1 && position > 0) {
throw new MMScriptException("The acquisition was open as a single position data set.\n"
+ "Open acqusition with two or more positions in order to crate a multi-position data set.");
}
// check position, for multi-position data set the number of declared
// positions should be at least 2
if (acq.getChannels() <= channel) {
throw new MMScriptException("This acquisition was opened with " +
acq.getChannels() + " channels.\n" +
"The channel number must not exceed declared number of positions.");
}
JSONObject tags = taggedImg.tags;
// if the acquisition was not previously initialized, set physical
// dimensions of the image
if (!acq.isInitialized()) {
// automatically initialize physical dimensions of the image
try {
initializeAcquisitionFromTags(name, tags);
} catch (JSONException e) {
throw new MMScriptException(e);
}
}
// create required coordinate tags
try {
MDUtils.setFrameIndex(tags, frame);
MDUtils.setChannelIndex(tags, channel);
MDUtils.setSliceIndex(tags, slice);
MDUtils.setPositionIndex(tags, position);
if (!MDUtils.hasSlicesFirst(tags) && !MDUtils.hasTimeFirst(tags)) {
// add default setting
MDUtils.setSlicesFirst(tags, true);
MDUtils.setTimeFirst(tags, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (!MDUtils.hasPositionName(tags)) {
MDUtils.setPositionName(tags, "Pos" + position);
}
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
acq.insertImage(taggedImg);
}
@Override
public void setAcquisitionAddImageAsynchronous(String name) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setAsynchronous();
}
/**
* A quick way to implicitly snap an image and add it to the data set. Works
* in the same way as above.
* @param slice
* @throws org.micromanager.utils.MMScriptException
*/
@Override
public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException {
TaggedImage ti;
try {
if (core_.isSequenceRunning()) {
ti = core_.getLastTaggedImage();
} else {
core_.snapImage();
ti = core_.getTaggedImage();
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setFrameIndex(ti.tags, frame);
MDUtils.setSliceIndex(ti.tags, slice);
MDUtils.setPositionIndex(ti.tags, position);
MMAcquisition acq = acqMgr_.getAcquisition(name);
if (!acq.isInitialized()) {
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
long bitDepth = core_.getImageBitDepth();
int multiCamNumCh = (int) core_.getNumberOfCameraChannels();
acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh);
acq.initialize();
}
if (acq.getPositions() > 1) {
MDUtils.setPositionName(ti.tags, "Pos" + position);
}
addImageToAcquisition(name, frame, channel, slice, position, ti);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
@Override
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
@Override
public String[] getAcquisitionNames()
{
return acqMgr_.getAcquisitionNames();
}
// This function shouldn't be exposed in the API since users shouldn't need
// direct access to Acquisition objects. For internal use, we have
// getAcquisitionWithName(), below.
@Override
@Deprecated
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
public MMAcquisition getAcquisitionWithName(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
@Override
public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException {
return getAcquisition(acquisitionName).getImageCache();
}
@Override
public void message(final String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (scriptPanel_ != null) {
scriptPanel_.message(text);
}
}
});
}
}
@Override
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
@Override
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
@Override
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
@Override
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
@Override
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
@Override
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public String getXYStageName() {
return core_.getXYStageDevice();
}
@Override
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionWrapperEngine getAcquisitionEngine() {
return engine_;
}
public SnapLiveManager getSnapLiveManager() {
return snapLiveManager_;
}
@Override
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
@Override
public IAcquisitionEngine2010 getAcquisitionEngine2010() {
try {
acquisitionEngine2010LoadingThread_.join();
if (acquisitionEngine2010_ == null) {
acquisitionEngine2010_ = (IAcquisitionEngine2010) acquisitionEngine2010Class_.getConstructor(ScriptInterface.class).newInstance(studio_);
}
return acquisitionEngine2010_;
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
return null;
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
return null;
} catch (InstantiationException e) {
ReportingUtils.logError(e);
return null;
} catch (InterruptedException e) {
ReportingUtils.logError(e);
return null;
} catch (NoSuchMethodException e) {
ReportingUtils.logError(e);
return null;
} catch (SecurityException e) {
ReportingUtils.logError(e);
return null;
} catch (InvocationTargetException e) {
ReportingUtils.logError(e);
return null;
}
}
@Override
public void addImageProcessor(DataProcessor<TaggedImage> processor) {
getAcquisitionEngine().addImageProcessor(processor);
}
@Override
public void removeImageProcessor(DataProcessor<TaggedImage> processor) {
getAcquisitionEngine().removeImageProcessor(processor);
}
@Override
public ArrayList<DataProcessor<TaggedImage>> getImageProcessorPipeline() {
return getAcquisitionEngine().getImageProcessorPipeline();
}
@Override
public void registerProcessorClass(Class<? extends DataProcessor<TaggedImage>> processorClass, String name) {
getAcquisitionEngine().registerProcessorClass(processorClass, name);
}
// NB will need @Override tags once these functions are exposed in the
// ScriptInterface.
@Override
public void setImageProcessorPipeline(List<DataProcessor<TaggedImage>> pipeline) {
getAcquisitionEngine().setImageProcessorPipeline(pipeline);
}
@Override
public void setPause(boolean state) {
getAcquisitionEngine().setPause(state);
}
@Override
public boolean isPaused() {
return getAcquisitionEngine().isPaused();
}
@Override
public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) {
getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable);
}
@Override
public void clearRunnables() {
getAcquisitionEngine().clearRunnables();
}
@Override
public SequenceSettings getAcquisitionSettings() {
if (engine_ == null)
return new SequenceSettings();
return engine_.getSequenceSettings();
}
@Override
public void setAcquisitionSettings(SequenceSettings ss) {
if (engine_ == null)
return;
engine_.setSequenceSettings(ss);
acqControlWin_.updateGUIContents();
}
// Deprecated; use correctly spelled version. (Used to be part of API.)
public void setAcqusitionSettings(SequenceSettings ss) {
setAcquisitionSettings(ss);
}
@Override
public String getAcquisitionPath() {
if (engine_ == null)
return null;
return engine_.getImageCache().getDiskLocation();
}
@Override
public void promptToSaveAcquisition(String name, boolean prompt) throws MMScriptException {
getAcquisition(name).promptToSave(prompt);
}
@Override
public void registerForEvents(Object obj) {
EventManager.register(obj);
}
@Override
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
staticInfo_.refreshValues();
if (liveRunning) {
enableLiveMode(true);
}
}
public void setAcquisitionEngine(AcquisitionWrapperEngine eng) {
engine_ = eng;
}
@Override
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
@Override
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
@Override
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
@Override
public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException {
if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) ||
imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) {
throw new MMScriptException("Unrecognized saving class");
}
ImageUtils.setImageStorageClass(imageSavingClass);
if (acqControlWin_ != null) {
acqControlWin_.updateSavingTypeButtons();
}
}
/**
* Allows MMListeners to register themselves
* @param newL
*/
@Override
public void addMMListener(MMListenerInterface newL) {
coreCallback_.addMMListener(newL);
}
/**
* Allows MMListeners to remove themselves
* @param oldL
*/
@Override
public void removeMMListener(MMListenerInterface oldL) {
coreCallback_.removeMMListener(oldL);
}
@Override
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
@Override
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
@Override
public void showMessage(String msg, Component parent) {
ReportingUtils.showMessage(msg, parent);
}
@Override
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
@Override
public void logError(Exception e) {
ReportingUtils.logError(e);
}
@Override
public void logError(String msg) {
ReportingUtils.logError(msg);
}
@Override
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
@Override
public void showError(Exception e) {
ReportingUtils.showError(e);
}
@Override
public void showError(String msg) {
ReportingUtils.showError(msg);
}
@Override
public void showError(Exception e, String msg, Component parent) {
ReportingUtils.showError(e, msg, parent);
}
@Override
public void showError(Exception e, Component parent) {
ReportingUtils.showError(e, parent);
}
@Override
public void showError(String msg, Component parent) {
ReportingUtils.showError(msg, parent);
}
@Override
public void autostretchCurrentWindow() {
VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(WindowManager.getCurrentImage());
if (display != null) {
display.getHistograms().autoscaleAllChannels();
}
}
}
|
package etomica.space;
import etomica.box.Box;
import etomica.lattice.IndexIteratorSizable;
import etomica.math.geometry.Polytope;
/**
* Parent class of boundary objects that describe the size and periodic nature
* of the box boundaries. Each Box has its own instance of this class. It
* may be referenced by a coordinate pair when computing distances between
* atoms, or by a cell iterator when generating neighbor lists. It is also used
* by objects that enforce periodic images.
* <p>
* The boundary is responsible for firing inflate events when the boundary
* dimensions change.
*/
public abstract class Boundary {
protected final Polytope shape;
protected final Space space;
private final Vector center;
protected Box box;
protected BoundaryEvent inflateEvent;
protected BoundaryEventManager eventManager;
/**
* Subclasses must invoke this constructor and provide a Space instance that
* can be used to generate Vectors, and a Polytope that defines the shape
* and volume of the boundary region. Both are final.
*/
public Boundary(Space space, Polytope shape) {
this.space = space;
this.shape = shape;
double zip[] = new double[space.D()];
for (int i = 0; i < space.D(); i++) zip[i] = 0.0;
center = space.makeVector(zip);
eventManager = new BoundaryEventManager();
}
/**
* @return the boundary's Box. Might be null if the boundary is not
* associated with a box.
*/
public Box getBox() {
return box;
}
/**
* Sets the box that holds the boundary. If no box holds the boundary,
* the box should be set to null.
*
* @param newBox the box that holds the boundary
*/
public void setBox(Box newBox) {
box = newBox;
if (box == null) {
inflateEvent = null;
} else {
inflateEvent = new BoundaryEvent(this);
}
}
public Polytope getShape() {
return shape;
}
/**
* @return the volume enclosed by the boundary
*/
public double volume() {
return shape.getVolume();
}
/**
* @return the center point (origin) of the boundary
*/
public Vector getCenter() {
return center;
}
/**
* @return the event manager, which fires notifications about changes to
* this boundary to any added listener.
*/
public BoundaryEventManager getEventManager() {
return eventManager;
}
public abstract IndexIteratorSizable getIndexIterator();
/**
* Set of vectors describing the displacements needed to translate the
* central image to all of the periodic images. The first index specifies
* each periodic image, while the second index indicates the xyz components
* of the translation vector.
*
* @param nShells the number of shells of images to be computed
*/
public abstract double[][] imageOrigins(int nShells);
/**
* Determines the translation vector needed to apply a periodic-image
* transformation that moves the given point to an image point within the
* boundary (if it lies outside, in a direction subject to periodic
* imaging).
*
* @param r vector position of untransformed point; r is not changed by
* this method
* @return the displacement that must be applied to r to move it to its
* central-image location
*/
public abstract Vector centralImage(Vector r);
/**
* The nearest image is the pair of atom images that are closest when all
* periodic-boundary images are considered.
* <p>
* If the vector passed to this method is the displacement vector between
* two points, the vector will be transformed such that it corresponds to
* the vector between the nearest image of those two points.
*
* @param dr the vector to be transformed
*/
public abstract void nearestImage(Vector dr);
/**
* Returns the length of the sides of a rectangular box oriented in the lab
* frame and in which the boundary is inscribed. For a rectangular
* boundary, this is simply the length of the boundary in each direction.
* Each element of the returned vector gives in that coordinate direction
* the maximum distance from one point on the boundary to another.
* <p>
* Manipulation of this copy will not cause any change to the boundary's
* dimensions.
*
* @return the box size
*/
public abstract Vector getBoxSize();
/**
* Scales the boundary dimensions such that the boundary's would be
* inscribed within a rectangle of the of the given size. For a
* rectangular boundary, this simply sets the boundary length in each
* dimension. Specific interpretation of the given values for
* non-rectangular shapes depends on the subclass.
*
* @param v the box's new size
*/
public abstract void setBoxSize(Vector v);
/**
* Returns the vector that defines the edge of this boundary for the given
* dimension. All vectors returned by this method can be considered to
* originate from one corner.
*
* @param d the dimension of the desired edge vector
* @return the edge vector
*/
public abstract Vector getEdgeVector(int d);
/**
* Returns true if the boundary is periodic in the given direction (as
* defined by the getEdgeVector method).
*
* @param d the dimension of the desired periodicity
* @return the periodicity of dimension d
*/
public abstract boolean getPeriodicity(int d);
}
|
package org.apache.xerces.parsers;
import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Hashtable;
import java.util.Locale;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.util.EntityResolverWrapper;
import org.apache.xerces.util.ErrorHandlerWrapper;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLParseException;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.DocumentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DeclHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.LocatorImpl;
/**
* This is the base class of all SAX parsers. It implements both the
* SAX1 and SAX2 parser functionality, while the actual pipeline is
* defined in the parser configuration.
*
* @author Stubs generated by DesignDoc on Mon Sep 11 11:10:57 PDT 2000
* @author Arnaud Le Hors, IBM
* @author Andy Clark, IBM
*
* @version $Id$
*/
public abstract class AbstractSAXParser
extends AbstractXMLDocumentParser
implements Parser, XMLReader // SAX1, SAX2
{
// Constants
// features
/** Feature identifier: namespaces. */
protected static final String NAMESPACES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
/** Feature identifier: namespace prefixes. */
protected static final String NAMESPACE_PREFIXES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE;
// NOTE: The symbol table properties is for internal use. -Ac
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
// Data
// features
/** Namespaces. */
protected boolean fNamespaces;
/** Namespace prefixes. */
protected boolean fNamespacePrefixes = false;
// parser handlers
/** Content handler. */
protected ContentHandler fContentHandler;
/** Document handler. */
protected DocumentHandler fDocumentHandler;
/** DTD handler. */
protected org.xml.sax.DTDHandler fDTDHandler;
/** Decl handler. */
protected DeclHandler fDeclHandler;
/** Lexical handler. */
protected LexicalHandler fLexicalHandler;
protected QName fQName = new QName();
// symbols
/** Symbol: empty string (""). */
private String fEmptySymbol;
private String fXmlnsSymbol;
// state
/**
* True if a parse is in progress. This state is needed because
* some features/properties cannot be set while parsing (e.g.
* validation and namespaces).
*/
protected boolean fParseInProgress = false;
// temp vars
private final AttributesProxy fAttributesProxy = new AttributesProxy();
// Constructors
/** Default constructor. */
protected AbstractSAXParser(XMLParserConfiguration config) {
super(config);
final String[] recognizedFeatures = {
NAMESPACES,
NAMESPACE_PREFIXES,
Constants.SAX_FEATURE_PREFIX + Constants.STRING_INTERNING_FEATURE,
};
config.addRecognizedFeatures(recognizedFeatures);
final String[] recognizedProperties = {
Constants.SAX_PROPERTY_PREFIX + Constants.LEXICAL_HANDLER_PROPERTY,
Constants.SAX_PROPERTY_PREFIX + Constants.DECLARATION_HANDLER_PROPERTY,
Constants.SAX_PROPERTY_PREFIX + Constants.DOM_NODE_PROPERTY,
};
config.addRecognizedProperties(recognizedProperties);
} // <init>(XMLParserConfiguration)
// XMLDocumentHandler methods
/**
* The start of the document.
*
* @param systemId The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
if (locator != null) {
fDocumentHandler.setDocumentLocator(new LocatorProxy(locator));
}
fDocumentHandler.startDocument();
}
// SAX2
if (fContentHandler != null) {
if (locator != null) {
fContentHandler.setDocumentLocator(new LocatorProxy(locator));
}
fContentHandler.startDocument();
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // startDocument(String,String)
/**
* Notifies of the presence of the DOCTYPE line in the document.
*
* @param rootElement The name of the root element.
* @param publicId The public identifier if an external DTD or null
* if the external DTD is specified using SYSTEM.
* @param systemId The system identifier if an external DTD, null
* otherwise.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void doctypeDecl(String rootElement,
String publicId, String systemId, Augmentations augs)
throws XNIException {
fInDTD = true;
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.startDTD(rootElement, publicId, systemId);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // doctypeDecl(String,String,String)
/**
* This method notifies of the start of an entity. The DTD has the
* pseudo-name of "[dtd]" parameter entity names start with '%'; and
* general entity names are just the entity name.
* <p>
* <strong>Note:</strong> Since the document is an entity, the handler
* will be notified of the start of the document entity by calling the
* startEntity method with the entity name "[xml]" <em>before</em> calling
* the startDocument method. When exposing entity boundaries through the
* SAX API, the document entity is never reported, however.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity if the entity
* is external, null otherwise.
* @param systemId The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal parameter entities).
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startEntity(String name, String publicId, String systemId,
String baseSystemId, String encoding, Augmentations augs)
throws XNIException {
startEntity(name, publicId, systemId, baseSystemId, encoding);
} // startEntity(String,String,String,String,String)
/**
* This method notifies the end of an entity. The DTD has the pseudo-name
* of "[dtd]" parameter entity names start with '%'; and general entity
* names are just the entity name.
* <p>
* <strong>Note:</strong> Since the document is an entity, the handler
* will be notified of the end of the document entity by calling the
* endEntity method with the entity name "[xml]" <em>after</em> calling
* the endDocument method. When exposing entity boundaries through the
* SAX API, the document entity is never reported, however.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endEntity(String name, Augmentations augs) throws XNIException {
endEntity(name);
} // endEntity(String)
/**
* The start of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param uri The URI bound to the prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
try {
// SAX2
if (fContentHandler != null) {
fContentHandler.startPrefixMapping(prefix, uri);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // startPrefixMapping(String prefix, String uri)
/**
* The start of an element. If the document specifies the start element
* by using an empty tag, then the startElement method will immediately
* be followed by the endElement method, with no intervening methods.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
fAttributesProxy.setAttributes(attributes);
fDocumentHandler.startElement(element.rawname, fAttributesProxy);
}
// SAX2
if (fContentHandler != null) {
int len = attributes.getLength();
for (int i = len - 1; i >= 0; i
attributes.getName(i, fQName);
if (fQName.prefix == fXmlnsSymbol ||
fQName.rawname == fXmlnsSymbol) {
if (!fNamespacePrefixes) {
// remove namespace declaration attributes
attributes.removeAttributeAt(i);
}
else if (fNamespaces && fNamespacePrefixes) {
// localpart should be empty string as per SAX documentation:
fQName.prefix = fEmptySymbol;
fQName.localpart = fEmptySymbol;
attributes.setName(i, fQName);
}
}
}
String uri = element.uri != null ? element.uri : fEmptySymbol;
String localpart = fNamespaces ? element.localpart : fEmptySymbol;
fAttributesProxy.setAttributes(attributes);
fContentHandler.startElement(uri, localpart, element.rawname,
fAttributesProxy);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // startElement(QName,XMLAttributes)
/**
* Character content.
*
* @param text The content.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void characters(XMLString text, Augmentations augs) throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
fDocumentHandler.characters(text.ch, text.offset, text.length);
}
// SAX2
if (fContentHandler != null) {
fContentHandler.characters(text.ch, text.offset, text.length);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // characters(XMLString)
/**
* Ignorable whitespace. For this method to be called, the document
* source must have some way of determining that the text containing
* only whitespace characters should be considered ignorable. For
* example, the validator can determine if a length of whitespace
* characters in the document are ignorable based on the element
* content model.
*
* @param text The ignorable whitespace.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
fDocumentHandler.ignorableWhitespace(text.ch, text.offset, text.length);
}
// SAX2
if (fContentHandler != null) {
fContentHandler.ignorableWhitespace(text.ch, text.offset, text.length);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // ignorableWhitespace(XMLString)
/**
* The end of an element.
*
* @param element The name of the element.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element, Augmentations augs) throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
fDocumentHandler.endElement(element.rawname);
}
// SAX2
if (fContentHandler != null) {
String uri = element.uri != null ? element.uri : fEmptySymbol;
String localpart = fNamespaces ? element.localpart : fEmptySymbol;
fContentHandler.endElement(uri, localpart,
element.rawname);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endElement(QName)
/**
* The end of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException {
try {
// SAX2
if (fContentHandler != null) {
fContentHandler.endPrefixMapping(prefix);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endPrefixMapping(String)
/**
* The start of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA(Augmentations augs) throws XNIException {
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.startCDATA();
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // startCDATA()
/**
* The end of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA(Augmentations augs) throws XNIException {
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.endCDATA();
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endCDATA()
/**
* A comment.
*
* @param text The text in the comment.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text, Augmentations augs) throws XNIException {
comment (text);
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
processingInstruction (target, data);
} // processingInstruction(String,XMLString)
/**
* The end of the document.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDocument(Augmentations augs) throws XNIException {
try {
// SAX1
if (fDocumentHandler != null) {
fDocumentHandler.endDocument();
}
// SAX2
if (fContentHandler != null) {
fContentHandler.endDocument();
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endDocument()
// XMLDTDHandler methods
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data)
throws XNIException {
// REVISIT - I keep running into SAX apps that expect
// null data to be an empty string, which is contrary
// to the comment for this method in the SAX API.
try {
// SAX1
if (fDocumentHandler != null) {
fDocumentHandler.processingInstruction(target,
data.toString());
}
// SAX2
if (fContentHandler != null) {
fContentHandler.processingInstruction(target, data.toString());
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // processingInstruction(String,XMLString)
/**
* A comment.
*
* @param text The text in the comment.
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text) throws XNIException {
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.comment(text.ch, 0, text.length);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // comment(XMLString)
/**
* This method notifies of the start of an entity. The DTD has the
* pseudo-name of "[dtd]" parameter entity names start with '%'; and
* general entity names are just the entity name.
* <p>
* <strong>Note:</strong> Since the document is an entity, the handler
* will be notified of the start of the document entity by calling the
* startEntity method with the entity name "[xml]" <em>before</em> calling
* the startDocument method. When exposing entity boundaries through the
* SAX API, the document entity is never reported, however.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity if the entity
* is external, null otherwise.
* @param systemId The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal parameter entities).
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startEntity(String name, String publicId, String systemId,
String baseSystemId, String encoding)
throws XNIException {
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.startEntity(name);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // startEntity(String,String,String,String,String)
/**
* This method notifies the end of an entity. The DTD has the pseudo-name
* of "[dtd]" parameter entity names start with '%'; and general entity
* names are just the entity name.
* <p>
* <strong>Note:</strong> Since the document is an entity, the handler
* will be notified of the end of the document entity by calling the
* endEntity method with the entity name "[xml]" <em>after</em> calling
* the endDocument method. When exposing entity boundaries through the
* SAX API, the document entity is never reported, however.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endEntity(String name) throws XNIException {
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.endEntity(name);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endEntity(String)
/**
* An element declaration.
*
* @param name The name of the element.
* @param contentModel The element content model.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void elementDecl(String name, String contentModel)
throws XNIException {
try {
// SAX2 extension
if (fDeclHandler != null) {
fDeclHandler.elementDecl(name, contentModel);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // elementDecl(String,String)
/**
* An attribute declaration.
*
* @param elementName The name of the element that this attribute
* is associated with.
* @param attributeName The name of the attribute.
* @param type The attribute type. This value will be one of
* the following: "CDATA", "ENTITY", "ENTITIES",
* "ENUMERATION", "ID", "IDREF", "IDREFS",
* "NMTOKEN", "NMTOKENS", or "NOTATION".
* @param enumeration If the type has the value "ENUMERATION" or
* "NOTATION", this array holds the allowed attribute
* values; otherwise, this array is null.
* @param defaultType The attribute default type. This value will be
* one of the following: "#FIXED", "#IMPLIED",
* "#REQUIRED", or null.
* @param defaultValue The attribute default value, or null if no
* default value is specified.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void attributeDecl(String elementName, String attributeName,
String type, String[] enumeration,
String defaultType, XMLString defaultValue)
throws XNIException {
try {
// SAX2 extension
if (fDeclHandler != null) {
if (type.equals("NOTATION")) {
StringBuffer str = new StringBuffer();
str.append(type);
str.append(" (");
for (int i = 0; i < enumeration.length; i++) {
str.append(enumeration[i]);
if (i < enumeration.length - 1) {
str.append('|');
}
}
str.append(')');
type = str.toString();
}
String value = (defaultValue==null) ? null : defaultValue.toString();
fDeclHandler.attributeDecl(elementName, attributeName,
type, defaultType, value);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // attributeDecl(String,String,String,String[],String,XMLString)
/**
* An internal entity declaration.
*
* @param name The name of the entity. Parameter entity names start with
* '%', whereas the name of a general entity is just the
* entity name.
* @param text The value of the entity.
* @param nonNormalizedText The non-normalized value of the entity. This
* value contains the same sequence of characters that was in
* the internal entity declaration, without any entity
* references expanded.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void internalEntityDecl(String name, XMLString text,
XMLString nonNormalizedText)
throws XNIException {
try {
// SAX2 extensions
if (fDeclHandler != null) {
fDeclHandler.internalEntityDecl(name, text.toString());
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // internalEntityDecl(String,XMLString,XMLString)
/**
* An external entity declaration.
*
* @param name The name of the entity. Parameter entity names start
* with '%', whereas the name of a general entity is just
* the entity name.
* @param publicId The public identifier of the entity or null if the
* the entity was specified with SYSTEM.
* @param systemId The system identifier of the entity.
* @param baseSystemId The baseSystem identifier of the entity.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void externalEntityDecl(String name, String publicId,
String systemId, String baseSystemId) throws XNIException {
try {
// SAX2 extension
if (fDeclHandler != null) {
fDeclHandler.externalEntityDecl(name, publicId, systemId);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // externalEntityDecl(String,String,String,String)
/**
* An unparsed entity declaration.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity, or null if not
* specified.
* @param systemId The system identifier of the entity, or null if not
* specified.
* @param notation The name of the notation.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notation)
throws XNIException {
try {
// SAX2 extension
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(name, publicId,
systemId, notation);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // unparsedEntityDecl(String,String,String,String)
/**
* A notation declaration
*
* @param name The name of the notation.
* @param publicId The public identifier of the notation, or null if not
* specified.
* @param systemId The system identifier of the notation, or null if not
* specified.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void notationDecl(String name, String publicId, String systemId)
throws XNIException {
try {
// SAX1 and SAX2
if (fDTDHandler != null) {
fDTDHandler.notationDecl(name, publicId, systemId);
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // notationDecl(String,String,String)
/**
* The end of the DTD.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDTD() throws XNIException {
fInDTD = false;
try {
// SAX2 extension
if (fLexicalHandler != null) {
fLexicalHandler.endDTD();
}
}
catch (SAXException e) {
throw new XNIException(e);
}
} // endDTD()
// Parser and XMLReader methods
/**
* Parses the input source specified by the given system identifier.
* <p>
* This method is equivalent to the following:
* <pre>
* parse(new InputSource(systemId));
* </pre>
*
* @param source The input source.
*
* @exception org.xml.sax.SAXException Throws exception on SAX error.
* @exception java.io.IOException Throws exception on i/o error.
*/
public void parse(String systemId) throws SAXException, IOException {
// parse document
XMLInputSource source = new XMLInputSource(null, systemId, null);
try {
parse(source);
}
// wrap XNI exceptions as SAX exceptions
catch (XMLParseException e) {
Exception ex = e.getException();
if (ex == null) {
// must be a parser exception; mine it for locator info and throw
// a SAXParseException
LocatorImpl locatorImpl = new LocatorImpl();
locatorImpl.setPublicId(e.getPublicId());
locatorImpl.setSystemId(e.getSystemId());
locatorImpl.setLineNumber(e.getLineNumber());
locatorImpl.setColumnNumber(e.getColumnNumber());
throw new SAXParseException(e.getMessage(), locatorImpl);
}
if (ex instanceof SAXException) {
// why did we create an XMLParseException?
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
catch (XNIException e) {
Exception ex = e.getException();
if (ex == null) {
throw new SAXException(e.getMessage());
}
if (ex instanceof SAXException) {
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
// close stream opened by the parser
finally {
try {
Reader reader = source.getCharacterStream();
if (reader != null) {
reader.close();
}
else {
InputStream is = source.getByteStream();
if (is != null) {
is.close();
}
}
}
catch (IOException e) {
// ignore
}
}
} // parse(String)
/**
* parse
*
* @param inputSource
*
* @exception org.xml.sax.SAXException
* @exception java.io.IOException
*/
public void parse(InputSource inputSource)
throws SAXException, IOException {
// parse document
try {
XMLInputSource xmlInputSource =
new XMLInputSource(inputSource.getPublicId(),
inputSource.getSystemId(),
null);
xmlInputSource.setByteStream(inputSource.getByteStream());
xmlInputSource.setCharacterStream(inputSource.getCharacterStream());
xmlInputSource.setEncoding(inputSource.getEncoding());
parse(xmlInputSource);
}
// wrap XNI exceptions as SAX exceptions
catch (XMLParseException e) {
Exception ex = e.getException();
if (ex == null) {
// must be a parser exception; mine it for locator info and throw
// a SAXParseException
LocatorImpl locatorImpl = new LocatorImpl();
locatorImpl.setPublicId(e.getPublicId());
locatorImpl.setSystemId(e.getSystemId());
locatorImpl.setLineNumber(e.getLineNumber());
locatorImpl.setColumnNumber(e.getColumnNumber());
throw new SAXParseException(e.getMessage(), locatorImpl);
}
if (ex instanceof SAXException) {
// why did we create an XMLParseException?
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
catch (XNIException e) {
Exception ex = e.getException();
if (ex == null) {
throw new SAXException(e.getMessage());
}
if (ex instanceof SAXException) {
throw (SAXException)ex;
}
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new SAXException(ex);
}
} // parse(InputSource)
/**
* Sets the resolver used to resolve external entities. The EntityResolver
* interface supports resolution of public and system identifiers.
*
* @param resolver The new entity resolver. Passing a null value will
* uninstall the currently installed resolver.
*/
public void setEntityResolver(EntityResolver resolver) {
try {
fConfiguration.setProperty(ENTITY_RESOLVER,
new EntityResolverWrapper(resolver));
}
catch (XMLConfigurationException e) {
// do nothing
}
} // setEntityResolver(EntityResolver)
/**
* Return the current entity resolver.
*
* @return The current entity resolver, or null if none
* has been registered.
* @see #setEntityResolver
*/
public EntityResolver getEntityResolver() {
EntityResolver entityResolver = null;
try {
XMLEntityResolver xmlEntityResolver =
(XMLEntityResolver)fConfiguration.getProperty(ENTITY_RESOLVER);
if (xmlEntityResolver != null &&
xmlEntityResolver instanceof EntityResolverWrapper) {
entityResolver = ((EntityResolverWrapper)xmlEntityResolver).getEntityResolver();
}
}
catch (XMLConfigurationException e) {
// do nothing
}
return entityResolver;
} // getEntityResolver():EntityResolver
/**
* Allow an application to register an error event handler.
*
* <p>If the application does not register an error handler, all
* error events reported by the SAX parser will be silently
* ignored; however, normal processing may not continue. It is
* highly recommended that all SAX applications implement an
* error handler to avoid unexpected bugs.</p>
*
* <p>Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.</p>
*
* @param errorHandler The error handler.
* @exception java.lang.NullPointerException If the handler
* argument is null.
* @see #getErrorHandler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
try {
fConfiguration.setProperty(ERROR_HANDLER,
new ErrorHandlerWrapper(errorHandler));
}
catch (XMLConfigurationException e) {
// do nothing
}
} // setErrorHandler(ErrorHandler)
/**
* Return the current error handler.
*
* @return The current error handler, or null if none
* has been registered.
* @see #setErrorHandler
*/
public ErrorHandler getErrorHandler() {
ErrorHandler errorHandler = null;
try {
XMLErrorHandler xmlErrorHandler =
(XMLErrorHandler)fConfiguration.getProperty(ERROR_HANDLER);
if (xmlErrorHandler != null &&
xmlErrorHandler instanceof ErrorHandlerWrapper) {
errorHandler = ((ErrorHandlerWrapper)xmlErrorHandler).getErrorHandler();
}
}
catch (XMLConfigurationException e) {
// do nothing
}
return errorHandler;
} // getErrorHandler():ErrorHandler
/**
* Set the locale to use for messages.
*
* @param locale The locale object to use for localization of messages.
*
* @exception SAXException An exception thrown if the parser does not
* support the specified locale.
*
* @see org.xml.sax.Parser
*/
public void setLocale(Locale locale) throws SAXException {
fConfiguration.setLocale(locale);
} // setLocale(Locale)
/**
* Allow an application to register a DTD event handler.
* <p>
* If the application does not register a DTD handler, all DTD
* events reported by the SAX parser will be silently ignored.
* <p>
* Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.
*
* @param dtdHandler The DTD handler.
*
* @exception java.lang.NullPointerException If the handler
* argument is null.
*
* @see #getDTDHandler
*/
public void setDTDHandler(DTDHandler dtdHandler) {
// REVISIT: SAX1 doesn't require a null pointer exception
// to be thrown but SAX2 does. [Q] How do we
// resolve this? Currently I'm erring on the side
// of SAX2. -Ac
if (dtdHandler == null) {
throw new NullPointerException();
}
fDTDHandler = dtdHandler;
} // setDTDHandler(DTDHandler)
// Parser methods
/**
* Allow an application to register a document event handler.
* <p>
* If the application does not register a document handler, all
* document events reported by the SAX parser will be silently
* ignored (this is the default behaviour implemented by
* HandlerBase).
* <p>
* Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.
*
* @param documentHandler The document handler.
*/
public void setDocumentHandler(DocumentHandler documentHandler) {
fDocumentHandler = documentHandler;
} // setDocumentHandler(DocumentHandler)
// XMLReader methods
/**
* Allow an application to register a content event handler.
* <p>
* If the application does not register a content handler, all
* content events reported by the SAX parser will be silently
* ignored.
* <p>
* Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.
*
* @param contentHandler The content handler.
*
* @exception java.lang.NullPointerException If the handler
* argument is null.
*
* @see #getContentHandler
*/
public void setContentHandler(ContentHandler contentHandler) {
fContentHandler = contentHandler;
} // setContentHandler(ContentHandler)
/**
* Return the current content handler.
*
* @return The current content handler, or null if none
* has been registered.
*
* @see #setContentHandler
*/
public ContentHandler getContentHandler() {
return fContentHandler;
} // getContentHandler():ContentHandler
/**
* Return the current DTD handler.
*
* @return The current DTD handler, or null if none
* has been registered.
* @see #setDTDHandler
*/
public DTDHandler getDTDHandler() {
return fDTDHandler;
} // getDTDHandler():DTDHandler
/**
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception SAXNotRecognizedException If the
* requested feature is not known.
* @exception SAXNotSupportedException If the
* requested feature is known, but the requested
* state is not supported.
*/
public void setFeature(String featureId, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
// SAX2 Features
if (featureId.startsWith(Constants.SAX_FEATURE_PREFIX)) {
String feature = featureId.substring(Constants.SAX_FEATURE_PREFIX.length());
if (feature.equals(Constants.NAMESPACES_FEATURE)) {
fConfiguration.setFeature(featureId, state);
fNamespaces = state;
return;
}
// controls the reporting of raw prefixed names and Namespace
// declarations (xmlns* attributes): when this feature is false
// (the default), raw prefixed names may optionally be reported,
// and xmlns* attributes must not be reported.
if (feature.equals(Constants.NAMESPACE_PREFIXES_FEATURE)) {
fConfiguration.setFeature(featureId, state);
fNamespacePrefixes = state;
return;
}
// controls the use of java.lang.String#intern() for strings
// passed to SAX handlers.
if (feature.equals(Constants.STRING_INTERNING_FEATURE)) {
if (!state) {
// REVISIT: Localize this error message. -Ac
throw new SAXNotSupportedException(
"PAR018 " + state + " state for feature \"" + featureId
+ "\" is not supported.\n" + state + '\t' + featureId);
}
return;
}
// Drop through and perform default processing
}
// Xerces Features
/*
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
//
// Drop through and perform default processing
//
}
*/
// Default handling
fConfiguration.setFeature(featureId, state);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // setFeature(String,boolean)
/**
* Query the state of a feature.
*
* Query the current state of any feature in a SAX2 parser. The
* parser might not recognize the feature.
*
* @param featureId The unique identifier (URI) of the feature
* being set.
* @return The current state of the feature.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested feature is not known.
* @exception SAXNotSupportedException If the
* requested feature is known but not supported.
*/
public boolean getFeature(String featureId)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
// SAX2 Features
if (featureId.startsWith(Constants.SAX_FEATURE_PREFIX)) {
String feature =
featureId.substring(Constants.SAX_FEATURE_PREFIX.length());
// controls the reporting of raw prefixed names and Namespace
// declarations (xmlns* attributes): when this feature is false
// (the default), raw prefixed names may optionally be reported,
// and xmlns* attributes must not be reported.
if (feature.equals(Constants.NAMESPACE_PREFIXES_FEATURE)) {
boolean state = fConfiguration.getFeature(featureId);
return state;
}
// controls the use of java.lang.String#intern() for strings
// passed to SAX handlers.
if (feature.equals(Constants.STRING_INTERNING_FEATURE)) {
return true;
}
// Drop through and perform default processing
}
// Xerces Features
/*
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
//
// Drop through and perform default processing
//
}
*/
return fConfiguration.getFeature(featureId);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // getFeature(String):boolean
/**
* Set the value of any property in a SAX2 parser. The parser
* might not recognize the property, and if it does recognize
* it, it might not support the requested value.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @param Object The value to which the property is being set.
*
* @exception SAXNotRecognizedException If the
* requested property is not known.
* @exception SAXNotSupportedException If the
* requested property is known, but the requested
* value is not supported.
*/
public void setProperty(String propertyId, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
// SAX2 core properties
if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) {
String property =
propertyId.substring(Constants.SAX_PROPERTY_PREFIX.length());
// Value type: org.xml.sax.ext.LexicalHandler
// Access: read/write, pre-parse only
// Set the lexical event handler.
if (property.equals(Constants.LEXICAL_HANDLER_PROPERTY)) {
try {
setLexicalHandler((LexicalHandler)value);
}
catch (ClassCastException e) {
// REVISIT: Localize this error message. -ac
throw new SAXNotSupportedException(
"PAR012 For propertyID \""
+propertyId+"\", the value \""
+value+"\" cannot be cast to LexicalHandler."
+'\n'+propertyId+'\t'+value+"\tLexicalHandler");
}
return;
}
// Value type: org.xml.sax.ext.DeclHandler
// Access: read/write, pre-parse only
// Set the DTD declaration event handler.
if (property.equals(Constants.DECLARATION_HANDLER_PROPERTY)) {
try {
setDeclHandler((DeclHandler)value);
}
catch (ClassCastException e) {
// REVISIT: Localize this error message. -ac
throw new SAXNotSupportedException(
"PAR012 For propertyID \""
+propertyId+"\", the value \""
+value+"\" cannot be cast to DeclHandler."
+'\n'+propertyId+'\t'+value+"\tDeclHandler"
);
}
return;
}
// Value type: DOM Node
// Access: read-only
// Get the DOM node currently being visited, if the SAX parser is
// iterating over a DOM tree. If the parser recognises and
// supports this property but is not currently visiting a DOM
// node, it should return null (this is a good way to check for
// availability before the parse begins).
if (property.equals(Constants.DOM_NODE_PROPERTY)) {
// REVISIT: Localize this error message. -ac
throw new SAXNotSupportedException(
"PAR013 Property \""+propertyId+"\" is read only."
+'\n'+propertyId
); // read-only property
}
// Drop through and perform default processing
}
// Xerces Properties
/*
else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
//
// Drop through and perform default processing
//
}
*/
// Perform default processing
fConfiguration.setProperty(propertyId, value);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // setProperty(String,Object)
/**
* Query the value of a property.
*
* Return the current value of a property in a SAX2 parser.
* The parser might not recognize the property.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @return The current value of the property.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested property is not known.
* @exception SAXNotSupportedException If the
* requested property is known but not supported.
*/
public Object getProperty(String propertyId)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
// SAX2 core properties
if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) {
String property =
propertyId.substring(Constants.SAX_PROPERTY_PREFIX.length());
// Value type: org.xml.sax.ext.LexicalHandler
// Access: read/write, pre-parse only
// Set the lexical event handler.
if (property.equals(Constants.LEXICAL_HANDLER_PROPERTY)) {
return getLexicalHandler();
}
// Value type: org.xml.sax.ext.DeclHandler
// Access: read/write, pre-parse only
// Set the DTD declaration event handler.
if (property.equals(Constants.DECLARATION_HANDLER_PROPERTY)) {
return getDeclHandler();
}
// Value type: DOM Node
// Access: read-only
// Get the DOM node currently being visited, if the SAX parser is
// iterating over a DOM tree. If the parser recognises and
// supports this property but is not currently visiting a DOM
// node, it should return null (this is a good way to check for
// availability before the parse begins).
if (property.equals(Constants.DOM_NODE_PROPERTY)) {
// REVISIT: Localize this error message. -Ac
throw new SAXNotSupportedException(
"PAR014 Cannot getProperty(\""+propertyId
+"\". No DOM Tree exists.\n"+propertyId
); // we are not iterating a DOM tree
}
// Drop through and perform default processing
}
// Xerces properties
/*
else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
//
// Drop through and perform default processing
//
}
*/
// Perform default processing
return fConfiguration.getProperty(propertyId);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // getProperty(String):Object
// Protected methods
// SAX2 core properties
protected void setDeclHandler(DeclHandler handler)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize this error message. -Ac
throw new SAXNotSupportedException(
"PAR011 Feature: http://xml.org/sax/properties/declaration-handler"
+" is not supported during parse."
+"\nhttp://xml.org/sax/properties/declaration-handler");
}
fDeclHandler = handler;
} // setDeclHandler(DeclHandler)
/**
* Returns the DTD declaration event handler.
*
* @see #setDeclHandler
*/
protected DeclHandler getDeclHandler()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fDeclHandler;
} // getDeclHandler():DeclHandler
protected void setLexicalHandler(LexicalHandler handler)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize this error message. -Ac
throw new SAXNotSupportedException(
"PAR011 Feature: http://xml.org/sax/properties/lexical-handler"
+" is not supported during parse."
+"\nhttp://xml.org/sax/properties/lexical-handler");
}
fLexicalHandler = handler;
} // setLexicalHandler(LexicalHandler)
/**
* Returns the lexical handler.
*
* @see #setLexicalHandler
*/
protected LexicalHandler getLexicalHandler()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fLexicalHandler;
} // getLexicalHandler():LexicalHandler
// XMLDocumentParser methods
/**
* Reset all components before parsing.
*
* @throws SAXException Thrown if an error occurs during initialization.
*/
public void reset() throws XNIException {
super.reset();
// reset state
fInDTD = false;
// features
fNamespaces = fConfiguration.getFeature(NAMESPACES);
fNamespacePrefixes = fConfiguration.getFeature(NAMESPACE_PREFIXES);
// save needed symbols
SymbolTable symbolTable = (SymbolTable)fConfiguration.getProperty(SYMBOL_TABLE);
if (symbolTable != null) {
fEmptySymbol = symbolTable.addSymbol("");
fXmlnsSymbol = symbolTable.addSymbol("xmlns");
}
} // reset()
// Classes
protected static class LocatorProxy
implements Locator {
// Data
/** XML locator. */
protected XMLLocator fLocator;
// Constructors
/** Constructs an XML locator proxy. */
public LocatorProxy(XMLLocator locator) {
fLocator = locator;
}
// Locator methods
/** Public identifier. */
public String getPublicId() {
return fLocator.getPublicId();
}
/** System identifier. */
public String getSystemId() {
return fLocator.getSystemId();
}
/** Line number. */
public int getLineNumber() {
return fLocator.getLineNumber();
}
/** Column number. */
public int getColumnNumber() {
return fLocator.getColumnNumber();
}
} // class LocatorProxy
protected static final class AttributesProxy
implements AttributeList, Attributes {
// Data
/** XML attributes. */
protected XMLAttributes fAttributes;
// Public methods
/** Sets the XML attributes. */
public void setAttributes(XMLAttributes attributes) {
fAttributes = attributes;
} // setAttributes(XMLAttributes)
public int getLength() {
return fAttributes.getLength();
}
public String getName(int i) {
return fAttributes.getQName(i);
}
public String getQName(int index) {
return fAttributes.getQName(index);
}
public String getURI(int index) {
// REVISIT: this hides the fact that internally we use
// null instead of empty string
// SAX requires URI to be a string or an empty string
String uri= fAttributes.getURI(index);
return uri != null ? uri : "";
}
public String getLocalName(int index) {
return fAttributes.getLocalName(index);
}
public String getType(int i) {
return fAttributes.getType(i);
}
public String getType(String name) {
return fAttributes.getType(name);
}
public String getType(String uri, String localName) {
return uri.equals("") ? fAttributes.getType(null, localName) :
fAttributes.getType(uri, localName);
}
public String getValue(int i) {
return fAttributes.getValue(i);
}
public String getValue(String name) {
return fAttributes.getValue(name);
}
public String getValue(String uri, String localName) {
return uri.equals("") ? fAttributes.getValue(null, localName) :
fAttributes.getValue(uri, localName);
}
public int getIndex(String qName) {
return fAttributes.getIndex(qName);
}
public int getIndex(String uri, String localPart) {
return uri.equals("") ? fAttributes.getIndex(null, localPart) :
fAttributes.getIndex(uri, localPart);
}
} // class AttributesProxy
} // class AbstractSAXParser
|
package jodd.petite;
import junit.framework.TestCase;
import jodd.petite.config.AutomagicPetiteConfigurator;
import jodd.petite.test.Boo;
import jodd.petite.test.BooC;
import jodd.petite.test.BooC2;
import jodd.petite.test.Foo;
import jodd.petite.test.Zoo;
import jodd.petite.test.Goo;
import jodd.petite.test.Loo;
import jodd.petite.test.Ioo;
import jodd.petite.test.impl.DefaultIoo;
import jodd.petite.scope.ProtoScope;
import java.util.List;
public class WireTest extends TestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
Foo.instanceCounter = 0;
}
public void testContainer() {
PetiteContainer pc = new PetiteContainer();
AutomagicPetiteConfigurator configurator = new AutomagicPetiteConfigurator();
configurator.setIncludedEntries("jodd.petite.*");
configurator.setExcludedEntries("jodd.petite.data.*", "jodd.petite.test3.*");
configurator.configure(pc);
assertEquals(1, pc.getTotalBeans());
assertEquals(1, pc.getTotalScopes());
assertEquals(0, Foo.instanceCounter);
Foo foo = (Foo) pc.getBean("foo");
assertNotNull(foo);
assertEquals(1, foo.hello());
foo = (Foo) pc.getBean("foo");
assertEquals(1, foo.hello());
// register again the same class, but this time with proto scope
pc.registerBean("foo2", Foo.class, ProtoScope.class);
assertEquals(2, pc.getTotalBeans());
assertEquals(2, pc.getTotalScopes());
assertEquals(2, ((Foo) pc.getBean("foo2")).hello());
assertEquals(3, ((Foo) pc.getBean("foo2")).hello());
// register boo
pc.registerBean(Boo.class);
assertEquals(3, pc.getTotalBeans());
assertEquals(2, pc.getTotalScopes());
Boo boo;
try {
//noinspection UnusedAssignment
boo = (Boo) pc.getBean("boo");
fail();
} catch (PetiteException pex) {
// zoo class is missing
}
pc.registerBean(Zoo.class);
assertEquals(4, pc.getTotalBeans());
assertEquals(2, pc.getTotalScopes());
boo = (Boo) pc.getBean("boo");
assertNotNull(boo);
assertNotNull(boo.getFoo());
assertNotNull(boo.zoo);
assertSame(boo.zoo.boo, boo);
assertEquals(3, boo.getFoo().hello());
assertEquals(1, boo.getFoo().getCounter());
}
public void testCreate() {
PetiteContainer pc = new PetiteContainer();
pc.registerBean(Foo.class);
pc.registerBean(Zoo.class);
pc.registerBean(Boo.class);
assertEquals(3, pc.getTotalBeans());
assertEquals(1, pc.getTotalScopes());
assertEquals(0, Foo.instanceCounter);
Boo boo = pc.createBean(Boo.class);
assertNotNull(boo);
assertNotNull(boo.getFoo());
assertNotNull(boo.zoo);
assertNotSame(boo.zoo.boo, boo); // not equal instances!!!
assertEquals(1, boo.getFoo().hello());
assertEquals(1, boo.getCount());
}
public void testCtor() {
PetiteContainer pc = new PetiteContainer();
pc.registerBean(BooC.class);
pc.registerBean(Foo.class);
assertEquals(2, pc.getTotalBeans());
assertEquals(1, pc.getTotalScopes());
assertEquals(0, Foo.instanceCounter);
BooC boo = (BooC) pc.getBean("booC");
assertNotNull(boo);
assertNotNull(boo.getFoo());
assertEquals(1, boo.getFoo().hello());
pc.registerBean("boo", BooC2.class);
pc.registerBean(Zoo.class);
assertEquals(4, pc.getTotalBeans());
assertEquals(1, pc.getTotalScopes());
assertEquals(1, Foo.instanceCounter);
try {
pc.getBean("boo");
fail();
} catch (PetiteException pex) {
// ignore // cyclic dependency
}
}
public void testAutowire() {
PetiteContainer pc = new PetiteContainer();
pc.registerBean(Goo.class, ProtoScope.class);
pc.registerBean(Loo.class);
assertEquals(2, pc.getTotalBeans());
Goo goo = (Goo) pc.getBean("goo");
assertNotNull(goo);
assertNotNull(goo.looCustom);
assertNull(goo.foo);
pc.registerBean(Foo.class);
goo = (Goo) pc.getBean("goo");
assertNotNull(goo);
assertNotNull(goo.looCustom);
assertNull(goo.foo);
pc = new PetiteContainer();
pc.getConfig().setDefaultWiringMode(WiringMode.AUTOWIRE);
pc.registerBean(Goo.class, ProtoScope.class);
pc.registerBean(Loo.class);
pc.registerBean(Foo.class);
goo = (Goo) pc.getBean("goo");
assertNotNull(goo);
assertNotNull(goo.looCustom);
assertNotNull(goo.foo);
pc.removeBean(Goo.class);
}
public void testInterface() {
PetiteContainer pc = new PetiteContainer();
pc.registerBean(Foo.class);
pc.registerBean("ioo", DefaultIoo.class);
assertEquals(2, pc.getTotalBeans());
Ioo ioo = (Ioo) pc.getBean("ioo");
assertNotNull(ioo);
assertNotNull(ioo.getFoo());
assertEquals(DefaultIoo.class, ioo.getClass());
}
public void testSelf() {
PetiteContainer pc = new PetiteContainer();
pc.addSelf();
assertEquals(1, pc.getTotalBeans());
PetiteContainer pc2 = (PetiteContainer) pc.getBean(PetiteContainer.PETITE_CONTAINER_REF_NAME);
assertEquals(pc2, pc);
}
public void testInit() {
PetiteContainer pc = new PetiteContainer();
pc.registerBean(Foo.class);
pc.registerBean(Zoo.class);
pc.registerBean(Boo.class);
pc.registerBean("boo2", Boo.class);
Boo boo = (Boo) pc.getBean("boo");
assertNotNull(boo.getFoo());
assertEquals(1, boo.getCount());
Boo boo2 = (Boo) pc.getBean("boo2");
assertNotSame(boo, boo2);
assertEquals(1, boo2.getCount());
assertSame(boo.getFoo(), boo2.getFoo());
List<String> order = boo.orders;
assertEquals(6, order.size());
assertEquals("first", order.get(0));
assertEquals("second", order.get(1)); // Collections.sort() is stable: equals methods are not reordered.
assertEquals("third", order.get(2));
assertEquals("init", order.get(3));
assertEquals("beforeLast", order.get(4));
assertEquals("last", order.get(5));
}
}
|
package org.biojava.bio.alignment;
import java.util.*;
import org.biojava.bio.BioError;
import org.biojava.bio.seq.*;
public class SimpleMarkovModel implements MarkovModel {
private Alphabet queryAlpha;
private Alphabet stateAlpha;
private Map transFrom;
private Map transTo;
private Map transitionScores;
private Transition _tran = new Transition(null, null);
{
transFrom = new HashMap();
transTo = new HashMap();
transitionScores = new HashMap();
}
public Alphabet queryAlphabet() { return queryAlpha; }
public Alphabet stateAlphabet() { return stateAlpha; }
public double getTransitionScore(State from, State to)
throws IllegalResidueException, IllegalTransitionException {
stateAlphabet().validate(from);
stateAlphabet().validate(to);
_tran.from = from;
_tran.to = to;
Double ts = (Double) transitionScores.get(_tran);
if(ts != null)
return ts.doubleValue();
throw new IllegalTransitionException(from, to);
}
public State sampleTransition(State from) throws IllegalResidueException {
stateAlphabet().validate(from);
double p = Math.random();
try {
for(Iterator i = transitionsFrom(from).iterator(); i.hasNext(); ) {
State s = (State) i.next();
if( (p -= Math.exp(getTransitionScore(from, s))) <= 0 )
return s;
}
} catch (IllegalResidueException ire) {
} catch (IllegalTransitionException ite) {
throw new BioError(ite, "Transition listend in transitionsFrom(" +
from.getName() + "has dissapeared.");
}
StringBuffer sb = new StringBuffer();
for(Iterator i = transitionsFrom(from).iterator(); i.hasNext(); ) {
try {
State s = (State) i.next();
double t = getTransitionScore(from, s);
if(t > 0.0)
sb.append("\t" + s.getName() + " -> " + t + "\n");
} catch (IllegalTransitionException ite) {
throw new BioError(ite, "Transition listend in transitionsFrom(" +
from.getName() + "has dissapeared.");
}
}
throw new IllegalResidueException("Could not find transition from state " +
from.getName() +
". Do the probabilities sum to 1?" +
"\np=" + p + "\n" + sb.toString());
}
public void setTransitionScore(State from, State to, double value)
throws IllegalResidueException, IllegalTransitionException {
stateAlphabet().validate(from);
stateAlphabet().validate(to);
_tran.from = from;
_tran.to = to;
if(transitionScores.containsKey(_tran)) {
transitionScores.put(_tran, new Double(value));
} else {
throw new IllegalTransitionException(from, to, "No transition from " + from.getName() +
" to " + to.getName() + " defined");
}
}
public void createTransition(State from, State to)
throws IllegalResidueException {
stateAlphabet().validate(from);
stateAlphabet().validate(to);
transitionScores.put(new Transition(from, to),
new Double(Double.NEGATIVE_INFINITY));
Set t = transitionsTo(to);
Set f = transitionsFrom(from);
f.add(to);
t.add(from);
}
public void destroyTransition(State from, State to)
throws IllegalResidueException {
stateAlphabet().validate(from);
stateAlphabet().validate(to);
_tran.from = from;
_tran.to = to;
transitionScores.remove(_tran);
transitionsFrom(from).remove(to);
transitionsTo(to).remove(from);
}
public boolean containsTransition(State from, State to)
throws IllegalResidueException {
stateAlphabet().validate(from);
stateAlphabet().validate(to);
return transitionsFrom(from).contains(to);
}
public Set transitionsFrom(State from) throws IllegalResidueException {
stateAlphabet().validate(from);
Set s = (Set) transFrom.get(from);
if(s == null)
throw new IllegalResidueException("State " + from.getName() +
" not known in states " +
stateAlphabet().getName());
return s;
}
public Set transitionsTo(State to) throws IllegalResidueException {
stateAlphabet().validate(to);
Set s = (Set) transTo.get(to);
if(s == null)
throw new IllegalResidueException("State " + to +
" not known in states " +
stateAlphabet().getName());
return s;
}
public SimpleMarkovModel(Alphabet queryAlpha, Alphabet stateAlpha)
throws SeqException {
this.queryAlpha = queryAlpha;
this.stateAlpha = stateAlpha;
// FIXME? Thomas Down added quick hack for PairwiseDP.
if(!stateAlpha.contains(DP.MAGICAL_STATE) && !stateAlpha.contains(PairwiseDP.MAGICAL_STATE))
throw new SeqException("Use new SimpleMarkovModel(queryAlpha, stateAlpha). " +
"stateAlpha did not contain DP.MAGICAL_STATE.");
for(Iterator i = stateAlpha.residues().iterator(); i.hasNext(); ) {
Object o = i.next();
transFrom.put(o, new HashSet());
transTo.put(o, new HashSet());
}
}
public void registerWithTrainer(ModelTrainer modelTrainer) {
if(modelTrainer.getTrainerForModel(this) == null) {
TransitionTrainer tTrainer = new SimpleTransitionTrainer(this);
try {
modelTrainer.registerTrainerForModel(this, tTrainer);
} catch (SeqException se) {
throw new BioError("Can't register trainer for model, even though " +
" there is no trainer associated with the model");
}
for(Iterator i = stateAlphabet().residues().iterator(); i.hasNext(); ) {
State s = (State) i.next();
s.registerWithTrainer(modelTrainer);
try {
for(Iterator j = transitionsFrom(s).iterator(); j.hasNext(); ) {
State t = (State) j.next();
modelTrainer.registerTrainerForTransition(s, t, tTrainer, s, t);
}
} catch (IllegalResidueException ire) {
throw new BioError(ire, "State " + s.getName() +
" listed in alphabet " +
stateAlphabet().getName() + " dissapeared.");
} catch (SeqException se) {
throw new BioError(se, "Somehow, my trainer is not registered.");
}
}
}
}
}
|
package org.bouncycastle.asn1.x9;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import java.math.BigInteger;
public class X9IntegerConverter
{
public int getByteLength(
ECCurve c)
{
return (c.getFieldSize() + 7) / 8;
}
public int getByteLength(
ECFieldElement fe)
{
return (fe.getFieldSize() + 7) / 8;
}
public byte[] integerToBytes(
BigInteger s,
int qLength)
{
byte[] bytes = s.toByteArray();
if (qLength < bytes.length)
{
byte[] tmp = new byte[qLength];
System.arraycopy(bytes, bytes.length - tmp.length, tmp, 0, tmp.length);
return tmp;
}
else if (qLength > bytes.length)
{
byte[] tmp = new byte[qLength];
System.arraycopy(bytes, 0, tmp, tmp.length - bytes.length, bytes.length);
return tmp;
}
return bytes;
}
}
|
package org.clapper.curn.plugins;
import org.clapper.curn.Curn;
import org.clapper.curn.CurnConfig;
import org.clapper.curn.CurnException;
import org.clapper.curn.FeedInfo;
import org.clapper.curn.MainConfigItemPlugIn;
import org.clapper.curn.FeedConfigItemPlugIn;
import org.clapper.curn.PostConfigPlugIn;
import org.clapper.curn.PreFeedDownloadPlugIn;
import org.clapper.curn.Util;
import org.clapper.curn.Version;
import org.clapper.util.config.ConfigurationException;
import org.clapper.util.logging.Logger;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.HashMap;
/**
* The <tt>GzipDownloadPlugIn</tt> handles setting the global and
* per-feed HTTP header that requests gzipped (compressed) feed data
* (assuming the remote server honors that header). It intercepts the
* following configuration parameters:
*
* <table border="1">
* <tr valign="top" align="left">
* <th>Section</th>
* <th>Parameter</th>
* <th>Meaning</th>
* </tr>
* <tr valign="top">
* <td><tt>[curn]</tt></td>
* <td><tt>GzipDownload</tt></td>
* <td>The global default setting, if none is supplied in individual feed
* sections. Defaults to true.</td>
* </tr>
* <tr valign="top">
* <td><tt>[Feed<i>xxx</i>]</tt></td>
* <td><tt>GzipDownload</tt></td>
* <td>Whether or not to ask for gzipped data for a particular feed.
* Defaults to the global setting if not specified.</td>
* </tr>
* </table>
*
* @version <tt>$Revision$</tt>
*/
public class GzipDownloadPlugIn
implements MainConfigItemPlugIn,
FeedConfigItemPlugIn,
PreFeedDownloadPlugIn
{
private static final String VAR_OLD_GET_GZIPPED_FEEDS = "GetGzippedFeeds";
private static final String VAR_GZIP_DOWNLOAD = "GzipDownload";
/**
* Feed save data, by feed
*/
private Map<FeedInfo,Boolean> perFeedGzipFlag =
new HashMap<FeedInfo,Boolean>();
/**
* Default setting
*/
private boolean requestGzipDefault = true;
/**
* Saved reference to the configuration
*/
private CurnConfig config = null;
/**
* For log messages
*/
private static Logger log =
new Logger (GzipDownloadPlugIn.class);
/**
* Default constructor (required).
*/
public GzipDownloadPlugIn()
{
}
/**
* Get a displayable name for the plug-in.
*
* @return the name
*/
public String getName()
{
return "Gzip Download";
}
/**
* Called immediately after <i>curn</i> has read and processed a
* configuration item in the main [curn] configuration section. All
* configuration items are passed, one by one, to each loaded plug-in.
* If a plug-in class is not interested in a particular configuration
* item, this method should simply return without doing anything. Note
* that some configuration items may simply be variable assignment;
* there's no real way to distinguish a variable assignment from a
* blessed configuration item.
*
* @param sectionName the name of the configuration section where
* the item was found
* @param paramName the name of the parameter
* @param config the {@link CurnConfig} object
*
* @throws CurnException on error
*
* @see CurnConfig
*/
public void runMainConfigItemPlugIn (String sectionName,
String paramName,
CurnConfig config)
throws CurnException
{
try
{
if (paramName.equals (VAR_GZIP_DOWNLOAD))
{
requestGzipDefault =
config.getRequiredBooleanValue (sectionName, paramName);
}
else if (paramName.equals (VAR_OLD_GET_GZIPPED_FEEDS))
{
String msg = getDeprecatedParamMessage (config,
paramName,
VAR_GZIP_DOWNLOAD);
Util.getErrorOut().println (msg);
log.warn (msg);
requestGzipDefault =
config.getRequiredBooleanValue (sectionName, paramName);
}
}
catch (ConfigurationException ex)
{
throw new CurnException (ex);
}
}
/**
* Called immediately after <i>curn</i> has read and processed a
* configuration item in a "feed" configuration section. All
* configuration items are passed, one by one, to each loaded plug-in.
* If a plug-in class is not interested in a particular configuration
* item, this method should simply return without doing anything. Note
* that some configuration items may simply be variable assignment;
* there's no real way to distinguish a variable assignment from a
* blessed configuration item.
*
* @param sectionName the name of the configuration section where
* the item was found
* @param paramName the name of the parameter
* @param config the active configuration
* @param feedInfo partially complete <tt>FeedInfo</tt> object
* for the feed. The URL is guaranteed to be
* present, but no other fields are.
*
* @return <tt>true</tt> to continue processing the feed,
* <tt>false</tt> to skip it
*
* @throws CurnException on error
*
* @see CurnConfig
* @see FeedInfo
* @see FeedInfo#getURL
*/
public boolean runFeedConfigItemPlugIn (String sectionName,
String paramName,
CurnConfig config,
FeedInfo feedInfo)
throws CurnException
{
try
{
if (paramName.equals (VAR_GZIP_DOWNLOAD))
{
boolean flag = config.getRequiredBooleanValue (sectionName,
paramName);
perFeedGzipFlag.put (feedInfo, flag);
log.debug ("[" + sectionName + "]: "
+ paramName
+ "="
+ flag);
}
else if (paramName.equals (VAR_OLD_GET_GZIPPED_FEEDS))
{
String msg = getDeprecatedParamMessage (config,
paramName,
VAR_GZIP_DOWNLOAD);
Util.getErrorOut().println (msg);
log.warn (msg);
boolean flag = config.getRequiredBooleanValue (sectionName,
paramName);
perFeedGzipFlag.put (feedInfo, flag);
log.debug ("[" + sectionName + "]: "
+ paramName
+ "="
+ flag);
}
return true;
}
catch (ConfigurationException ex)
{
throw new CurnException (ex);
}
}
/**
* <p>Called just before a feed is downloaded. This method can return
* <tt>false</tt> to signal <i>curn</i> that the feed should be
* skipped. The plug-in method can also set values on the
* <tt>URLConnection</tt> used to download the plug-in, via
* <tt>URL.setRequestProperty()</tt>. (Note that <i>all</i> URLs, even
* <tt>file:</tt> URLs, are passed into this method. Setting a request
* property on the <tt>URLConnection</tt> object for a <tt>file:</tt>
* URL will have no effect--though it isn't specifically harmful.)</p>
*
* <p>Possible uses for a pre-feed download plug-in include:</p>
*
* <ul>
* <li>filtering on feed URL to prevent downloading non-matching feeds
* <li>changing the default User-Agent value
* <li>setting a non-standard HTTP header field
* </ul>
*
* @param feedInfo the {@link FeedInfo} object for the feed to be
* downloaded
* @param urlConn the <tt>java.net.URLConnection</tt> object that will
* be used to download the feed's XML.
*
* @return <tt>true</tt> if <i>curn</i> should continue to process the
* feed, <tt>false</tt> to skip the feed
*
* @throws CurnException on error
*
* @see FeedInfo
*/
public boolean runPreFeedDownloadPlugIn (FeedInfo feedInfo,
URLConnection urlConn)
throws CurnException
{
Boolean gzipBoxed = perFeedGzipFlag.get (feedInfo);
boolean gzip = requestGzipDefault;
if (gzipBoxed != null)
gzip = gzipBoxed;
if (gzip)
{
log.debug ("Setting header \"Accept-Encoding\" to \"gzip\" "
+ "for feed \""
+ feedInfo.getURL()
+ "\"");
urlConn.setRequestProperty ("Accept-Encoding", "gzip");
}
return true;
}
private String getDeprecatedParamMessage (CurnConfig config,
String badParam,
String goodParam)
{
StringBuilder buf = new StringBuilder();
buf.append ("Warning: Configuration file ");
URL configURL = config.getConfigurationFileURL();
if (configURL != null)
{
buf.append ('"');
buf.append (configURL.toString());
buf.append ('"');
}
buf.append ("uses deprecated \"");
buf.append (badParam);
buf.append ("\" parameter, instead of new \"");
buf.append (goodParam);
buf.append ("\" parameter.");
return buf.toString();
}
}
|
package org.griphyn.cPlanner.engine;
import org.griphyn.cPlanner.classes.ADag;
import org.griphyn.cPlanner.classes.DagInfo;
import org.griphyn.cPlanner.classes.PCRelation;
import org.griphyn.cPlanner.classes.PegasusFile;
import org.griphyn.cPlanner.classes.PlannerOptions;
import org.griphyn.cPlanner.classes.SubInfo;
import org.griphyn.cPlanner.common.LogManager;
import org.griphyn.cPlanner.common.PegasusProperties;
import org.griphyn.cPlanner.provenance.pasoa.XMLProducer;
import org.griphyn.cPlanner.provenance.pasoa.producer.XMLProducerFactory;
import org.griphyn.cPlanner.provenance.pasoa.PPS;
import org.griphyn.cPlanner.provenance.pasoa.pps.PPSFactory;
import java.util.Enumeration;
import java.util.Set;
import java.util.HashSet;
import java.util.Vector;
import java.util.Iterator;
/**
*
* Reduction engine for Planner 2.
* Given a ADAG it looks up the replica catalog and
* determines which output files are in the
* Replica Catalog, and on the basis of these
* ends up reducing the dag.
*
* @author Karan Vahi
* @author Gaurang Mehta
* @version $Revision$
*
*/
public class ReductionEngine extends Engine implements Refiner{
/**
* the original dag object which
* needs to be reduced on the basis of
* the results returned from the
* Replica Catalog
*/
private ADag mOriginalDag;
/**
* the dag relations of the
* orginal dag
*/
private Vector mOrgDagRelations;
/**
* the reduced dag object which is
* returned.
*/
private ADag mReducedDag;
/**
* the jobs which are found to be in
* the Replica Catalog. These are
* the jobs whose output files are at
* some location in the Replica Catalog.
* This does not include the jobs which
* are deleted by applying the reduction
* algorithm
*/
private Vector mOrgJobsInRC ;
/**
* the jobs which are deleted due
* to the application of the
* Reduction algorithm. These do
* not include the jobs whose output
* files are in the RC. These are
* the ones which are deleted due
* to cascade delete
*/
private Vector mAddJobsDeleted;
/**
* all deleted jobs. This
* is mOrgJobsInRC + mAddJobsDeleted.
*/
private Vector mAllDeletedJobs;
/**
* the files whose locations are
* returned from the ReplicaCatalog
*/
private Set mFilesInRC;
/**
* The XML Producer object that records the actions.
*/
private XMLProducer mXMLStore;
/**
* The workflow object being worked upon.
*/
private ADag mWorkflow;
/**
* The constructor
*
* @param orgDag The original Dag object
* @param properties the <code>PegasusProperties</code> to be used.
* @param options The options specified by
* the user to run the
* planner
*/
public ReductionEngine( ADag orgDag, PegasusProperties properties, PlannerOptions options ){
super( properties );
this.mPOptions = options;
mOriginalDag = orgDag;
mOrgDagRelations = mOriginalDag.dagInfo.relations;
mOrgJobsInRC = new Vector();
mAddJobsDeleted = new Vector();
mAllDeletedJobs = new Vector();
mXMLStore = XMLProducerFactory.loadXMLProducer( properties );
mWorkflow = orgDag;
}
/**
* Returns a reference to the workflow that is being refined by the refiner.
*
*
* @return ADAG object.
*/
public ADag getWorkflow(){
return this.mWorkflow;
}
/**
* Returns a reference to the XMLProducer, that generates the XML fragment
* capturing the actions of the refiner. This is used for provenace
* purposes.
*
* @return XMLProducer
*/
public XMLProducer getXMLProducer(){
return this.mXMLStore;
}
/**
* Reduces the workflow on the basis of the existence of lfn's in the
* replica catalog. The existence of files, is determined via the bridge.
*
* @param rcb instance of the replica catalog bridge.
*
* @return the reduced dag
*
*/
public ADag reduceDag( ReplicaCatalogBridge rcb ){
//search for the replicas of
//the files. The search list
//is already present in Replica
//Mechanism classes
mFilesInRC = rcb.getFilesInReplica();
//we reduce the dag only if the
//force option is not specified.
if(mPOptions.getForce())
return mOriginalDag;
//load the PPS implementation
PPS pps = PPSFactory.loadPPS( this.mProps );
//mXMLStore.add( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
mXMLStore.add( "<workflow url=\"" + mPOptions.getDAX() + "\">" );
//call the begin workflow method
try{
pps.beginWorkflowRefinementStep(this, "REDUCTION", true);
}
catch( Exception e ){
throw new RuntimeException( "PASOA Exception", e );
}
//clear the XML store
mXMLStore.clear();
mLogger.log("Reducing the workflow",LogManager.DEBUG_MESSAGE_LEVEL);
mOrgJobsInRC =
getJobsInRC(mOriginalDag.vJobSubInfos,mFilesInRC);
mAllDeletedJobs = (Vector)mOrgJobsInRC.clone();
firstPass(mOrgJobsInRC);
secondPass();
firstPass(mAddJobsDeleted);
mLogMsg = "Nodes/Jobs Deleted from the Workflow during reduction ";
mLogger.log(mLogMsg,LogManager.DEBUG_MESSAGE_LEVEL);
for(Enumeration e = mAllDeletedJobs.elements();e.hasMoreElements();){
String deletedJob = (String) e.nextElement();
mLogger.log("\t" + deletedJob, LogManager.DEBUG_MESSAGE_LEVEL);
mXMLStore.add( "<removed job = \"" + deletedJob + "\"/>" );
mXMLStore.add( "\n" );
}
mLogger.logCompletion( mLogMsg, LogManager.DEBUG_MESSAGE_LEVEL );
mReducedDag = makeRedDagObject( mOriginalDag, mAllDeletedJobs );
//call the end workflow method for pasoa interactions
try{
mWorkflow = mReducedDag;
for( Iterator it = mWorkflow.jobIterator(); it.hasNext(); ){
SubInfo job = ( SubInfo )it.next();
pps.isIdenticalTo( job.getName(), job.getName() );
}
pps.endWorkflowRefinementStep( this );
}
catch( Exception e ){
throw new RuntimeException( "PASOA Exception", e );
}
mLogger.logCompletion("Reducing the workflow",
LogManager.DEBUG_MESSAGE_LEVEL);
return mReducedDag;
}
/**
* This determines the jobs which are in
* the RC corresponding to the files found
* in the Replica Catalog. A job is said to
* be in the RC if all the outfiles for
* that job are found to be in the RC.
* A job in RC can be removed from the Dag
* and the Dag correspondingly reduced.
*
* @param vSubInfos Vector of <code>SubInfo</code>
* objects corresponding to all
* the jobs of a Abstract Dag
*
* @param filesInRC Set of <code>String</code>
* objects corresponding to the
* logical filenames of files
* which are found to be in the
* Replica Catalog
*
* @return a Vector of jobNames (Strings)
*
* @see org.griphyn.cPlanner.classes.ReplicaLocations
* @see org.griphyn.cPlanner.classes.SubInfo
*/
private Vector getJobsInRC(Vector vSubInfos,Set filesInRC){
SubInfo subInfo;
Set vJobOutputFiles;
String jobName;
Vector vJobsInReplica = new Vector();
int noOfOutputFilesInJob = 0;
int noOfSuccessfulMatches = 0;
if( vSubInfos.isEmpty() ){
String msg = "ReductionEngine: The set of jobs in the workflow " +
"\n is empty.";
mLogger.log( msg, LogManager.DEBUG_MESSAGE_LEVEL );
return new Vector();
}
Enumeration e = vSubInfos.elements();
mLogger.log("Jobs whose o/p files already exist",
LogManager.DEBUG_MESSAGE_LEVEL);
while(e.hasMoreElements()){
//getting submit information about each submit file of a job
subInfo = (SubInfo)e.nextElement();
jobName = subInfo.jobName;
//System.out.println(jobName);
if(!subInfo.outputFiles.isEmpty()){
vJobOutputFiles = subInfo.getOutputFiles();
}else{
vJobOutputFiles = new HashSet();
}
/* Commented on Oct10. This ended up making the
Planner doing duplicate transfers
if(subInfo.stdOut.length()>0)
vJobOutputFiles.addElement(subInfo.stdOut);
*/
//determine the no of output files for that job
if(vJobOutputFiles.isEmpty()){
mLogger.log("Job " + subInfo.getName() + " has no o/p files",
LogManager.DEBUG_MESSAGE_LEVEL);
}
for( Iterator temp = vJobOutputFiles.iterator(); temp.hasNext(); ){
temp.next();
noOfOutputFilesInJob++;
}
//traversing through the output files of that particular job
for( Iterator en = vJobOutputFiles.iterator(); en.hasNext(); ){
PegasusFile pf = (PegasusFile)en.next();
//jobName = pf.getLFN();
//if(stringInList(jobName,filesInRC)){
if(filesInRC.contains(pf.getLFN())){
noOfSuccessfulMatches++;
}
}
//if the noOfOutputFilesInJob and noOfSuccessfulMatches are equal
//this means that all files required by job is in RC
if(noOfOutputFilesInJob == noOfSuccessfulMatches){
mLogger.log("\t" + subInfo.jobName,
LogManager.DEBUG_MESSAGE_LEVEL);
vJobsInReplica.addElement(subInfo.jobName);
}
//reinitialise the variables
noOfSuccessfulMatches = 0;
noOfOutputFilesInJob = 0;
}
mLogger.logCompletion("Jobs whose o/p files already exist",
LogManager.DEBUG_MESSAGE_LEVEL);
return vJobsInReplica;
}
/**
* If a job is deleted it marks
* all the relations related to that
* job as deleted
*
* @param vDelJobs the vector containing the names
* of the deleted jobs whose relations
* we want to nullify
*/
private void firstPass(Vector vDelJobs){
Enumeration edeljobs = vDelJobs.elements();
while(edeljobs.hasMoreElements()){
String deljob = (String)edeljobs.nextElement();
Enumeration epcrel = mOrgDagRelations.elements();
while( epcrel.hasMoreElements()){
PCRelation pcrc = (PCRelation)epcrel.nextElement();
if((pcrc.child.equalsIgnoreCase(deljob))||
(pcrc.parent.equalsIgnoreCase(deljob))){
pcrc.isDeleted=true;
}
}
}
}
/**
* In the second pass we find all the
* parents of the nodes which have been
* found to be in the RC.
* Corresponding to each parent, we find
* the corresponding siblings for that
* deleted job.
* If all the siblings are deleted, we
* can delete that parent.
*/
private void secondPass(){
Enumeration eDelJobs = mAllDeletedJobs.elements();
Enumeration ePcRel;
Enumeration eParents;
String node;
String parentNodeName;
PCRelation currentRelPair;
Vector vParents = new Vector();//all parents of a particular node
Vector vSiblings = new Vector();
while(eDelJobs.hasMoreElements()){
node = (String)eDelJobs.nextElement();
//getting the parents of that node
vParents = this.getNodeParents(node);
//now for each parent checking if the siblings are deleted
//if yes then delete the node
eParents = vParents.elements();
while(eParents.hasMoreElements()){
parentNodeName = (String)eParents.nextElement();
//getting all the siblings for parentNodeName
vSiblings = this.getChildren(parentNodeName);
//now we checking if all the siblings are in vdeljobs
Enumeration temp = vSiblings.elements();
boolean siblingsDeleted = true;
while(temp.hasMoreElements()){
if(stringInVector( (String)temp.nextElement(),mAllDeletedJobs)){
//means the sibling has been marked deleted
}
else{
siblingsDeleted = false;
}
}
//if all siblings are deleted add the job to vdeljobs
if(siblingsDeleted){
//only add if the parentNodeName is not already in the list
if(!stringInVector(parentNodeName,mAllDeletedJobs)){
String msg = "Deleted Node :" + parentNodeName;
mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL);
mAddJobsDeleted.addElement(new String (parentNodeName));
mAllDeletedJobs.addElement(new String (parentNodeName));
}
}
//clearing the siblings vector for that parent
vSiblings.clear();
}//end of while(eParents.hasMoreElements()){
//clearing the parents Vector for that job
vParents.clear();
}//end of while(eDelJobs.hasMoreElements)
}
/**
* Gets all the parents of a particular node.
*
* @param node the name of the job whose parents are to be found.
*
* @return Vector corresponding to the parents of the node.
*/
private Vector getNodeParents(String node){
//getting the parents of that node
return mOriginalDag.getParents(node);
}
/**
* Gets all the children of a particular node.
*
* @param node the name of the node whose children we want to find.
*
* @return Vector containing the children of the node.
*/
private Vector getChildren(String node){
return mOriginalDag.getChildren(node);
}
/**
* All the deleted jobs which
* happen to be leaf nodes. This
* entails that the output files
* of these jobs be transferred
* from the location returned
* by the Replica Catalog to the
* pool specified.
* This is a subset of mAllDeletedJobs
* Also to determine the deleted
* leaf jobs it refers the original
* dag, not the reduced dag.
*
* @return Vector containing the <code>SubInfo</code> of deleted leaf jobs.
*/
public Vector getDeletedLeafJobs(){
Vector delLeafJobs = new Vector();
mLogger.log("Finding deleted leaf jobs",LogManager.DEBUG_MESSAGE_LEVEL);
for( Iterator it = mAllDeletedJobs.iterator(); it.hasNext(); ){
String job = (String)it.next();
if(getChildren(job).isEmpty()){
//means a leaf job
String msg = "Found deleted leaf job :" + job;
mLogger.log(msg,LogManager.DEBUG_MESSAGE_LEVEL);
delLeafJobs.addElement( mOriginalDag.getSubInfo(job) );
}
}
mLogger.logCompletion("Finding deleted leaf jobs",
LogManager.DEBUG_MESSAGE_LEVEL);
return delLeafJobs;
}
/**
* makes the Reduced Dag object which
* corresponding to the deleted jobs
* which are specified.
*
* Note : We are plainly copying the
* inputFiles and the outputFiles. After
* reduction this changes but since we
* need those only to look up the RC,
* which we have done.
*
* @param orgDag the original Dag
* @param vDelJobs the Vector containing the
* names of the jobs whose
* SubInfos and Relations we
* want to remove.
*
* @return the reduced dag, which doesnot
* have the deleted jobs
*
*/
public ADag makeRedDagObject(ADag orgDag, Vector vDelJobs){
ADag redDag = new ADag();
redDag.dagInfo =
constructNewDagInfo(mOriginalDag.dagInfo,vDelJobs);
redDag.vJobSubInfos =
constructNewSubInfos(mOriginalDag.vJobSubInfos,vDelJobs);
return redDag;
}
/**
* Constructs a DagInfo object for the
* decomposed Dag on the basis of the jobs
* which are deleted from the DAG by the
* reduction algorithm
*
* Note : We are plainly copying the
* inputFiles and the outputFiles. After reduction
* this changes but since we need those
* only to look up the RC, which we have done.
*
* @param dagInfo the object which is reduced on
* the basis of vDelJobs
*
* @param vDelJobs Vector containing the logical file
* names of jobs which are to
* be deleted
*
* @return the DagInfo object corresponding
* to the Decomposed Dag
*
*/
private DagInfo constructNewDagInfo(DagInfo dagInfo,Vector vDelJobs){
DagInfo newDagInfo = (DagInfo)dagInfo.clone();
String jobName;
PCRelation currentRelation;
String parentName;
String childName;
boolean deleted;
//populating DagJobs
newDagInfo.dagJobs = new Vector();
Enumeration e = dagInfo.dagJobs.elements();
while(e.hasMoreElements()){
jobName = (String)e.nextElement();
if(!stringInVector( jobName,vDelJobs) ){
//that job is to be executed so we add it
newDagInfo.dagJobs.addElement(new String(jobName));
}
}
//populating PCRelation Vector
newDagInfo.relations = new Vector();
e = dagInfo.relations.elements();
while(e.hasMoreElements()){
currentRelation = (PCRelation)e.nextElement();
parentName = new String(currentRelation.parent);
childName = new String(currentRelation.child);
if( !(currentRelation.isDeleted) ){//the pair has not been marked deleted
newDagInfo.relations.addElement(new PCRelation(parentName,childName,false));
}
}
return newDagInfo;
}//end of function
/**
* constructs the Vector of subInfo objects
* corresponding to the reduced ADAG.
*
* It also modifies the strargs to remove
* them up of markup and display correct paths
* to the filenames
*
*
* @param vSubInfos the SubInfo object including
* the jobs which are not needed
* after the execution of the
* reduction algorithm
*
* @param vDelJobs the jobs which are deleted by
* the reduction algo as their
* output files are in the Replica Catalog
*
* @return the SubInfo objects except the ones
* for the deleted jobs
*
*/
private Vector constructNewSubInfos(Vector vSubInfos,Vector vDelJobs){
Vector vNewSubInfos = new Vector();
SubInfo newSubInfo;
SubInfo currentSubInfo;
String jobName;
Enumeration e = vSubInfos.elements();
while(e.hasMoreElements()){
currentSubInfo = (SubInfo)e.nextElement();
jobName = currentSubInfo.jobName;
//we add only if the jobName is not in vDelJobs
if(!stringInVector(jobName,vDelJobs)){
newSubInfo = (SubInfo)currentSubInfo.clone();
//adding to Vector
vNewSubInfos.addElement(newSubInfo);
}
}//end of while
return vNewSubInfos;
}
}
|
package org.mockito.internal.util;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.mockito.internal.creation.DelegatingMethod;
import org.mockito.internal.invocation.MockitoMethod;
public class ObjectMethodsGuru implements Serializable {
private static final long serialVersionUID = -1286718569065470494L;
public boolean isToString(Method method) {
return isToString(new DelegatingMethod(method));
}
public boolean isToString(MockitoMethod method) {
return method.getReturnType() == String.class && method.getParameterTypes().length == 0
&& method.getName().equals("toString");
}
public boolean isEqualsMethod(Method method) {
return method.getName().equals("equals") && method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class;
}
public boolean isHashCodeMethod(Method method) {
return method.getName().equals("hashCode") && method.getParameterTypes().length == 0;
}
}
|
package org.opencms.widgets;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsMessages;
import org.opencms.json.JSONException;
import org.opencms.json.JSONObject;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.xml.content.I_CmsXmlContentHandler.DisplayType;
import org.opencms.xml.types.A_CmsXmlContentValue;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.logging.Log;
/**
* Provides a display only widget, for use on a widget dialog.<p>
*
* @since 6.0.0
*/
public class CmsLocationPickerWidget extends A_CmsWidget implements I_CmsADEWidget {
/** The default widget configuration. */
private static final String DEFAULT_CONFIG = "{\"edit\":[\"map\", \"address\", \"coords\", \"size\", \"zoom\", \"type\", \"mode\"]}";
/** Key post fix, so you can display different help text if used a "normal" widget, and a display widget. */
private static final String DISABLED_POSTFIX = ".disabled";
/** The configuration key for the Google maps API key. */
public static final String CONFIG_API_KEY = "apiKey";
/** The logger instance for this class. */
private static final Log LOG = CmsLog.getLog(CmsLocationPickerWidget.class);
/**
* Creates a new input widget.<p>
*/
public CmsLocationPickerWidget() {
// empty constructor is required for class registration
this("");
}
/**
* Creates a new input widget with the given configuration.<p>
*
* @param configuration the configuration to use
*/
public CmsLocationPickerWidget(String configuration) {
super(configuration);
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getConfiguration(org.opencms.file.CmsObject, org.opencms.xml.types.A_CmsXmlContentValue, org.opencms.i18n.CmsMessages, org.opencms.file.CmsResource, java.util.Locale)
*/
public String getConfiguration(
CmsObject cms,
A_CmsXmlContentValue schemaType,
CmsMessages messages,
CmsResource resource,
Locale contentLocale) {
String config = getConfiguration();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(config)) {
config = DEFAULT_CONFIG;
} else {
if (!config.startsWith("{")) {
config = "{" + config + "}";
}
}
try {
// make sure the configuration is a parsable JSON string
JSONObject conf = new JSONObject(config);
if (!conf.has(CONFIG_API_KEY)) {
String sitePath;
if (resource.getStructureId().isNullUUID()) {
sitePath = "/";
} else {
sitePath = cms.getSitePath(resource);
}
try {
String apiKey = cms.readPropertyObject(
sitePath,
CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY,
true).getValue();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(apiKey)) {
conf.put(CONFIG_API_KEY, apiKey);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
config = conf.toString();
} catch (JSONException e) {
config = DEFAULT_CONFIG;
LOG.error(e.getLocalizedMessage(), e);
}
return config;
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getCssResourceLinks(org.opencms.file.CmsObject)
*/
public List<String> getCssResourceLinks(CmsObject cms) {
return null;
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getDefaultDisplayType()
*/
public DisplayType getDefaultDisplayType() {
return DisplayType.singleline;
}
/**
* @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
public String getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
String value = param.getStringValue(cms);
String localizedValue = value;
if (CmsStringUtil.TRUE.equalsIgnoreCase(value) || CmsStringUtil.FALSE.equalsIgnoreCase(value)) {
boolean booleanValue = Boolean.valueOf(value).booleanValue();
if (booleanValue) {
localizedValue = Messages.get().getBundle(widgetDialog.getLocale()).key(Messages.GUI_LABEL_TRUE_0);
} else {
localizedValue = Messages.get().getBundle(widgetDialog.getLocale()).key(Messages.GUI_LABEL_FALSE_0);
}
}
String id = param.getId();
StringBuffer result = new StringBuffer(16);
result.append("<td class=\"xmlTd\">");
result.append("<span class=\"xmlInput textInput\" style=\"border: 0px solid black;\">");
if (CmsStringUtil.isNotEmpty(getConfiguration())) {
result.append(getConfiguration());
} else {
result.append(localizedValue);
}
result.append("</span>");
result.append("<input type=\"hidden\"");
result.append(" name=\"");
result.append(id);
result.append("\" id=\"");
result.append(id);
result.append("\" value=\"");
result.append(CmsEncoder.escapeXml(value));
result.append("\">");
result.append("</td>");
return result.toString();
}
/**
* @see org.opencms.widgets.A_CmsWidget#getHelpBubble(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public String getHelpBubble(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
StringBuffer result = new StringBuffer(128);
String locKey = getDisabledHelpKey(param);
String locValue = widgetDialog.getMessages().key(locKey, true);
if (locValue == null) {
// there was no help message found for this key, so return a spacer cell
return widgetDialog.dialogHorizontalSpacer(16);
} else {
result.append("<td>");
result.append("<img name=\"img");
result.append(locKey);
result.append("\" id=\"img");
result.append(locKey);
result.append("\" src=\"");
result.append(OpenCms.getLinkManager().substituteLink(cms, "/system/workplace/resources/commons/help.png"));
result.append("\" alt=\"\" border=\"0\"");
if (widgetDialog.useNewStyle()) {
result.append(getJsHelpMouseHandler(widgetDialog, locKey, null));
} else {
result.append(
getJsHelpMouseHandler(
widgetDialog,
locKey,
CmsEncoder.escape(locValue, cms.getRequestContext().getEncoding())));
}
result.append("></td>");
return result.toString();
}
}
/**
* @see org.opencms.widgets.A_CmsWidget#getHelpText(org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public String getHelpText(I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
String helpId = getDisabledHelpKey(param);
Set<String> helpIdsShown = widgetDialog.getHelpMessageIds();
if (helpIdsShown.contains(helpId)) {
// help hey has already been included in output
return "";
}
helpIdsShown.add(helpId);
// calculate the key
String locValue = widgetDialog.getMessages().key(helpId, true);
if (locValue == null) {
// there was no help message found for this key, so return an empty string
return "";
} else {
if (widgetDialog.useNewStyle()) {
StringBuffer result = new StringBuffer(128);
result.append("<div class=\"help\" id=\"help");
result.append(helpId);
result.append("\"");
result.append(getJsHelpMouseHandler(widgetDialog, helpId, helpId));
result.append(">");
result.append(locValue);
result.append("</div>\n");
return result.toString();
} else {
return "";
}
}
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getInitCall()
*/
public String getInitCall() {
return null;
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getJavaScriptResourceLinks(org.opencms.file.CmsObject)
*/
public List<String> getJavaScriptResourceLinks(CmsObject cms) {
return null;
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#getWidgetName()
*/
public String getWidgetName() {
return CmsLocationPickerWidget.class.getName();
}
/**
* @see org.opencms.widgets.I_CmsADEWidget#isInternal()
*/
public boolean isInternal() {
return true;
}
/**
* @see org.opencms.widgets.I_CmsWidget#newInstance()
*/
public I_CmsWidget newInstance() {
return new CmsLocationPickerWidget(getConfiguration());
}
/**
* Returns the localized help key for the provided widget parameter.<p>
*
* @param param the widget parameter to return the localized help key for
*
* @return the localized help key for the provided widget parameter
*/
private String getDisabledHelpKey(I_CmsWidgetParameter param) {
StringBuffer result = new StringBuffer(64);
result.append(LABEL_PREFIX);
result.append(param.getKey());
result.append(HELP_POSTFIX);
result.append(DISABLED_POSTFIX);
return result.toString();
}
}
|
// GradientImage.java
package imagej.core.plugins;
import imagej.model.AxisLabel;
import imagej.model.Dataset;
import imagej.plugin.ImageJPlugin;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.type.logic.BitType;
import mpicbg.imglib.type.numeric.RealType;
import mpicbg.imglib.type.numeric.integer.ByteType;
import mpicbg.imglib.type.numeric.integer.IntType;
import mpicbg.imglib.type.numeric.integer.LongType;
import mpicbg.imglib.type.numeric.integer.ShortType;
import mpicbg.imglib.type.numeric.integer.Unsigned12BitType;
import mpicbg.imglib.type.numeric.integer.UnsignedByteType;
import mpicbg.imglib.type.numeric.integer.UnsignedIntType;
import mpicbg.imglib.type.numeric.integer.UnsignedShortType;
import mpicbg.imglib.type.numeric.real.DoubleType;
import mpicbg.imglib.type.numeric.real.FloatType;
/**
* A demonstration plugin that generates a gradient image.
*
* @author Curtis Rueden
*/
@Plugin(menuPath = "Process>Gradient")
public class GradientImage implements ImageJPlugin {
public static final String DEPTH1 = "1-bit";
public static final String DEPTH8 = "8-bit";
public static final String DEPTH12 = "12-bit";
public static final String DEPTH16 = "16-bit";
public static final String DEPTH32 = "32-bit";
public static final String DEPTH64 = "64-bit";
@Parameter(min = "1")
private int width = 512;
@Parameter(min = "1")
private int height = 512;
@Parameter(callback = "bitDepthChanged",
choices = { DEPTH1, DEPTH8, DEPTH12, DEPTH16, DEPTH32, DEPTH64 })
private String bitDepth = DEPTH8;
@Parameter(callback = "signedChanged")
private boolean signed = false;
@Parameter(callback = "floatingChanged")
private boolean floating = false;
@Parameter(output = true)
private Dataset dataset;
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void run() {
// create the dataset
final String name = "Gradient Image";
final RealType type = makeType();
final int[] dims = { width, height };
final AxisLabel[] axes = { AxisLabel.X, AxisLabel.Y };
dataset = Dataset.create(name, type, dims, axes);
// fill in the diagonal gradient
final LocalizableCursor<? extends RealType<?>> cursor =
(LocalizableCursor<? extends RealType<?>>)
dataset.getImage().createLocalizableCursor();
while (cursor.hasNext()) {
cursor.fwd();
final int x = cursor.getPosition(0);
final int y = cursor.getPosition(1);
cursor.getType().setReal(x + y);
}
cursor.close();
}
// -- Parameter callback methods --
protected void bitDepthChanged() {
if (signedForbidden()) signed = false;
if (signedRequired()) signed = true;
if (floatingForbidden()) floating = false;
}
protected void signedChanged() {
if (signed && signedForbidden() || !signed && signedRequired()) {
bitDepth = DEPTH8;
}
if (!signed) floating = false; // no unsigned floating types
}
protected void floatingChanged() {
if (floating && floatingForbidden()) bitDepth = DEPTH32;
if (floating) signed = true; // no unsigned floating types
}
// -- Helper methods --
private RealType<? extends RealType<?>> makeType() {
if (bitDepth.equals(DEPTH1)) {
assert !signed && !floating;
return new BitType();
}
if (bitDepth.equals(DEPTH8)) {
assert !floating;
if (signed) return new ByteType();
return new UnsignedByteType();
}
if (bitDepth.equals(DEPTH12)) {
assert !signed && !floating;
return new Unsigned12BitType();
}
if (bitDepth.equals(DEPTH16)) {
assert !floating;
if (signed) return new ShortType();
return new UnsignedShortType();
}
if (bitDepth.equals(DEPTH32)) {
if (floating) {
assert signed;
return new FloatType();
}
if (signed) return new IntType();
return new UnsignedIntType();
}
if (bitDepth.equals(DEPTH64)) {
assert signed;
if (floating) return new DoubleType();
return new LongType();
}
throw new IllegalStateException("Invalid parameters: bitDepth=" +
bitDepth + ", signed=" + signed + ", floating=" + floating);
}
private boolean signedForbidden() {
// 1-bit and 12-bit signed data are not supported
return bitDepth.equals(DEPTH1) || bitDepth.equals(DEPTH12);
}
private boolean signedRequired() {
// 64-bit unsigned data is not supported
return bitDepth.equals(DEPTH64);
}
private boolean floatingForbidden() {
// only 32-bit and 64-bit floating point are supported
return !bitDepth.equals(DEPTH32) && !bitDepth.equals(DEPTH64);
}
}
|
package heufybot.modules;
import heufybot.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Help extends Module
{
public Help()
{
this.authType = AuthType.Anyone;
this.apiVersion = 60;
this.triggerTypes = new TriggerType[] { TriggerType.Message };
this.trigger = "^" + commandPrefix + "(help)($| .*)";
}
public void processEvent(String server, String source, String message, String triggerUser, List<String> params)
{
if (params.size() == 1)
{
ArrayList<String> moduleNames = new ArrayList<String>();
for(Module module : bot.getServer(server).getModuleInterface().getModuleList())
{
moduleNames.add(module.toString());
}
Collections.sort(moduleNames);
String response = "Modules loaded: " + StringUtils.join(moduleNames, ", ");
bot.getServer(server).cmdPRIVMSG(source, response);
}
else
{
params.remove(0);
String helpParams = StringUtils.join(params, " ");
String help = bot.getServer(server).getModuleInterface().getModuleHelp(helpParams);
if(help != null)
{
bot.getServer(server).cmdPRIVMSG(source, help);
}
else
{
bot.getServer(server).cmdPRIVMSG(source, "Module or command matching \"" + helpParams + "\" is not loaded or does not exist!");
}
}
}
@Override
public String getHelp(String message)
{
return "Commands: " + commandPrefix + "help (<module>) | Shows all modules that are currently loaded or shows help for a given module. Command syntax will be as such: command <parameter>. Parameters in brackets are optional.";
}
@Override
public void onLoad()
{
}
@Override
public void onUnload()
{
}
}
|
package sorcer.fidelities;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sorcer.core.plexus.FiMap;
import sorcer.service.FidelityList;
import sorcer.util.ModelTable;
import sorcer.util.Table;
import static org.junit.Assert.assertEquals;
import static sorcer.co.operator.*;
import static sorcer.eo.operator.*;
public class FidelityTest {
private static Logger logger = LoggerFactory.getLogger(FidelityTest.class);
@Test
public void fisToString() {
FidelityList fl1 = fis(fi("atX", "x1"));
logger.info("as String: " + fl1);
assertEquals(fl1.toString(), "fis(fi(\"atX\", \"x1\"))");
FidelityList fl2 = fis(fi("atX", "x1"), fi("atY", "y2"));
logger.info("as String: " + fl2);
assertEquals(fl2.toString(), "fis(fi(\"atX\", \"x1\"), fi(\"atY\", \"y2\"))");
FidelityList fl3 = fis(fi("atZ", "z2"), fl1, fl2);
logger.info("as String: " + fl3);
assertEquals(fl3.toString(), "fis(fi(\"atZ\", \"z2\"), fi(\"atX\", \"x1\"), fi(\"atX\", \"x1\"), fi(\"atY\", \"y2\"))");
}
@Test
public void fiMap() {
FiMap fm = new FiMap();
fm.add(fiEnt(2, fis(fi("atX", "x1"))));
fm.add(fiEnt(5, fis(fi("atX", "x1"), fi("atY", "y2"))));
logger.info("fi map: " + fm);
assertEquals(fm.get(2), fis(fi("atX", "x1")));
assertEquals(fm.get(5), fis(fi("atX", "x1"), fi("atY", "y2")));
}
@Test
public void populateMap() {
FiMap fm = new FiMap();
fm.add(fiEnt(2, fis(fi("atX", "x1"))));
fm.add(fiEnt(5, fis(fi("atX", "x1"), fi("atY", "y2"))));
fm.populateFidelities(10);
assertEquals(fm.size(), 9);
assertEquals(fm.get(10), fis(fi("atX", "x1"), fi("atY", "y2")));
}
@Test
public void fidelityTable() {
Table dataTable = table(header("span"),
row(110.0),
row(120.0),
row(130.0),
row(140.0),
row(150.0),
row(160.0));
ModelTable fiTable = appendFidelities(dataTable,
fiEnt(1, fis(fi("atX", "x1"))),
fiEnt(3, fis(fi("atX", "x1"), fi("atY", "y2"))));
logger.info("fi table: " + fiTable);
FiMap fiMap = new FiMap(dataTable);
fiMap.populateFidelities(dataTable.getRowCount()-1);
logger.info("fi map populated: " + fiMap);
assertEquals(fiMap.get(0), null);
assertEquals(fiMap.get(1), fis(fi("atX", "x1")));
assertEquals(fiMap.get(2), fis(fi("atX", "x1")));
assertEquals(fiMap.get(4), fis(fi("atX", "x1"), fi("atY", "y2")));
assertEquals(fiMap.get(5), fis(fi("atX", "x1"), fi("atY", "y2")));
}
@Test
public void populateFidelityTable() {
Table dataTable = table(header("span"),
row(110.0),
row(120.0),
row(130.0),
row(140.0),
row(150.0),
row(160.0));
ModelTable fiTable = populateFidelities(dataTable,
fiEnt(1, fis(fi("atX", "x1"))),
fiEnt(3, fis(fi("atX", "x1"), fi("atY", "y2"))));
logger.info("fi table: " + fiTable);
FiMap fiMap = new FiMap(dataTable);
logger.info("fi map: " + fiMap);
assertEquals(fiMap.get(0), null);
assertEquals(fiMap.get(1), fis(fi("atX", "x1")));
assertEquals(fiMap.get(2), fis(fi("atX", "x1")));
assertEquals(fiMap.get(4), fis(fi("atX", "x1"), fi("atY", "y2")));
assertEquals(fiMap.get(5), fis(fi("atX", "x1"), fi("atY", "y2")));
}
@Test
public void selectFiMap() {
Table dataTable = table(header("span", "fis"),
row(110.0, fis(fi("tip/displacement", "astros"))),
row(120.0),
row(130.0, fis(fi("tip/displacement", "nastran"))),
row(140.0));
FiMap fiMap = new FiMap(dataTable);
logger.info("fi map: " + fiMap);
assertEquals(fiMap.size(), 4);
assertEquals(fiMap.get(1), null);
assertEquals(fiMap.get(3), null);
fiMap.populateFidelities(dataTable.getRowCount()-1);
logger.info("fi map populated: " + fiMap);
assertEquals(fiMap.get(1), fis(fi("tip/displacement", "astros")));
assertEquals(fiMap.get(3), fis(fi("tip/displacement", "nastran")));
}
}
|
package com.headstartech.beansgraph;
import org.jgrapht.DirectedGraph;
import org.jgrapht.alg.cycle.JohnsonSimpleCycles;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.UnmodifiableDirectedGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.*;
/**
* Produces the bean graph on every ContextRefreshedEvent and calls and registered listeners.
*
* @see BeansGraphListener
* @author Per Johansson
* @since 1.0
*/
@Component
public class BeansGraphProducer implements ApplicationListener<ContextRefreshedEvent> {
private static Logger log = LoggerFactory.getLogger(BeansGraphProducer.class);
private List<BeansGraphListener> listeners = new ArrayList<BeansGraphListener>();
public void addListener(BeansGraphListener listener) {
listeners.add(listener);
}
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
UnmodifiableDirectedGraph<Bean, DefaultEdge> dependencyGraph = createDependencyGraph(applicationContext);
JohnsonSimpleCycles<Bean, DefaultEdge> cyclesFinder = new JohnsonSimpleCycles<Bean, DefaultEdge>(dependencyGraph);
List<List<Bean>> cycles = cyclesFinder.findSimpleCycles();
BeansGraphResult result = new BeansGraphResult(dependencyGraph, Collections.unmodifiableList(cycles));
for (BeansGraphListener listener : listeners) {
listener.onBeanGraphResult(applicationContext, result);
}
}
private UnmodifiableDirectedGraph<Bean, DefaultEdge> createDependencyGraph(ApplicationContext context) {
DirectedGraph<Bean, DefaultEdge> graph = new DefaultDirectedGraph<Bean, DefaultEdge>(DefaultEdge.class);
if (!(context instanceof AbstractApplicationContext)) {
log.info("ApplicationContext not instance of {}", AbstractApplicationContext.class.getName());
return new UnmodifiableDirectedGraph<Bean, DefaultEdge>(graph);
}
ConfigurableListableBeanFactory factory = ((AbstractApplicationContext) context).getBeanFactory();
Queue<Bean> queue = new ArrayDeque<Bean>();
for (String beanName : factory.getBeanDefinitionNames()) {
Bean bv = createBeanVertex(factory, beanName);
if(bv != null) {
queue.add(bv);
}
}
while (!queue.isEmpty()) {
Bean bv = queue.remove();
graph.addVertex(bv);
for (String dependency : getDependenciesForBean(factory, bv.getName())) {
Bean depBV = createBeanVertex(factory, dependency);
if(depBV != null) {
if (!graph.containsVertex(depBV)) {
graph.addVertex(depBV);
queue.add(depBV);
}
graph.addEdge(bv, depBV);
}
}
}
return new UnmodifiableDirectedGraph<Bean, DefaultEdge>(graph);
}
private Collection<String> getDependenciesForBean(final ConfigurableListableBeanFactory factory, final String sourceBeanName) {
final List<String> res = new ArrayList<String>();
res.addAll(Arrays.asList(factory.getDependenciesForBean(sourceBeanName)));
try {
Object bean = factory.getBean(sourceBeanName);
Class<?> clazz = AopUtils.getTargetClass(bean);
ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) {
if (method.isAnnotationPresent(ManuallyWired.class)) {
ManuallyWired manuallyWired = method.getAnnotation(ManuallyWired.class);
for (String beanName : manuallyWired.beanNames()) {
if(beanName != null && !beanName.isEmpty()) {
res.add(beanName);
}
}
}
}
}
);
} catch(BeansException e) {
// do nothing
}
return res;
}
private Bean createBeanVertex(final ConfigurableListableBeanFactory factory, String beanName) {
if(factory.containsBeanDefinition(beanName)) {
BeanDefinition def = factory.getBeanDefinition(beanName);
if(def.isAbstract()) {
return null;
}
}
Bean res = new Bean(beanName);
try {
Object bean = factory.getBean(beanName);
Class<?> clazz = AopUtils.getTargetClass(bean);
res.setClassName(clazz.getCanonicalName());
} catch(BeansException e) {
// do nothing
}
return res;
}
}
|
package org.zstack.core.gc;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.cloudbus.ResourceDestinationMaker;
import org.zstack.core.config.GlobalConfig;
import org.zstack.core.config.GlobalConfigUpdateExtensionPoint;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.PeriodicTask;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.header.AbstractService;
import org.zstack.header.Component;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.zstack.core.Platform.operr;
public class GarbageCollectorManagerImpl extends AbstractService
implements GarbageCollectorManager, Component, ManagementNodeReadyExtensionPoint {
static final CLogger logger = Utils.getLogger(GarbageCollectorManagerImpl.class);
@Autowired
private ResourceDestinationMaker destinationMaker;
@Autowired
private ThreadFacade thdf;
@Autowired
private CloudBus bus;
@Autowired
private DatabaseFacade dbf;
@Autowired
private ErrorFacade errf;
private Future<Void> scanOrphanJobsTask;
private ConcurrentHashMap<String, GarbageCollector> managedGarbageCollectors = new ConcurrentHashMap<>();
private void startScanOrphanJobs() {
if (scanOrphanJobsTask != null) {
scanOrphanJobsTask.cancel(true);
}
scanOrphanJobsTask = thdf.submitPeriodicTask(new PeriodicTask() {
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return GCGlobalConfig.SCAN_ORPHAN_JOB_INTERVAL.value(Long.class);
}
@Override
public String getName() {
return "scan-orphan-gc-jobs";
}
@Override
public void run() {
try {
loadOrphanJobs();
} catch (Exception e) {
throw new CloudRuntimeException(e);
}
}
});
logger.debug(String.format("[GC] starts scanning orphan job thread with the interval[%ss]", GCGlobalConfig.SCAN_ORPHAN_JOB_INTERVAL.value(Integer.class)));
}
void registerGC(GarbageCollector gc) {
managedGarbageCollectors.put(gc.uuid, gc);
}
void deregisterGC(GarbageCollector gc) {
managedGarbageCollectors.remove(gc.uuid);
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
private GarbageCollector loadGCJob(GarbageCollectorVO vo) {
try {
GarbageCollector ret = null;
Class clz = Class.forName(vo.getRunnerClass());
if (vo.getType().equals(GarbageCollectorType.EventBased.toString())) {
EventBasedGarbageCollector gc = (EventBasedGarbageCollector) clz.newInstance();
gc.load(vo);
ret = gc;
} else if (vo.getType().equals(GarbageCollectorType.TimeBased.toString())) {
TimeBasedGarbageCollector gc = (TimeBasedGarbageCollector) clz.newInstance();
gc.load(vo);
ret = gc;
} else if (vo.getType().equals(GarbageCollectorType.CycleBased.toString())) {
TimeBasedGarbageCollector gc = (TimeBasedGarbageCollector) clz.newInstance();
gc.load(vo);
ret = gc;
} else {
DebugUtils.Assert(false, "should not be here");
}
return ret;
} catch (Exception e) {
throw new CloudRuntimeException(e);
}
}
private void loadOrphanJobs() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
List<GarbageCollectorVO> vos = Q.New(GarbageCollectorVO.class)
.eq(GarbageCollectorVO_.status, GCStatus.Idle)
.isNull(GarbageCollectorVO_.managementNodeUuid)
.list();
int count = 0;
for (GarbageCollectorVO vo : vos) {
if (!destinationMaker.isManagedByUs(vo.getUuid())) {
continue;
}
loadGCJob(vo);
count ++;
}
logger.debug(String.format("[GC] loaded %s orphan jobs", count));
}
@Override
public void managementNodeReady() {
startScanOrphanJobs();
GCGlobalConfig.SCAN_ORPHAN_JOB_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startScanOrphanJobs();
}
});
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
}
private void handleLocalMessage(Message msg) {
bus.dealWithUnknownMessage(msg);
}
private void handleApiMessage(APIMessage msg) {
if (msg instanceof APITriggerGCJobMsg) {
handle((APITriggerGCJobMsg) msg);
} else if (msg instanceof APIDeleteGCJobMsg) {
handle((APIDeleteGCJobMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(APIDeleteGCJobMsg msg) {
GarbageCollector gc = managedGarbageCollectors.get(msg.getUuid());
if (gc != null) {
gc.cancel();
}
GarbageCollectorVO vo = dbf.findByUuid(msg.getUuid(), GarbageCollectorVO.class);
dbf.remove(vo);
APIDeleteGCJobEvent evt = new APIDeleteGCJobEvent(msg.getId());
bus.publish(evt);
}
private void handle(APITriggerGCJobMsg msg) {
GarbageCollector gc = managedGarbageCollectors.get(msg.getUuid());
if (gc != null) {
gc.runTrigger();
} else {
GarbageCollectorVO vo = dbf.findByUuid(msg.getUuid(), GarbageCollectorVO.class);
if (vo.getStatus() == GCStatus.Done) {
throw new OperationFailureException(operr("cannot trigger a finished GC job[uuid:%s, name:%s]",
vo.getUuid(), vo.getName()));
}
gc = loadGCJob(vo);
gc.runTrigger();
}
APITriggerGCJobEvent evt = new APITriggerGCJobEvent(msg.getId());
bus.publish(evt);
}
@Override
public String getId() {
return bus.makeLocalServiceId(GCConstants.SERVICE_ID);
}
}
|
package nars.grid2d;
import java.util.List;
import nars.core.Build;
import nars.core.EventEmitter.EventObserver;
import nars.core.Events;
import nars.core.NAR;
import nars.core.Parameters;
import nars.core.build.Default;
import nars.grid2d.Cell.Logic;
import nars.grid2d.Cell.Material;
import static nars.grid2d.Hauto.DOWN;
import static nars.grid2d.Hauto.LEFT;
import static nars.grid2d.Hauto.RIGHT;
import static nars.grid2d.Hauto.UP;
import nars.grid2d.map.Maze;
import nars.grid2d.object.Key;
import nars.grid2d.operator.Activate;
import nars.grid2d.operator.Deactivate;
import nars.grid2d.operator.Goto;
import nars.grid2d.operator.Pick;
import nars.gui.NARSwing;
import nars.plugin.app.plan.TemporalParticlePlanner;
import nars.plugin.mental.FullInternalExperience;
import nars.plugin.mental.InternalExperience;
import processing.core.PVector;
public class TestChamber {
public static boolean staticInformation=false;
//TIMING
static int narUpdatePeriod = 20; /*milliseconds */
int gridUpdatePeriod = 2;
int automataPeriod = 2;
int agentPeriod = 2;
static long guiUpdateTime = 25; /* milliseconds */
//OPTIONS
public static boolean curiousity=false;
public static void main(String[] args) {
Build builder = new Default();
//set NAR architecture parameters:
//builder...
Parameters.DEFAULT_JUDGMENT_DURABILITY=0.99f; //try to don't forget the input in TestChamber domain
NAR nar = builder.build();
//set NAR runtime parmeters:
/*for(NAR.PluginState pluginstate : nar.getPlugins()) {
if(pluginstate.plugin instanceof InternalExperience || pluginstate.plugin instanceof FullInternalExperience) {
nar.removePlugin(pluginstate);
}
}*/
//nar.addPlugin(new TemporalParticlePlanner());
//(nar.param).duration.set(10);
(nar.param).noiseLevel.set(0);
new NARSwing(nar);
new TestChamber(nar);
nar.start(narUpdatePeriod);
}
static Grid2DSpace space;
public PVector lasttarget = new PVector(5, 25); //not work
public static boolean executed_going=false;
static String goal = "";
static String opname="";
public static LocalGridObject inventorybag=null;
public static int keyn=-1;
public static String getobj(int x,int y) {
for(GridObject gridi : space.objects) {
if(gridi instanceof LocalGridObject) { //Key && ((Key)gridi).doorname.equals(goal)) {
LocalGridObject gridu=(LocalGridObject) gridi;
if(gridu.x==x && gridu.y==y && !"".equals(gridu.doorname))
return gridu.doorname;
}
}
return "";
}
public static void operateObj(String arg,String opnamer) {
opname=opnamer;
Hauto cells = space.cells;
goal = arg;
for (int i = 0; i < cells.w; i++) {
for (int j = 0; j < cells.h; j++) {
if (cells.readCells[i][j].name.equals(arg)) {
if(opname.equals("go-to"))
space.target = new PVector(i, j);
}
}
}
//if("pick".equals(opname)) {
for(GridObject gridi : space.objects) {
if(gridi instanceof LocalGridObject && ((LocalGridObject)gridi).doorname.equals(goal)) { //Key && ((Key)gridi).doorname.equals(goal)) {
LocalGridObject gridu=(LocalGridObject) gridi;
if(opname.equals("go-to"))
space.target = new PVector(gridu.x, gridu.y);
}
}
}
boolean invalid=false;
public static boolean active=true;
public static boolean executed=false;
public static boolean needpizza=false;
public static int hungry=250;
public List<PVector> path=null;
public TestChamber() {
super();
}
public TestChamber(NAR nar) {
this(nar, true);
}
public TestChamber(NAR nar, boolean showWindow) {
super();
int w = 50;
int h = 50;
int water_threshold = 30;
Hauto cells = new Hauto(w, h, nar);
cells.forEach(0, 0, w, h, new CellFunction() {
@Override
public void update(Cell c) {
///c.setHeight((int)(Math.random() * 12 + 1));
float smoothness = 20f;
c.material = Material.GrassFloor;
double n = SimplexNoise.noise(c.state.x / smoothness, c.state.y / smoothness);
if ((n * 64) > water_threshold) {
c.material = Material.Water;
}
c.setHeight((int) (Math.random() * 24 + 1));
}
});
Maze.buildMaze(cells, 3, 3, 23, 23);
space = new Grid2DSpace(cells, nar);
space.FrameRate = 0;
space.automataPeriod = automataPeriod/gridUpdatePeriod;
space.agentPeriod = agentPeriod/gridUpdatePeriod;
TestChamber into=this;
nar.memory.event.on(Events.FrameEnd.class, new EventObserver() {
private long lastDrawn = 0;
@Override
public void event(Class event, Object... arguments) {
if (nar.time() % gridUpdatePeriod == 0) {
space.update(into);
long now = System.nanoTime();
if (now - lastDrawn > guiUpdateTime*1e6) {
space.redraw();
lastDrawn = now;
}
}
}
});
if (showWindow)
space.newWindow(1000, 800, true);
cells.forEach(16, 16, 18, 18, new Hauto.SetMaterial(Material.DirtFloor));
GridAgent a = new GridAgent(17, 17, nar) {
@Override
public void update(Effect nextEffect) {
if(active) {
//nar.stop();
executed=false;
if(path==null || path.size()<=0 && !executed_going) {
for (int i = 0; i < 5; i++) { //make thinking in testchamber bit faster
//nar.step(1);
if (executed) {
break;
}
}
}
if(needpizza) {
hungry
if(hungry<0) {
hungry=250;
nar.addInput("(&&,<#1 --> pizza>,<#1 --> [at]>)!"); //also works but better:
/*for (GridObject obj : space.objects) {
if (obj instanceof Pizza) {
nar.addInput("<" + ((Pizza) obj).doorname + "--> at>!");
}
}*/
}
}
}
// int a = 0;
// if (Math.random() < 0.4) {
// int randDir = (int)(Math.random()*4);
// if (randDir == 0) a = LEFT;
// else if (randDir == 1) a = RIGHT;
// else if (randDir == 2) a = UP;
// else if (randDir == 3) a = DOWN;
// /*else if (randDir == 4) a = UPLEFT;
// else if (randDir == 5) a = UPRIGHT;
// else if (randDir == 6) a = DOWNLEFT;
// else if (randDir == 7) a = DOWNRIGHT;*/
// turn(a);
/*if (Math.random() < 0.2) {
forward(1);
}*/
lasttarget = space.target;
space.current = new PVector(x, y);
// System.out.println(nextEffect);
if (nextEffect == null) {
path = Grid2DSpace.Shortest_Path(space, this, space.current, space.target);
actions.clear();
// System.out.println(path);
if(path==null) {
executed_going=false;
}
if (path != null) {
if(inventorybag!=null) {
inventorybag.x=(int)space.current.x;
inventorybag.y=(int)space.current.y;
inventorybag.cx=(int)space.current.x;
inventorybag.cy=(int)space.current.y;
}
if(inventorybag==null || !(inventorybag instanceof Key)) {
keyn=-1;
}
if (path.size() <= 1) {
active=true;
executed_going=false;
//System.out.println("at destination; didnt need to find path");
if (!"".equals(goal) && space.current.equals(space.target)) {
//--nar.step(6);
GridObject obi=null;
if(!"".equals(opname)) {
for(GridObject gridi : space.objects) {
if(gridi instanceof LocalGridObject && ((LocalGridObject)gridi).doorname.equals(goal) &&
((LocalGridObject)gridi).x==(int)space.current.x &&
((LocalGridObject)gridi).y==(int)space.current.y ) {
obi=gridi;
break;
}
}
}
if(obi!=null || cells.readCells[(int)space.current.x][(int)space.current.y].name.equals(goal)) { //only possible for existing ones
if("pick".equals(opname)) {
if(inventorybag!=null && inventorybag instanceof LocalGridObject) {
//we have to drop it
LocalGridObject ob=(LocalGridObject) inventorybag;
ob.x=(int)space.current.x;
ob.y=(int)space.current.y;
space.objects.add(ob);
}
inventorybag=(LocalGridObject)obi;
if(obi!=null) {
space.objects.remove(obi);
if(inventorybag.doorname.startsWith("{key")) {
keyn=Integer.parseInt(inventorybag.doorname.replaceAll("key", "").replace("}", "").replace("{", ""));
for(int i=0;i<cells.h;i++) {
for(int j=0;j<cells.w;j++) {
if(Hauto.doornumber(cells.readCells[i][j])==keyn) {
cells.readCells[i][j].is_solid=false;
cells.writeCells[i][j].is_solid=false;
}
}
}
}
}
//nar.addInput("<"+goal+" --> hold>. :|:");
}
else
if("deactivate".equals(opname)) {
for(int i=0;i<cells.h;i++) {
for(int j=0;j<cells.w;j++) {
if(cells.readCells[i][j].name.equals(goal)) {
if(cells.readCells[i][j].logic==Logic.SWITCH) {
cells.readCells[i][j].logic=Logic.OFFSWITCH;
cells.writeCells[i][j].logic=Logic.OFFSWITCH;
cells.readCells[i][j].charge=0.0f;
cells.writeCells[i][j].charge=0.0f;
//nar.addInput("<"+goal+" --> off>. :|:");
}
}
}
}
}
else
if("activate".equals(opname)) {
for(int i=0;i<cells.h;i++) {
for(int j=0;j<cells.w;j++) {
if(cells.readCells[i][j].name.equals(goal)) {
if(cells.readCells[i][j].logic==Logic.OFFSWITCH) {
cells.readCells[i][j].logic=Logic.SWITCH;
cells.writeCells[i][j].logic=Logic.SWITCH;
cells.readCells[i][j].charge=1.0f;
cells.writeCells[i][j].charge=1.0f;
//nar.addInput("<"+goal+" --> on>. :|:");
}
}
}
}
}
if("go-to".equals(opname)) {
executed_going=false;
nar.addInput("<"+goal+"
if (goal.startsWith("{pizza")) {
GridObject ToRemove = null;
for (GridObject obj : space.objects) { //remove pizza
if (obj instanceof LocalGridObject) {
LocalGridObject obo = (LocalGridObject) obj;
if (obo.doorname.equals(goal)) {
ToRemove = obj;
}
}
}
if (ToRemove != null) {
space.objects.remove(ToRemove);
}
hungry=500;
//nar.addInput("<"+goal+" --> eat>. :|:"); //that is sufficient:
nar.addInput("<"+goal+"
}
active=true;
}
}
}
opname="";
nar.memory.setEnabled(true);
/*if(!executed && !executed_going)
nar.step(1);*/
} else {
//nar.step(10);
//nar.memory.setEnabled(false);
executed_going=true;
active=false;
//nar.step(1);
int numSteps = Math.min(10, path.size());
float cx = x;
float cy = y;
for (int i = 1; i < numSteps; i++) {
PVector next = path.get(i);
int dx = (int) (next.x - cx);
int dy = (int) (next.y - cy);
if ((dx == 0) && (dy == 1)) {
turn(UP);
forward(1);
}
if ((dx == 1) && (dy == 0)) {
turn(RIGHT);
forward(1);
}
if ((dx == -1) && (dy == 0)) {
turn(LEFT);
forward(1);
}
if ((dx == 0) && (dy == -1)) {
turn(DOWN);
forward(1);
}
cx = next.x;
cy = next.y;
}
}
}
}
}
};
Goto wu = new Goto(this, "^go-to");
nar.memory.addOperator(wu);
Pick wa = new Pick(this, "^pick");
nar.memory.addOperator(wa);
Activate waa = new Activate(this, "^activate");
nar.memory.addOperator(waa);
Deactivate waaa = new Deactivate(this, "^deactivate");
nar.memory.addOperator(waaa);
space.add(a);
}
}
|
package org.jpos.bsh;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.core.ReConfigurable;
import org.jpos.iso.ISOChannel;
import org.jpos.iso.ISORequestListener;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOSource;
import org.jpos.util.Log;
import bsh.Interpreter;
/**
* BSHRequestListener - BeanShell based request listener
* @author <a href="mailto:apr@cs.com.uy">Alejandro P. Revilla</a>
* @version $Revision$ $Date$
*/
public class BSHRequestListener extends Log
implements ISORequestListener, ReConfigurable
{
protected static final String MTI_MACRO = "$mti";
Configuration cfg;
public BSHRequestListener () {
super();
}
/**
* @param cfg
* <ul>
* <li>source - BSH script(s) to run (can be more than one)
* </ul>
*/
public void setConfiguration (Configuration cfg)
throws ConfigurationException
{
this.cfg = cfg;
}
public boolean process (ISOSource source, ISOMsg m) {
try{
String mti = m.getMTI ();
String[] bshSource = cfg.getAll ("source");
for (int i=0; i<bshSource.length; i++) {
try {
Interpreter bsh = new Interpreter ();
bsh.set ("source", source);
bsh.set ("message", m);
bsh.set ("log", this);
bsh.set ("cfg", cfg);
//replace $mti with the actual value in script file name
int idx = bshSource[i].indexOf(MTI_MACRO);
String script;
if(idx >= 0)
script = bshSource[i].substring(0, idx) + mti + bshSource[i].substring(idx + MTI_MACRO.length());
else
script = bshSource[i];
bsh.source (script);
} catch (Exception e) {
warn (e);
}
}
}catch (Exception e){
warn(e);
}
return true;
}
}
|
// -*- mode: java; c-basic-offset: 2; -*-
package com.google.appinventor.client.editor.youngandroid;
import static com.google.appinventor.client.Ode.MESSAGES;
import com.google.appinventor.client.ErrorReporter;
import com.google.appinventor.client.Ode;
import com.google.appinventor.client.OdeAsyncCallback;
import com.google.appinventor.client.boxes.AssetListBox;
import com.google.appinventor.client.boxes.PaletteBox;
import com.google.appinventor.client.boxes.PropertiesBox;
import com.google.appinventor.client.boxes.SourceStructureBox;
import com.google.appinventor.client.editor.ProjectEditor;
import com.google.appinventor.client.editor.simple.ComponentNotFoundException;
import com.google.appinventor.client.editor.simple.SimpleComponentDatabase;
import com.google.appinventor.client.editor.simple.SimpleEditor;
import com.google.appinventor.client.editor.simple.SimpleNonVisibleComponentsPanel;
import com.google.appinventor.client.editor.simple.SimpleVisibleComponentsPanel;
import com.google.appinventor.client.editor.simple.components.FormChangeListener;
import com.google.appinventor.client.editor.simple.components.MockComponent;
import com.google.appinventor.client.editor.simple.components.MockContainer;
import com.google.appinventor.client.editor.simple.components.MockForm;
import com.google.appinventor.client.editor.simple.palette.DropTargetProvider;
import com.google.appinventor.client.editor.simple.palette.SimpleComponentDescriptor;
import com.google.appinventor.client.editor.simple.palette.SimplePalettePanel;
import com.google.appinventor.client.editor.youngandroid.palette.YoungAndroidPalettePanel;
import com.google.appinventor.client.explorer.SourceStructureExplorer;
import com.google.appinventor.client.explorer.project.ComponentDatabaseChangeListener;
import com.google.appinventor.client.output.OdeLog;
import com.google.appinventor.client.properties.json.ClientJsonParser;
import com.google.appinventor.client.properties.json.ClientJsonString;
import com.google.appinventor.client.widgets.dnd.DropTarget;
import com.google.appinventor.client.widgets.properties.EditableProperties;
import com.google.appinventor.client.widgets.properties.EditableProperty;
import com.google.appinventor.client.widgets.properties.PropertiesPanel;
import com.google.appinventor.client.widgets.properties.PropertyChangeListener;
import com.google.appinventor.client.youngandroid.YoungAndroidFormUpgrader;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.shared.properties.json.JSONArray;
import com.google.appinventor.shared.properties.json.JSONObject;
import com.google.appinventor.shared.properties.json.JSONParser;
import com.google.appinventor.shared.properties.json.JSONValue;
import com.google.appinventor.shared.rpc.project.ChecksumedFileException;
import com.google.appinventor.shared.rpc.project.ChecksumedLoadFile;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidFormNode;
import com.google.appinventor.shared.settings.SettingsConstants;
import com.google.appinventor.shared.youngandroid.YoungAndroidSourceAnalyzer;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.gwt.core.client.Callback;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Navigator;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.RootPanel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Editor for Young Android Form (.scm) files.
*
* <p>This editor shows a designer that provides support for visual design of
* forms.</p>
*
* @author markf@google.com (Mark Friedman)
* @author lizlooney@google.com (Liz Looney)
*/
public final class YaFormEditor extends SimpleEditor implements FormChangeListener, ComponentDatabaseChangeListener, PropertyChangeListener {
private static class FileContentHolder {
private String content;
FileContentHolder(String content) {
this.content = content;
}
void setFileContent(String content) {
this.content = content;
}
String getFileContent() {
return content;
}
}
private static final String ERROR_EXISTING_UUID = "Component with UUID \"%1$s\" already exists.";
private static final String ERROR_NONEXISTENT_UUID = "No component exists with UUID \"%1$s\".";
// JSON parser
private static final JSONParser JSON_PARSER = new ClientJsonParser();
private final SimpleComponentDatabase COMPONENT_DATABASE;
private final YoungAndroidFormNode formNode;
// Flag to indicate when loading the file is completed. This is needed because building the mock
// form from the file properties fires events that need to be ignored, otherwise the file will be
// marked as being modified.
private boolean loadComplete;
// References to other panels that we need to control.
private final SourceStructureExplorer sourceStructureExplorer;
// Panels that are used as the content of the palette and properties boxes.
private final YoungAndroidPalettePanel palettePanel;
private final PropertiesPanel designProperties;
// UI elements
private final SimpleVisibleComponentsPanel visibleComponentsPanel;
private final SimpleNonVisibleComponentsPanel nonVisibleComponentsPanel;
private MockForm form; // initialized lazily after the file is loaded from the ODE server
// [lyn, 2014/10/13] Need to remember JSON initially loaded from .scm file *before* it is upgraded
// by YoungAndroidFormUpgrader within upgradeFile. This JSON contains pre-upgrade component
// version info that is needed by Blockly.SaveFile.load to perform upgrades in the Blocks Editor.
// This was unnecessary in AI Classic because the .blk file contained component version info
// as well as the .scm file. But in AI2, the .bky file contains no component version info,
// and we rely on the pre-upgraded .scm file for this info.
private String preUpgradeJsonString;
private final List<ComponentDatabaseChangeListener> componentDatabaseChangeListeners = new ArrayList<ComponentDatabaseChangeListener>();
private JSONArray authURL; // List of App Inventor versions we have been edited on.
/**
* A mapping of component UUIDs to mock components in the designer view.
*/
private final Map<String, MockComponent> componentsDb = new HashMap<String, MockComponent>();
private static final int OLD_PROJECT_YAV = 150; // Projects older then this have no authURL
private boolean shouldSelectMultipleComponents = false;
private EditableProperties selectedProperties = null;
private List<MockComponent> selectedComponents = new ArrayList<MockComponent>();
/**
* Creates a new YaFormEditor.
*
* @param projectEditor the project editor that contains this file editor
* @param formNode the YoungAndroidFormNode associated with this YaFormEditor
*/
YaFormEditor(ProjectEditor projectEditor, YoungAndroidFormNode formNode) {
super(projectEditor, formNode);
this.formNode = formNode;
COMPONENT_DATABASE = SimpleComponentDatabase.getInstance(getProjectId());
// Get reference to the source structure explorer
sourceStructureExplorer =
SourceStructureBox.getSourceStructureBox().getSourceStructureExplorer();
// Create UI elements for the designer panels.
nonVisibleComponentsPanel = new SimpleNonVisibleComponentsPanel();
componentDatabaseChangeListeners.add(nonVisibleComponentsPanel);
visibleComponentsPanel = new SimpleVisibleComponentsPanel(this, nonVisibleComponentsPanel);
componentDatabaseChangeListeners.add(visibleComponentsPanel);
DockPanel componentsPanel = new DockPanel();
componentsPanel.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
componentsPanel.add(visibleComponentsPanel, DockPanel.NORTH);
componentsPanel.add(nonVisibleComponentsPanel, DockPanel.SOUTH);
componentsPanel.setSize("100%", "100%");
RootPanel.get().addDomHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if (Navigator.getPlatform().toLowerCase().startsWith("mac")) {
shouldSelectMultipleComponents = event.isMetaKeyDown();
} else {
shouldSelectMultipleComponents = event.isControlKeyDown();
}
}
}, KeyDownEvent.getType());
RootPanel.get().addDomHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (Navigator.getPlatform().toLowerCase().startsWith("mac")) {
shouldSelectMultipleComponents = event.isMetaKeyDown();
} else {
shouldSelectMultipleComponents = event.isControlKeyDown();
}
}
}, KeyUpEvent.getType());
// Create palettePanel, which will be used as the content of the PaletteBox.
palettePanel = new YoungAndroidPalettePanel(this);
palettePanel.loadComponents(new DropTargetProvider() {
@Override
public DropTarget[] getDropTargets() {
// TODO(markf): Figure out a good way to memorize the targets or refactor things so that
// getDropTargets() doesn't get called for each component.
// NOTE: These targets must be specified in depth-first order.
List<DropTarget> dropTargets = form.getDropTargetsWithin();
dropTargets.add(visibleComponentsPanel);
dropTargets.add(nonVisibleComponentsPanel);
return dropTargets.toArray(new DropTarget[dropTargets.size()]);
}
});
palettePanel.setSize("100%", "100%");
componentDatabaseChangeListeners.add(palettePanel);
// Create designProperties, which will be used as the content of the PropertiesBox.
designProperties = new PropertiesPanel();
designProperties.setSize("100%", "100%");
initWidget(componentsPanel);
setSize("100%", "100%");
}
public List<MockComponent> getSelectedComponents() {
return selectedComponents;
}
public boolean getShouldSelectMultipleComponents() {
return shouldSelectMultipleComponents;
}
public boolean shouldDisplayHiddenComponents() {
return visibleComponentsPanel.isHiddenComponentsCheckboxChecked();
}
// FileEditor methods
@Override
public void loadFile(final Command afterFileLoaded) {
final long projectId = getProjectId();
final String fileId = getFileId();
OdeAsyncCallback<ChecksumedLoadFile> callback = new OdeAsyncCallback<ChecksumedLoadFile>(MESSAGES.loadError()) {
@Override
public void onSuccess(ChecksumedLoadFile result) {
String contents;
try {
contents = result.getContent();
} catch (ChecksumedFileException e) {
this.onFailure(e);
return;
}
final FileContentHolder fileContentHolder = new FileContentHolder(contents);
upgradeFile(fileContentHolder, new Command() {
@Override
public void execute() {
try {
onFileLoaded(fileContentHolder.getFileContent());
} catch(IllegalArgumentException e) {
return;
}
if (afterFileLoaded != null) {
afterFileLoaded.execute();
}
}
});
}
@Override
public void onFailure(Throwable caught) {
if (caught instanceof ChecksumedFileException) {
Ode.getInstance().recordCorruptProject(projectId, fileId, caught.getMessage());
}
super.onFailure(caught);
}
};
Ode.getInstance().getProjectService().load2(projectId, fileId, callback);
}
@Override
public String getTabText() {
return formNode.getFormName();
}
@Override
public void onShow() {
OdeLog.log("YaFormEditor: got onShow() for " + getFileId());
super.onShow();
loadDesigner();
}
@Override
public void onHide() {
OdeLog.log("YaFormEditor: got onHide() for " + getFileId());
// When an editor is detached, if we are the "current" editor,
// set the current editor to null and clean up the UI.
// Note: I'm not sure it is possible that we would not be the "current"
// editor when this is called, but we check just to be safe.
if (Ode.getInstance().getCurrentFileEditor() == this) {
super.onHide();
unloadDesigner();
} else {
OdeLog.wlog("YaFormEditor.onHide: Not doing anything since we're not the "
+ "current file editor!");
}
}
@Override
public void onClose() {
form.removeFormChangeListener(this);
// Note: our partner YaBlocksEditor will remove itself as a FormChangeListener, even
// though we added it.
}
@Override
public String getRawFileContent() {
String encodedProperties = encodeFormAsJsonString(false);
JSONObject propertiesObject = JSON_PARSER.parse(encodedProperties).asObject();
return YoungAndroidSourceAnalyzer.generateSourceFile(propertiesObject);
}
@Override
public void onSave() {
}
// SimpleEditor methods
@Override
public boolean isLoadComplete() {
return loadComplete;
}
@Override
public Map<String, MockComponent> getComponents() {
Map<String, MockComponent> map = Maps.newHashMap();
if (loadComplete) {
populateComponentsMap(form, map);
}
return map;
}
@Override
public List<String> getComponentNames() {
return new ArrayList<String>(getComponents().keySet());
}
@Override
public SimplePalettePanel getComponentPalettePanel() {
return palettePanel;
}
@Override
public SimpleNonVisibleComponentsPanel getNonVisibleComponentsPanel() {
return nonVisibleComponentsPanel;
}
public SimpleVisibleComponentsPanel getVisibleComponentsPanel() {
return visibleComponentsPanel;
}
@Override
public boolean isScreen1() {
return formNode.isScreen1();
}
// PropertyChangeListener implementation
@Override
public void onPropertyChange(String propertyName, String propertyValue) {
for (MockComponent selectedComponent : selectedComponents) {
selectedComponent.changeProperty(propertyName, propertyValue);
}
}
// FormChangeListener implementation
@Override
public void onComponentPropertyChanged(MockComponent component,
String propertyName, String propertyValue) {
if (loadComplete) {
// If the property isn't actually persisted to the .scm file, we don't need to do anything.
if (component.isPropertyPersisted(propertyName)) {
Ode.getInstance().getEditorManager().scheduleAutoSave(this);
updatePhone(); // Push changes to the phone if it is connected
}
} else {
OdeLog.elog("onComponentPropertyChanged called when loadComplete is false");
}
}
private boolean isIntersectedProperty(String propertyName) {
for (MockComponent selectedComponent : selectedComponents) {
if (!selectedComponent.hasProperty(propertyName)) {
return false;
}
}
return true;
}
@Override
public void onComponentRemoved(MockComponent component, boolean permanentlyDeleted) {
if (loadComplete) {
if (permanentlyDeleted) {
if (isSelectedComponent(component)) {
selectedComponents.remove(component);
EditableProperties propertyIntersection = new EditableProperties(true);
for (MockComponent selectedComponent : selectedComponents) {
for (EditableProperty property : selectedComponent.getProperties()) {
String propertyName = property.getName();
if (propertyName == "Uuid") {
continue;
}
if (isIntersectedProperty(propertyName)) {
propertyIntersection.addProperty(
propertyName,
property.getDefaultValue(),
property.getCaption(),
property.getEditor(),
property.getType()
);
}
}
}
selectedProperties = propertyIntersection;
selectedProperties.addPropertyChangeListener(this);
}
onFormStructureChange();
}
} else {
OdeLog.elog("onComponentRemoved called when loadComplete is false");
}
}
@Override
public void onComponentAdded(MockComponent component) {
if (loadComplete) {
selectedProperties = component.getProperties();
selectedComponents = new ArrayList<MockComponent>();
onFormStructureChange();
} else {
OdeLog.elog("onComponentAdded called when loadComplete is false");
}
}
@Override
public void onComponentRenamed(MockComponent component, String oldName) {
if (loadComplete) {
onFormStructureChange();
updatePropertiesPanel(component);
} else {
OdeLog.elog("onComponentRenamed called when loadComplete is false");
}
}
public boolean isSelectedComponent(MockComponent component) {
String name = component.getName();
for (MockComponent selectedComponent : selectedComponents) {
if (selectedComponent.getName() == name) {
return true;
}
}
return false;
}
private boolean isIntersectedValue(String propertyName) {
String value = null;
for (MockComponent selectedComponent : selectedComponents) {
String propertyValue = selectedComponent.getPropertyValue(propertyName);
if (value == null) {
value = propertyValue;
} else if (!value.equals(propertyValue)) {
return false;
}
}
return true;
}
@Override
public void onComponentSelectionChange(MockComponent component, boolean selected) {
if (loadComplete) {
if (selected) {
// Select the item in the source structure explorer.
sourceStructureExplorer.selectItem(component.getSourceStructureExplorerItem());
EditableProperties componentProperties = component.getProperties();
if (selectedProperties != null && shouldSelectMultipleComponents) {
if (!isSelectedComponent(component)) {
selectedComponents.add(component);
}
EditableProperties propertyIntersection = new EditableProperties(true);
for (EditableProperty property : componentProperties) {
String propertyName = property.getName();
if (propertyName == "Uuid") {
continue;
}
if (selectedProperties.hasProperty(propertyName)) {
propertyIntersection.addProperty(
propertyName,
(isIntersectedValue(propertyName)) ? property.getValue() : property.getDefaultValue(),
property.getCaption(),
property.getEditor(),
property.getType()
);
}
}
selectedProperties = propertyIntersection;
selectedProperties.addPropertyChangeListener(this);
} else {
selectedComponents = new ArrayList<MockComponent>();
selectedComponents.add(component);
selectedProperties = componentProperties;
}
// Show the component properties in the properties panel.
updatePropertiesPanel(component);
} else if (isSelectedComponent(component) && selectedComponents.size() > 1) {
selectedComponents.remove(component);
EditableProperties propertyIntersection = new EditableProperties(true);
for (EditableProperty property : selectedComponents.get(0).getProperties()) {
String propertyName = property.getName();
if (propertyName == "Uuid") {
continue;
}
if (isIntersectedProperty(propertyName)) {
propertyIntersection.addProperty(
propertyName,
(isIntersectedValue(propertyName)) ? property.getValue() : property.getDefaultValue(),
property.getCaption(),
property.getEditor(),
property.getType()
);
}
}
selectedProperties = propertyIntersection;
selectedProperties.addPropertyChangeListener(this);
updatePropertiesPanel(selectedComponents.size() == 1 ? selectedComponents.get(0) : null);
onFormStructureChange();
}
} else {
OdeLog.elog("onComponentSelectionChange called when loadComplete is false");
}
}
// other public methods
/**
* Returns the form associated with this YaFormEditor.
*
* @return a MockForm
*/
public MockForm getForm() {
return form;
}
public String getComponentInstanceTypeName(String instanceName) {
return getComponents().get(instanceName).getType();
}
// private methods
/*
* Upgrades the given file content, saves the upgraded content back to the
* ODE server, and calls the afterUpgradeComplete command after the save
* operation succeeds.
*
* If no upgrade is necessary, the afterSavingFiles command is called
* immediately.
*
* @param fileContentHolder holds the file content
* @param afterUpgradeComplete optional command to be executed after the
* file has upgraded and saved back to the ODE
* server
*/
private void upgradeFile(FileContentHolder fileContentHolder,
final Command afterUpgradeComplete) {
JSONObject propertiesObject = YoungAndroidSourceAnalyzer.parseSourceFile(
fileContentHolder.getFileContent(), JSON_PARSER);
// BEGIN PROJECT TAGGING CODE
// | Project Tagging Code: |
// | Because of the likely proliferation of various versions of App |
// | Inventor, we want to mark a project with the history of which |
// | versions have seen it. We do that with the "authURL" tag which we |
// | add to the Form files. It is a JSON array of versions identified |
// | by the hostname portion of the URL of the service editing the |
// | project. Older projects will not have this field, so if we detect |
// | an older project (YAV < OLD_PROJECT_YAV) we create the list and |
// | add ourselves. If we read in a project where YAV >= |
// | OLD_PROJECT_YAV *and* there is no authURL, we assume that it was |
// | tagging and we add an "*UNKNOWN*" tag to indicate this. So for |
// | example if you examine a (newer) project and look in the |
// | Screen1.scm file, you should just see an authURL that looks like |
// | ["ai2.appinventor.mit.edu"]. This would indicate a project that |
// | has only been edited on MIT App Inventor. If instead you see |
// | something like ["localhost", "ai2.appinventor.mit.edu"] it |
// | implies that at some point in its history this project was edited |
// | using the local dev server on someone's own computer. |
authURL = (JSONArray) propertiesObject.get("authURL");
String ourHost = Window.Location.getHostName();
JSONValue us = new ClientJsonString(ourHost);
if (authURL != null) {
List<JSONValue> values = authURL.asArray().getElements();
boolean foundUs = false;
for (JSONValue value : values) {
if (value.asString().getString().equals(ourHost)) {
foundUs = true;
break;
}
}
if (!foundUs) {
authURL.asArray().getElements().add(us);
}
} else {
// Kludgey way to create an empty JSON array. But we cannot call ClientJsonArray ourselves
// because it is not a public class. So rather then make it public (and violate an abstraction
// barrier). We create the array this way. Sigh.
authURL = JSON_PARSER.parse("[]").asArray();
// Warning: If YaVersion isn't present, we will get an NPF on
// the line below. But it should always be there...
// Note: YaVersion although a numeric value is stored as a Json String so we have
// to parse it as a string and then convert it to a number in Java.
int yav = Integer.parseInt(propertiesObject.get("YaVersion").asString().getString());
// If yav is > OLD_PROJECT_YAV, and we still don't have an
// authURL property then we likely originated from a non-MIT App
// Inventor instance so add an *Unknown* tag before our tag
if (yav > OLD_PROJECT_YAV) {
authURL.asArray().getElements().add(new ClientJsonString("*UNKNOWN*"));
}
authURL.asArray().getElements().add(us);
}
// END OF PROJECT TAGGING CODE
preUpgradeJsonString = propertiesObject.toJson(); // [lyn, [2014/10/13] remember pre-upgrade component versions.
if (YoungAndroidFormUpgrader.upgradeSourceProperties(propertiesObject.getProperties())) {
String upgradedContent = YoungAndroidSourceAnalyzer.generateSourceFile(propertiesObject);
fileContentHolder.setFileContent(upgradedContent);
Ode ode = Ode.getInstance();
if (ode.isReadOnly()) { // Do not attempt to save out the project if we are in readonly mode
if (afterUpgradeComplete != null) {
afterUpgradeComplete.execute(); // But do call the afterUpgradeComplete call
}
} else {
Ode.getInstance().getProjectService().save(Ode.getInstance().getSessionId(),
getProjectId(), getFileId(), upgradedContent,
new OdeAsyncCallback<Long>(MESSAGES.saveError()) {
@Override
public void onSuccess(Long result) {
// Execute the afterUpgradeComplete command if one was given.
if (afterUpgradeComplete != null) {
afterUpgradeComplete.execute();
}
}
});
}
} else {
// No upgrade was necessary.
// Execute the afterUpgradeComplete command if one was given.
if (afterUpgradeComplete != null) {
afterUpgradeComplete.execute();
}
}
}
private void onFileLoaded(String content) {
JSONObject propertiesObject = YoungAndroidSourceAnalyzer.parseSourceFile(
content, JSON_PARSER);
try {
form = createMockForm(propertiesObject.getProperties().get("Properties").asObject());
} catch(ComponentNotFoundException e) {
Ode.getInstance().recordCorruptProject(getProjectId(), getProjectRootNode().getName(),
e.getMessage());
ErrorReporter.reportError(MESSAGES.noComponentFound(e.getComponentName(),
getProjectRootNode().getName()));
throw e;
}
// Initialize the nonVisibleComponentsPanel and visibleComponentsPanel.
nonVisibleComponentsPanel.setForm(form);
visibleComponentsPanel.setForm(form);
form.select();
String subsetjson = form.getPropertyValue(SettingsConstants.YOUNG_ANDROID_SETTINGS_BLOCK_SUBSET);
if (subsetjson.length() > 0) {
reloadComponentPalette(subsetjson);
}
// Set loadCompleted to true.
// From now on, all change events will be taken seriously.
loadComplete = true;
// Originally this was done in loadDesigner. However, this resulted in
// the form and blocks editor not being registered for events until after
// they were opened. This became problematic if the user deleted an extension
// prior to opening the screen as they would never trigger a save, resulting
// in a corrupt project.
// Listen to changes on the form.
form.addFormChangeListener(this);
// Also have the blocks editor listen to changes. Do this here instead
// of in the blocks editor so that we don't risk it missing any updates.
form.addFormChangeListener(((YaProjectEditor) projectEditor)
.getBlocksFileEditor(form.getName()));
}
public void reloadComponentPalette(String subsetjson) {
OdeLog.log(subsetjson);
Set<String> shownComponents = new HashSet<String>();
if (subsetjson.length() > 0) {
try {
String shownComponentsStr = getShownComponents(subsetjson);
if (shownComponentsStr.length() > 0) {
shownComponents = new HashSet<String>(Arrays.asList(shownComponentsStr.split(",")));
}
} catch (Exception e) {
OdeLog.log("invalid subset string");
}
// Toolkit does not currently support Extensions. The Extensions palette should be left alone.
palettePanel.clearComponentsExceptExtension();
} else {
shownComponents = COMPONENT_DATABASE.getComponentNames();
palettePanel.clearComponents();
}
for (String component : shownComponents) {
palettePanel.addComponent(component);
}
}
private native String getShownComponents(String subsetString)/*-{
var jsonObj = JSON.parse(subsetString);
var shownComponentTypes = jsonObj["shownComponentTypes"];
var shownString = "";
for (var category in shownComponentTypes) {
var categoryArr = shownComponentTypes[category];
for (var i = 0; i < categoryArr.length; i++) {
shownString = shownString + "," + categoryArr[i]["type"];
//console.log(categoryArr[i]["type"]);
}
}
var shownCompStr = shownString.substring(1);
//console.log(shownCompStr);
return shownCompStr;
}-*/;
/*
* Parses the JSON properties and creates the form and its component structure.
*/
private MockForm createMockForm(JSONObject propertiesObject) {
return (MockForm) createMockComponent(propertiesObject, null);
}
/*
* Parses the JSON properties and creates the component structure. This method is called
* recursively for nested components. For the initial invocation parent shall be null.
*/
private MockComponent createMockComponent(JSONObject propertiesObject, MockContainer parent) {
Map<String, JSONValue> properties = propertiesObject.getProperties();
// Component name and type
String componentType = properties.get("$Type").asString().getString();
// Instantiate a mock component for the visual designer
MockComponent mockComponent;
if (componentType.equals(MockForm.TYPE)) {
Preconditions.checkArgument(parent == null);
// Instantiate new root component
mockComponent = new MockForm(this);
} else {
mockComponent = SimpleComponentDescriptor.createMockComponent(componentType,
COMPONENT_DATABASE.getComponentType(componentType), this);
// Add the component to its parent component (and if it is non-visible, add it to the
// nonVisibleComponent panel).
parent.addComponent(mockComponent);
if (!mockComponent.isVisibleComponent()) {
nonVisibleComponentsPanel.addComponent(mockComponent);
}
}
// Set the name of the component (on instantiation components are assigned a generated name)
String componentName = properties.get("$Name").asString().getString();
mockComponent.changeProperty("Name", componentName);
// Set component properties
for (String name : properties.keySet()) {
if (name.charAt(0) != '$') { // Ignore special properties (name, type and nested components)
mockComponent.changeProperty(name, properties.get(name).asString().getString());
}
}
//This is for old project which doesn't have the AppName property
if (mockComponent instanceof MockForm) {
if (!properties.keySet().contains("AppName")) {
String fileId = getFileId();
String projectName = fileId.split("/")[3];
mockComponent.changeProperty("AppName", projectName);
}
}
// Add component type to the blocks editor
YaProjectEditor yaProjectEditor = (YaProjectEditor) projectEditor;
YaBlocksEditor blockEditor = yaProjectEditor.getBlocksFileEditor(formNode.getFormName());
blockEditor.addComponent(mockComponent.getType(), mockComponent.getName(),
mockComponent.getUuid());
// Add nested components
if (properties.containsKey("$Components")) {
for (JSONValue nestedComponent : properties.get("$Components").asArray().getElements()) {
createMockComponent(nestedComponent.asObject(), (MockContainer) mockComponent);
}
}
return mockComponent;
}
@Override
public void getBlocksImage(Callback<String, String> callback) {
YaProjectEditor yaProjectEditor = (YaProjectEditor) projectEditor;
YaBlocksEditor blockEditor = yaProjectEditor.getBlocksFileEditor(formNode.getFormName());
blockEditor.getBlocksImage(callback);
}
/*
* Updates the the whole designer: form, palette, source structure explorer,
* assets list, and properties panel.
*/
private void loadDesigner() {
form.refresh();
MockComponent selectedComponent = form.getSelectedComponent();
// Set the palette box's content.
PaletteBox paletteBox = PaletteBox.getPaletteBox();
paletteBox.setContent(palettePanel);
// Update the source structure explorer with the tree of this form's components.
sourceStructureExplorer.updateTree(form.buildComponentsTree(),
selectedComponent.getSourceStructureExplorerItem());
SourceStructureBox.getSourceStructureBox().setVisible(true);
// Show the assets box.
AssetListBox assetListBox = AssetListBox.getAssetListBox();
assetListBox.setVisible(true);
// Set the properties box's content.
PropertiesBox propertiesBox = PropertiesBox.getPropertiesBox();
propertiesBox.setContent(designProperties);
updatePropertiesPanel(selectedComponent);
propertiesBox.setVisible(true);
}
/*
* Show the given component's properties in the properties panel.
*/
private void updatePropertiesPanel(MockComponent component) {
if (selectedComponents.size() > 1) {
designProperties.setProperties(selectedProperties);
designProperties.setPropertiesCaption(selectedComponents.size() + " components selected");
} else {
designProperties.setProperties(component.getProperties());
// need to update the caption after the setProperties call, since
// setProperties clears the caption!
designProperties.setPropertiesCaption(component.getName());
}
}
private void onFormStructureChange() {
Ode.getInstance().getEditorManager().scheduleAutoSave(this);
// Update source structure panel
sourceStructureExplorer.updateTree(form.buildComponentsTree(),
form.getSelectedComponent().getSourceStructureExplorerItem());
updatePhone(); // Push changes to the phone if it is connected
}
private void populateComponentsMap(MockComponent component, Map<String, MockComponent> map) {
EditableProperties properties = component.getProperties();
map.put(properties.getPropertyValue("Name"), component);
List<MockComponent> children = component.getChildren();
for (MockComponent child : children) {
populateComponentsMap(child, map);
}
}
/*
* Encodes the form's properties as a JSON encoded string. Used by YaBlocksEditor as well,
* to send the form info to the blockly world during code generation.
*/
protected String encodeFormAsJsonString(boolean forYail) {
StringBuilder sb = new StringBuilder();
sb.append("{");
// Include authURL in output if it is non-null
if (authURL != null) {
sb.append("\"authURL\":").append(authURL.toJson()).append(",");
}
sb.append("\"YaVersion\":\"").append(YaVersion.YOUNG_ANDROID_VERSION).append("\",");
sb.append("\"Source\":\"Form\",");
sb.append("\"Properties\":");
encodeComponentProperties(form, sb, forYail);
sb.append("}");
return sb.toString();
}
// [lyn, 2014/10/13] returns the *pre-upgraded* JSON for this form.
// needed to allow associated blocks editor to get this info.
protected String preUpgradeJsonString() {
return preUpgradeJsonString;
}
/*
* Encodes a component and its properties into a JSON encoded string.
*/
private void encodeComponentProperties(MockComponent component, StringBuilder sb, boolean forYail) {
// The component encoding starts with component name and type
String componentType = component.getType();
EditableProperties properties = component.getProperties();
sb.append("{\"$Name\":\"");
sb.append(properties.getPropertyValue("Name"));
sb.append("\",\"$Type\":\"");
sb.append(componentType);
sb.append("\",\"$Version\":\"");
sb.append(COMPONENT_DATABASE.getComponentVersion(componentType));
sb.append('"');
// Next the actual component properties
// NOTE: It is important that these be encoded before any children components.
String propertiesString = properties.encodeAsPairs(forYail);
if (propertiesString.length() > 0) {
sb.append(',');
sb.append(propertiesString);
}
// Finally any children of the component
List<MockComponent> children = component.getChildren();
if (!children.isEmpty()) {
sb.append(",\"$Components\":[");
String separator = "";
for (MockComponent child : children) {
sb.append(separator);
encodeComponentProperties(child, sb, forYail);
separator = ",";
}
sb.append(']');
}
sb.append('}');
}
/*
* Clears the palette, source structure explorer, and properties panel.
*/
private void unloadDesigner() {
// The form can still potentially change if the blocks editor is displayed
// so don't remove the formChangeListener.
// Clear the palette box.
PaletteBox paletteBox = PaletteBox.getPaletteBox();
paletteBox.clear();
// Clear and hide the source structure explorer.
sourceStructureExplorer.clearTree();
SourceStructureBox.getSourceStructureBox().setVisible(false);
// Hide the assets box.
AssetListBox assetListBox = AssetListBox.getAssetListBox();
assetListBox.setVisible(false);
// Clear and hide the properties box.
PropertiesBox propertiesBox = PropertiesBox.getPropertiesBox();
propertiesBox.clear();
propertiesBox.setVisible(false);
}
/**
* Runs through all the Mock Components and upgrades if its corresponding Component was Upgraded
* @param componentTypes the Component Types that got upgraded
*/
private void updateMockComponents(List<String> componentTypes) {
Map<String, MockComponent> componentMap = getComponents();
for (MockComponent mockComponent : componentMap.values()) {
if (componentTypes.contains(mockComponent.getType())) {
mockComponent.upgrade();
mockComponent.upgradeComplete();
}
}
}
/*
* Push changes to a connected phone (or emulator).
*/
private void updatePhone() {
YaProjectEditor yaProjectEditor = (YaProjectEditor) projectEditor;
YaBlocksEditor blockEditor = yaProjectEditor.getBlocksFileEditor(formNode.getFormName());
blockEditor.sendComponentData();
}
@Override
public void onComponentTypeAdded(List<String> componentTypes) {
COMPONENT_DATABASE.removeComponentDatabaseListener(this);
for (ComponentDatabaseChangeListener cdbChangeListener : componentDatabaseChangeListeners) {
cdbChangeListener.onComponentTypeAdded(componentTypes);
}
//Update Mock Components
updateMockComponents(componentTypes);
//Update the Properties Panel
updatePropertiesPanel(form.getSelectedComponent());
}
@Override
public boolean beforeComponentTypeRemoved(List<String> componentTypes) {
boolean result = true;
for (ComponentDatabaseChangeListener cdbChangeListener : componentDatabaseChangeListeners) {
result = result & cdbChangeListener.beforeComponentTypeRemoved(componentTypes);
}
List<MockComponent> mockComponents = new ArrayList<MockComponent>(getForm().getChildren());
for (String compType : componentTypes) {
for (MockComponent mockComp : mockComponents) {
if (mockComp.getType().equals(compType)) {
mockComp.delete();
}
}
}
return result;
}
@Override
public void onComponentTypeRemoved(Map<String, String> componentTypes) {
COMPONENT_DATABASE.removeComponentDatabaseListener(this);
for (ComponentDatabaseChangeListener cdbChangeListener : componentDatabaseChangeListeners) {
cdbChangeListener.onComponentTypeRemoved(componentTypes);
}
}
@Override
public void onResetDatabase() {
COMPONENT_DATABASE.removeComponentDatabaseListener(this);
for (ComponentDatabaseChangeListener cdbChangeListener : componentDatabaseChangeListeners) {
cdbChangeListener.onResetDatabase();
}
}
}
|
package soot;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import soot.JastAddJ.BytecodeParser;
import soot.JastAddJ.CompilationUnit;
import soot.JastAddJ.JastAddJavaParser;
import soot.JastAddJ.JavaParser;
import soot.JastAddJ.Program;
import soot.javaToJimple.IInitialResolver.Dependencies;
import soot.options.Options;
/** Loads symbols for SootClasses from either class files or jimple files. */
public class SootResolver
{
/** Maps each resolved class to a list of all references in it. */
private final Map<SootClass, ArrayList> classToTypesSignature = new HashMap<SootClass, ArrayList>();
/** Maps each resolved class to a list of all references in it. */
private final Map<SootClass, ArrayList> classToTypesHierarchy = new HashMap<SootClass, ArrayList>();
/** SootClasses waiting to be resolved. */
private final LinkedList/*SootClass*/[] worklist = new LinkedList[4];
protected Program program;
public SootResolver (Singletons.Global g) {
worklist[SootClass.HIERARCHY] = new LinkedList();
worklist[SootClass.SIGNATURES] = new LinkedList();
worklist[SootClass.BODIES] = new LinkedList();
program = new Program();
program.state().reset();
program.initBytecodeReader(new BytecodeParser());
program.initJavaParser(
new JavaParser() {
public CompilationUnit parse(InputStream is, String fileName) throws IOException, beaver.Parser.Exception {
return new JastAddJavaParser().parse(is, fileName);
}
}
);
program.options().initOptions();
program.options().addKeyValueOption("-classpath");
program.options().setValueForOption(Scene.v().getSootClassPath(), "-classpath");
if(Options.v().src_prec() == Options.src_prec_java)
program.setSrcPrec(Program.SRC_PREC_JAVA);
else if(Options.v().src_prec() == Options.src_prec_class)
program.setSrcPrec(Program.SRC_PREC_CLASS);
else if(Options.v().src_prec() == Options.src_prec_only_class)
program.setSrcPrec(Program.SRC_PREC_CLASS);
program.initPaths();
}
public static SootResolver v() { return G.v().soot_SootResolver();}
/** Returns true if we are resolving all class refs recursively. */
private boolean resolveEverything() {
return( Options.v().whole_program() || Options.v().whole_shimple()
|| Options.v().full_resolver()
|| Options.v().output_format() == Options.output_format_dava );
}
/** Returns a (possibly not yet resolved) SootClass to be used in references
* to a class. If/when the class is resolved, it will be resolved into this
* SootClass.
* */
public SootClass makeClassRef(String className)
{
if(Scene.v().containsClass(className))
return Scene.v().getSootClass(className);
SootClass newClass;
newClass = new SootClass(className);
newClass.setResolvingLevel(SootClass.DANGLING);
Scene.v().addClass(newClass);
return newClass;
}
/**
* Resolves the given class. Depending on the resolver settings, may
* decide to resolve other classes as well. If the class has already
* been resolved, just returns the class that was already resolved.
* */
public SootClass resolveClass(String className, int desiredLevel) {
SootClass resolvedClass = null;
try{
resolvedClass = makeClassRef(className);
addToResolveWorklist(resolvedClass, desiredLevel);
processResolveWorklist();
return resolvedClass;
} catch(SootClassNotFoundException e) {
//remove unresolved class and rethrow
if(resolvedClass!=null) {
assert resolvedClass.resolvingLevel()==SootClass.DANGLING;
Scene.v().removeClass(resolvedClass);
}
throw e;
}
}
/** Resolve all classes on toResolveWorklist. */
private void processResolveWorklist() {
for( int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i
while( !worklist[i].isEmpty() ) {
SootClass sc = (SootClass) worklist[i].removeFirst();
if( resolveEverything() ) {
boolean onlySignatures = sc.isPhantom() || (
Options.v().no_bodies_for_excluded() &&
Scene.v().isExcluded(sc) &&
!Scene.v().getBasicClasses().contains(sc.getName())
);
if( onlySignatures ) {
bringToSignatures(sc);
sc.setPhantomClass();
if(sc.isPhantom()) {
for( SootMethod m: sc.getMethods() ) {
m.setPhantom(true);
}
for( SootField f: sc.getFields() ) {
f.setPhantom(true);
}
}
} else bringToBodies(sc);
} else {
switch(i) {
case SootClass.BODIES: bringToBodies(sc); break;
case SootClass.SIGNATURES: bringToSignatures(sc); break;
case SootClass.HIERARCHY: bringToHierarchy(sc); break;
}
}
}
}
}
private void addToResolveWorklist(Type type, int level) {
if( type instanceof RefType )
addToResolveWorklist(((RefType) type).getClassName(), level);
else if( type instanceof ArrayType )
addToResolveWorklist(((ArrayType) type).baseType, level);
}
private void addToResolveWorklist(String className, int level) {
addToResolveWorklist(makeClassRef(className), level);
}
private void addToResolveWorklist(SootClass sc, int desiredLevel) {
if( sc.resolvingLevel() >= desiredLevel ) return;
worklist[desiredLevel].add(sc);
}
/** Hierarchy - we know the hierarchy of the class and that's it
* requires at least Hierarchy for all supertypes and enclosing types.
* */
private void bringToHierarchy(SootClass sc) {
if(sc.resolvingLevel() >= SootClass.HIERARCHY ) return;
if(Options.v().debug_resolver())
G.v().out.println("bringing to HIERARCHY: "+sc);
sc.setResolvingLevel(SootClass.HIERARCHY);
String className = sc.getName();
ClassSource is = SourceLocator.v().getClassSource(className);
boolean modelAsPhantomRef = is == null;
// Options.v().no_jrl() &&
// Scene.v().isExcluded(sc) &&
// !Scene.v().getBasicClasses().contains(sc.getName())
if( modelAsPhantomRef ) {
if(!Scene.v().allowsPhantomRefs()) {
String suffix="";
if(className.equals("java.lang.Object")) {
suffix = " Try adding rt.jar to Soot's classpath, e.g.:\n" +
"java -cp sootclasses.jar soot.Main -cp " +
".:/path/to/jdk/jre/lib/rt.jar <other options>";
} else if(className.equals("javax.crypto.Cipher")) {
suffix = " Try adding jce.jar to Soot's classpath, e.g.:\n" +
"java -cp sootclasses.jar soot.Main -cp " +
".:/path/to/jdk/jre/lib/rt.jar:/path/to/jdk/jre/lib/jce.jar <other options>";
}
throw new SootClassNotFoundException("couldn't find class: " +
className + " (is your soot-class-path set properly?)"+suffix);
} else {
G.v().out.println(
"Warning: " + className + " is a phantom class!");
sc.setPhantomClass();
classToTypesSignature.put( sc, new ArrayList() );
classToTypesHierarchy.put( sc, new ArrayList() );
}
} else {
Dependencies dependencies = is.resolve(sc);
classToTypesSignature.put( sc, new ArrayList(dependencies.typesToSignature) );
classToTypesHierarchy.put( sc, new ArrayList(dependencies.typesToHierarchy) );
}
reResolveHierarchy(sc);
}
public void reResolveHierarchy(SootClass sc) {
// Bring superclasses to hierarchy
if(sc.hasSuperclass())
addToResolveWorklist(sc.getSuperclass(), SootClass.HIERARCHY);
if(sc.hasOuterClass())
addToResolveWorklist(sc.getOuterClass(), SootClass.HIERARCHY);
for( Iterator ifaceIt = sc.getInterfaces().iterator(); ifaceIt.hasNext(); ) {
final SootClass iface = (SootClass) ifaceIt.next();
addToResolveWorklist(iface, SootClass.HIERARCHY);
}
}
/** Signatures - we know the signatures of all methods and fields
* requires at least Hierarchy for all referred to types in these signatures.
* */
private void bringToSignatures(SootClass sc) {
if(sc.resolvingLevel() >= SootClass.SIGNATURES ) return;
bringToHierarchy(sc);
if(Options.v().debug_resolver())
G.v().out.println("bringing to SIGNATURES: "+sc);
sc.setResolvingLevel(SootClass.SIGNATURES);
for( Iterator fIt = sc.getFields().iterator(); fIt.hasNext(); ) {
final SootField f = (SootField) fIt.next();
addToResolveWorklist( f.getType(), SootClass.HIERARCHY );
}
for( Iterator mIt = sc.getMethods().iterator(); mIt.hasNext(); ) {
final SootMethod m = (SootMethod) mIt.next();
addToResolveWorklist( m.getReturnType(), SootClass.HIERARCHY );
for( Iterator ptypeIt = m.getParameterTypes().iterator(); ptypeIt.hasNext(); ) {
final Type ptype = (Type) ptypeIt.next();
addToResolveWorklist( ptype, SootClass.HIERARCHY );
}
for (SootClass exception : m.getExceptions()) {
addToResolveWorklist( exception, SootClass.HIERARCHY );
}
}
// Bring superclasses to signatures
if(sc.hasSuperclass())
addToResolveWorklist(sc.getSuperclass(), SootClass.SIGNATURES);
for( Iterator ifaceIt = sc.getInterfaces().iterator(); ifaceIt.hasNext(); ) {
final SootClass iface = (SootClass) ifaceIt.next();
addToResolveWorklist(iface, SootClass.SIGNATURES);
}
}
/** Bodies - we can now start loading the bodies of methods
* for all referred to methods and fields in the bodies, requires
* signatures for the method receiver and field container, and
* hierarchy for all other classes referenced in method references.
* Current implementation does not distinguish between the receiver
* and other references. Therefore, it is conservative and brings all
* of them to signatures. But this could/should be improved.
* */
private void bringToBodies(SootClass sc) {
if(sc.resolvingLevel() >= SootClass.BODIES ) return;
bringToSignatures(sc);
if(Options.v().debug_resolver())
G.v().out.println("bringing to BODIES: "+sc);
sc.setResolvingLevel(SootClass.BODIES);
{
Collection references = classToTypesHierarchy.get(sc);
if( references == null ) return;
Iterator it = references.iterator();
while( it.hasNext() ) {
final Object o = it.next();
if( o instanceof String ) {
addToResolveWorklist((String) o, SootClass.HIERARCHY);
} else if( o instanceof Type ) {
addToResolveWorklist((Type) o, SootClass.HIERARCHY);
} else throw new RuntimeException(o.toString());
}
}
{
Collection references = classToTypesSignature.get(sc);
if( references == null ) return;
Iterator it = references.iterator();
while( it.hasNext() ) {
final Object o = it.next();
if( o instanceof String ) {
addToResolveWorklist((String) o, SootClass.SIGNATURES);
} else if( o instanceof Type ) {
addToResolveWorklist((Type) o, SootClass.SIGNATURES);
} else throw new RuntimeException(o.toString());
}
}
}
public void reResolve(SootClass cl) {
int resolvingLevel = cl.resolvingLevel();
if( resolvingLevel < SootClass.HIERARCHY ) return;
reResolveHierarchy(cl);
cl.setResolvingLevel(SootClass.HIERARCHY);
addToResolveWorklist(cl, resolvingLevel);
processResolveWorklist();
}
public Program getProgram() {
return program;
}
private class SootClassNotFoundException extends RuntimeException {
private SootClassNotFoundException(String s) {
super(s);
}
}
}
|
package source;
/**
*
* @author ppesq
*/
public interface Constantes {
//URLs Imagenes
public static final String iUrlFondo = "images/background1.png";
public static final String iUrlCerveza = "images/beers.png";
public static final String iUrlBotellas = "images/bottles.png";
public static final String iUrlSilla1 = "images/chair1.png";
public static final String iUrlSilla2 = "images/chair2.png";
public static final String iUrlSilla3 = "images/chair3.png";
public static final String iUrlSilla4 = "images/chair4.png";
public static final String iUrlBarraInfo = "images/infoBar2.png";
public static final String iUrlPausa = "images/pause.png";
public static final String iUrlPlato1 = "images/plate1.png";
public static final String iUrlMesaBillar1 = "images/pooltable1.png";
public static final String iUrlMesa = "images/table1.1.png";
public static final String iUrlBotonAtras = "images/backBoton.png";
public static final String iUrlColorAzul = "images/colorAzul.png";
public static final String iUrlColorGris = "images/colorGris.png";
public static final String iUrlColorRojo = "images/colorRojo.png";
public static final String iUrlColorVerde = "images/colorVerde.png";
public static final String iUrlBotonCredits = "images/creditsBoton.png";
public static final String iUrlBotonPuntajesAltos = "images/highscoreBoton.png";
public static final String iUrlMenuInstrucciones = "images/instruccionesMenu.png";
public static final String iUrlLogo = "images/logo.png";
public static final String iUrlBotonNext = "images/nextBoton.png";
public static final String iUrlBotonPlay = "images/playBoton.png";
public static final String iUrlSelecColor1 = "images/selectColorForPlayer1.png";
public static final String iUrlSelecColor2 = "images/selectColorForPlayer2.png";
public static final String iUrlSelecNombre1 = "images/selectNameForPlayer1.png";
public static final String iUrlSelecNombre2 = "images/selectNameForPlayer2.png";
public static final String iUrlBarraNombre = "images/barraNombre.png";
public static final String iUrlBotonBack = "images/backBoton.png";
public static final String iUrlLogoGrande = "images/sit&conquer_biglogo.png";
public static final String iUrlPantallaPausa = "images/pantallaPausaSinTexto.png";
public static final String iUrlGanaste = "images/ganaste.png";
public static final String iUrlSelectColor1 = "images/selectColorForPlayer1.png";
public static final String iUrlSelectColor2 = "images/selectColorForPlayer2.png";
public static final String iUrlSelectName1 = "images/selectNameForPlayer1.png";
public static final String iUrlSelectName2 = "images/selectNameForPlayer2.png";
public static final String iUrlInstruccionesMenuColor = "images/instruccionesMenuColor.png";
public static final String iUrlInstruccionesMenuNombre = "images/instruccionesMenuNombre.png";
public static final String iUrlInstruccionesMovimiento = "images/instruccionesMovimiento.png";
public static final String iUrlLetreroPausado = "images/letreroPausado.png";
public static final String iUrlBarra = "images/infoBar2.png";
//Colores
public static final int BLUE = 1;
public static final int GRAY = 2;
public static final int RED = 3;
public static final int GREEN = 4;
//Table types int values
public static final int BAR_ROUND = 0;
public static final int BAR_POOL = 1;
//Int values de personaje
public static final int SENTADO = 0;
public static final int PARADO = 1;
public static final int ENMOVIMIENTO = 2;
//Dimensiones Applet
public static final int GAME_WIDTH = 900;
public static final int GAME_HEIGHT = 600;
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyrl.core;
import java.io.File;
import java.math.BigInteger;
import java.util.*;
import wyautl.util.BigRational;
import wyrl.util.*;
import static wyrl.util.SyntaxError.*;
public class TypeInference {
private File file;
private final HashMap<String, Type.Term> terms = new HashMap<String, Type.Term>();
// maps constructor names to their declared types.
private final HashMap<String, Pair<Type, Type>> constructors = new HashMap<String, Pair<Type, Type>>();
// globals contains the list of global variables
private final HashMap<String,Type> macros = new HashMap();
public void infer(SpecFile spec) {
file = spec.file;
// First, we have to inline all the type declarations.
for (SpecFile.Decl d : spec.declarations) {
if (d instanceof SpecFile.IncludeDecl) {
SpecFile.IncludeDecl id = (SpecFile.IncludeDecl) d;
File myFile = file; // save
infer(id.file);
file = myFile; // restore
} else if (d instanceof SpecFile.TermDecl) {
SpecFile.TermDecl td = (SpecFile.TermDecl) d;
terms.put(td.type.name(), td.type);
constructors.put(td.type.name(),
new Pair<Type, Type>(td.type.element(), td.type));
} else if (d instanceof SpecFile.FunctionDecl) {
SpecFile.FunctionDecl td = (SpecFile.FunctionDecl) d;
constructors.put(td.name, new Pair<Type, Type>(td.from, td.to));
} else if (d instanceof SpecFile.TypeDecl) {
SpecFile.TypeDecl td = (SpecFile.TypeDecl) d;
macros.put(td.name, td.type);
}
}
// Second, sanity check all type and function constructors
for (SpecFile.Decl d : spec.declarations) {
if (d instanceof SpecFile.TermDecl) {
SpecFile.TermDecl td = (SpecFile.TermDecl) d;
check(td.type,td);
} else if (d instanceof SpecFile.FunctionDecl) {
SpecFile.FunctionDecl td = (SpecFile.FunctionDecl) d;
check(td.from,td);
check(td.to,td);
}
}
// Third, type check all rewrite declarations
for (SpecFile.Decl d : spec.declarations) {
if (d instanceof SpecFile.RewriteDecl) {
infer((SpecFile.RewriteDecl) d);
}
}
}
public void infer(SpecFile.RewriteDecl rd) {
HashMap<String,Type> environment = new HashMap<String,Type>();
infer(rd.pattern,environment);
for(SpecFile.RuleDecl rule : rd.rules) {
infer(rule,environment);
}
}
public Type.Ref infer(Pattern pattern, HashMap<String,Type> environment) {
Type.Ref type;
if(pattern instanceof Pattern.Leaf) {
Pattern.Leaf p = (Pattern.Leaf) pattern;
type = Type.T_REF(p.type);
} else if(pattern instanceof Pattern.Term) {
Pattern.Term p = (Pattern.Term) pattern;
Type.Term declared = terms.get(p.name);
if(declared == null) {
syntaxError("unknown type encountered", file, p);
} else if(!(declared instanceof Type.Term)) {
// should be dead code?
syntaxError("expected term type", file, p);
}
Type.Ref declared_element = declared.element();
if(declared_element == null && p.data != null) {
syntaxError("term type does not have children", file, p);
}
Type.Ref d = null;
if(p.data != null) {
d = infer(p.data,environment);
} else if(p.data == null && declared.element() != null) {
d = declared.element(); // auto-complete
}
if(p.variable != null) {
environment.put(p.variable, d);
}
type = Type.T_REF(Type.T_TERM(p.name, d));
} else {
Pattern.Collection p = (Pattern.Collection) pattern;
ArrayList<Type> types = new ArrayList<Type>();
Pair<Pattern,String>[] p_elements = p.elements;
for (int i=0;i!=p_elements.length;++i) {
Pair<Pattern,String> ps = p_elements[i];
String var = ps.second();
Pattern pat = ps.first();
Type t = infer(pat,environment);
types.add(t);
if(var != null) {
if(p.unbounded && (i+1) == p_elements.length) {
if(p instanceof Pattern.List) {
t = Type.T_LIST(true,t);
} else if(pattern instanceof Pattern.Bag) {
t = Type.T_BAG(true,t);
} else {
t = Type.T_SET(true,t);
}
}
environment.put(var,t);
}
}
if(p instanceof Pattern.List) {
type = Type.T_REF(Type.T_LIST(p.unbounded, types));
} else if(p instanceof Pattern.Bag) {
type = Type.T_REF(Type.T_BAG(p.unbounded, types));
} else {
type = Type.T_REF(Type.T_SET(p.unbounded, types));
}
}
pattern.attributes().add(new Attribute.Type(type));
return type;
}
public void infer(SpecFile.RuleDecl rd, HashMap<String,Type> environment) {
environment = new HashMap<String,Type>(environment);
ArrayList<Pair<String,Expr>> rd_lets = rd.lets;
for(int i=0;i!=rd_lets.size();++i) {
Pair<String,Expr> let = rd_lets.get(i);
Pair<Expr,Type> p = resolve(let.second(),environment);
rd.lets.set(i, new Pair(let.first(),p.first()));
environment.put(let.first(), p.second());
}
if(rd.condition != null) {
Pair<Expr,Type> p = resolve(rd.condition,environment);
rd.condition = p.first();
checkSubtype(Type.T_BOOL(),p.second(),rd.condition);
}
Pair<Expr,Type> result = resolve(rd.result,environment);
rd.result = result.first();
// TODO: check result is a ref?
}
protected Pair<Expr,Type> resolve(Expr expr, HashMap<String,Type> environment) {
try {
Type result;
if (expr instanceof Expr.Constant) {
result = resolve((Expr.Constant) expr, environment);
} else if (expr instanceof Expr.UnOp) {
result = resolve((Expr.UnOp) expr, environment);
} else if (expr instanceof Expr.BinOp) {
result = resolve((Expr.BinOp) expr, environment);
} else if (expr instanceof Expr.NaryOp) {
result = resolve((Expr.NaryOp) expr, environment);
} else if (expr instanceof Expr.ListUpdate) {
result = resolve((Expr.ListUpdate) expr, environment);
} else if (expr instanceof Expr.ListAccess) {
Pair<Expr,Type> tmp = resolve((Expr.ListAccess) expr, environment);
expr = tmp.first();
result = tmp.second();
} else if (expr instanceof Expr.Substitute) {
result = resolve((Expr.Substitute) expr, environment);
} else if (expr instanceof Expr.Constructor) {
result = resolve((Expr.Constructor) expr, environment);
} else if (expr instanceof Expr.Variable) {
result = resolve((Expr.Variable) expr, environment);
} else if (expr instanceof Expr.Comprehension) {
result = resolve((Expr.Comprehension) expr, environment);
} else if (expr instanceof Expr.Cast) {
result = resolve((Expr.Cast) expr, environment);
} else if (expr instanceof Expr.TermAccess) {
result = resolve((Expr.TermAccess) expr, environment);
} else {
syntaxError("unknown code encountered (" + expr.getClass().getName() + ")", file, expr);
return null;
}
expr.attributes().add(new Attribute.Type(result));
return new Pair(expr,result);
} catch (SyntaxError se) {
throw se;
} catch (Exception ex) {
syntaxError("internal failure", file, expr, ex);
}
return null; // dead code
}
protected Type resolve(Expr.Constant expr, HashMap<String, Type> environment) {
Object v = expr.value;
if (v instanceof Boolean) {
return Type.T_BOOL();
} else if (v instanceof BigInteger) {
return Type.T_INT();
} else if (v instanceof BigRational) {
return Type.T_REAL();
} else if (v instanceof String) {
return Type.T_STRING();
} else if (v instanceof Type) {
Type t = (Type) v;
return Type.T_META(t);
} else {
syntaxError("unknown constant encountered ("
+ v.getClass().getName() + ")", file, expr);
return null; // deadcode
}
}
protected Type resolve(Expr.Constructor expr, HashMap<String,Type> environment) {
Pair<Type,Type> arrowType = constructors.get(expr.name);
if (arrowType == null) {
syntaxError("function not declared", file, expr);
} else if (expr.argument != null && arrowType.first() == null) {
syntaxError("constructor does not take a parameter", file, expr);
} else if (expr.argument != null) {
Pair<Expr, Type> arg_t = resolve(expr.argument, environment);
expr.argument = arg_t.first();
// FIXME: put back when subtyping works properly!
//checkSubtype(term.element(), arg_t.second(), expr.argument);
}
expr.external = !terms.containsKey(expr.name);
return arrowType.second();
}
protected Type resolve(Expr.UnOp uop, HashMap<String,Type> environment) {
if(uop.op == Expr.UOp.NOT) {
// We need to clone in this case to guard against potential
// retypings inside the expression.
environment = (HashMap<String,Type>) environment.clone();
}
Pair<Expr,Type> p = resolve(uop.mhs,environment);
uop.mhs = p.first();
Type t = Type.unbox(p.second());
switch (uop.op) {
case LENGTHOF:
if(!(t instanceof Type.Collection || t instanceof Type.Strung)) {
syntaxError("collection type required",file,uop.mhs);
}
t = Type.T_INT();
break;
case NEG:
if(!(t instanceof Type.Int)) {
checkSubtype(Type.T_REAL(), t, uop);
}
break;
case DENOMINATOR:
case NUMERATOR:
checkSubtype(Type.T_REAL(), t, uop);
t = Type.T_INT();
break;
case NOT:
checkSubtype(Type.T_BOOL(), t, uop);
break;
default:
syntaxError("unknown unary expression encountered", file, uop);
}
return t;
}
protected Type resolve(Expr.BinOp bop, HashMap<String,Type> environment) {
// First, handle special case for OR
Pair<Expr, Type> p1 = null;
Pair<Expr, Type> p2 = null;
switch (bop.op) {
case OR:
// We need to clone the environment because, otherwise, any retyping
// which takes place inside may leak out of the disjunction.
p1 = resolve(bop.lhs, (HashMap<String,Type>) environment.clone());
p2 = resolve(bop.rhs, (HashMap<String,Type>) environment.clone());
break;
default:
p1 = resolve(bop.lhs,environment);
p2 = resolve(bop.rhs,environment);
}
// Second, handle remaining cases
bop.lhs = p1.first();
bop.rhs = p2.first();
Type lhs_t = p1.second();
Type rhs_t = p2.second();
Type result;
// deal with auto-unboxing
switch(bop.op) {
case EQ:
case NEQ:
break;
case IN:
rhs_t = Type.unbox(rhs_t);
break;
default:
lhs_t = Type.unbox(lhs_t);
rhs_t = Type.unbox(rhs_t);
}
// Second, do the thing for each
switch (bop.op) {
case ADD:
case SUB:
case DIV:
case MUL: {
if(lhs_t instanceof Type.Int || rhs_t instanceof Type.Int) {
checkSubtype(Type.T_INT(), lhs_t, bop);
checkSubtype(Type.T_INT(), rhs_t, bop);
result = Type.T_INT();
} else {
checkSubtype(Type.T_REAL(), lhs_t, bop);
checkSubtype(Type.T_REAL(), rhs_t, bop);
result = Type.T_REAL();
}
break;
}
case EQ:
case NEQ: {
result = Type.T_BOOL();
break;
}
case LT:
case LTEQ:
case GT:
case GTEQ: {
if(lhs_t instanceof Type.Int || rhs_t instanceof Type.Int) {
checkSubtype(Type.T_INT(), lhs_t, bop);
checkSubtype(Type.T_INT(), rhs_t, bop);
} else if(lhs_t instanceof Type.Real || rhs_t instanceof Type.Real){
checkSubtype(Type.T_REAL(), lhs_t, bop);
checkSubtype(Type.T_REAL(), rhs_t, bop);
} else if(lhs_t instanceof Type.Strung || rhs_t instanceof Type.Strung) {
checkSubtype(Type.T_STRING(), lhs_t, bop);
checkSubtype(Type.T_STRING(), rhs_t, bop);
} else {
checkSubtype(Type.T_REAL(), lhs_t, bop);
checkSubtype(Type.T_REAL(), rhs_t, bop);
}
result = Type.T_BOOL();
break;
}
case AND:
case OR: {
checkSubtype(Type.T_BOOL(), lhs_t, bop);
checkSubtype(Type.T_BOOL(), rhs_t, bop);
result = Type.T_BOOL();
break;
}
case APPEND: {
if (lhs_t instanceof Type.List && rhs_t instanceof Type.List) {
Type.Collection ls = (Type.Collection) lhs_t;
Type.Collection rs = (Type.Collection) rhs_t;
if(ls.unbounded() || rs.unbounded()) {
// FIXME: we could do better here.
result = Type.T_LIST(true,Type.T_OR(ls.element(),rs.element()));
} else {
result = Type.T_LIST(false,append(ls.elements(),rs.elements()));
}
} else if (lhs_t instanceof Type.Bag && rhs_t instanceof Type.Bag) {
Type.Collection ls = (Type.Collection) lhs_t;
Type.Collection rs = (Type.Collection) rhs_t;
// FIXME: we could do better here.
result = Type.T_BAG(ls.unbounded() || rs.unbounded(),Type.T_OR(ls.element(),rs.element()));
} else if (lhs_t instanceof Type.Set && rhs_t instanceof Type.Set) {
Type.Collection ls = (Type.Collection) lhs_t;
Type.Collection rs = (Type.Collection) rhs_t;
// FIXME: we could do better here.
result = Type.T_SET(ls.unbounded() || rs.unbounded(),Type.T_OR(ls.element(),rs.element()));
} else if (lhs_t instanceof Type.Collection
&& rhs_t instanceof Type.Collection) {
// FIXME: we need better support for non-uniform appending
// (e.g. set ++ bag, bag ++ list, etc).
result = Type.T_OR(lhs_t, rhs_t);
} else if (rhs_t instanceof Type.List) {
lhs_t = Type.box(lhs_t);
Type.List rhs_tc = (Type.List) rhs_t;
// right append
result = Type.T_LIST(rhs_tc.unbounded(),
append(lhs_t, rhs_tc.elements()));
} else if (lhs_t instanceof Type.List){
// left append
Type.List lhs_tc = (Type.List) lhs_t;
rhs_t = Type.box(rhs_t);
if (!lhs_tc.unbounded()) {
result = Type.T_LIST(lhs_tc.unbounded(),
append(lhs_tc.elements(), rhs_t));
} else {
Type[] lhs_elements = lhs_tc.elements();
int length = lhs_elements.length;
Type[] nelements = Arrays.copyOf(lhs_elements, length);
length
nelements[length] = Type.T_OR(rhs_t, nelements[length]);
result = Type.T_LIST(true,nelements);
}
} else if (lhs_t instanceof Type.Collection) {
Type.Collection lhs_tc = (Type.Collection) lhs_t;
rhs_t = Type.box(rhs_t);
Type element = Type.T_OR(append(rhs_t,lhs_tc.elements()));
result = Type.T_COMPOUND(lhs_tc,true,element);
} else if (rhs_t instanceof Type.Collection) {
Type.Collection rhs_tc = (Type.Collection) rhs_t;
lhs_t = Type.box(lhs_t);
Type element = Type.T_OR(append(lhs_t,rhs_tc.elements()));
result = Type.T_COMPOUND(rhs_tc,true,element);
} else {
syntaxError("cannot append non-list types",file,bop);
return null;
}
break;
}
case IS: {
checkSubtype(Type.T_METAANY(), rhs_t, bop);
Type.Meta m = (Type.Meta) rhs_t;
checkSubtype(lhs_t, m.element(), bop);
if(bop.lhs instanceof Expr.Variable) {
// retyping
Expr.Variable v = (Expr.Variable) bop.lhs;
// FIXME: should compute intersection here
environment.put(v.var, m.element());
}
result = Type.T_BOOL();
break;
}
case IN: {
if(!(rhs_t instanceof Type.Collection)) {
syntaxError("collection type required",file,bop.rhs);
}
Type.Collection tc = (Type.Collection) rhs_t;
checkSubtype(tc.element(), lhs_t, bop);
result = Type.T_BOOL();
break;
}
case RANGE: {
checkSubtype(Type.T_INT(), lhs_t, bop);
checkSubtype(Type.T_INT(), rhs_t, bop);
result = Type.T_LIST(true,Type.T_INT());
break;
}
default:
syntaxError("unknown binary expression encountered", file, bop);
return null; // dead-code
}
return result;
}
protected Type resolve(Expr.Comprehension expr, HashMap<String, Type> environment) {
environment = (HashMap) environment.clone();
ArrayList<Pair<Expr.Variable,Expr>> expr_sources = expr.sources;
for(int i=0;i!=expr_sources.size();++i) {
Pair<Expr.Variable,Expr> p = expr_sources.get(i);
Expr.Variable variable = p.first();
Expr source = p.second();
if(environment.containsKey(variable.var)) {
syntaxError("duplicate variable '" + variable + "'",file,variable);
}
Pair<Expr,Type> tmp = resolve(source,environment);
expr_sources.set(i, new Pair(variable,tmp.first()));
Type type = tmp.second();
if(!(type instanceof Type.Collection)) {
syntaxError("collection type required",file,source);
}
Type.Collection sourceType = (Type.Collection) type;
Type elementType = sourceType.element();
variable.attributes().add(new Attribute.Type(elementType));
environment.put(variable.var, elementType);
}
if(expr.condition != null) {
Pair<Expr,Type> p = resolve(expr.condition,environment);
expr.condition = p.first();
checkSubtype(Type.T_BOOL(),p.second(),expr.condition);
}
switch(expr.cop) {
case NONE:
case SOME:
return Type.T_BOOL();
case SETCOMP: {
Pair<Expr,Type> result = resolve(expr.value,environment);
expr.value = result.first();
return Type.T_SET(true,Type.box(result.second()));
}
case BAGCOMP: {
Pair<Expr,Type> result = resolve(expr.value,environment);
expr.value = result.first();
return Type.T_BAG(true,Type.box(result.second()));
}
case LISTCOMP: {
Pair<Expr,Type> result = resolve(expr.value,environment);
expr.value = result.first();
return Type.T_LIST(true,Type.box(result.second()));
}
default:
throw new IllegalArgumentException("unknown comprehension kind");
}
}
protected Pair<Expr,Type> resolve(Expr.ListAccess expr, HashMap<String, Type> environment) {
Pair<Expr,Type> p2 = resolve(expr.index,environment);
expr.index= p2.first();
Type idx_t = p2.second();
// First, a little check for the unusual case that this is, in fact, not
// a list access but a constructor with a single element list valued
// argument.
if(expr.src instanceof Expr.Variable) {
Expr.Variable v = (Expr.Variable) expr.src;
if(!environment.containsKey(v.var) && constructors.containsKey(v.var)) {
// ok, this is a candidate
ArrayList<Expr> arguments = new ArrayList<Expr>();
arguments.add(expr.index);
Expr argument = new Expr.NaryOp(Expr.NOp.LISTGEN, arguments,
expr.attribute(Attribute.Source.class));
resolve(argument,environment); // must succeed ;)
return new Pair<Expr, Type>(new Expr.Constructor(v.var,
argument, expr.attributes()), constructors.get(v.var)
.second());
}
}
Pair<Expr,Type> p1 = resolve(expr.src,environment);
expr.src = p1.first();
Type src_t = Type.unbox(p1.second());
checkSubtype(Type.T_LISTANY(), src_t, expr.src);
checkSubtype(Type.T_INT(), idx_t, expr.index);
Type.List list_t = (Type.List) src_t;
Type[] list_elements = list_t.elements();
if(expr.index instanceof Expr.Constant) {
Expr.Constant idx = (Expr.Constant) expr.index;
BigInteger v = (BigInteger) idx.value; // must succeed
if(v.compareTo(BigInteger.ZERO) < 0) {
syntaxError("negative list access",file,idx);
return null; // dead-code
} else if(!list_t.unbounded() && v.compareTo(BigInteger.valueOf(list_elements.length)) >= 0) {
syntaxError("list access out-of-bounds",file,idx);
return null; // dead-code
} else {
return new Pair<Expr,Type>(expr,list_elements[v.intValue()]);
}
} else {
return new Pair<Expr, Type>(expr, list_t.element());
}
}
protected Type resolve(Expr.ListUpdate expr, HashMap<String, Type> environment) {
Pair<Expr,Type> p1 = resolve(expr.src,environment);
Pair<Expr,Type> p2 = resolve(expr.index,environment);
Pair<Expr,Type> p3 = resolve(expr.value,environment);
expr.src = p1.first();
expr.index = p2.first();
expr.value = p3.first();
Type src_t = p1.second();
Type idx_t = p2.second();
Type value_t = p3.second();
checkSubtype(Type.T_LISTANY(), src_t, expr.src);
checkSubtype(Type.T_INT(), idx_t, expr.index);
Type.List src_lt = (Type.List) src_t;
Type[] src_elements = src_lt.elements();
Type[] new_elements = new Type[src_elements.length];
for(int i=0;i!=src_elements.length;++i) {
new_elements[i] = Type.T_OR(src_elements[i],value_t);
}
return Type.T_LIST(src_lt.unbounded(),new_elements);
}
protected Type resolve(Expr.Substitute expr, HashMap<String, Type> environment) {
Pair<Expr,Type> p1 = resolve(expr.src,environment);
Pair<Expr,Type> p2 = resolve(expr.original,environment);
Pair<Expr,Type> p3 = resolve(expr.replacement,environment);
expr.src = p1.first();
expr.original= p2.first();
expr.replacement= p3.first();
Type src_t = p1.second();
// FIXME: need to generate something better here!!
return src_t;
}
protected Type resolve(Expr.NaryOp expr, HashMap<String, Type> environment) {
ArrayList<Expr> operands = expr.arguments;
Type[] types = new Type[operands.size()];
for (int i = 0; i != types.length; ++i) {
Pair<Expr,Type> p = resolve(operands.get(i),environment);
operands.set(i, p.first());
types[i] = Type.box(p.second());
}
if(expr.op == Expr.NOp.LISTGEN) {
return Type.T_LIST(false, types);
} else if(expr.op == Expr.NOp.BAGGEN) {
return Type.T_BAG(false, types);
} else {
return Type.T_SET(false, types);
}
}
protected Type resolve(Expr.Variable code, HashMap<String, Type> environment) {
Type result = environment.get(code.var);
if (result == null) {
Pair<Type, Type> tmp = constructors.get(code.var);
if (tmp == null) {
syntaxError("unknown variable or constructor encountered",
file, code);
} else if (tmp.first() != null) {
syntaxError("cannot instantiate non-unit term", file, code);
}
return tmp.second();
} else {
return result;
}
}
protected Type resolve(Expr.Cast expr, HashMap<String, Type> environment) {
Pair<Expr,Type> p = resolve(expr.src,environment);
expr.src = p.first();
Type type = p.second();
type = Type.unbox(type);
if(!(type instanceof Type.Int && expr.type instanceof Type.Real)) {
syntaxError("cannot cast from " + type + " to " + expr.type, file, expr);
}
return expr.type;
}
protected Type resolve(Expr.TermAccess expr, HashMap<String, Type> environment) {
Pair<Expr,Type> p = resolve(expr.src,environment);
Expr src = p.first();
Type type = p.second();
expr.src = src;
type = Type.unbox(type);
if(!(type instanceof Type.Term)) {
syntaxError("expecting term type, got type " + type, file, expr);
}
type = ((Type.Term) type).element();
if(type == null) {
return Type.T_VOID();
} else {
return type;
}
}
public Type[] append(Type head, Type[] tail) {
Type[] r = new Type[tail.length+1];
System.arraycopy(tail,0,r,1,tail.length);
r[0] = head;
return r;
}
public Type[] append(Type[] head, Type tail) {
Type[] r = new Type[head.length+1];
System.arraycopy(head,0,r,0,head.length);
r[head.length] = tail;
return r;
}
public Type[] append(Type[] head, Type[] tail) {
Type[] r = new Type[head.length + tail.length];
System.arraycopy(head, 0, r, 0, head.length);
System.arraycopy(tail, 0, r, head.length, tail.length);
return r;
}
/**
* Check that this type is consistent and that all constructors used within
* it are declared.
*
* @param t
* @param constructors
*/
public void check(Type type, SyntacticElement elem) {
if(type instanceof Type.Atom) {
// Do nothing in this case
} else if(type instanceof Type.Unary) {
Type.Unary t = (Type.Unary) type;
check(t.element(),elem);
} else if(type instanceof Type.Term) {
Type.Term t = (Type.Term) type;
if(terms.get(t.name()) == null && macros.get(t.name()) == null) {
syntaxError("unknown term encountered: " + t.name(), file, elem);
}
Type element = t.element();
if(element != null) {
check(t.element(),elem);
}
} else if(type instanceof Type.Nominal) {
Type.Nominal t = (Type.Nominal) type;
if(macros.get(t.name()) == null) {
syntaxError("unknown nominal encountered: " + t.name(), file, elem);
}
// NOTE: we don't check the element of a nominal, since this may be
// recursive and we don't need to here.
} else if(type instanceof Type.Collection) {
Type.Collection t = (Type.Collection) type;
for(Type child : t.elements()) {
check(child,elem);
}
} else if(type instanceof Type.Nary) {
Type.Nary t = (Type.Nary) type;
for(Type child : t.elements()) {
check(child,elem);
}
} else {
syntaxError("invalid type: " + type.getClass().getName(), file, elem);
}
}
/**
* Check whether t1 :> t2; that is, whether t2 is a subtype of t1.
*
* @param t1
* @param t2
* @param elem
*/
public void checkSubtype(Type t1, Type t2, SyntacticElement elem) {
t1 = Type.unbox(t1);
t2 = Type.unbox(t2);
if (t1.isSubtype(t2)) {
return;
}
syntaxError("expecting type " + t1 + ", got type " + t2, file, elem);
}
}
|
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.IMethodAnalysisEngine;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory;
import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private static final boolean DEBUG2 = DEBUG;
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private boolean top;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class ItemBase {
public ItemBase() {};
}
public static class Item extends ItemBase
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final int MATH_ABS = 11;
public static final int MASKED_NON_NEGATIVE = 12;
public static final int NASTY_FLOAT_MATH = 13;
private static final int IS_INITIAL_PARAMETER_FLAG=1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull ClassMember source;
private int flags;
// private boolean isNull = false;
private int registerNumber = -1;
// private boolean isInitialParameter = false;
// private boolean couldBeZero = false;
private Object userValue = null;
private int fieldLoadedFromRegister = -1;
public int getSize() {
if (getSignature().equals("J") || getSignature().equals("D")) return 2;
return 1;
}
public boolean isWide() {
return getSize() == 2;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (getSignature() != null)
r+= getSignature().hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (source != null)
r+= source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.getSignature(), that.getSignature())
&& equals(this.constValue, that.constValue)
&& equals(this.source, that.source)
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.flags == that.flags
&& this.userValue == that.userValue
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(getSignature());
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case MASKED_NON_NEGATIVE:
buf.append(", masked_non_negative");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero()) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (equals(i1.getSignature(),i2.getSignature()))
m.setSignature(i1.getSignature());
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.source,i2.source)) {
m.source = i1.source;
}
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.setSignature(it.getSignature());
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.flags = it.flags;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.setSignature(signature);
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.setSignature(signature);
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public Item(String signature, Object constantValue) {
this.setSignature(signature);
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
}
public Item() {
setSignature("Ljava/lang/Object;");
constValue = null;
setNull(true);
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = getSignature();
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return getSignature().startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return getSignature();
else {
int pos = 0;
int len = getSignature().length();
while (pos < len) {
if (getSignature().charAt(pos) != '[')
break;
pos++;
}
return getSignature().substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == MASKED_NON_NEGATIVE) return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !getSignature().startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known.
* NOTE: if the value is a constant Class object, the constant value returned is the name of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField) return (XField) source;
return null;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the method
* invoked
*/
public @CheckForNull XMethod getReturnValueOf() {
if (source instanceof XMethod) return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
/**
* @param isInitialParameter The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
/**
* @param signature The signature to set.
*/
private void setSignature(String signature) {
if (signature.indexOf(".") >= 0)
throw new IllegalArgumentException("Bad dotted signature of " + signature);
this.signature = signature;
}
}
@Override
public String toString() {
if (isTop())
return "TOP";
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
private boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0) return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
boolean stackUpdated = false;
if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) {
pop();
Item top = new Item("I");
top.setCouldBeZero(true);
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
setReachOnlyByBranch(false);
List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC());
if (DEBUG2) {
System.out.println("XXXXXXX " + isReachOnlyByBranch());
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
System.out.println(" merging stack entry " + jumpStackEntry);
System.out.println(" current stack values " + stack);
}
if (isTop()) {
lvValues = new ArrayList<Item>(jumpEntry);
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
setTop(false);
return;
}
if (isReachOnlyByBranch()) {
setTop(false);
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
}
}
else {
setTop(false);
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (isReachOnlyByBranch() && !stackUpdated) {
stack.clear();
for(CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
setReachOnlyByBranch(false);
setTop(false);
return;
}
}
setTop(true);
}
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
try
{
if (isTop()) {
return;
}
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
{
seenTransferOfControl = true;
pop(2);
int branchTarget = dbc.getBranchTarget();
addJumpValue(branchTarget);
break;
}
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case DUP2_X2:
handleDup2X2();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
setReachOnlyByBranch(true);
setTop(true);
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.setSignature(castTo);
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
break;
case GOTO:
case GOTO_W:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
addJumpValue(dbc.getBranchTarget());
stack.clear();
setTop(true);
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
{
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() instanceof Integer) {
push(new Item("I", ( Integer)(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() instanceof Long) {
push(new Item("J", ( Long)(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case FNEG:
it = pop();
if (it.getConstant() instanceof Float) {
push(new Item("F", ( Float)(-(Float) it.getConstant())));
} else {
push(new Item("F"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() instanceof Double) {
push(new Item("D", ( Double)(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
case FREM:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
it = new Item("I", (char)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.MASKED_NON_NEGATIVE);
push(it);
break;
case I2L:
case D2L:
case F2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", (Float)(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
seenTransferOfControl = true;
setReachOnlyByBranch(false);
push(new Item("")); // push return address on stack
addJumpValue(dbc.getBranchTarget());
pop();
setTop(false);
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
String msg = "Error procssing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName();
AnalysisContext.logError(msg , e);
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
/**
* handle dcmp
*
*/
private void handleDcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
/**
* handle fcmp
*
*/
private void handleFcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (f2 < f)
push(new Item("I", (Integer)(-1)));
else if (f2 > f)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
/**
* handle lcmp
*/
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
/**
* handle swap
*/
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
/**
* handleDup
*/
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
/**
* handle dupX1
*/
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
/**
* handle dup2
*/
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
/**
* handle Dup2x1
*/
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDup2X2() {
String signature;
Item it = pop();
Item it2 = pop();
if (it.isWide()) {
if (it2.isWide()) {
push(it);
push(it2);
push(it);
} else {
Item it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
} else {
Item it3 = pop();
if (it3.isWide()) {
push(it2);
push(it);
push(it3);
push(it2);
push(it);
} else {
Item it4 = pop();
push(it2);
push(it);
push(it4);
push(it3);
push(it2);
push(it);
}
}
}
/**
* Handle DupX2
*/
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null && getStackDepth() > 0) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
if (clsName.equals("java/lang/Math") && methodName.equals("abs")) {
Item i = pop();
i.setSpecialKind(Item.MATH_ABS);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
} else if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG2) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG2) {
if (intoSize == fromSize)
System.out.println("Merging items");
else
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG2) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
static class JumpInfo {
final Map<Integer, List<Item>> jumpEntries;
final Map<Integer, List<Item>> jumpStackEntries;
final BitSet jumpEntryLocations;
JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) {
this.jumpEntries = jumpEntries;
this.jumpStackEntries = jumpStackEntries;
this.jumpEntryLocations = jumpEntryLocations;
}
public String toString() {
return jumpEntries.toString()
+"\n\t" + jumpStackEntries.toString();
}
}
public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> {
public JumpInfoFactory() {
super("Jump info for opcode stack", JumpInfo.class);
}
public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);
AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
Code code = method.getCode();
final OpcodeStack stack = new OpcodeStack();
if (code == null) {
return null;
}
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
stack.sawOpcode(this, seen);
}
};
branchAnalysis.setupVisitorForClass(jclass);
int oldCount = 0;
while (true) {
stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method);
branchAnalysis.doVisitMethod(method);
int newCount = stack.jumpEntries.size();
if (newCount == oldCount) break;
oldCount = newCount;
}
return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations);
}}
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues );
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, deepCopy(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(target, deepCopy(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(target);
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
DismantleBytecode v;
public void learnFrom(JumpInfo info) {
jumpEntries = deepCopy(info.jumpEntries);
jumpStackEntries = deepCopy(info.jumpStackEntries);
jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone();
}
public List<Item> deepCopy(List<Item> list) {
ArrayList<Item> result = new ArrayList<Item>(list.size());
for(Item i : list)
result.add(new Item(i));
return result;
}
public Map<Integer, List<Item>> deepCopy( Map<Integer, List<Item>> jumpData) {
HashMap<Integer, List<Item>> result = new HashMap<Integer, List<Item>>();
for(Map.Entry<Integer, List<Item>> e : jumpData.entrySet()) {
result.put(e.getKey(), deepCopy(e.getValue()));
}
return result;
}
public void initialize() {
setTop(false);
jumpEntries.clear();
jumpStackEntries.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
setReachOnlyByBranch(false);
}
public int resetForMethodEntry(final DismantleBytecode v) {
this.v = v;
initialize();
int result = resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null)
return result;
if (useIterativeAnalysis) {
IAnalysisCache analysisCache = Global.getAnalysisCache();
XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod());
try {
JumpInfo jump = analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor());
if (jump != null) {
learnFrom(jump);
}
} catch (CheckedAnalysisException e) {
AnalysisContext.logError("Error getting jump information", e);
}
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
return resetForMethodEntry0(v.getClassName(), v.getMethod());
}
private int resetForMethodEntry0(@SlashedClassName String className, Method m) {
methodName = m.getName();
if (DEBUG) System.out.println("
String signature = m.getSignature();
stack.clear();
lvValues.clear();
top = false;
setReachOnlyByBranch(false);
seenTransferOfControl = false;
exceptionHandlers.clear();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
AnalysisContext.logError("Can't get stack offset " + stackOffset
+ " from " + stack.toString() +" @ " + v.getPC() + " in "
+ v.getFullyQualifiedMethodName(), new IllegalArgumentException());
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", (Integer)(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", (Float)(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", (Double)(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", (Long)(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND) {
int value = (Integer) lhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
} else if (rhs.getConstant() != null && seen == IAND) {
int value = (Integer) rhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
}
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else if (seen == FREM)
result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else if (seen == DREM)
result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, (Object) null));
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for(Item i : lvValues) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
for(Item i : stack) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
}
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
/**
* @param top The top to set.
*/
private void setTop(boolean top) {
if (top) {
if (!this.top)
this.top = true;
} else if (this.top)
this.top = false;
}
/**
* @return Returns the top.
*/
private boolean isTop() {
if (top)
return true;
return false;
}
/**
* @param reachOnlyByBranch The reachOnlyByBranch to set.
*/
void setReachOnlyByBranch(boolean reachOnlyByBranch) {
if (reachOnlyByBranch)
setTop(true);
this.reachOnlyByBranch = reachOnlyByBranch;
}
/**
* @return Returns the reachOnlyByBranch.
*/
boolean isReachOnlyByBranch() {
return reachOnlyByBranch;
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class Item
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final int MATH_ABS = 11;
public static final int MASKED_NON_NEGATIVE = 12;
public static final int NASTY_FLOAT_MATH = 13;
private static final int IS_INITIAL_PARAMETER_FLAG=1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull ClassMember source;
private int flags;
// private boolean isNull = false;
private int registerNumber = -1;
// private boolean isInitialParameter = false;
// private boolean couldBeZero = false;
private Object userValue = null;
private int fieldLoadedFromRegister = -1;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (source != null)
r+= source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.source, that.source)
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.flags == that.flags
&& this.userValue == that.userValue
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case MASKED_NON_NEGATIVE:
buf.append(", masked_non_negative");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero()) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.source,i2.source)) {
m.source = i1.source;
}
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.flags = it.flags;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
setNull(true);
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == MASKED_NON_NEGATIVE) return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known.
* NOTE: if the value is a constant Class object, the constant value returned is the name of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField) return (XField) source;
return null;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the method
* invoked
*/
public @CheckForNull XMethod getReturnValueOf() {
if (source instanceof XMethod) return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
/**
* @param isInitialParameter The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
}
@Override
public String toString() {
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0) return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
boolean stackUpdated = false;
if (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3) {
pop();
Item top = new Item("I");
top.setCouldBeZero(true);
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
if (DEBUG) {
System.out.println("XXXXXXX " + reachOnlyByBranch);
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
}
List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC());
if (reachOnlyByBranch) {
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
}
}
else {
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (reachOnlyByBranch && !stackUpdated) {
stack.clear();
boolean foundException = false;
for(CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
foundException = true;
}
}
if (!foundException)
push(new Item("Ljava/lang/Throwable;"));
}
reachOnlyByBranch = false;
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
try
{
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
addJumpValue(dbc.getBranchTarget());
break;
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
reachOnlyByBranch = true;
addJumpValue(dbc.getBranchTarget());
stack.clear();
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
{
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", ( Integer)(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", ( Long)(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", ( Double)(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
it = new Item("I", (char)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.MASKED_NON_NEGATIVE);
push(it);
break;
case I2L:
case D2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", (Float)(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
// TODO: log this
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item());
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
/**
* @param opcode TODO
*
*/
private void handleDcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
/**
* @param opcode TODO
*
*/
private void handleFcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (f2 < f)
push(new Item("I", (Integer)(-1)));
else if (f2 > f)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
if (clsName.equals("java/lang/Math") && methodName.equals("abs")) {
Item i = pop();
i.setSpecialKind(Item.MATH_ABS);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
} else if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG) {
System.out.println("Merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues );
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(target, new ArrayList<Item>(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(target);
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
public int resetForMethodEntry(final DismantleBytecode v) {
methodName = v.getMethodName();
jumpEntries.clear();
jumpStackEntries.clear();
jumpEntryLocations.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
reachOnlyByBranch = false;
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (!jumpEntries.isEmpty())
branchAnalysis.doVisitMethod(v.getMethod());
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
lvValues.clear();
reachOnlyByBranch = false;
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
assert false : "Can't get stack offset " + stackOffset + " from " + stack.toString();
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", (Integer)(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", (Float)(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", (Double)(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", (Long)(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND) {
int value = (Integer) lhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
} else if (rhs.getConstant() != null && seen == IAND) {
int value = (Integer) rhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
}
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, (Object) null));
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for(Item i : lvValues) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
for(Item i : stack) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
}
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
}
// vim:ts=4
|
package eu.lestard.fluxfx;
import javafx.application.Platform;
import org.reactfx.EventSource;
import org.reactfx.EventStream;
/**
* The central dispatcher that manages incoming {@link Action}s and provides them as EventStream so that
* {@link Store}s can subscribe them.
*
* Views don't need to care about the dispatcher because there is a {@link View#publishAction(Action)} method in the {@link View}
* interface that should be used to publish actions.
*
* Only external systems (f.e. backend services) that like to publish actions have to use this dispatcher class.
*
*/
public class Dispatcher {
private static final Dispatcher SINGLETON = new Dispatcher();
private final EventSource<Action> actionStream = new EventSource<>();
private Dispatcher() {
}
/**
* @return a singleton instance of the Dispatcher.
*/
public static Dispatcher getInstance() {
return SINGLETON;
}
/**
* Dispatch the given action. Dispatching is always done on the JavaFX application
* thread, even if this method is called from another thread.
*
* @param action the action that will be dispatched to the stores.
*/
public void dispatch(Action action) {
if(Platform.isFxApplicationThread()) {
actionStream.push(action);
} else {
Platform.runLater(() -> actionStream.push(action));
}
}
/**
* @return an event-stream of all published actions.
*/
public EventStream<Action> getActionStream(){
return actionStream;
}
/**
* A filtered event-stream of actions of the given type.
*
* @param actionType the class type of the action.
* @param <T> the generic type of the action.
* @return an event-stream of all actions of the given type.
*/
@SuppressWarnings("unchecked")
<T extends Action> EventStream<T> getActionStream(Class<T> actionType) {
return Dispatcher.getInstance()
.getActionStream()
.filter(action -> action.getClass().equals(actionType))
.map(action -> (T) action);
}
}
|
package org.flymine.task;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
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.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.util.DynamicUtil;
import org.intermine.util.StringUtil;
import org.flymine.model.genomic.Location;
import org.flymine.model.genomic.Protein;
import org.flymine.model.genomic.ProteinFeature;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
/**
* An example Task that creates ProteinFeature objects using data from a flat file.
* @author Kim Rutherford
*/
public class SimpleLoadTask extends Task
{
private String oswAlias;
private List fileSets = new ArrayList();
private ObjectStoreWriter osw;
/**
* The ObjectStoreWriter alias to use when querying and creating objects.
* @param oswAlias the ObjectStoreWriter alias
*/
public void setOswAlias(String oswAlias) {
this.oswAlias = oswAlias;
}
/**
* Return the oswAlias set by setOswAlias()
* @return the object store alias
*/
public String getOswAlias() {
return oswAlias;
}
/**
* Return the set of files that should be read from.
* @return the List of FileSets
*/
public List getFileSets() {
return fileSets;
}
/**
* Return the ObjectStoreWriter given by oswAlias.
* @return the ObjectStoreWriter
* @throws BuildException if there is an error while processing
*/
protected ObjectStoreWriter getObjectStoreWriter() throws BuildException {
if (oswAlias == null) {
throw new BuildException("oswAlias attribute is not set");
}
if (osw == null) {
try {
osw = ObjectStoreWriterFactory.getObjectStoreWriter(oswAlias);
} catch (ObjectStoreException e) {
throw new BuildException("cannot get ObjectStoreWriter for: " + oswAlias, e);
}
}
return osw;
}
/**
* Add a FileSet to read from
* @param fileSet the FileSet
*/
public void addFileSet(FileSet fileSet) {
fileSets.add(fileSet);
}
/**
* Load data into the ObjectStoire given by oswAlias.
* @throws BuildException if an ObjectStore method fails
*/
public void execute() throws BuildException {
if (getOswAlias() == null) {
throw new BuildException("oswAlias not set");
}
try {
getObjectStoreWriter().beginTransaction();
} catch (ObjectStoreException e) {
throw new BuildException("cannot begin a transaction", e);
}
Iterator fileSetIter = getFileSets().iterator();
while (fileSetIter.hasNext()) {
FileSet fileSet = (FileSet) fileSetIter.next();
DirectoryScanner ds = fileSet.getDirectoryScanner(getProject());
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
File file = new File(ds.getBasedir(), files[i]);
processFile(file);
}
}
try {
getObjectStoreWriter().commitTransaction();
} catch (ObjectStoreException e) {
throw new BuildException("cannot begin a transaction", e);
}
}
private void processFile(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().length() == 0) {
continue;
}
String bits[] = StringUtil.split(line, " ");
String proteinName = bits[0];
Set proteins = getProteinsForName(proteinName);
String proteinStart = bits[1];
String proteinEnd = bits[2];
String proteinFeatureIdentifier = bits[3];
String proteinFeatureName = bits[4];
ProteinFeature proteinFeature =
(ProteinFeature) DynamicUtil.createObject(Collections.singleton(ProteinFeature.class));
proteinFeature.setIdentifier(proteinFeatureIdentifier);
proteinFeature.setName(proteinFeatureName);
proteinFeature.setProteins(proteins);
Iterator proteinIter = proteins.iterator();
while (proteinIter.hasNext()) {
Protein thisProtein = (Protein) proteinIter.next();
thisProtein.addProteinFeatures(proteinFeature);
osw.store(thisProtein);
Location featureLocation =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
try {
featureLocation.setStart(new Integer(Integer.parseInt(proteinStart)));
} catch (NumberFormatException e) {
throw new RuntimeException("failed to parse start position: " + proteinStart, e);
}
try {
featureLocation.setEnd(new Integer(Integer.parseInt(proteinEnd)));
} catch (NumberFormatException e) {
throw new RuntimeException("failed to parse end position: " + proteinEnd, e);
}
featureLocation.setSubject(proteinFeature);
featureLocation.setObject(thisProtein);
osw.store(featureLocation);
}
osw.store(proteinFeature);
}
} catch (FileNotFoundException e) {
throw new BuildException("problem reading file - file not found: " + file, e);
} catch (IOException e) {
throw new BuildException("problem reading file - I/O exception for:" + file, e);
} catch (ObjectStoreException e) {
throw new BuildException("problem storing object", e);
}
}
private Set getProteinsForName(String proteinIdentifier) {
Query q = new Query();
QueryClass qc = new QueryClass(Protein.class);
q.addFrom(qc);
q.addToSelect(qc);
QueryValue qv = new QueryValue(proteinIdentifier);
QueryField qf = new QueryField(qc, "identifier");
SimpleConstraint sc = new SimpleConstraint(qf, ConstraintOp.EQUALS, qv);
q.setConstraint(sc);
Set returnList = new HashSet();
try {
Results res = osw.getObjectStore().execute(q);
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
returnList.add(rr.get(0));
}
} catch (ObjectStoreException e) {
throw new BuildException("cannot query Protein objects from database", e);
}
return returnList;
}
}
|
package play.cache;
/**
* Provides an access point for Play's cache service.
*/
public class Cache {
/**
* Retrieves an object by key.
*
* @return object
*/
public static Object get(String key) {
return play.libs.Scala.orNull(play.api.cache.Cache.get(key,play.api.Play.unsafeApplication()));
}
/**
* Sets a value with expiration.
*
* @param expiration expiration in seconds
*/
public static void set(String key, Object value, int expiration) {
play.api.cache.Cache.set(key,value,expiration, play.api.Play.unsafeApplication());
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyjc;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import wybs.io.BinaryOutputStream;
import wybs.lang.Attribute;
import wybs.lang.Builder;
import wybs.lang.Logger;
import wybs.lang.NameID;
import wybs.lang.NameSpace;
import wybs.lang.Path;
import wybs.lang.SyntaxError;
import wybs.util.Pair;
import static wybs.lang.SyntaxError.*;
import wyautl.util.BigRational;
import wyil.lang.*;
import wyil.lang.Constant;
import wyjc.util.WyjcBuildTask;
import static wyil.lang.Block.*;
import jasm.attributes.Code.Handler;
import jasm.attributes.LineNumberTable;
import jasm.attributes.SourceFile;
import jasm.lang.*;
import jasm.lang.Modifier;
//import jasm.lang.Constant;
import jasm.verifier.*;
import wyrl.io.JavaIdentifierOutputStream;
import static jasm.lang.JvmTypes.*;
/**
* Responsible for converting WYIL files into Java Classfiles. This is a
* relatively straightforward process, given the all the hard work has already
* been done by the Whiley-2-Wyil builder.
*
* @author David J. Pearce
*
*/
public class Wyil2JavaBuilder implements Builder {
private static int CLASS_VERSION = 49;
private Logger logger = Logger.NULL;
protected String filename;
protected JvmType.Clazz owner;
public void setLogger(Logger logger) {
this.logger = logger;
}
public NameSpace namespace() {
return null; // TODO: this seems like a mistake in Builder ?
}
public void build(List<Pair<Path.Entry<?>,Path.Entry<?>>> delta) throws IOException {
Runtime runtime = Runtime.getRuntime();
long start = System.currentTimeMillis();
long memory = runtime.freeMemory();
// Translate files
for(Pair<Path.Entry<?>,Path.Entry<?>> p : delta) {
Path.Entry<?> f = p.second();
if(f.contentType() == WyjcBuildTask.ContentType) {
Path.Entry<WyilFile> sf = (Path.Entry<WyilFile>) p.first();
Path.Entry<ClassFile> df = (Path.Entry<ClassFile>) f;
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas = new ArrayList<Pair<NameID, Type.FunctionOrMethod>>();
// Translate WyilFile into JVM ClassFile
ClassFile contents = build(sf.read(), lambdas);
// validate generated bytecode
new Validation().apply(contents);
// FIXME: deadCode elimination is currently unsafe because the
// LineNumberTable and Exceptions attributes do not deal with rewrites
// properly.
// eliminate any dead code that was introduced.
// new DeadCodeElimination().apply(file);
// Compute the StackMapTable
//new TypeAnalysis().apply(file);
// finally, write the file into its destination
df.write(contents);
// TODO: handle lambdas!
}
}
// Done
long endTime = System.currentTimeMillis();
logger.logTimedMessage("Wyil => Java: compiled " + delta.size() + " file(s)",
endTime - start, memory - runtime.freeMemory());
}
private ClassFile build(WyilFile module,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas) {
owner = new JvmType.Clazz(module.id().parent().toString().replace('.','/'),
module.id().last());
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_FINAL);
ClassFile cf = new ClassFile(49, owner, JAVA_LANG_OBJECT,
new ArrayList<JvmType.Clazz>(), modifiers);
this.filename = module.filename();
if(filename != null) {
cf.attributes().add(new SourceFile(filename));
}
boolean addMainLauncher = false;
HashMap<JvmConstant,Integer> constants = new HashMap<JvmConstant,Integer>();
for(WyilFile.FunctionOrMethodDeclaration method : module.methods()) {
if(method.name().equals("main")) {
addMainLauncher = true;
}
cf.methods().addAll(build(method, constants, lambdas));
}
buildConstants(constants,cf);
if(addMainLauncher) {
cf.methods().add(buildMainLauncher(owner));
}
return cf;
}
private void buildConstants(HashMap<JvmConstant,Integer> constants, ClassFile cf) {
buildCoercions(constants,cf);
buildValues(constants,cf);
}
private void buildCoercions(HashMap<JvmConstant,Integer> constants, ClassFile cf) {
HashSet<JvmConstant> done = new HashSet<JvmConstant>();
HashMap<JvmConstant,Integer> original = constants;
// this could be a little more efficient I think!!
while(done.size() != constants.size()) {
// We have to clone the constants map, since it may be expanded as a
// result of buildCoercion(). This will occur if the coercion
// constructed requires a helper coercion that was not in the
// original constants map.
HashMap<JvmConstant,Integer> nconstants = new HashMap<JvmConstant,Integer>(constants);
for(Map.Entry<JvmConstant,Integer> entry : constants.entrySet()) {
JvmConstant e = entry.getKey();
if(!done.contains(e) && e instanceof JvmCoercion) {
JvmCoercion c = (JvmCoercion) e;
buildCoercion(c.from,c.to,entry.getValue(),nconstants,cf);
}
done.add(e);
}
constants = nconstants;
}
original.putAll(constants);
}
private void buildValues(HashMap<JvmConstant,Integer> constants, ClassFile cf) {
int nvalues = 0;
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
for(Map.Entry<JvmConstant,Integer> entry : constants.entrySet()) {
JvmConstant c = entry.getKey();
if(c instanceof JvmValue) {
nvalues++;
Constant constant = ((JvmValue)c).value;
int index = entry.getValue();
// First, create the static final field that will hold this constant
String name = "constant$" + index;
ArrayList<Modifier> fmods = new ArrayList<Modifier>();
fmods.add(Modifier.ACC_PRIVATE);
fmods.add(Modifier.ACC_STATIC);
fmods.add(Modifier.ACC_FINAL);
JvmType type = convertType(constant.type());
ClassFile.Field field = new ClassFile.Field(name, type, fmods);
cf.fields().add(field);
// Now, create code to intialise this field
translate(constant,0,bytecodes);
bytecodes.add(new Bytecode.PutField(owner, name, type, Bytecode.FieldMode.STATIC));
}
}
if(nvalues > 0) {
// create static initialiser method, but only if we really need to.
bytecodes.add(new Bytecode.Return(null));
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ftype = new JvmType.Function(new JvmType.Void());
ClassFile.Method clinit = new ClassFile.Method("<clinit>", ftype, modifiers);
cf.methods().add(clinit);
// finally add code for staticinitialiser method
jasm.attributes.Code code = new jasm.attributes.Code(bytecodes,new ArrayList(),clinit);
clinit.attributes().add(code);
}
}
private ClassFile.Method buildMainLauncher(JvmType.Clazz owner) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PUBLIC);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ft1 = new JvmType.Function(T_VOID, new JvmType.Array(
JAVA_LANG_STRING));
ClassFile.Method cm = new ClassFile.Method("main", ft1, modifiers);
JvmType.Array strArr = new JvmType.Array(JAVA_LANG_STRING);
ArrayList<Bytecode> codes = new ArrayList<Bytecode>();
ft1 = new JvmType.Function(WHILEYRECORD, new JvmType.Array(
JAVA_LANG_STRING));
codes.add(new Bytecode.Load(0, strArr));
codes.add(new Bytecode.Invoke(WHILEYUTIL, "systemConsole", ft1,
Bytecode.InvokeMode.STATIC));
Type.Method wyft = Type.Method(Type.T_VOID, Type.T_VOID,
WHILEY_SYSTEM_T);
JvmType.Function ft3 = convertFunType(wyft);
codes.add(new Bytecode.Invoke(owner, nameMangle("main", wyft), ft3,
Bytecode.InvokeMode.STATIC));
codes.add(new Bytecode.Return(null));
jasm.attributes.Code code = new jasm.attributes.Code(codes,
new ArrayList(), cm);
cm.attributes().add(code);
return cm;
}
private List<ClassFile.Method> build(
WyilFile.FunctionOrMethodDeclaration method,
HashMap<JvmConstant, Integer> constants,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas) {
ArrayList<ClassFile.Method> methods = new ArrayList<ClassFile.Method>();
int num = 1;
for (WyilFile.Case c : method.cases()) {
if (method.isNative()) {
methods.add(buildNativeOrExport(c, method, constants));
} else {
if (method.isExport()) {
methods.add(buildNativeOrExport(c, method, constants));
}
methods.add(build(num++, c, method, constants, lambdas));
}
}
return methods;
}
private ClassFile.Method build(int caseNum, WyilFile.Case mcase,
WyilFile.FunctionOrMethodDeclaration method,
HashMap<JvmConstant, Integer> constants,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
if(method.isPublic()) {
modifiers.add(Modifier.ACC_PUBLIC);
}
modifiers.add(Modifier.ACC_STATIC);
JvmType.Function ft = convertFunType(method.type());
String name = nameMangle(method.name(),method.type());
/* need to put this back somehow?
if(method.cases().size() > 1) {
name = name + "$" + caseNum;
}
*/
ClassFile.Method cm = new ClassFile.Method(name,ft,modifiers);
for(Attribute a : mcase.attributes()) {
if(a instanceof BytecodeAttribute) {
// FIXME: this is a hack
cm.attributes().add((BytecodeAttribute)a);
}
}
ArrayList<Handler> handlers = new ArrayList<Handler>();
ArrayList<LineNumberTable.Entry> lineNumbers = new ArrayList<LineNumberTable.Entry>();
ArrayList<Bytecode> codes;
codes = translate(mcase,constants,lambdas,handlers,lineNumbers);
jasm.attributes.Code code = new jasm.attributes.Code(codes,handlers,cm);
if(!lineNumbers.isEmpty()) {
code.attributes().add(new LineNumberTable(lineNumbers));
}
cm.attributes().add(code);
return cm;
}
private ClassFile.Method buildNativeOrExport(WyilFile.Case mcase,
WyilFile.FunctionOrMethodDeclaration method, HashMap<JvmConstant,Integer> constants) {
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
if(method.isPublic() || method.isProtected()) {
modifiers.add(Modifier.ACC_PUBLIC);
}
modifiers.add(Modifier.ACC_STATIC);
JvmType.Function ft = convertFunType(method.type());
String name = method.name();
if(method.isNative()) {
name = nameMangle(method.name(),method.type());
}
ClassFile.Method cm = new ClassFile.Method(name,ft,modifiers);
for(Attribute a : mcase.attributes()) {
if(a instanceof BytecodeAttribute) {
// FIXME: this is a hack
cm.attributes().add((BytecodeAttribute)a);
}
}
ArrayList<Handler> handlers = new ArrayList<Handler>();
ArrayList<Bytecode> codes;
codes = translateNativeOrExport(method);
jasm.attributes.Code code = new jasm.attributes.Code(codes,handlers,cm);
cm.attributes().add(code);
return cm;
}
private ArrayList<Bytecode> translateNativeOrExport(WyilFile.FunctionOrMethodDeclaration method) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
Type.FunctionOrMethod ft = method.type();
int slot = 0;
for (Type param : ft.params()) {
bytecodes.add(new Bytecode.Load(slot++, convertType(param)));
}
if (method.isNative()) {
JvmType.Clazz redirect = new JvmType.Clazz(owner.pkg(), owner
.components().get(0).first(), "native");
bytecodes.add(new Bytecode.Invoke(redirect, method.name(),
convertFunType(ft), Bytecode.InvokeMode.STATIC));
} else {
JvmType.Clazz redirect = new JvmType.Clazz(owner.pkg(), owner
.components().get(0).first());
bytecodes.add(new Bytecode.Invoke(redirect, nameMangle(
method.name(), method.type()), convertFunType(ft),
Bytecode.InvokeMode.STATIC));
}
if (ft.ret() == Type.T_VOID) {
bytecodes.add(new Bytecode.Return(null));
} else {
bytecodes.add(new Bytecode.Return(convertType(ft.ret())));
}
return bytecodes;
}
private ArrayList<Bytecode> translate(WyilFile.Case mcase,
HashMap<JvmConstant, Integer> constants,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas,
ArrayList<Handler> handlers,
ArrayList<LineNumberTable.Entry> lineNumbers) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
translate(mcase.body(), mcase.body().numSlots(), constants, lambdas, handlers,
lineNumbers, bytecodes);
return bytecodes;
}
private void translate(Block blk, int freeSlot,
HashMap<JvmConstant, Integer> constants,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas,
ArrayList<Handler> handlers,
ArrayList<LineNumberTable.Entry> lineNumbers,
ArrayList<Bytecode> bytecodes) {
ArrayList<UnresolvedHandler> unresolvedHandlers = new ArrayList<UnresolvedHandler>();
for (Entry s : blk) {
Attribute.Source loc = s.attribute(Attribute.Source.class);
if(loc != null) {
lineNumbers.add(new LineNumberTable.Entry(bytecodes.size(),loc.line));
}
freeSlot = translate(s, freeSlot, constants, lambdas,
unresolvedHandlers, bytecodes);
}
if (unresolvedHandlers.size() > 0) {
HashMap<String, Integer> labels = new HashMap<String, Integer>();
for (int i = 0; i != bytecodes.size(); ++i) {
Bytecode b = bytecodes.get(i);
if (b instanceof Bytecode.Label) {
Bytecode.Label lab = (Bytecode.Label) b;
labels.put(lab.name, i);
}
}
for (UnresolvedHandler ur : unresolvedHandlers) {
int start = labels.get(ur.start);
int end = labels.get(ur.end);
Handler handler = new Handler(start, end, ur.target,
ur.exception);
handlers.add(handler);
}
}
// here, we need to resolve the handlers.
}
private int translate(Entry entry, int freeSlot,
HashMap<JvmConstant, Integer> constants,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas,
ArrayList<UnresolvedHandler> handlers,
ArrayList<Bytecode> bytecodes) {
try {
Code code = entry.code;
if(code instanceof Code.BinArithOp) {
translate((Code.BinArithOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.Convert) {
translate((Code.Convert)code,freeSlot,constants,bytecodes);
} else if(code instanceof Code.Const) {
translate((Code.Const) code, freeSlot, constants, bytecodes);
} else if(code instanceof Code.Debug) {
translate((Code.Debug)code,freeSlot,bytecodes);
} else if(code instanceof Code.LoopEnd) {
translate((Code.LoopEnd)code,freeSlot,bytecodes);
} else if(code instanceof Code.AssertOrAssume) {
translate((Code.AssertOrAssume)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.FieldLoad) {
translate((Code.FieldLoad)code,freeSlot,bytecodes);
} else if(code instanceof Code.ForAll) {
freeSlot = translate((Code.ForAll)code,freeSlot,bytecodes);
} else if(code instanceof Code.Goto) {
translate((Code.Goto)code,freeSlot,bytecodes);
} else if(code instanceof Code.If) {
translateIfGoto((Code.If) code, entry, freeSlot, bytecodes);
} else if(code instanceof Code.IfIs) {
translate((Code.IfIs) code, entry, freeSlot, constants, bytecodes);
} else if(code instanceof Code.IndirectInvoke) {
translate((Code.IndirectInvoke)code,freeSlot,bytecodes);
} else if(code instanceof Code.Invoke) {
translate((Code.Invoke)code,freeSlot,bytecodes);
} else if(code instanceof Code.Invert) {
translate((Code.Invert)code,freeSlot,bytecodes);
} else if(code instanceof Code.Label) {
translate((Code.Label)code,freeSlot,bytecodes);
} else if(code instanceof Code.BinListOp) {
translate((Code.BinListOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.Lambda) {
translate((Code.Lambda)code,freeSlot,lambdas,bytecodes);
} else if(code instanceof Code.LengthOf) {
translate((Code.LengthOf)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.SubList) {
translate((Code.SubList)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.IndexOf) {
translate((Code.IndexOf)code,freeSlot,bytecodes);
} else if(code instanceof Code.Assign) {
translate((Code.Assign)code,freeSlot,bytecodes);
} else if(code instanceof Code.Loop) {
translate((Code.Loop)code,freeSlot,bytecodes);
} else if(code instanceof Code.Move) {
translate((Code.Move)code,freeSlot,bytecodes);
} else if(code instanceof Code.Update) {
translate((Code.Update)code,freeSlot,bytecodes);
} else if(code instanceof Code.NewMap) {
translate((Code.NewMap)code,freeSlot,bytecodes);
} else if(code instanceof Code.NewList) {
translate((Code.NewList)code,freeSlot,bytecodes);
} else if(code instanceof Code.NewRecord) {
translate((Code.NewRecord)code,freeSlot,bytecodes);
} else if(code instanceof Code.NewSet) {
translate((Code.NewSet)code,freeSlot,bytecodes);
} else if(code instanceof Code.NewTuple) {
translate((Code.NewTuple)code,freeSlot,bytecodes);
} else if(code instanceof Code.UnArithOp) {
translate((Code.UnArithOp)code,freeSlot,bytecodes);
} else if(code instanceof Code.Dereference) {
translate((Code.Dereference)code,freeSlot,bytecodes);
} else if(code instanceof Code.Return) {
translate((Code.Return)code,freeSlot,bytecodes);
} else if(code instanceof Code.Nop) {
// do nothing
} else if(code instanceof Code.BinSetOp) {
translate((Code.BinSetOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.BinStringOp) {
translate((Code.BinStringOp)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.SubString) {
translate((Code.SubString)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.Switch) {
translate((Code.Switch)code,entry,freeSlot,bytecodes);
} else if(code instanceof Code.TryCatch) {
translate((Code.TryCatch)code,entry,freeSlot,handlers,constants,bytecodes);
} else if(code instanceof Code.NewObject) {
translate((Code.NewObject)code,freeSlot,bytecodes);
} else if(code instanceof Code.Throw) {
translate((Code.Throw)code,freeSlot,bytecodes);
} else if(code instanceof Code.TupleLoad) {
translate((Code.TupleLoad)code,freeSlot,bytecodes);
} else {
internalFailure("unknown wyil code encountered (" + code + ")", filename, entry);
}
} catch (SyntaxError ex) {
throw ex;
} catch (Exception ex) {
internalFailure(ex.getMessage(), filename, entry, ex);
}
return freeSlot;
}
private void translate(Code.Const c, int freeSlot,
HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
Constant constant = c.constant;
JvmType jt = convertType(constant.type());
if (constant instanceof Constant.Decimal || constant instanceof Constant.Bool
|| constant instanceof Constant.Null || constant instanceof Constant.Byte) {
translate(constant,freeSlot,bytecodes);
} else {
int id = JvmValue.get(constant,constants);
String name = "constant$" + id;
bytecodes.add(new Bytecode.GetField(owner, name, jt, Bytecode.FieldMode.STATIC));
// the following is necessary to prevent in-place updates of our
// constants!
addIncRefs(constant.type(),bytecodes);
}
bytecodes.add(new Bytecode.Store(c.target, jt));
}
private void translate(Code.Convert c, int freeSlot,
HashMap<JvmConstant, Integer> constants, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type)));
addCoercion(c.type, c.result, freeSlot, constants, bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.result)));
}
private void translate(Code.Update code, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(code.target, convertType(code.type)));
translateUpdate(code.iterator(), code, bytecodes);
bytecodes.add(new Bytecode.Store(code.target,
convertType(code.afterType)));
}
private void translateUpdate(Iterator<Code.LVal> iterator, Code.Update code,
ArrayList<Bytecode> bytecodes) {
Code.LVal lv = iterator.next();
if(lv instanceof Code.ListLVal) {
Code.ListLVal l = (Code.ListLVal) lv;
if(iterator.hasNext()) {
// In this case, we're partially updating the element at a
// given position.
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.Load(l.indexOperand,WHILEYINT));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYLIST,WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "internal_get", ftype,
Bytecode.InvokeMode.STATIC));
addReadConversion(l.rawType().element(),bytecodes);
translateUpdate(iterator,code,bytecodes);
bytecodes.add(new Bytecode.Load(l.indexOperand,WHILEYINT));
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.Load(l.indexOperand,WHILEYINT));
bytecodes.add(new Bytecode.Load(code.operand, convertType(l
.rawType().element())));
addWriteConversion(code.rhs(),bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,
WHILEYLIST,WHILEYINT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "set", ftype,
Bytecode.InvokeMode.STATIC));
} else if(lv instanceof Code.StringLVal) {
Code.StringLVal l = (Code.StringLVal) lv;
// assert: level must be zero here
bytecodes.add(new Bytecode.Load(l.indexOperand, WHILEYINT));
bytecodes.add(new Bytecode.Load(code.operand, T_CHAR));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,
JAVA_LANG_STRING, WHILEYINT, T_CHAR);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "set", ftype,
Bytecode.InvokeMode.STATIC));
} else if(lv instanceof Code.MapLVal) {
Code.MapLVal l = (Code.MapLVal) lv;
JvmType keyType = convertType(l.rawType().key());
JvmType valueType = convertType(l.rawType().value());
if(iterator.hasNext()) {
// In this case, we're partially updating the element at a
// given position.
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.rawType().key(),bytecodes);
JvmType.Function ftype = new JvmType.Function(
JAVA_LANG_OBJECT, WHILEYMAP, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "internal_get", ftype,
Bytecode.InvokeMode.STATIC));
addReadConversion(l.rawType().value(),bytecodes);
translateUpdate(iterator,code,bytecodes);
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.rawType().key(),bytecodes);
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.Load(l.keyOperand,keyType));
addWriteConversion(l.rawType().key(),bytecodes);
bytecodes.add(new Bytecode.Load(code.operand, valueType));
addWriteConversion(l.rawType().value(),bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYMAP,
WHILEYMAP,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.InvokeMode.STATIC));
} else if(lv instanceof Code.RecordLVal) {
Code.RecordLVal l = (Code.RecordLVal) lv;
Type.EffectiveRecord type = l.rawType();
if (iterator.hasNext()) {
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(l.field));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYRECORD, JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD, "internal_get",
ftype, Bytecode.InvokeMode.STATIC));
addReadConversion(type.field(l.field), bytecodes);
translateUpdate(iterator, code, bytecodes);
bytecodes.add(new Bytecode.LoadConst(l.field));
bytecodes.add(new Bytecode.Swap());
} else {
bytecodes.add(new Bytecode.LoadConst(l.field));
bytecodes.add(new Bytecode.Load(code.operand, convertType(type
.field(l.field))));
addWriteConversion(type.field(l.field), bytecodes);
}
JvmType.Function ftype = new JvmType.Function(WHILEYRECORD,WHILEYRECORD,JAVA_LANG_STRING,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.InvokeMode.STATIC));
} else {
Code.ReferenceLVal l = (Code.ReferenceLVal) lv;
bytecodes.add(new Bytecode.Dup(WHILEYOBJECT));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYOBJECT, "state", ftype,
Bytecode.InvokeMode.VIRTUAL));
addReadConversion(l.rawType().element(), bytecodes);
translateUpdate(iterator, code, bytecodes);
ftype = new JvmType.Function(WHILEYOBJECT, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYOBJECT, "setState", ftype,
Bytecode.InvokeMode.VIRTUAL));
}
}
private void translate(Code.Return c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if (c.type == Type.T_VOID) {
bytecodes.add(new Bytecode.Return(null));
} else {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand,jt));
bytecodes.add(new Bytecode.Return(jt));
}
}
private void translate(Code.Throw c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Dup(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Load(c.operand,convertType(c.type)));
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYEXCEPTION, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
bytecodes.add(new Bytecode.Throw());
}
private void translate(Code.TupleLoad c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
WHILEYTUPLE, T_INT);
bytecodes.add(new Bytecode.Load(c.operand,convertType((Type) c.type)));
bytecodes.add(new Bytecode.LoadConst(c.index));
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "get", ftype,
Bytecode.InvokeMode.STATIC));
addReadConversion(c.type.elements().get(c.index), bytecodes);
bytecodes.add(new Bytecode.Store(c.target,convertType(c.type
.element(c.index))));
}
private void translate(Code.Switch c, Block.Entry entry, int freeSlot,
ArrayList<Bytecode> bytecodes) {
ArrayList<jasm.util.Pair<Integer, String>> cases = new ArrayList();
boolean canUseSwitchBytecode = true;
for (Pair<Constant, String> p : c.branches) {
// first, check whether the switch value is indeed an integer.
Constant v = (Constant) p.first();
if (!(v instanceof Constant.Integer)) {
canUseSwitchBytecode = false;
break;
}
// second, check whether integer value can fit into a Java int
Constant.Integer vi = (Constant.Integer) v;
int iv = vi.value.intValue();
if (!BigInteger.valueOf(iv).equals(vi.value)) {
canUseSwitchBytecode = false;
break;
}
// ok, we're all good so far
cases.add(new jasm.util.Pair(iv, p.second()));
}
if (canUseSwitchBytecode) {
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Load(c.operand,convertType((Type) c.type)));
bytecodes.add(new Bytecode.Invoke(WHILEYINT, "intValue", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Switch(c.defaultTarget, cases));
} else {
// ok, in this case we have to fall back to series of the if
// conditions. Not ideal.
for (Pair<Constant, String> p : c.branches) {
Constant value = p.first();
String target = p.second();
translate(value, freeSlot, bytecodes);
bytecodes
.add(new Bytecode.Load(c.operand, convertType(c.type)));
translateIfGoto(value.type(), Code.Comparator.EQ, target, entry,
freeSlot + 1, bytecodes);
}
bytecodes.add(new Bytecode.Goto(c.defaultTarget));
}
}
private void translate(Code.TryCatch c, Block.Entry entry, int freeSlot,
ArrayList<UnresolvedHandler> handlers,
HashMap<JvmConstant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// this code works by redirecting *all* whiley exceptions into the
// trampoline block. The trampoline then pulls out the matching ones,
// and lets the remainder be rethrown.
String start = freshLabel();
String trampolineStart = freshLabel();
bytecodes.add(new Bytecode.Goto(start));
// trampoline goes here
bytecodes.add(new Bytecode.Label(trampolineStart));
bytecodes.add(new Bytecode.Dup(WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Store(freeSlot, WHILEYEXCEPTION));
bytecodes.add(new Bytecode.GetField(WHILEYEXCEPTION, "value", JAVA_LANG_OBJECT, Bytecode.FieldMode.NONSTATIC));
ArrayList<String> bounces = new ArrayList<String>();
for (Pair<Type, String> handler : c.catches) {
String bounce = freshLabel();
bounces.add(bounce);
bytecodes.add(new Bytecode.Dup(JAVA_LANG_OBJECT));
translateTypeTest(bounce, Type.T_ANY, handler.first(),
bytecodes, constants);
}
// rethrow what doesn't match
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Load(freeSlot, WHILEYEXCEPTION));
bytecodes.add(new Bytecode.Throw());
for(int i=0;i!=bounces.size();++i) {
String bounce = bounces.get(i);
Pair<Type,String> handler = c.catches.get(i);
bytecodes.add(new Bytecode.Label(bounce));
addReadConversion(handler.first(),bytecodes);
bytecodes.add(new Bytecode.Store(c.operand, convertType(handler
.first())));
bytecodes.add(new Bytecode.Goto(handler.second()));
}
bytecodes.add(new Bytecode.Label(start));
UnresolvedHandler trampolineHandler = new UnresolvedHandler(start,
c.target, trampolineStart, WHILEYEXCEPTION);
handlers.add(trampolineHandler);
}
private void translateIfGoto(Code.If code, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(code.type);
bytecodes.add(new Bytecode.Load(code.leftOperand,jt));
bytecodes.add(new Bytecode.Load(code.rightOperand,jt));
translateIfGoto(code.type,code.op,code.target,stmt,freeSlot,bytecodes);
}
private void translateIfGoto(Type c_type, Code.Comparator cop, String target, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c_type);
if(c_type == Type.T_BOOL) {
// boolean is a special case, since it is not implemented as an
// object on the JVM stack. Therefore, we need to use the "if_cmp"
// bytecode, rather than calling .equals() and using "if" bytecode.
switch(cop) {
case EQ:
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.EQ, type, target));
break;
case NEQ:
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.NE, type, target));
break;
}
} else if(c_type == Type.T_CHAR || c_type == Type.T_BYTE) {
int op;
switch(cop) {
case EQ:
op = Bytecode.IfCmp.EQ;
break;
case NEQ:
op = Bytecode.IfCmp.NE;
break;
case LT:
op = Bytecode.IfCmp.LT;
break;
case LTEQ:
op = Bytecode.IfCmp.LE;
break;
case GT:
op = Bytecode.IfCmp.GT;
break;
case GTEQ:
op = Bytecode.IfCmp.GE;
break;
default:
internalFailure("unknown if condition encountered",filename,stmt);
return;
}
bytecodes.add(new Bytecode.IfCmp(op, T_BYTE,target));
} else {
// Non-primitive case. Just use the Object.equals() method, followed
// by "if" bytecode.
Bytecode.IfMode op;
switch(cop) {
case EQ:
{
if(Type.isSubtype(c_type, Type.T_NULL)) {
// this indicates an interesting special case. The left
// handside of this equality can be null. Therefore, we
// cannot directly call "equals()" on this method, since
// this would cause a null pointer exception!
JvmType.Function ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "equals", ftype,
Bytecode.InvokeMode.STATIC));
} else {
JvmType.Function ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "equals", ftype,
Bytecode.InvokeMode.VIRTUAL));
}
op = Bytecode.IfMode.NE;
break;
}
case NEQ:
{
if (Type.isSubtype(c_type, Type.T_NULL)) {
// this indicates an interesting special case. The left
// handside of this equality can be null. Therefore, we
// cannot directly call "equals()" on this method, since
// this would cause a null pointer exception!
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "equals",
ftype, Bytecode.InvokeMode.STATIC));
} else {
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"equals", ftype, Bytecode.InvokeMode.VIRTUAL));
}
op = Bytecode.IfMode.EQ;
break;
}
case LT:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type, "compareTo", ftype,
Bytecode.InvokeMode.VIRTUAL));
op = Bytecode.IfMode.LT;
break;
}
case LTEQ:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.InvokeMode.VIRTUAL));
op = Bytecode.IfMode.LE;
break;
}
case GT:
{
JvmType.Function ftype = new JvmType.Function(T_INT, type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.InvokeMode.VIRTUAL));
op = Bytecode.IfMode.GT;
break;
}
case GTEQ:
{
JvmType.Function ftype = new JvmType.Function(T_INT,type);
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"compareTo", ftype, Bytecode.InvokeMode.VIRTUAL));
op = Bytecode.IfMode.GE;
break;
}
case SUBSETEQ:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,WHILEYSET,WHILEYSET);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "subsetEq", ftype,
Bytecode.InvokeMode.STATIC));
op = Bytecode.IfMode.NE;
break;
}
case SUBSET:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,WHILEYSET,WHILEYSET);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "subset", ftype,
Bytecode.InvokeMode.STATIC));
op = Bytecode.IfMode.NE;
break;
}
case ELEMOF:
{
JvmType.Function ftype = new JvmType.Function(T_BOOL,
JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "contains",
ftype, Bytecode.InvokeMode.INTERFACE));
op = Bytecode.IfMode.NE;
break;
}
default:
syntaxError("unknown if condition encountered",filename,stmt);
return;
}
// do the jump
bytecodes.add(new Bytecode.If(op, target));
}
}
private void translate(Code.IfIs c, Entry stmt, int freeSlot,
HashMap<JvmConstant,Integer> constants, ArrayList<Bytecode> bytecodes) {
// In this case, we're updating the type of a local variable. To
// make this work, we must update the JVM type of that slot as well
// using a checkcast.
String exitLabel = freshLabel();
String trueLabel = freshLabel();
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type)));
translateTypeTest(trueLabel, c.type, c.rightOperand, bytecodes, constants);
Type gdiff = Type.intersect(c.type,Type.Negation(c.rightOperand));
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type)));
// now, add checkcast
addReadConversion(gdiff,bytecodes);
bytecodes.add(new Bytecode.Store(c.operand,convertType(gdiff)));
bytecodes.add(new Bytecode.Goto(exitLabel));
bytecodes.add(new Bytecode.Label(trueLabel));
Type glb = Type.intersect(c.type, c.rightOperand);
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type)));
// now, add checkcast
addReadConversion(glb,bytecodes);
bytecodes.add(new Bytecode.Store(c.operand,convertType(glb)));
bytecodes.add(new Bytecode.Goto(c.target));
bytecodes.add(new Bytecode.Label(exitLabel));
}
// The purpose of this method is to translate a type test. We're testing to
// see whether what's on the top of the stack (the value) is a subtype of
// the type being tested.
protected void translateTypeTest(String trueTarget, Type src, Type test,
ArrayList<Bytecode> bytecodes, HashMap<JvmConstant,Integer> constants) {
// First, try for the easy cases
if (test instanceof Type.Null) {
// Easy case
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NULL, trueTarget));
} else if(test instanceof Type.Bool) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_BOOLEAN));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
} else if(test instanceof Type.Char) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_CHARACTER));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
} else if(test instanceof Type.Int) {
bytecodes.add(new Bytecode.InstanceOf(WHILEYINT));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
} else if(test instanceof Type.Real) {
bytecodes.add(new Bytecode.InstanceOf(WHILEYRAT));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
} else if(test instanceof Type.Strung) {
bytecodes.add(new Bytecode.InstanceOf(JAVA_LANG_STRING));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
} else {
// Fall-back to an external (recursive) check
Constant constant = Constant.V_TYPE(test);
int id = JvmValue.get(constant,constants);
String name = "constant$" + id;
bytecodes.add(new Bytecode.GetField(owner, name, WHILEYTYPE, Bytecode.FieldMode.STATIC));
JvmType.Function ftype = new JvmType.Function(T_BOOL,convertType(src),WHILEYTYPE);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "instanceOf",
ftype, Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.NE, trueTarget));
}
}
private void translate(Code.Loop c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Label(c.target + "$head"));
}
protected void translate(Code.LoopEnd end,
int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Goto(end.label + "$head"));
bytecodes.add(new Bytecode.Label(end.label));
}
private int translate(Code.ForAll c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
Type elementType = c.type.element();
bytecodes.add(new Bytecode.Load(c.sourceOperand, convertType((Type) c.type)));
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "iterator", ftype, Bytecode.InvokeMode.STATIC));
ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Store(freeSlot, JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Label(c.target + "$head"));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(freeSlot, JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext", ftype,
Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.EQ, c.target));
bytecodes.add(new Bytecode.Load(freeSlot, JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next", ftype,
Bytecode.InvokeMode.INTERFACE));
addReadConversion(elementType, bytecodes);
bytecodes.add(new Bytecode.Store(c.indexOperand, convertType(elementType)));
// we need to increase the freeSlot, since we've allocated one slot to
// hold the iterator.
return freeSlot + 1;
}
private void translate(Code.Goto c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Goto(c.target));
}
private void translate(Code.Label c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Label(c.label));
}
private void translate(Code.Debug c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Load(c.operand, JAVA_LANG_STRING));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "debug", ftype,
Bytecode.InvokeMode.STATIC));
}
private void translate(Code.AssertOrAssume c, Block.Entry entry, int freeSlot,
ArrayList<Bytecode> bytecodes) {
String lab = freshLabel();
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.leftOperand, jt));
bytecodes.add(new Bytecode.Load(c.rightOperand, jt));
translateIfGoto(c.type, c.op, lab, entry, freeSlot, bytecodes);
bytecodes.add(new Bytecode.New(JAVA_LANG_RUNTIMEEXCEPTION));
bytecodes.add(new Bytecode.Dup(JAVA_LANG_RUNTIMEEXCEPTION));
bytecodes.add(new Bytecode.LoadConst(c.msg));
JvmType.Function ftype = new JvmType.Function(T_VOID, JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_RUNTIMEEXCEPTION, "<init>",
ftype, Bytecode.InvokeMode.SPECIAL));
bytecodes.add(new Bytecode.Throw());
bytecodes.add(new Bytecode.Label(lab));
}
private void translate(Code.Assign c, int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, jt));
addIncRefs(c.type,bytecodes);
bytecodes.add(new Bytecode.Store(c.target, jt));
}
private void translate(Code.Move c, int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType jt = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, jt));
bytecodes.add(new Bytecode.Store(c.target, jt));
}
private void translate(Code.BinListOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
switch(c.kind) {
case APPEND:
leftType = WHILEYLIST;
rightType = WHILEYLIST;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
case LEFT_APPEND:
leftType = WHILEYLIST;
rightType = JAVA_LANG_OBJECT;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
break;
case RIGHT_APPEND:
leftType = JAVA_LANG_OBJECT;
rightType = WHILEYLIST;
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
default:
internalFailure("unknown list operation",filename,stmt);
return;
}
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,leftType,rightType);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "append", ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
private void translate(Code.LengthOf c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, convertType((Type) c.type)));
JvmType.Clazz ctype = JAVA_LANG_OBJECT;
JvmType.Function ftype = new JvmType.Function(WHILEYINT, ctype);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "length", ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYINT));
}
private void translate(Code.SubList c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operands[0], WHILEYLIST));
bytecodes.add(new Bytecode.Load(c.operands[1], WHILEYINT));
bytecodes.add(new Bytecode.Load(c.operands[2], WHILEYINT));
JvmType.Function ftype = new JvmType.Function(WHILEYLIST, WHILEYLIST,
WHILEYINT, WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "sublist", ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
private void translate(Code.IndexOf c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.leftOperand, WHILEYLIST));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.key())));
addWriteConversion(c.type.key(),bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYCOLLECTION, "indexOf", ftype,
Bytecode.InvokeMode.STATIC));
addReadConversion(c.type.value(), bytecodes);
bytecodes.add(new Bytecode.Store(c.target,
convertType(c.type.element())));
}
private void translate(Code.FieldLoad c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operand, WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(c.field));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,WHILEYRECORD,JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"get",ftype,Bytecode.InvokeMode.STATIC));
addReadConversion(c.fieldType(),bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.fieldType())));
}
private void translate(Code.BinArithOp c, Block.Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
JvmType.Function ftype = new JvmType.Function(type,type);
// first, load operands
switch(c.kind) {
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
case BITWISEAND:
case BITWISEOR:
case BITWISEXOR:
bytecodes.add(new Bytecode.Load(c.leftOperand, type));
bytecodes.add(new Bytecode.Load(c.rightOperand, type));
break;
case LEFTSHIFT:
case RIGHTSHIFT:
bytecodes.add(new Bytecode.Load(c.leftOperand, type));
bytecodes.add(new Bytecode.Load(c.rightOperand, WHILEYINT));
break;
case RANGE:
bytecodes.add(new Bytecode.Load(c.leftOperand, WHILEYINT));
bytecodes.add(new Bytecode.Load(c.rightOperand, WHILEYINT));
break;
}
// second, apply operation
switch(c.kind) {
case ADD:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "add", ftype,
Bytecode.InvokeMode.VIRTUAL));
break;
case SUB:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "subtract", ftype,
Bytecode.InvokeMode.VIRTUAL));
break;
case MUL:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "multiply", ftype,
Bytecode.InvokeMode.VIRTUAL));
break;
case DIV:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz)type, "divide", ftype,
Bytecode.InvokeMode.VIRTUAL));
break;
case REM:
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) type,
"remainder", ftype, Bytecode.InvokeMode.VIRTUAL));
break;
case RANGE:
ftype = new JvmType.Function(WHILEYLIST,WHILEYINT,WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"range", ftype, Bytecode.InvokeMode.STATIC));
break;
case BITWISEAND:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.AND,T_INT));
break;
case BITWISEOR:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.OR,T_INT));
break;
case BITWISEXOR:
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.XOR,T_INT));
break;
case LEFTSHIFT:
ftype = new JvmType.Function(type,type,WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"leftshift", ftype, Bytecode.InvokeMode.STATIC));
break;
case RIGHTSHIFT:
ftype = new JvmType.Function(type,type,WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,
"rightshift", ftype, Bytecode.InvokeMode.STATIC));
break;
default:
internalFailure("unknown binary expression encountered",filename,stmt);
}
bytecodes.add(new Bytecode.Store(c.target, type));
}
private void translate(Code.BinSetOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
// First, load operands
switch(c.kind) {
case UNION:
case DIFFERENCE:
case INTERSECTION:
leftType = WHILEYSET;
rightType = WHILEYSET;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
case LEFT_UNION:
case LEFT_DIFFERENCE:
case LEFT_INTERSECTION:
leftType = WHILEYSET;
rightType = JAVA_LANG_OBJECT;
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
break;
case RIGHT_UNION:
case RIGHT_INTERSECTION:
leftType = JAVA_LANG_OBJECT;
rightType = WHILEYSET;
bytecodes.add(new Bytecode.Load(c.leftOperand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
break;
default:
internalFailure("Unknown set operation encountered: ",filename,stmt);
return; // dead-code
}
JvmType.Function ftype= new JvmType.Function(WHILEYSET,leftType,rightType);
// Second, select operation
String operation;
switch(c.kind) {
case UNION:
case LEFT_UNION:
case RIGHT_UNION:
operation = "union";
break;
case INTERSECTION:
case LEFT_INTERSECTION:
case RIGHT_INTERSECTION:
operation = "intersect";
break;
case DIFFERENCE:
case LEFT_DIFFERENCE:
operation = "difference";
break;
default:
internalFailure("Unknown set operation encountered: ",filename,stmt);
return; // dead-code
}
bytecodes.add(new Bytecode.Invoke(WHILEYSET, operation, ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, WHILEYSET));
}
private void translate(Code.BinStringOp c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType leftType;
JvmType rightType;
switch(c.kind) {
case APPEND:
leftType = JAVA_LANG_STRING;
rightType = JAVA_LANG_STRING;
break;
case LEFT_APPEND:
leftType = JAVA_LANG_STRING;
rightType = T_CHAR;
break;
case RIGHT_APPEND:
leftType = T_CHAR;
rightType = JAVA_LANG_STRING;
break;
default:
internalFailure("Unknown string operation encountered: ",filename,stmt);
return; // dead-code
}
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,leftType,rightType);
bytecodes.add(new Bytecode.Load(c.leftOperand, leftType));
bytecodes.add(new Bytecode.Load(c.rightOperand, rightType));
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "append", ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, JAVA_LANG_STRING));
}
private void translate(Code.SubString c, Entry stmt, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.Load(c.operands[0], JAVA_LANG_STRING));
bytecodes.add(new Bytecode.Load(c.operands[1], WHILEYINT));
bytecodes.add(new Bytecode.Load(c.operands[2], WHILEYINT));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_STRING,JAVA_LANG_STRING,
WHILEYINT, WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL, "substring", ftype,
Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Store(c.target, JAVA_LANG_STRING));
}
private void translate(Code.Invert c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
bytecodes.add(new Bytecode.Load(c.operand, type));
bytecodes.add(new Bytecode.LoadConst(-1));
bytecodes.add(new Bytecode.BinOp(Bytecode.BinOp.XOR, T_INT));
bytecodes.add(new Bytecode.Store(c.target, type));
}
private void translate(Code.UnArithOp c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType srcType = convertType(c.type);
JvmType targetType = null;
String name = null;
switch(c.kind) {
case NEG:
targetType = srcType;
name = "negate";
break;
case NUMERATOR:
targetType = WHILEYINT;
name = "numerator";
break;
case DENOMINATOR:
targetType = WHILEYINT;
name = "denominator";
break;
}
JvmType.Function ftype = new JvmType.Function(targetType);
bytecodes.add(new Bytecode.Load(c.operand, srcType));
bytecodes.add(new Bytecode.Invoke((JvmType.Clazz) srcType, name,
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Store(c.target, targetType));
}
private void translate(Code.NewObject c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
bytecodes.add(new Bytecode.New(WHILEYOBJECT));
bytecodes.add(new Bytecode.Dup(WHILEYOBJECT));
bytecodes.add(new Bytecode.Dup(WHILEYOBJECT));
bytecodes.add(new Bytecode.Load(c.operand, convertType(c.type.element())));
addWriteConversion(c.type.element(),bytecodes);
JvmType.Function ftype = new JvmType.Function(T_VOID,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYOBJECT, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(T_VOID);
bytecodes.add(new Bytecode.Invoke(WHILEYOBJECT, "start", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Store(c.target, type));
}
private void translate(Code.Dereference c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType type = convertType(c.type);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Load(c.operand, type));
bytecodes.add(new Bytecode.Invoke(WHILEYOBJECT, "state", ftype,
Bytecode.InvokeMode.VIRTUAL));
// finally, we need to cast the object we got back appropriately.
Type.Reference pt = (Type.Reference) c.type;
addReadConversion(pt.element(), bytecodes);
bytecodes.add(new Bytecode.Store(c.target, convertType(c.type.element())));
}
protected void translate(Code.NewList c, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYLIST));
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.LoadConst(c.operands.length));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(WHILEYLIST, WHILEYLIST, JAVA_LANG_OBJECT);
for (int i = 0; i != c.operands.length; ++i) {
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(c.type
.element())));
addWriteConversion(c.type.element(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "internal_add",
ftype, Bytecode.InvokeMode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYLIST));
}
protected void translate(Code.NewMap c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
construct(WHILEYMAP, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
JvmType keyType = convertType(c.type.key());
JvmType valueType = convertType(c.type.value());
for (int i = 0; i != c.operands.length; i=i+2) {
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Load(c.operands[i], keyType));
addWriteConversion(c.type.key(), bytecodes);
bytecodes.add(new Bytecode.Load(c.operands[i + 1],valueType));
addWriteConversion(c.type.value(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYMAP));
}
private void translate(Code.NewRecord code, int freeSlot,
ArrayList<Bytecode> bytecodes) {
construct(WHILEYRECORD, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
HashMap<String,Type> fields = code.type.fields();
ArrayList<String> keys = new ArrayList<String>(fields.keySet());
Collections.sort(keys);
for (int i = 0; i != code.operands.length; i++) {
int register = code.operands[i];
String key = keys.get(i);
Type fieldType = fields.get(key);
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
bytecodes.add(new Bytecode.Load(register, convertType(fieldType)));
addWriteConversion(fieldType,bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Store(code.target, WHILEYRECORD));
}
protected void translate(Code.NewSet c, int freeSlot, ArrayList<Bytecode> bytecodes) {
construct(WHILEYSET, freeSlot, bytecodes);
JvmType.Function ftype = new JvmType.Function(WHILEYSET,
WHILEYSET,JAVA_LANG_OBJECT);
for(int i=0;i!=c.operands.length;++i) {
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(c.type
.element())));
addWriteConversion(c.type.element(),bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYSET,"internal_add",ftype,Bytecode.InvokeMode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYSET));
}
protected void translate(Code.NewTuple c, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYTUPLE ));
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE ));
bytecodes.add(new Bytecode.LoadConst(c.operands.length));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE , "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(WHILEYTUPLE , WHILEYTUPLE , JAVA_LANG_OBJECT);
for (int i = 0; i != c.operands.length; ++i) {
Type elementType = c.type.elements().get(i);
bytecodes.add(new Bytecode.Load(c.operands[i], convertType(elementType)));
addWriteConversion(elementType, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE , "internal_add",
ftype, Bytecode.InvokeMode.STATIC));
}
bytecodes.add(new Bytecode.Store(c.target, WHILEYTUPLE));
}
private void translate(Code.Lambda c, int freeSlot,
ArrayList<Pair<NameID, Type.FunctionOrMethod>> lambdas,
ArrayList<Bytecode> bytecodes) {
// First, register lambda so that corresponding class can be created to
// call the given function or method. This class will extend
// class wyjc.runtime.WyFunctionOrMethod.
lambdas.add(new Pair<NameID,Type.FunctionOrMethod>(c.name,c.type));
// Second, create and duplicate new lambda object. This will then stay
// on the stack (whilst the parameters are constructed) until the
// object's constructor is called.
JvmType.Clazz lambdaClassType = new JvmType.Clazz(owner.pkg(), owner
.lastComponent().first(), Integer.toString(lambdas.size()));
bytecodes.add(new Bytecode.New(lambdaClassType));
bytecodes.add(new Bytecode.Dup(lambdaClassType));
// Third, construct the parameter for lambda class constructor. In the
// case that a binding is given for this lambda, then we need to supply
// this as an argument to the lambda class constructor; otherwise, we
// just pass null. To do this, we first check whether or not a binding
// is required.
boolean hasBinding = false;
for(int operand : c.operands) {
if(operand != Code.NULL_REG) {
hasBinding = true;
break;
}
}
if(hasBinding) {
// Yes, binding is required.
bytecodes.add(new Bytecode.LoadConst(c.operands.length));
bytecodes.add(new Bytecode.New(JAVA_LANG_OBJECT_ARRAY));
for (int i = 0; i != c.operands.length; ++i) {
bytecodes.add(new Bytecode.Dup(JAVA_LANG_OBJECT_ARRAY));
bytecodes.add(new Bytecode.LoadConst(i));
int operand = c.operands[i];
if (operand != Code.NULL_REG) {
Type pt = c.type.params().get(i);
bytecodes.add(new Bytecode.Load(operand, convertType(pt)));
addWriteConversion(pt, bytecodes);
} else {
bytecodes.add(new Bytecode.LoadConst(null));
}
bytecodes.add(new Bytecode.ArrayStore(JAVA_LANG_OBJECT_ARRAY));
}
} else {
// No, binding not required.
bytecodes.add(new Bytecode.LoadConst(null));
}
// Fifth, invoke lambda class constructor
JvmType.Function ftype = new JvmType.Function(T_VOID, JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(lambdaClassType, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
// Sixth, assign newly created lambda object to target register
JvmType.Clazz clazz = (JvmType.Clazz) convertType(c.type);
bytecodes.add(new Bytecode.Store(c.target, clazz));
}
private void translate(Code.Invoke c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
for (int i = 0; i != c.operands.length; ++i) {
int register = c.operands[i];
JvmType parameterType = convertType(c.type.params().get(i));
bytecodes.add(new Bytecode.Load(register, parameterType));
}
Path.ID mid = c.name.module();
String mangled = nameMangle(c.name.name(), c.type);
JvmType.Clazz owner = new JvmType.Clazz(mid.parent().toString()
.replace('/', '.'), mid.last());
JvmType.Function type = convertFunType(c.type);
bytecodes
.add(new Bytecode.Invoke(owner, mangled, type, Bytecode.InvokeMode.STATIC));
// now, handle the case of an invoke which returns a value that should
// be discarded.
if(c.target != Code.NULL_REG){
bytecodes.add(new Bytecode.Store(c.target, convertType(c.type.ret())));
} else if(c.target == Code.NULL_REG && c.type.ret() != Type.T_VOID) {
bytecodes.add(new Bytecode.Pop(convertType(c.type.ret())));
}
}
private void translate(Code.IndirectInvoke c, int freeSlot,
ArrayList<Bytecode> bytecodes) {
Type.FunctionOrMethod ft = c.type;
JvmType.Clazz owner = (JvmType.Clazz) convertType(ft);
bytecodes.add(new Bytecode.Load(c.operand,convertType(ft)));
bytecodes.add(new Bytecode.LoadConst(ft.params().size()));
bytecodes.add(new Bytecode.New(JAVA_LANG_OBJECT_ARRAY));
for (int i = 0; i != c.operands.length; ++i) {
int register = c.operands[i];
Type pt = c.type.params().get(i);
JvmType jpt = convertType(pt);
bytecodes.add(new Bytecode.Dup(JAVA_LANG_OBJECT_ARRAY));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.Load(register, jpt));
addWriteConversion(pt,bytecodes);
bytecodes.add(new Bytecode.ArrayStore(JAVA_LANG_OBJECT_ARRAY));
}
JvmType.Function type = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT_ARRAY);
bytecodes.add(new Bytecode.Invoke(owner, "call", type,
Bytecode.InvokeMode.VIRTUAL));
// now, handle the case of an invoke which returns a value that should
// be discarded.
if (c.target != Code.NULL_REG) {
addReadConversion(ft.ret(),bytecodes);
bytecodes.add(new Bytecode.Store(c.target,
convertType(c.type.ret())));
} else if (c.target == Code.NULL_REG) {
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
private void translate(Constant v, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if(v instanceof Constant.Null) {
translate((Constant.Null)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Bool) {
translate((Constant.Bool)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Byte) {
translate((Constant.Byte)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Char) {
translate((Constant.Char)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Integer) {
translate((Constant.Integer)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Type) {
translate((Constant.Type)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Decimal) {
translate((Constant.Decimal)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Strung) {
translate((Constant.Strung)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Set) {
translate((Constant.Set)v,freeSlot,bytecodes);
} else if(v instanceof Constant.List) {
translate((Constant.List)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Record) {
translate((Constant.Record)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Map) {
translate((Constant.Map)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Tuple) {
translate((Constant.Tuple)v,freeSlot,bytecodes);
} else if(v instanceof Constant.Lambda) {
translate((Constant.Lambda)v,freeSlot,bytecodes);
} else {
throw new IllegalArgumentException("unknown value encountered:" + v);
}
}
protected void translate(Constant.Null e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(null));
}
protected void translate(Constant.Bool e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
if (e.value) {
bytecodes.add(new Bytecode.LoadConst(1));
} else {
bytecodes.add(new Bytecode.LoadConst(0));
}
}
protected void translate(Constant.Type e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream bout = new BinaryOutputStream(jout);
Type.BinaryWriter writer = new Type.BinaryWriter(bout);
try {
writer.write(e.type);
writer.close();
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(),ex);
}
bytecodes.add(new Bytecode.LoadConst(jout.toString()));
JvmType.Function ftype = new JvmType.Function(WHILEYTYPE,
JAVA_LANG_STRING);
bytecodes.add(new Bytecode.Invoke(WHILEYTYPE, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
}
protected void translate(Constant.Byte e, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Constant.Char e, int freeSlot, ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Constant.Integer e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
BigInteger num = e.value;
if(num.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
bytecodes.add(new Bytecode.Conversion(T_INT,T_LONG));
JvmType.Function ftype = new JvmType.Function(WHILEYINT,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYINT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else if(num.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
JvmType.Function ftype = new JvmType.Function(WHILEYINT,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYINT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else {
// in this context, we need to use a byte array to construct the
// integer object.
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(WHILEYINT));
bytecodes.add(new Bytecode.Dup(WHILEYINT));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
JvmType.Function ftype = new JvmType.Function(T_VOID,bat);
bytecodes.add(new Bytecode.Invoke(WHILEYINT, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
}
}
protected void translate(Constant.Decimal e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
BigRational rat = new BigRational(e.value);
BigInteger den = rat.denominator();
BigInteger num = rat.numerator();
if(rat.isInteger()) {
// this
if(num.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else if(num.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else {
// in this context, we need to use a byte array to construct the
// integer object.
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(WHILEYRAT));
bytecodes.add(new Bytecode.Dup(WHILEYRAT));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
JvmType.Function ftype = new JvmType.Function(T_VOID,bat);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
}
} else if(num.bitLength() < 32 && den.bitLength() < 32) {
bytecodes.add(new Bytecode.LoadConst(num.intValue()));
bytecodes.add(new Bytecode.LoadConst(den.intValue()));
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,T_INT,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else if(num.bitLength() < 64 && den.bitLength() < 64) {
bytecodes.add(new Bytecode.LoadConst(num.longValue()));
bytecodes.add(new Bytecode.LoadConst(den.longValue()));
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,T_LONG,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else {
// First, do numerator bytes
byte[] bytes = num.toByteArray();
JvmType.Array bat = new JvmType.Array(JvmTypes.T_BYTE);
bytecodes.add(new Bytecode.New(WHILEYRAT));
bytecodes.add(new Bytecode.Dup(WHILEYRAT));
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
// Second, do denominator bytes
bytes = den.toByteArray();
bytecodes.add(new Bytecode.LoadConst(bytes.length));
bytecodes.add(new Bytecode.New(bat));
for(int i=0;i!=bytes.length;++i) {
bytecodes.add(new Bytecode.Dup(bat));
bytecodes.add(new Bytecode.LoadConst(i));
bytecodes.add(new Bytecode.LoadConst(bytes[i]));
bytecodes.add(new Bytecode.ArrayStore(bat));
}
// Finally, construct BigRational object
JvmType.Function ftype = new JvmType.Function(T_VOID,bat,bat);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
}
}
protected void translate(Constant.Strung e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.LoadConst(e.value));
}
protected void translate(Constant.Set lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYSET));
bytecodes.add(new Bytecode.Dup(WHILEYSET));
JvmType.Function ftype = new JvmType.Function(T_VOID);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Constant e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYSET));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Constant.List lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYLIST));
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
bytecodes.add(new Bytecode.LoadConst(lv.values.size()));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Constant e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYLIST));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "add", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Constant.Tuple lv, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(WHILEYTUPLE));
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE));
bytecodes.add(new Bytecode.LoadConst(lv.values.size()));
JvmType.Function ftype = new JvmType.Function(T_VOID,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
ftype = new JvmType.Function(T_BOOL, JAVA_LANG_OBJECT);
for (Constant e : lv.values) {
bytecodes.add(new Bytecode.Dup(WHILEYTUPLE));
translate(e, freeSlot, bytecodes);
addWriteConversion(e.type(), bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE, "add", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
}
protected void translate(Constant.Record expr, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
construct(WHILEYRECORD, freeSlot, bytecodes);
for (Map.Entry<String, Constant> e : expr.values.entrySet()) {
Type et = e.getValue().type();
bytecodes.add(new Bytecode.Dup(WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(e.getKey()));
translate(e.getValue(), freeSlot, bytecodes);
addWriteConversion(et, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD, "put", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
protected void translate(Constant.Map expr, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,
JAVA_LANG_OBJECT, JAVA_LANG_OBJECT);
construct(WHILEYMAP, freeSlot, bytecodes);
for (Map.Entry<Constant, Constant> e : expr.values.entrySet()) {
Type kt = e.getKey().type();
Type vt = e.getValue().type();
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
translate(e.getKey(), freeSlot, bytecodes);
addWriteConversion(kt, bytecodes);
translate(e.getValue(), freeSlot, bytecodes);
addWriteConversion(vt, bytecodes);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put", ftype,
Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
}
protected void translate(Constant.Lambda e, int freeSlot,
ArrayList<Bytecode> bytecodes) {
JvmType.Clazz clazz = (JvmType.Clazz) convertType(e.type);
JvmType.Function ftype = new JvmType.Function(clazz, JAVA_LANG_STRING,
JAVA_LANG_STRING, JAVA_LANG_OBJECT_ARRAY);
NameID nid = e.name;
bytecodes.add(new Bytecode.LoadConst(nid.module().toString()
.replace('/', '.')));
bytecodes.add(new Bytecode.LoadConst(nameMangle(nid.name(), e.type)));
bytecodes.add(new Bytecode.LoadConst(null));
bytecodes.add(new Bytecode.Invoke(clazz, "create", ftype,
Bytecode.InvokeMode.STATIC));
}
protected void addCoercion(Type from, Type to, int freeSlot,
HashMap<JvmConstant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// First, deal with coercions which require a change of representation
// when going into a union. For example, bool must => Boolean.
if (!(to instanceof Type.Bool) && from instanceof Type.Bool) {
// this is either going into a union type, or the any type
buildCoercion((Type.Bool) from, to, freeSlot, bytecodes);
} else if(from == Type.T_BYTE) {
buildCoercion((Type.Byte)from, to, freeSlot,bytecodes);
} else if(from == Type.T_CHAR) {
buildCoercion((Type.Char)from, to, freeSlot,bytecodes);
} else if (Type.intersect(from, to).equals(from)) {
// do nothing!
// (note, need to check this after primitive types to avoid risk of
// missing coercion to any)
} else if(from == Type.T_INT) {
buildCoercion((Type.Int)from, to, freeSlot,bytecodes);
} else if(from == Type.T_STRING && to instanceof Type.List) {
buildCoercion((Type.Strung)from, (Type.List) to, freeSlot,bytecodes);
} else {
// ok, it's a harder case so we use an explicit coercion function
int id = JvmCoercion.get(from,to,constants);
String name = "coercion$" + id;
JvmType.Function ft = new JvmType.Function(convertType(to), convertType(from));
bytecodes.add(new Bytecode.Invoke(owner, name, ft, Bytecode.InvokeMode.STATIC));
}
}
private void buildCoercion(Type.Bool fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BOOLEAN,T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
// done deal!
}
private void buildCoercion(Type.Byte fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BYTE,T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
// done deal!
}
private void buildCoercion(Type.Int fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
Type glb = Type.intersect(Type.T_REAL, toType);
if(glb == Type.T_REAL) {
// coercion required!
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,WHILEYINT);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
} else {
// must be => char
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYINT,"intValue",ftype,Bytecode.InvokeMode.VIRTUAL));
}
}
private void buildCoercion(Type.Char fromType, Type toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
if(!Type.isSubtype(toType,fromType)) {
if(toType == Type.T_REAL) {
// coercion required!
JvmType.Function ftype = new JvmType.Function(WHILEYRAT,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYRAT,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
} else {
bytecodes.add(new Bytecode.Conversion(T_INT, T_LONG));
JvmType.Function ftype = new JvmType.Function(WHILEYINT,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYINT,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
}
} else {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_CHARACTER,T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER,"valueOf",ftype,Bytecode.InvokeMode.STATIC));
}
}
private void buildCoercion(Type.Strung fromType, Type.List toType,
int freeSlot, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,JAVA_LANG_STRING);
if(toType.element() == Type.T_CHAR) {
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"str2cl",ftype,Bytecode.InvokeMode.STATIC));
} else {
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"str2il",ftype,Bytecode.InvokeMode.STATIC));
}
}
/**
* The build coercion method constructs a static final private method which
* accepts a value of type "from", and coerces it into a value of type "to".
*
* @param to
* @param from
*
*/
protected void buildCoercion(Type from, Type to, int id,
HashMap<JvmConstant, Integer> constants, ClassFile cf) {
ArrayList<Bytecode> bytecodes = new ArrayList<Bytecode>();
int freeSlot = 1;
bytecodes.add(new Bytecode.Load(0,convertType(from)));
buildCoercion(from,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Return(convertType(to)));
ArrayList<Modifier> modifiers = new ArrayList<Modifier>();
modifiers.add(Modifier.ACC_PRIVATE);
modifiers.add(Modifier.ACC_STATIC);
modifiers.add(Modifier.ACC_SYNTHETIC);
JvmType.Function ftype = new JvmType.Function(convertType(to),convertType(from));
String name = "coercion$" + id;
ClassFile.Method method = new ClassFile.Method(name, ftype, modifiers);
cf.methods().add(method);
jasm.attributes.Code code = new jasm.attributes.Code(bytecodes,new ArrayList(),method);
method.attributes().add(code);
}
protected void buildCoercion(Type from, Type to, int freeSlot,
HashMap<JvmConstant, Integer> constants, ArrayList<Bytecode> bytecodes) {
// Second, case analysis on the various kinds of coercion
if(from instanceof Type.Tuple && to instanceof Type.Tuple) {
buildCoercion((Type.Tuple) from, (Type.Tuple) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Reference && to instanceof Type.Reference) {
// TODO
} else if(from instanceof Type.Set && to instanceof Type.Set) {
buildCoercion((Type.Set) from, (Type.Set) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Set && to instanceof Type.Map) {
buildCoercion((Type.Set) from, (Type.Map) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.Set) {
buildCoercion((Type.List) from, (Type.Set) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.Map && to instanceof Type.Map) {
buildCoercion((Type.Map) from, (Type.Map) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.Map) {
buildCoercion((Type.List) from, (Type.Map) to, freeSlot, constants, bytecodes);
} else if(from instanceof Type.List && to instanceof Type.List) {
buildCoercion((Type.List) from, (Type.List) to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Record && from instanceof Type.Record) {
buildCoercion((Type.Record) from, (Type.Record) to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Function && from instanceof Type.Function) {
// TODO
} else if(from instanceof Type.Negation || to instanceof Type.Negation) {
// no need to do anything, since convertType on a negation returns java/lang/Object
} else if(from instanceof Type.Union) {
buildCoercion((Type.Union) from, to, freeSlot, constants, bytecodes);
} else if(to instanceof Type.Union) {
buildCoercion(from, (Type.Union) to, freeSlot, constants, bytecodes);
} else {
throw new RuntimeException("invalid coercion encountered: " + from + " => " + to);
}
}
protected void buildCoercion(Type.Tuple fromType, Type.Tuple toType,
int freeSlot, HashMap<JvmConstant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
int oldSlot = freeSlot++;
int newSlot = freeSlot++;
bytecodes.add(new Bytecode.Store(oldSlot,WHILEYTUPLE));
construct(WHILEYTUPLE,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(newSlot,WHILEYTUPLE));
List<Type> from_elements = fromType.elements();
List<Type> to_elements = toType.elements();
for(int i=0;i!=to_elements.size();++i) {
Type from = from_elements.get(i);
Type to = to_elements.get(i);
bytecodes.add(new Bytecode.Load(newSlot,WHILEYTUPLE));
bytecodes.add(new Bytecode.Load(oldSlot,WHILEYTUPLE));
bytecodes.add(new Bytecode.LoadConst(i));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,T_INT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE,"get",ftype,Bytecode.InvokeMode.VIRTUAL));
addReadConversion(from,bytecodes);
// now perform recursive conversion
addCoercion(from,to,freeSlot,constants,bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYTUPLE,"add",ftype,Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
}
bytecodes.add(new Bytecode.Load(newSlot,WHILEYTUPLE));
}
protected void buildCoercion(Type.List fromType, Type.List toType,
int freeSlot, HashMap<JvmConstant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYLIST,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYLIST));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYLIST));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.InvokeMode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYLIST, "add",
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYLIST));
}
protected void buildCoercion(Type.List fromType, Type.Map toType,
int freeSlot, HashMap<JvmConstant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int source = freeSlot++;
int target = freeSlot++;
bytecodes.add(new Bytecode.Store(source,JAVA_UTIL_LIST));
bytecodes.add(new Bytecode.LoadConst(0));
bytecodes.add(new Bytecode.Store(iter,T_INT));
construct(WHILEYMAP,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(target, WHILEYMAP));
bytecodes.add(new Bytecode.Label(loopLabel));
JvmType.Function ftype = new JvmType.Function(T_INT);
bytecodes.add(new Bytecode.Load(iter,JvmTypes.T_INT));
bytecodes.add(new Bytecode.Load(source,JAVA_UTIL_LIST));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_LIST, "size",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.IfCmp(Bytecode.IfCmp.GE, T_INT, exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,T_INT));
bytecodes.add(new Bytecode.Conversion(T_INT,T_LONG));
ftype = new JvmType.Function(WHILEYINT,T_LONG);
bytecodes.add(new Bytecode.Invoke(WHILEYINT, "valueOf",
ftype, Bytecode.InvokeMode.STATIC));
bytecodes.add(new Bytecode.Load(source,WHILEYMAP));
bytecodes.add(new Bytecode.Load(iter,T_INT));
ftype = new JvmType.Function(JAVA_LANG_OBJECT,T_INT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_LIST, "get",
ftype, Bytecode.InvokeMode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.value(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put",
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Iinc(iter,1));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
}
protected void buildCoercion(Type.Map fromType, Type.Map toType,
int freeSlot, HashMap<JvmConstant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if (fromType.key() == Type.T_VOID || toType.key() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int source = freeSlot++;
int target = freeSlot++;
bytecodes.add(new Bytecode.Dup(WHILEYMAP));
bytecodes.add(new Bytecode.Store(source, WHILEYMAP));
construct(WHILEYMAP,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(target, WHILEYMAP));
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_SET);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "keySet",
ftype, Bytecode.InvokeMode.VIRTUAL));
ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_SET, "iterator",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.InvokeMode.INTERFACE));
addReadConversion(fromType.key(),bytecodes);
bytecodes.add(new Bytecode.Dup(convertType(fromType.key())));
addCoercion(fromType.key(), toType.key(), freeSlot,
constants, bytecodes);
addWriteConversion(toType.key(),bytecodes);
bytecodes.add(new Bytecode.Swap());
bytecodes.add(new Bytecode.Load(source,WHILEYMAP));
bytecodes.add(new Bytecode.Swap());
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "get",
ftype, Bytecode.InvokeMode.VIRTUAL));
addReadConversion(fromType.value(),bytecodes);
addCoercion(fromType.value(), toType.value(), freeSlot,
constants, bytecodes);
addWriteConversion(toType.value(),bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYMAP, "put",
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(target,WHILEYMAP));
}
protected void buildCoercion(Type.Set fromType, Type.Map toType,
int freeSlot, HashMap<JvmConstant, Integer> constants,
ArrayList<Bytecode> bytecodes) {
if (fromType.element() != Type.T_VOID) {
throw new RuntimeException("invalid coercion encountered: "
+ fromType + " => " + toType);
}
bytecodes.add(new Bytecode.Pop(WHILEYSET));
construct(WHILEYMAP, freeSlot, bytecodes);
}
protected void buildCoercion(Type.List fromType, Type.Set toType,
int freeSlot, HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYSET,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYSET));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.InvokeMode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add",
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
}
protected void buildCoercion(Type.Set fromType, Type.Set toType,
int freeSlot, HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
if(fromType.element() == Type.T_VOID) {
// nothing to do, in this particular case
return;
}
// The following piece of code implements a java for-each loop which
// iterates every element of the input collection, and recursively
// converts it before loading it back onto a new WhileyList.
String loopLabel = freshLabel();
String exitLabel = freshLabel();
int iter = freeSlot++;
int tmp = freeSlot++;
JvmType.Function ftype = new JvmType.Function(JAVA_UTIL_ITERATOR);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_COLLECTION, "iterator",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.Store(iter,
JAVA_UTIL_ITERATOR));
construct(WHILEYSET,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(tmp, WHILEYSET));
bytecodes.add(new Bytecode.Label(loopLabel));
ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "hasNext",
ftype, Bytecode.InvokeMode.INTERFACE));
bytecodes.add(new Bytecode.If(Bytecode.IfMode.EQ, exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
bytecodes.add(new Bytecode.Load(iter,JAVA_UTIL_ITERATOR));
ftype = new JvmType.Function(JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(JAVA_UTIL_ITERATOR, "next",
ftype, Bytecode.InvokeMode.INTERFACE));
addReadConversion(fromType.element(),bytecodes);
addCoercion(fromType.element(), toType.element(), freeSlot,
constants, bytecodes);
ftype = new JvmType.Function(T_BOOL,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYSET, "add",
ftype, Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(T_BOOL));
bytecodes.add(new Bytecode.Goto(loopLabel));
bytecodes.add(new Bytecode.Label(exitLabel));
bytecodes.add(new Bytecode.Load(tmp,WHILEYSET));
}
private void buildCoercion(Type.Record fromType, Type.Record toType,
int freeSlot, HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
int oldSlot = freeSlot++;
int newSlot = freeSlot++;
bytecodes.add(new Bytecode.Store(oldSlot,WHILEYRECORD));
construct(WHILEYRECORD,freeSlot,bytecodes);
bytecodes.add(new Bytecode.Store(newSlot,WHILEYRECORD));
Map<String,Type> toFields = toType.fields();
Map<String,Type> fromFields = fromType.fields();
for(String key : toFields.keySet()) {
Type to = toFields.get(key);
Type from = fromFields.get(key);
bytecodes.add(new Bytecode.Load(newSlot,WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
bytecodes.add(new Bytecode.Load(oldSlot,WHILEYRECORD));
bytecodes.add(new Bytecode.LoadConst(key));
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"get",ftype,Bytecode.InvokeMode.VIRTUAL));
// TODO: in cases when the read conversion is a no-op, we can do
// better here.
addReadConversion(from,bytecodes);
addCoercion(from,to,freeSlot,constants,bytecodes);
addWriteConversion(from,bytecodes);
ftype = new JvmType.Function(JAVA_LANG_OBJECT,JAVA_LANG_OBJECT,JAVA_LANG_OBJECT);
bytecodes.add(new Bytecode.Invoke(WHILEYRECORD,"put",ftype,Bytecode.InvokeMode.VIRTUAL));
bytecodes.add(new Bytecode.Pop(JAVA_LANG_OBJECT));
}
bytecodes.add(new Bytecode.Load(newSlot,WHILEYRECORD));
}
private void buildCoercion(Type.Union from, Type to,
int freeSlot, HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
String exitLabel = freshLabel();
List<Type> bounds = new ArrayList<Type>(from.bounds());
ArrayList<String> labels = new ArrayList<String>();
// basically, we're building a big dispatch table. I think there's no
// question that this could be more efficient in some cases.
for(int i=0;i!=bounds.size();++i) {
Type bound = bounds.get(i);
if((i+1) == bounds.size()) {
addReadConversion(bound,bytecodes);
addCoercion(bound,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Goto(exitLabel));
} else {
String label = freshLabel();
labels.add(label);
bytecodes.add(new Bytecode.Dup(convertType(from)));
translateTypeTest(label,from,bound,bytecodes,constants);
}
}
for(int i=0;i<labels.size();++i) {
String label = labels.get(i);
Type bound = bounds.get(i);
bytecodes.add(new Bytecode.Label(label));
addReadConversion(bound,bytecodes);
addCoercion(bound,to,freeSlot,constants,bytecodes);
bytecodes.add(new Bytecode.Goto(exitLabel));
}
bytecodes.add(new Bytecode.Label(exitLabel));
}
private void buildCoercion(Type from, Type.Union to,
int freeSlot, HashMap<JvmConstant,Integer> constants,
ArrayList<Bytecode> bytecodes) {
Type.Union t2 = (Type.Union) to;
// First, check for identical type (i.e. no coercion necessary)
for (Type b : t2.bounds()) {
if (from.equals(b)) {
// nothing to do
return;
}
}
// Second, check for single non-coercive match
for (Type b : t2.bounds()) {
if (Type.isSubtype(b, from)) {
buildCoercion(from,b,freeSlot,constants,bytecodes);
return;
}
}
// Third, test for single coercive match
for (Type b : t2.bounds()) {
if (Type.isImplicitCoerciveSubtype(b, from)) {
buildCoercion(from,b,freeSlot,constants,bytecodes);
return;
}
}
// I don't think we should be able to get here!
}
/**
* The read conversion is necessary in situations where we're reading a
* value from a collection (e.g. WhileyList, WhileySet, etc) and then
* putting it on the stack. In such case, we need to convert boolean values
* from Boolean objects to bool primitives.
*/
private void addReadConversion(Type et, ArrayList<Bytecode> bytecodes) {
if(et instanceof Type.Bool) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_BOOLEAN));
JvmType.Function ftype = new JvmType.Function(T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,
"booleanValue", ftype, Bytecode.InvokeMode.VIRTUAL));
} else if(et instanceof Type.Byte) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_BYTE));
JvmType.Function ftype = new JvmType.Function(T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE,
"byteValue", ftype, Bytecode.InvokeMode.VIRTUAL));
} else if(et instanceof Type.Char) {
bytecodes.add(new Bytecode.CheckCast(JAVA_LANG_CHARACTER));
JvmType.Function ftype = new JvmType.Function(T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER,
"charValue", ftype, Bytecode.InvokeMode.VIRTUAL));
} else {
addCheckCast(convertType(et),bytecodes);
}
}
/**
* The write conversion is necessary in situations where we're write a value
* from the stack into a collection (e.g. WhileyList, WhileySet, etc). In
* such case, we need to convert boolean values from bool primitives to
* Boolean objects.
*/
private void addWriteConversion(Type et, ArrayList<Bytecode> bytecodes) {
if(et instanceof Type.Bool) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BOOLEAN,T_BOOL);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BOOLEAN,
"valueOf", ftype, Bytecode.InvokeMode.STATIC));
} else if(et instanceof Type.Byte) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_BYTE,
T_BYTE);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_BYTE, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
} else if(et instanceof Type.Char) {
JvmType.Function ftype = new JvmType.Function(JAVA_LANG_CHARACTER,
T_CHAR);
bytecodes.add(new Bytecode.Invoke(JAVA_LANG_CHARACTER, "valueOf", ftype,
Bytecode.InvokeMode.STATIC));
}
}
private void addCheckCast(JvmType type, ArrayList<Bytecode> bytecodes) {
// The following can happen in situations where a variable has type
// void. In principle, we could remove this as obvious dead-code, but
// for now I just avoid it.
if(type instanceof JvmType.Void) {
return;
} else if(!type.equals(JAVA_LANG_OBJECT)) {
// pointless to add a cast for object
bytecodes.add(new Bytecode.CheckCast(type));
}
}
/**
* Return true if this type is, or maybe reference counted.
*
* @param t
* @return
*/
private static boolean isRefCounted(Type t) {
if (t instanceof Type.Union) {
Type.Union n = (Type.Union) t;
for (Type b : n.bounds()) {
if (isRefCounted(b)) {
return true;
}
}
return false;
} else {
// FIXME: what about negations?
return t instanceof Type.Any || t instanceof Type.List
|| t instanceof Type.Tuple || t instanceof Type.Set
|| t instanceof Type.Map || t instanceof Type.Record;
}
}
/**
* Add bytecodes for incrementing the reference count.
*
* @param type
* @param bytecodes
*/
private static void addIncRefs(Type type, ArrayList<Bytecode> bytecodes) {
if(isRefCounted(type)){
JvmType jtype = convertType(type);
JvmType.Function ftype = new JvmType.Function(jtype,jtype);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.InvokeMode.STATIC));
}
}
private static void addIncRefs(Type.List type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYLIST,WHILEYLIST);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.InvokeMode.STATIC));
}
private static void addIncRefs(Type.Record type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYRECORD,WHILEYRECORD);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.InvokeMode.STATIC));
}
private static void addIncRefs(Type.Map type, ArrayList<Bytecode> bytecodes) {
JvmType.Function ftype = new JvmType.Function(WHILEYMAP,WHILEYMAP);
bytecodes.add(new Bytecode.Invoke(WHILEYUTIL,"incRefs",ftype,Bytecode.InvokeMode.STATIC));
}
/**
* The construct method provides a generic way to construct a Java object.
*
* @param owner
* @param freeSlot
* @param bytecodes
* @param params
*/
private void construct(JvmType.Clazz owner, int freeSlot,
ArrayList<Bytecode> bytecodes) {
bytecodes.add(new Bytecode.New(owner));
bytecodes.add(new Bytecode.Dup(owner));
ArrayList<JvmType> paramTypes = new ArrayList<JvmType>();
JvmType.Function ftype = new JvmType.Function(T_VOID,paramTypes);
bytecodes.add(new Bytecode.Invoke(owner, "<init>", ftype,
Bytecode.InvokeMode.SPECIAL));
}
private final static Type.Record WHILEY_PRINTWRITER_T = Type.Record(false,
new HashMap() {
{
put("print", Type.Method(Type.T_VOID, Type.T_VOID, Type.T_ANY));
put("println", Type.Method(Type.T_VOID, Type.T_VOID, Type.T_ANY));
}
});
private final static Type WHILEY_SYSTEM_T = Type.Record(false,
new HashMap() {
{
put("out", WHILEY_PRINTWRITER_T);
put("args", Type.List(Type.T_STRING,false));
}
});
private final static JvmType.Clazz WHILEYUTIL = new JvmType.Clazz("wyjc.runtime","Util");
private final static JvmType.Clazz WHILEYLIST = new JvmType.Clazz("wyjc.runtime","WyList");
private final static JvmType.Clazz WHILEYSET = new JvmType.Clazz("wyjc.runtime","WySet");
private final static JvmType.Clazz WHILEYTUPLE = new JvmType.Clazz("wyjc.runtime","WyTuple");
private final static JvmType.Clazz WHILEYCOLLECTION = new JvmType.Clazz("wyjc.runtime","WyCollection");
private final static JvmType.Clazz WHILEYTYPE = new JvmType.Clazz("wyjc.runtime","WyType");
private final static JvmType.Clazz WHILEYMAP = new JvmType.Clazz("wyjc.runtime","WyMap");
private final static JvmType.Clazz WHILEYRECORD = new JvmType.Clazz("wyjc.runtime","WyRecord");
private final static JvmType.Clazz WHILEYOBJECT = new JvmType.Clazz("wyjc.runtime", "WyObject");
private final static JvmType.Clazz WHILEYEXCEPTION = new JvmType.Clazz("wyjc.runtime","WyException");
private final static JvmType.Clazz WHILEYINT = new JvmType.Clazz("java.math","BigInteger");
private final static JvmType.Clazz WHILEYRAT = new JvmType.Clazz("wyjc.runtime","WyRat");
private final static JvmType.Clazz WHILEYFUNCTION = new JvmType.Clazz("wyjc.runtime","WyFunction");
private final static JvmType.Clazz WHILEYMETHOD = new JvmType.Clazz("wyjc.runtime","WyMethod");
private static final JvmType.Clazz JAVA_LANG_CHARACTER = new JvmType.Clazz("java.lang","Character");
private static final JvmType.Clazz JAVA_LANG_SYSTEM = new JvmType.Clazz("java.lang","System");
private static final JvmType.Array JAVA_LANG_OBJECT_ARRAY = new JvmType.Array(JAVA_LANG_OBJECT);
private static final JvmType.Clazz JAVA_UTIL_LIST = new JvmType.Clazz("java.util","List");
private static final JvmType.Clazz JAVA_UTIL_SET = new JvmType.Clazz("java.util","Set");
//private static final JvmType.Clazz JAVA_LANG_REFLECT_METHOD = new JvmType.Clazz("java.lang.reflect","Method");
private static final JvmType.Clazz JAVA_IO_PRINTSTREAM = new JvmType.Clazz("java.io","PrintStream");
private static final JvmType.Clazz JAVA_LANG_RUNTIMEEXCEPTION = new JvmType.Clazz("java.lang","RuntimeException");
private static final JvmType.Clazz JAVA_LANG_ASSERTIONERROR = new JvmType.Clazz("java.lang","AssertionError");
private static final JvmType.Clazz JAVA_UTIL_COLLECTION = new JvmType.Clazz("java.util","Collection");
private JvmType.Function convertFunType(Type.FunctionOrMethod ft) {
ArrayList<JvmType> paramTypes = new ArrayList<JvmType>();
for(Type pt : ft.params()) {
paramTypes.add(convertType(pt));
}
JvmType rt = convertType(ft.ret());
return new JvmType.Function(rt,paramTypes);
}
private static JvmType convertType(Type t) {
if(t == Type.T_VOID) {
return T_VOID;
} else if(t == Type.T_ANY) {
return JAVA_LANG_OBJECT;
} else if(t == Type.T_NULL) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Bool) {
return T_BOOL;
} else if(t instanceof Type.Byte) {
return T_BYTE;
} else if(t instanceof Type.Char) {
return T_CHAR;
} else if(t instanceof Type.Int) {
return WHILEYINT;
} else if(t instanceof Type.Real) {
return WHILEYRAT;
} else if(t instanceof Type.Meta) {
return WHILEYTYPE;
} else if(t instanceof Type.Strung) {
return JAVA_LANG_STRING;
} else if(t instanceof Type.EffectiveList) {
return WHILEYLIST;
} else if(t instanceof Type.EffectiveSet) {
return WHILEYSET;
} else if(t instanceof Type.EffectiveMap) {
return WHILEYMAP;
} else if(t instanceof Type.EffectiveRecord) {
return WHILEYRECORD;
} else if(t instanceof Type.EffectiveTuple) {
return WHILEYTUPLE;
} else if(t instanceof Type.Reference) {
return WHILEYOBJECT;
} else if(t instanceof Type.Negation) {
// can we do any better?
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Union) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Meta) {
return JAVA_LANG_OBJECT;
} else if(t instanceof Type.Function) {
return WHILEYFUNCTION;
} else if(t instanceof Type.Method) {
return WHILEYMETHOD;
} else {
throw new RuntimeException("unknown type encountered: " + t);
}
}
protected int label = 0;
protected String freshLabel() {
return "cfblab" + label++;
}
private static String nameMangle(String name, Type.FunctionOrMethod ft) {
try {
return name + "$" + typeMangle(ft);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private static String typeMangle(Type.FunctionOrMethod ft) throws IOException {
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream binout = new BinaryOutputStream(jout);
Type.BinaryWriter tm = new Type.BinaryWriter(binout);
tm.write(ft);
binout.close(); // force flush
return jout.toString();
}
/**
* A constant is some kind of auxillary functionality used in generated code, which can be reused at multiple sites. This includes value constants, and coercion functions.
* @author David J. Pearce
*
*/
private abstract static class JvmConstant {}
private static final class JvmValue extends JvmConstant {
public final Constant value;
public JvmValue(Constant v) {
value = v;
}
public boolean equals(Object o) {
if(o instanceof JvmValue) {
JvmValue vc = (JvmValue) o;
return value.equals(vc.value);
}
return false;
}
public int hashCode() {
return value.hashCode();
}
public static int get(Constant value, HashMap<JvmConstant,Integer> constants) {
JvmValue vc = new JvmValue(value);
Integer r = constants.get(vc);
if(r != null) {
return r;
} else {
int x = constants.size();
constants.put(vc, x);
return x;
}
}
}
private static final class JvmCoercion extends JvmConstant {
public final Type from;
public final Type to;
public JvmCoercion(Type from, Type to) {
this.from = from;
this.to = to;
}
public boolean equals(Object o) {
if(o instanceof JvmCoercion) {
JvmCoercion c = (JvmCoercion) o;
return from.equals(c.from) && to.equals(c.to);
}
return false;
}
public int hashCode() {
return from.hashCode() + to.hashCode();
}
public static int get(Type from, Type to, HashMap<JvmConstant,Integer> constants) {
JvmCoercion vc = new JvmCoercion(from,to);
Integer r = constants.get(vc);
if(r != null) {
return r;
} else {
int x = constants.size();
constants.put(vc, x);
return x;
}
}
}
private static class UnresolvedHandler {
public String start;
public String end;
public String target;
public JvmType.Clazz exception;
public UnresolvedHandler(String start, String end, String target,
JvmType.Clazz exception) {
this.start = start;
this.end = end;
this.target = target;
this.exception = exception;
}
}
/*
public static void testMangle1(Type.Fun ft) throws IOException {
IdentifierOutputStream jout = new IdentifierOutputStream();
BinaryOutputStream binout = new BinaryOutputStream(jout);
Types.BinaryWriter tm = new Types.BinaryWriter(binout);
Type.build(tm,ft);
binout.close();
System.out.println("MANGLED: " + ft + " => " + jout.toString());
Type.Fun type = (Type.Fun) new Types.BinaryReader(
new BinaryInputStream(new IdentifierInputStream(
jout.toString()))).read();
System.out.println("UNMANGLED TO: " + type);
if(!type.equals(ft)) {
throw new RuntimeException("INVALID TYPE RECONSTRUCTED");
}
}
*/
}
|
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item> {
private int head, tail, n;
private Item[] s;
public Deque() {
s = (Item[]) new Object[1];
head = 0;
tail = 0;
n = 0;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
public void addFirst(Item item) {
if (head == 0)
head = s.length - 1;
else
head
s[head] = item;
n++;
if (n == s.length)
resizeArray(2 * s.length);
}
public void addLast(Item item) {
if (tail == s.length - 1) {
s[tail] = item;
tail = 0;
} else {
s[tail++] = item;
}
n++;
if (n == s.length)
resizeArray(2 * s.length);
}
public Item removeFirst() {
Item temp;
if (head == s.length - 1) {
temp = s[head];
s[head] = null;
head = 0;
} else {
temp = s[head];
s[head--] = null;
}
n
if (n == s.length / 4)
resizeArray(s.length / 2);
return temp;
}
public Item removeLast() {
Item temp;
if (tail == 0) {
temp = s[s.length - 1];
tail = s.length - 1;
s[tail] = null;
} else {
temp = s[--tail];
s[tail] = null;
}
n
if (n == s.length / 4)
resizeArray(s.length / 2);
return temp;
}
public Iterator<Item> iterator() {
return null;
// return an iterator over items in order from front to end
}
private void resizeArray(int cap) {
Item[] copy = (Item[]) new Object[cap];
for (int i = 0; i < s.length; i++) {
}
}
public static void main(String[] args) {
// unit testing
}
}
|
package edu.lehigh.cse.lol;
// TODO: verify chooser and level music stops on Android events
// TODO: Should we allow the creation of multi-fixture bodies? It probably won't work with resize...
// TODO: verify that flipped animations work correctly, even when they change while flipped
// TODO: the unlock mechanism is untested
// TODO: hero-enemy triggers and hero-goodie triggers would allow neat animation effects, without
// resorting to the ugliness in level 55
// TODO: Hero animation sequences could use work. The problem is that goodie count animation
// information can be lost if we animate, then return from the animation. Part of the problem is
// that animateByGoodieCount is ugly. Furthermore, we don't have support for invincible+X
// animation, or jump+crawl animation
// TODO: it would be good to have persistent scores... can we easily do it in a general way?
// TODO: add jump-to-defeat enemies
// TODO: consider adding a wrapper to expose Box2d collision groups?
// TODO: Make sure we have good error messages for common mistakes (filenames, animation, routes)
// TODO: Demo projectile setCollisionOk?
// TODO: consider making sprite sheets more useful
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Timer;
public abstract class Lol extends Game {
/**
* The current mode of the program
*/
private Modes mMode;
/**
* The current level being played
*/
int mCurrLevelNum;
/**
* Track the current help scene being displayed
*/
int mCurrHelpNum;
/**
* A reference to the game object
*/
static Lol sGame;
/**
* This variable lets us track whether the user pressed 'back' on an
* android, or 'escape' on the desktop. We are using polling, so we swallow
* presses that aren't preceded by a release. In that manner, holding 'back'
* can't exit all the way out... you must press 'back' repeatedly, once for
* each screen to revert.
*/
boolean mKeyDown;
/**
* The configuration of the game is accessible through this
*/
LolConfiguration mConfig;
/**
* The configuration of the splash screen is accessible through this
*/
SplashConfiguration mSplashConfig;
/**
* The configuratoin of the chooser screen is accessible through this
*/
ChooserConfiguration mChooserConfig;
/**
* Modes of the game: we can be showing the main screen, the help screens,
* the level chooser, or a playable level
*/
private enum Modes {
SPLASH, HELP, CHOOSE, PLAY
};
/**
* Use this to load the splash screen
*/
void doSplash() {
// set the default display mode
mCurrLevelNum = 0;
mCurrHelpNum = 0;
mMode = Modes.SPLASH;
setScreen(new Splash());
}
/**
* Use this to load the level-chooser screen. Note that when a game has only
* one level, we'll never draw the level-picker screen, thereby mimicing the
* behavior of "infinite" games.
*/
void doChooser() {
if (mConfig.getNumLevels() == 1) {
if (mCurrLevelNum == 1)
doSplash();
else
doPlayLevel(1);
return;
}
mCurrHelpNum = 0;
mMode = Modes.CHOOSE;
setScreen(new Chooser());
}
/**
* Use this to load a playable level.
*
* @param which The index of the level to load
*/
void doPlayLevel(int which) {
mCurrLevelNum = which;
mCurrHelpNum = 0;
mMode = Modes.PLAY;
configureLevel(which);
setScreen(Level.sCurrent);
}
/**
* Use this to load a help level.
*
* @param which The index of the help level to load
*/
void doHelpLevel(int which) {
mCurrHelpNum = which;
mCurrLevelNum = 0;
mMode = Modes.HELP;
configureHelpScene(which);
setScreen(HelpLevel.sCurrentLevel);
}
/**
* Use this to quit the app
*/
void doQuit() {
getScreen().dispose();
Gdx.app.exit();
}
/**
* Vibrate the phone for a fixed amount of time. Note that this only
* vibrates the phone if the configuration says that vibration should be
* permitted.
*
* @param millis The amount of time to vibrate
*/
void vibrate(int millis) {
if (mConfig.getVibration())
Gdx.input.vibrate(millis);
}
/**
* We can use this method from the render loop to poll for back presses
*/
private void handleKeyDown() {
// if neither BACK nor ESCAPE is being pressed, do nothing, but
// recognize future presses
if (!Gdx.input.isKeyPressed(Keys.BACK) && !Gdx.input.isKeyPressed(Keys.ESCAPE)) {
mKeyDown = false;
return;
}
// if they key is being held down, ignore it
if (mKeyDown)
return;
// recognize a new back press as being a 'down' press
mKeyDown = true;
handleBack();
}
/**
* When the back key is pressed, or when we are simulating the back key
* being pressed (e.g., a back button), this code runs.
*/
void handleBack() {
// clear all timers, just in case...
Timer.instance().clear();
// if we're looking at main menu, then exit
if (mMode == Modes.SPLASH) {
dispose();
Gdx.app.exit();
}
// if we're looking at the chooser or help, switch to the splash
// screen
else if (mMode == Modes.CHOOSE || mMode == Modes.HELP) {
doSplash();
}
// ok, we're looking at a game scene... switch to chooser
else {
doChooser();
}
}
/**
* save the value of 'unlocked' so that the next time we play, we don't have
* to start at level 0
*
* @param value The value to save as the most recently unlocked level
*/
void saveUnlocked(int value) {
Preferences prefs = Gdx.app.getPreferences(mConfig.getStorageKey());
prefs.putInteger("unlock", value);
prefs.flush();
}
/**
* read the current value of 'unlocked' to know how many levels to unlock
*/
int readUnlocked() {
Preferences prefs = Gdx.app.getPreferences(mConfig.getStorageKey());
return prefs.getInteger("unlock", 1);
}
/**
* This is an internal method for initializing a game. User code should
* never call this.
*/
@Override
public void create() {
sGame = this;
// get configuration
mConfig = config();
mSplashConfig = splashConfig();
mChooserConfig = chooserConfig();
// for handling back presses
Gdx.input.setCatchBackKey(true);
// get number of unlocked levels
readUnlocked();
// Load Resources
nameResources();
// show the splash screen
doSplash();
}
/**
* This is an internal method for quitting a game. User code should never
* call this.
*/
@Override
public void dispose() {
super.dispose();
// dispose of all fonts, textureregions, etc...
// It appears that GDX manages all textures for images and fonts, as
// well as all sounds and music files. That
// being the case, the only thing we need to be careful about is that we
// get rid of any references to fonts that
// might be hanging around
Media.onDispose();
}
/**
* This is an internal method for drawing game levels. User code should
* never call this.
*/
@Override
public void render() {
// Check for back press
handleKeyDown();
// Draw the current scene
super.render();
}
/*
* PUBLIC INTERFACE
*/
/**
* The programmer configures the splash screen by implementing this method,
* and returning a SplashConfiguration object
*/
abstract public LolConfiguration config();
/**
* The programmer configures the chooser screen by implementing this method,
* and returning a ChooserConfiguration object
*/
abstract public ChooserConfiguration chooserConfig();
/**
* The programmer configures the splash screen by implementing this method,
* and returning a SplashConfiguration object
*/
abstract public SplashConfiguration splashConfig();
/**
* Register any sound or image files to be used by the game
*/
abstract public void nameResources();
/**
* Describe how to draw the levels of the game
*
* @param whichLevel The number of the level being drawn
*/
abstract public void configureLevel(int whichLevel);
/**
* Describe how to draw the help scenes
*
* @param whichScene The number of the help scene being drawn
*/
abstract public void configureHelpScene(int whichScene);
/**
* When a Hero collides with an Obstacle for which a HeroCollideTrigger has
* been set, this code will run
*
* @param id The number assigned to the Obstacle's HeroCollideTrigger
* @param whichLevel The current level
* @param o The obstacle involved in the collision
* @param h The hero involved in the collision
*/
abstract public void onHeroCollideTrigger(int id, int whichLevel, Obstacle o, Hero h);
/**
* When the player touches an entity that has a TouchTrigger attached to it,
* this code will run
*
* @param id The number assigned to the entity's TouchTrigger
* @param whichLevel The current level
* @param o The entity involved in the collision
*/
abstract public void onTouchTrigger(int id, int whichLevel, PhysicsSprite o);
/**
* When the player requests a TimerTrigger, and the required time passes,
* this code will run
*
* @param id The number assigned to the TimerTrigger
* @param whichLevel The current level
*/
abstract public void onTimerTrigger(int id, int whichLevel);
/**
* When a player requests an EnemyTimerTrigger, and the required time
* passes, and the enemy is still visible, this code will run
*
* @param id The number assigned to the EnemyTimerTrigger
* @param whichLevel The current level
* @param e The enemy to which the timer was attached
*/
abstract public void onEnemyTimerTrigger(int id, int whichLevel, Enemy e);
/**
* When an enemy is defeated, this code will run if the enemy has an
* EnemyDefeatTrigger
*
* @param id The number assigned to this trigger
* @param whichLevel The current level
* @param e The enemy who was defeated
*/
abstract public void onEnemyDefeatTrigger(int id, int whichLevel, Enemy e);
/**
* When an obstacle collides with an enemy, if the obstacle has an
* EnemyCollideTrigger, then this code will run.
*
* @param id The number assigned to this trigger
* @param whichLevel The current level
* @param o The obstacle involved in the collision
* @param e The enemy involved in the collision
*/
abstract public void onEnemyCollideTrigger(int id, int whichLevel, Obstacle o, Enemy e);
/**
* When a projectile collides with an obstacle, if the obstacle has a
* ProjectileCollideTrigger, then this code will run
*
* @param id The number assigned to this trigger
* @param whichLevel The current level
* @param o The obstacle involved in the collision
* @param p The projectile involved in the collision
*/
abstract public void onProjectileCollideTrigger(int id, int whichLevel, Obstacle o, Projectile p);
/**
* When a level finishes, this code will run
*
* @param whichLevel The current level
* @param win True if the level was won, false otherwise
*/
abstract public void levelCompleteTrigger(int whichLevel, boolean win);
/**
* When a Control is pressed, for which there is a ControlTrigger, this code
* will run.
*
* @param id The number assigned to this trigger
* @param whichLevel The current level
*/
abstract public void onControlPressTrigger(int id, int whichLevel);
}
interface Renderable {
void render(SpriteBatch sb, float elapsed);
}
|
package com.restfb.logging;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Logger implementation based on {@code java.util.logging}.
*
* The JUL configuration should be provided by a external application. The mapping is defined like:
* <ul>
* <li>trace maps to java.util.logging.Level.<i>FINER</i></li>
* <li>debug maps to java.util.logging.Level.<i>FINE</i></li>
* <li>info maps to java.util.logging.Level.<i>INFO</i></li>
* <li>warn maps to java.util.logging.Level.<i>WARNING</i></li>
* <li>error maps to java.util.logging.Level.<i>SEVERE</i></li>
* <li>fatal maps to java.util.logging.Level.<i>SEVERE</i></li>
* </ul>
*/
public class JulLogger extends RestFBLogger {
private final Logger logger;
public JulLogger(String logName) {
logger = Logger.getLogger(logName);
}
@Override
public void trace(Object msg) {
log(Level.FINER, msg, null);
}
@Override
public void trace(Object msg, Throwable thr) {
log(Level.FINER, msg, thr);
}
@Override
public void debug(Object msg) {
log(Level.FINE, msg, null);
}
@Override
public void debug(Object msg, Throwable thr) {
log(Level.FINE, msg, thr);
}
@Override
public void info(Object msg) {
log(Level.INFO, msg, null);
}
@Override
public void info(Object msg, Throwable thr) {
log(Level.INFO, msg, thr);
}
@Override
public void warn(Object msg) {
log(Level.WARNING, msg, null);
}
@Override
public void warn(Object msg, Throwable thr) {
log(Level.WARNING, msg, thr);
}
@Override
public void error(Object msg) {
log(Level.SEVERE, msg, null);
}
@Override
public void error(Object msg, Throwable thr) {
log(Level.SEVERE, msg, thr);
}
@Override
public void fatal(Object msg) {
log(Level.SEVERE, msg, null);
}
@Override
public void fatal(Object msg, Throwable thr) {
log(Level.SEVERE, msg, thr);
}
@Override
public boolean isDebugEnabled() {
return logger.isLoggable(Level.FINE);
}
@Override
public boolean isInfoEnabled() {
return logger.isLoggable(java.util.logging.Level.INFO);
}
@Override
public boolean isTraceEnabled() {
return logger.isLoggable(Level.FINER);
}
private void log(Level level, Object msg, Throwable thrown) {
if (logger.isLoggable(level)) {
LogRecord logRecord = new LogRecord(level, String.valueOf(msg));
if (thrown != null) {
logRecord.setThrown(thrown);
}
StackTraceElement[] stacktrace = new Throwable().getStackTrace();
for (StackTraceElement element : stacktrace) {
if (!element.getClassName().equals(JulLogger.class.getName())) {
logRecord.setSourceClassName(element.getClassName());
logRecord.setSourceMethodName(element.getMethodName());
break;
}
}
logRecord.setLoggerName(logger.getName());
logger.log(logRecord);
}
}
}
|
package org.jasig.portal.channels;
import org.jasig.portal.channels.BaseChannel;
import org.jasig.portal.IXMLChannel;
import org.jasig.portal.RdbmServices;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.StylesheetSet;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.GenericPortalBean;
import org.jasig.portal.Logger;
import org.jasig.portal.security.IPerson;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xalan.xslt.XSLTInputSource;
import org.apache.xalan.xslt.XSLTResultTarget;
import org.apache.xalan.xslt.XSLTProcessor;
import org.apache.xalan.xslt.XSLTProcessorFactory;
import org.xml.sax.InputSource;
import org.xml.sax.DocumentHandler;
import org.xml.sax.EntityResolver;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Enumeration;
/**
*
* @author Peter Kharchenko
* @author Steven Toth
* @author Bernie Durfee
* @version $Revision$
*/
public class CBookmarks
extends BaseChannel
{
// A DOM document where all the bookmark information will be contained
protected DocumentImpl m_bookmarksXML;
// This is the cached content
String m_cachedContent = null;
// Initialize StylesheetSet
StylesheetSet m_styleSheetSet;
// Define some constants to keep the state of the channel
private final int VIEWMODE = 0;
private final int EDITMODE = 1;
private final int EDITNODEMODE = 3;
private final int ADDNODEMODE = 4;
private final int MOVENODEMODE = 5;
private final int DELETENODEMODE = 6;
// Start out in view mode by default
private int m_currentState = 0;
// Keep track of the node that the user is currently working with
String m_activeNodeID = null;
String m_activeNodeType = null;
public CBookmarks ()
{
String fs = System.getProperty("file.separator");
// Location of the stylesheet files
String stylesheetDir = GenericPortalBean.getPortalBaseDir() + "webpages" + fs + "stylesheets" + fs + "org" + fs + "jasig" + fs + "portal" + fs + "channels" + fs + "CBookmarks" + fs;
m_styleSheetSet = new StylesheetSet(stylesheetDir + "CBookmarks.ssl");
m_styleSheetSet.setMediaProps(GenericPortalBean.getPortalBaseDir () + "properties" + fs + "media.properties");
}
private DocumentImpl getBookmarkXML()
{
Connection connection = null;
// Return the cached bookmarks if they've already been read in
if(m_bookmarksXML != null)
{
return(m_bookmarksXML);
}
try
{
String inputXML = null;
// Create a new parser for the incoming bookmarks document
DOMParser domParser = new DOMParser();
// Get a connection to the database
connection = getConnection();
// Get the current user's ID
int userid = staticData.getPerson().getID();
// Attempt to retrieve the user's bookmark's
String query = "SELECT BOOKMARK_XML, PORTAL_USER_ID FROM UPC_BOOKMARKS WHERE PORTAL_USER_ID='" + userid + "'";
// Get the result set
ResultSet rs = connection.createStatement().executeQuery(query);
if(rs.next())
{
// If a result came back then use that for the XML...
inputXML = rs.getString("BOOKMARK_XML");
}
if(inputXML == null || inputXML.length() == 0)
{
// ...or else use the bookmarks from the default user
inputXML = getDefaultBookmarks();
}
// Turn validation on for the DOM parser to make sure it reads the DTD
domParser.setFeature ("http://xml.org/sax/features/validation", true);
domParser.setEntityResolver(new org.jasig.portal.utils.DTDResolver("xbel-1.0.dtd"));
// Parse the XML document containing the user's bookmarks
domParser.parse(new InputSource (new StringReader(inputXML)));
// Cache the bookmarks DOM locally
m_bookmarksXML = (DocumentImpl)domParser.getDocument();
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
}
finally
{
// Release the database connection
if(connection != null)
{
releaseConnection(connection);
}
}
// Return what is cached
return(m_bookmarksXML);
}
private String getDefaultBookmarks()
{
Connection connection = null;
String inputXML = null;
try
{
// Get a connection to the database
connection = getConnection();
// Get the bookmarks for the 'default' user
String query = "SELECT BOOKMARK_XML, PORTAL_USER_ID FROM UPC_BOOKMARKS WHERE PORTAL_USER_ID = 0";
// Try to get the 'default' bookmarks from the database
ResultSet rs = connection.createStatement().executeQuery(query);
if(rs.next())
{
// Use the 'default' user's bookmarks...
inputXML = rs.getString("BOOKMARK_XML");
}
else
{
// Generate the XML here as a last resort
inputXML = "<?xml version=\"1.0\"?>" +
"<!DOCTYPE xbel PUBLIC \"+
"<xbel>" +
" <title>Default Bookmarks</title>" +
" <info>" +
" <metadata owner=\'" + staticData.getPerson().getID() + "\'/>" +
" </info>" +
"</xbel>";
Logger.log(Logger.WARN, "CBookmarks.getDefaultBookmarks(): Could not find bookmarks for 'default' user");
}
// Now add a row to the database for the user
String insert = "INSERT INTO UPC_BOOKMARKS (ID, PORTAL_USER_ID, BOOKMARK_XML) " +
"VALUES (" + staticData.getPerson().getID() + ", " + staticData.getPerson().getID() + ",'" + inputXML + "')";
//Logger.log(Logger.DEBUG, insert);
connection.createStatement().executeUpdate(insert);
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
}
finally
{
if(connection != null)
{
releaseConnection(connection);
}
if(inputXML == null)
{
// ...or else just start with an empty set of bookmarks
Logger.log(Logger.ERROR, "CBookmarks.getDefaultBookmarks() - Could not retrieve default bookmark xml, using blank xml.");
inputXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xbel></xbel>";
}
}
return(inputXML);
}
protected void saveXML()
{
Connection connection = null;
if(m_bookmarksXML == null)
{
return;
}
try
{
StringWriter stringWriter = new StringWriter();
// Serialize the DOM tree to a string
XMLSerializer xmlSerializer = new XMLSerializer(stringWriter, new OutputFormat(m_bookmarksXML));
xmlSerializer.serialize(m_bookmarksXML);
// Get a connection to the database
connection = getConnection();
String update = "UPDATE UPC_BOOKMARKS SET BOOKMARK_XML = '" + stringWriter.toString () + "' " +
"WHERE PORTAL_USER_ID = '" + staticData.getPerson().getID() + "'";
connection.createStatement().executeUpdate(update);
}
catch (Exception e)
{
Logger.log (Logger.ERROR,e);
}
finally
{
releaseConnection(connection);
}
}
/**
* Render the user's layout based on the current state of the channel
*/
public void renderXML(DocumentHandler out)
{
// Retrieve the command passed in by the user
String command = runtimeData.getParameter("command");
// Output the cached content if the user has not interacted
if(command == null && m_cachedContent != null)
{
outputContent(out);
return;
}
if(command != null)
{
if(command.equals("fold"))
{
// Get the ID of the specified folder to close
String folderID = runtimeData.getParameter("ID");
if(folderID != null)
{
Element folderElement = getBookmarkXML().getElementById(folderID);
if(folderElement != null && folderElement.getNodeName().equals("folder"))
{
folderElement.setAttribute("folded", "yes");
}
}
}
else
if(command.equals("unfold"))
{
// Get the ID of the specified folder to open
String folderID = runtimeData.getParameter("ID");
if(folderID != null)
{
Element folderElement = getBookmarkXML().getElementById(folderID);
if(folderElement != null && folderElement.getNodeName().equals("folder"))
{
folderElement.setAttribute("folded", "no");
}
}
}
else
if(command.equals("View"))
{
// Switch to view mode
m_currentState = VIEWMODE;
m_activeNodeID = null;
}
else
if(command.equals("Edit"))
{
// Switch to edit mode
m_currentState = EDITMODE;
m_activeNodeID = null;
}
else
if(command.equals("AddBookmark"))
{
if(m_currentState != ADDNODEMODE)
{
// Switch to add bookmark mode
m_currentState = ADDNODEMODE;
m_activeNodeID = null;
m_activeNodeType = "bookmark";
}
else
{
String submitButton = runtimeData.getParameter("SubmitButton");
if(submitButton != null && submitButton.equals("Cancel"))
{
// The user pressed the cancel button so return to view mode
m_activeNodeID = null;
m_activeNodeType = null;
m_currentState = VIEWMODE;
}
else
if(submitButton != null && submitButton.equals("Add"))
{
// Check for the incoming parameters
String bookmarkTitle = runtimeData.getParameter("BookmarkTitle");
String bookmarkURL = runtimeData.getParameter("BookmarkURL");
String bookmarkDesc = runtimeData.getParameter("BookmarkDescription");
String folderID = runtimeData.getParameter("FolderRadioButton");
if(bookmarkTitle == null || bookmarkTitle.length() < 1)
{
}
else
if(bookmarkURL == null || bookmarkURL.length() < 1)
{
}
else
if(folderID == null || folderID.length() < 1)
{
}
else
{
Element folderElement;
if(folderID.equals("RootLevel"))
{
folderElement = (Element)m_bookmarksXML.getElementsByTagName("xbel").item(0);
}
else
{
folderElement = m_bookmarksXML.getElementById(folderID);
}
if(folderElement == null)
{
}
else
{
// Build the bookmark XML DOM
Element bookmarkElement = m_bookmarksXML.createElement("bookmark");
bookmarkElement.setAttribute("href", bookmarkURL);
bookmarkElement.setAttribute("id", createUniqueID());
// Create the title element
Element titleElement = m_bookmarksXML.createElement("title");
titleElement.appendChild(m_bookmarksXML.createTextNode(bookmarkTitle));
bookmarkElement.appendChild(titleElement);
// Create the desc element
Element descElement = m_bookmarksXML.createElement("desc");
descElement.appendChild(m_bookmarksXML.createTextNode(bookmarkDesc));
bookmarkElement.appendChild(descElement);
folderElement.appendChild(bookmarkElement);
// Notify the DOM of the new ID
m_bookmarksXML.putIdentifier(bookmarkElement.getAttribute("id"), bookmarkElement);
// The user pressed the cancel button so return to view mode
m_activeNodeID = null;
m_activeNodeType = null;
// Return to view mode
m_currentState = VIEWMODE;
// Clear the content cache
m_cachedContent = null;
// Save the user's XML
saveXML();
}
}
}
}
}
else
if(command.equals("AddFolder"))
{
if(m_currentState != ADDNODEMODE)
{
// Switch to add bookmark mode
m_currentState = ADDNODEMODE;
m_activeNodeID = null;
m_activeNodeType = "folder";
}
else
{
String submitButton = runtimeData.getParameter("SubmitButton");
if(submitButton != null && submitButton.equals("Cancel"))
{
// The user pressed the cancel button so return to view mode
m_activeNodeID = null;
m_activeNodeType = null;
m_currentState = VIEWMODE;
}
else
if(submitButton != null && submitButton.equals("Add"))
{
// Check for the incoming parameters
String folderTitle = runtimeData.getParameter("FolderTitle");
String folderID = runtimeData.getParameter("FolderRadioButton");
if(folderTitle == null || folderTitle.length() < 1)
{
}
else
if(folderID == null || folderID.length() < 1)
{
}
else
{
Element folderElement;
if(folderID.equals("RootLevel"))
{
folderElement = (Element)m_bookmarksXML.getElementsByTagName("xbel").item(0);
}
else
{
folderElement = m_bookmarksXML.getElementById(folderID);
}
if(folderElement == null)
{
}
else
{
// Build the new folder XML node
Element newFolderElement = m_bookmarksXML.createElement("folder");
newFolderElement.setAttribute("id", createUniqueID());
// Create the title element
Element titleElement = m_bookmarksXML.createElement("title");
titleElement.appendChild(m_bookmarksXML.createTextNode(folderTitle));
newFolderElement.appendChild(titleElement);
folderElement.appendChild(newFolderElement);
// Notify the DOM of the new ID
m_bookmarksXML.putIdentifier(newFolderElement.getAttribute("id"), newFolderElement);
// The user pressed the cancel button so return to view mode
m_activeNodeID = null;
m_activeNodeType = null;
// Return to view mode
m_currentState = VIEWMODE;
// Clear the content cache
m_cachedContent = null;
// Save the user's XML
saveXML();
}
}
}
}
}
else
if(command.equals("MoveNode"))
{
m_activeNodeID = runtimeData.getParameter("ID");
m_currentState = MOVENODEMODE;
}
else
if(command.equals("EditNode"))
{
m_activeNodeID = runtimeData.getParameter("ID");
m_currentState = EDITNODEMODE;
}
else
if(command.equals("DeleteBookmark"))
{
if(m_currentState != DELETENODEMODE)
{
m_currentState = DELETENODEMODE;
m_activeNodeType = "bookmark";
}
else
{
String submitButton = runtimeData.getParameter("SubmitButton");
if(submitButton != null)
{
if(submitButton.equals("Cancel"))
{
m_currentState = VIEWMODE;
m_activeNodeType = null;
}
else
if(submitButton.equals("Delete"))
{
// Run through the passed in parameters and delete the bookmarks
Enumeration e = runtimeData.keys();
while(e.hasMoreElements())
{
String key = (String)e.nextElement();
if(key.startsWith("BookmarkCheckbox
{
String bookmarkID = key.substring(17);
Element bookmarkElement = m_bookmarksXML.getElementById(bookmarkID);
if(bookmarkElement != null && bookmarkElement.getNodeName().equals("bookmark"))
{
bookmarkElement.getParentNode().removeChild(bookmarkElement);
}
}
}
// Clear the content cache
m_cachedContent = null;
saveXML();
m_currentState = VIEWMODE;
m_activeNodeType = null;
}
else
if(submitButton.equals("ConfirmDelete"))
{
}
}
}
}
else
if(command.equals("DeleteFolder"))
{
if(m_currentState != DELETENODEMODE)
{
m_currentState = DELETENODEMODE;
m_activeNodeType = "folder";
}
else
{
String submitButton = runtimeData.getParameter("SubmitButton");
if(submitButton != null)
{
if(submitButton.equals("Cancel"))
{
m_currentState = VIEWMODE;
m_activeNodeType = null;
}
else
if(submitButton.equals("Delete"))
{
// Run through the passed in parameters and delete the bookmarks
Enumeration e = runtimeData.keys();
while(e.hasMoreElements())
{
String key = (String)e.nextElement();
if(key.startsWith("FolderCheckbox
{
// The ID should come after the FolderCheckbox# part
String bookmarkID = key.substring(15);
// Find the folder in the DOM tree
Element folderElement = m_bookmarksXML.getElementById(bookmarkID);
// Remove the folder from the DOM tree
if(folderElement != null && folderElement.getNodeName().equals("folder"))
{
folderElement.getParentNode().removeChild(folderElement);
}
}
}
// Clear the content cache
m_cachedContent = null;
saveXML();
m_currentState = VIEWMODE;
m_activeNodeType = null;
}
else
if(submitButton.equals("ConfirmDelete"))
{
}
}
}
}
}
try
{
// Render content based on the current state of the channel
switch(m_currentState)
{
case VIEWMODE:
renderViewModeXML(out);
break;
case EDITMODE:
renderEditModeXML(out);
break;
case EDITNODEMODE:
renderEditNodeXML(out);
break;
case ADDNODEMODE:
renderAddNodeXML(out);
break;
case MOVENODEMODE:
renderMoveNodeXML(out);
break;
case DELETENODEMODE:
renderDeleteNodeXML(out);
break;
}
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
}
}
private void renderViewModeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
transformXML(out, "view_mode", getBookmarkXML());
}
private void renderEditModeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
Hashtable parameters = new Hashtable(2);
parameters.put("NodeType", m_activeNodeType);
parameters.put("TreeMode", "EditMode");
transformXML(out, "edit_mode", getBookmarkXML(), parameters);
}
private void renderEditNodeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
Hashtable parameters = new Hashtable(2);
parameters.put("NodeType", m_activeNodeType);
parameters.put("TreeMode", "DeleteNode");
transformXML(out, "delete_node", getBookmarkXML(), parameters);
}
private void renderAddNodeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
Hashtable parameters = new Hashtable(1);
if(m_activeNodeType == null)
{
Logger.log(Logger.ERROR, "CBookmarks.renderAddNodeXML: No active node type has been set");
renderViewModeXML(out);
}
else
if(m_activeNodeType.equals("bookmark"))
{
parameters.put("EditMode", "AddBookmark");
transformXML(out, "add_node", getBookmarkXML(), parameters);
}
else
if(m_activeNodeType.equals("folder"))
{
parameters.put("EditMode", "AddFolder");
transformXML(out, "add_node", getBookmarkXML(), parameters);
}
else
{
Logger.log(Logger.ERROR, "CBookmarks.renderAddNodeXML: Unknown active node type - " + m_activeNodeType);
renderViewModeXML(out);
}
}
private void renderMoveNodeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
Hashtable parameters = new Hashtable(2);
parameters.put("NodeType", m_activeNodeType);
parameters.put("TreeMode", "MoveNode");
transformXML(out, "move_node", getBookmarkXML(), parameters);
}
private void renderDeleteNodeXML(DocumentHandler out)
throws org.xml.sax.SAXException
{
Hashtable parameters = new Hashtable(1);
if(m_activeNodeType == null)
{
Logger.log(Logger.ERROR, "CBookmarks.renderDeleteNodeXML: No active node type has been set");
renderViewModeXML(out);
}
else
if(m_activeNodeType.equals("bookmark"))
{
parameters.put("EditMode", "DeleteBookmark");
transformXML(out, "delete_node", getBookmarkXML(), parameters);
}
else
if(m_activeNodeType.equals("folder"))
{
parameters.put("EditMode", "DeleteFolder");
transformXML(out, "delete_node", getBookmarkXML(), parameters);
}
else
{
Logger.log(Logger.ERROR, "CBookmarks.renderDeleteNodeXML: Unknown active node type - " + m_activeNodeType);
renderViewModeXML(out);
}
}
private void outputContent(DocumentHandler out)
{
SAXParser saxParser = new SAXParser();
saxParser.setDocumentHandler(out);
try
{
saxParser.parse(new InputSource(new StringReader(m_cachedContent)));
}
catch(java.io.IOException ioe)
{
// Clear the cache because there's something wrong with it
m_cachedContent = null;
Logger.log(Logger.ERROR, ioe);
}
catch(org.xml.sax.SAXException se)
{
// Clear the cache because there's something wrong with it
m_cachedContent = null;
Logger.log(Logger.ERROR, se);
}
}
private void transformXML(DocumentHandler out, String styleSheetName, DocumentImpl inputXML)
{
transformXML(out, styleSheetName, inputXML, null);
}
private void transformXML(DocumentHandler out, String styleSheetName, DocumentImpl inputXML, Hashtable parameters)
{
try
{
XSLTInputSource stylesheet = m_styleSheetSet.getStylesheet(styleSheetName, runtimeData.getHttpRequest());
if(stylesheet != null)
{
StringWriter stringWriter = new StringWriter();
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
if(parameters != null)
{
Enumeration keys = parameters.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
processor.setStylesheetParam(key, processor.createXString((String)parameters.get(key)));
}
}
// Pass the baseActionURL down to the stylesheet
processor.setStylesheetParam("baseActionURL", processor.createXString(runtimeData.getBaseActionURL()));
// Pass the location of the image files down to the stylesheet
String imagesURL = "stylesheets/org/jasig/portal/channels/CBookmarks/";
processor.setStylesheetParam("imagesURL", processor.createXString(imagesURL));
// Perform the XSLT transformation and store the result in a string writer
processor.process(new XSLTInputSource(inputXML), stylesheet, new XSLTResultTarget(stringWriter));
// Cache the result of the XSLT transformation
m_cachedContent = stringWriter.toString();
// Display the content to the user
outputContent(out);
}
else
{
Logger.log (Logger.ERROR, "BookmarksChannel.processXML() - Unable to load stylesheet: " + styleSheetName);
}
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
}
}
private String createUniqueID()
{
String uniqueID = "n" + System.currentTimeMillis();
while(m_bookmarksXML.getElementById(uniqueID) != null)
{
uniqueID = "n" + System.currentTimeMillis();
}
return(uniqueID);
}
private static String makeUrlSafe(String url)
{
// Return if the url is correctly formed
if(url.toLowerCase().startsWith("http:
{
return(url);
}
// Make sure the URL is well formed
if(url.toLowerCase().startsWith("http:/"))
{
url = url.substring(0,6) + "/" + url.substring(7);
return(url);
}
// If it's a mail link then be sure mailto: is on the front
if(url.indexOf('@') != -1)
{
if(!url.toLowerCase().startsWith("mailto:"))
{
url = "mailto:" + url;
}
return(url);
}
url = "http://" + url;
return(url);
}
private Connection getConnection()
{
try
{
RdbmServices rdbmServices = new RdbmServices();
return(rdbmServices.getConnection());
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
return(null);
}
}
private void releaseConnection(Connection connection)
{
try
{
RdbmServices rdbmServices = new RdbmServices();
rdbmServices.releaseConnection(connection);
}
catch(Exception e)
{
Logger.log(Logger.ERROR, e);
}
}
}
|
package org.jfree.data.time;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.general.Series;
import org.jfree.data.general.SeriesChangeEvent;
import org.jfree.data.general.SeriesException;
import org.jfree.util.ObjectUtilities;
/**
* A structure containing zero, one or many {@link TimePeriodValue} instances.
* The time periods can overlap, and are maintained in the order that they are
* added to the collection.
* <p>
* This is similar to the {@link TimeSeries} class, except that the time
* periods can have irregular lengths.
*/
public class TimePeriodValues extends Series implements Serializable {
/** For serialization. */
static final long serialVersionUID = -2210593619794989709L;
/** Default value for the domain description. */
protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time";
/** Default value for the range description. */
protected static final String DEFAULT_RANGE_DESCRIPTION = "Value";
/** A description of the domain. */
private String domain;
/** A description of the range. */
private String range;
/** The list of data pairs in the series. */
private List data;
/** Index of the time period with the minimum start milliseconds. */
private int minStartIndex = -1;
/** Index of the time period with the maximum start milliseconds. */
private int maxStartIndex = -1;
/** Index of the time period with the minimum middle milliseconds. */
private int minMiddleIndex = -1;
/** Index of the time period with the maximum middle milliseconds. */
private int maxMiddleIndex = -1;
/** Index of the time period with the minimum end milliseconds. */
private int minEndIndex = -1;
/** Index of the time period with the maximum end milliseconds. */
private int maxEndIndex = -1;
/**
* Creates a new (empty) collection of time period values.
*
* @param name the name of the series (<code>null</code> not permitted).
*/
public TimePeriodValues(String name) {
this(name, DEFAULT_DOMAIN_DESCRIPTION, DEFAULT_RANGE_DESCRIPTION);
}
/**
* Creates a new time series that contains no data.
* <P>
* Descriptions can be specified for the domain and range. One situation
* where this is helpful is when generating a chart for the time series -
* axis labels can be taken from the domain and range description.
*
* @param name the name of the series (<code>null</code> not permitted).
* @param domain the domain description.
* @param range the range description.
*/
public TimePeriodValues(String name, String domain, String range) {
super(name);
this.domain = domain;
this.range = range;
this.data = new ArrayList();
}
/**
* Returns the domain description.
*
* @return The domain description (possibly <code>null</code>).
*
* @see #getRangeDescription()
* @see #setDomainDescription(String)
*/
public String getDomainDescription() {
return this.domain;
}
/**
* Sets the domain description and fires a property change event (with the
* property name <code>Domain</code> if the description changes).
*
* @param description the new description (<code>null</code> permitted).
*
* @see #getDomainDescription()
*/
public void setDomainDescription(String description) {
String old = this.domain;
this.domain = description;
firePropertyChange("Domain", old, description);
}
/**
* Returns the range description.
*
* @return The range description (possibly <code>null</code>).
*
* @see #getDomainDescription()
* @see #setRangeDescription(String)
*/
public String getRangeDescription() {
return this.range;
}
/**
* Sets the range description and fires a property change event with the
* name <code>Range</code>.
*
* @param description the new description (<code>null</code> permitted).
*
* @see #getRangeDescription()
*/
public void setRangeDescription(String description) {
String old = this.range;
this.range = description;
firePropertyChange("Range", old, description);
}
/**
* Returns the number of items in the series.
*
* @return The item count.
*/
public int getItemCount() {
return this.data.size();
}
/**
* Returns one data item for the series.
*
* @param index the item index (in the range <code>0</code> to
* <code>getItemCount() - 1</code>).
*
* @return One data item for the series.
*/
public TimePeriodValue getDataItem(int index) {
return (TimePeriodValue) this.data.get(index);
}
/**
* Returns the time period at the specified index.
*
* @param index the item index (in the range <code>0</code> to
* <code>getItemCount() - 1</code>).
*
* @return The time period at the specified index.
*
* @see #getDataItem(int)
*/
public TimePeriod getTimePeriod(int index) {
return getDataItem(index).getPeriod();
}
/**
* Returns the value at the specified index.
*
* @param index the item index (in the range <code>0</code> to
* <code>getItemCount() - 1</code>).
*
* @return The value at the specified index (possibly <code>null</code>).
*
* @see #getDataItem(int)
*/
public Number getValue(int index) {
return getDataItem(index).getValue();
}
/**
* Adds a data item to the series and sends a {@link SeriesChangeEvent} to
* all registered listeners.
*
* @param item the item (<code>null</code> not permitted).
*/
public void add(TimePeriodValue item) {
ParamChecks.nullNotPermitted(item, "item");
this.data.add(item);
updateBounds(item.getPeriod(), this.data.size() - 1);
fireSeriesChanged();
}
/**
* Update the index values for the maximum and minimum bounds.
*
* @param period the time period.
* @param index the index of the time period.
*/
private void updateBounds(TimePeriod period, int index) {
long start = period.getStart().getTime();
long end = period.getEnd().getTime();
long middle = start + ((end - start) / 2);
if (this.minStartIndex >= 0) {
long minStart = getDataItem(this.minStartIndex).getPeriod()
.getStart().getTime();
if (start < minStart) {
this.minStartIndex = index;
}
}
else {
this.minStartIndex = index;
}
if (this.maxStartIndex >= 0) {
long maxStart = getDataItem(this.maxStartIndex).getPeriod()
.getStart().getTime();
if (start > maxStart) {
this.maxStartIndex = index;
}
}
else {
this.maxStartIndex = index;
}
if (this.minMiddleIndex >= 0) {
long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()
.getTime();
long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()
.getTime();
long minMiddle = s + (e - s) / 2;
if (middle < minMiddle) {
this.minMiddleIndex = index;
}
}
else {
this.minMiddleIndex = index;
}
if (this.maxMiddleIndex >= 0) {
long s = getDataItem(this.maxMiddleIndex).getPeriod().getStart()
.getTime();
long e = getDataItem(this.maxMiddleIndex).getPeriod().getEnd()
.getTime();
long maxMiddle = s + (e - s) / 2;
if (middle > maxMiddle) {
this.maxMiddleIndex = index;
}
}
else {
this.maxMiddleIndex = index;
}
if (this.minEndIndex >= 0) {
long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd()
.getTime();
if (end < minEnd) {
this.minEndIndex = index;
}
}
else {
this.minEndIndex = index;
}
if (this.maxEndIndex >= 0) {
long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd()
.getTime();
if (end > maxEnd) {
this.maxEndIndex = index;
}
}
else {
this.maxEndIndex = index;
}
}
/**
* Recalculates the bounds for the collection of items.
*/
private void recalculateBounds() {
this.minStartIndex = -1;
this.minMiddleIndex = -1;
this.minEndIndex = -1;
this.maxStartIndex = -1;
this.maxMiddleIndex = -1;
this.maxEndIndex = -1;
for (int i = 0; i < this.data.size(); i++) {
TimePeriodValue tpv = (TimePeriodValue) this.data.get(i);
updateBounds(tpv.getPeriod(), i);
}
}
/**
* Adds a new data item to the series and sends a {@link SeriesChangeEvent}
* to all registered listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value.
*
* @see #add(TimePeriod, Number)
*/
public void add(TimePeriod period, double value) {
TimePeriodValue item = new TimePeriodValue(period, value);
add(item);
}
/**
* Adds a new data item to the series and sends a {@link SeriesChangeEvent}
* to all registered listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*/
public void add(TimePeriod period, Number value) {
TimePeriodValue item = new TimePeriodValue(period, value);
add(item);
}
/**
* Updates (changes) the value of a data item and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param index the index of the data item to update.
* @param value the new value (<code>null</code> not permitted).
*/
public void update(int index, Number value) {
TimePeriodValue item = getDataItem(index);
item.setValue(value);
fireSeriesChanged();
}
/**
* Deletes data from start until end index (end inclusive) and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*
* @param start the index of the first period to delete.
* @param end the index of the last period to delete.
*/
public void delete(int start, int end) {
for (int i = 0; i <= (end - start); i++) {
this.data.remove(start);
}
recalculateBounds();
fireSeriesChanged();
}
/**
* Tests the series for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TimePeriodValues)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
TimePeriodValues that = (TimePeriodValues) obj;
if (!ObjectUtilities.equal(this.getDomainDescription(),
that.getDomainDescription())) {
return false;
}
if (!ObjectUtilities.equal(this.getRangeDescription(),
that.getRangeDescription())) {
return false;
}
int count = getItemCount();
if (count != that.getItemCount()) {
return false;
}
for (int i = 0; i < count; i++) {
if (!getDataItem(i).equals(that.getDataItem(i))) {
return false;
}
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return The hashcode
*/
public int hashCode() {
int result;
result = (this.domain != null ? this.domain.hashCode() : 0);
result = 29 * result + (this.range != null ? this.range.hashCode() : 0);
result = 29 * result + this.data.hashCode();
result = 29 * result + this.minStartIndex;
result = 29 * result + this.maxStartIndex;
result = 29 * result + this.minMiddleIndex;
result = 29 * result + this.maxMiddleIndex;
result = 29 * result + this.minEndIndex;
result = 29 * result + this.maxEndIndex;
return result;
}
/**
* Returns a clone of the collection.
* <P>
* Notes:
* <ul>
* <li>no need to clone the domain and range descriptions, since String
* object is immutable;</li>
* <li>we pass over to the more general method createCopy(start, end).
* </li>
* </ul>
*
* @return A clone of the time series.
*
* @throws CloneNotSupportedException if there is a cloning problem.
*/
public Object clone() throws CloneNotSupportedException {
Object clone = createCopy(0, getItemCount() - 1);
return clone;
}
/**
* Creates a new instance by copying a subset of the data in this
* collection.
*
* @param start the index of the first item to copy.
* @param end the index of the last item to copy.
*
* @return A copy of a subset of the items.
*
* @throws CloneNotSupportedException if there is a cloning problem.
*/
public TimePeriodValues createCopy(int start, int end)
throws CloneNotSupportedException {
TimePeriodValues copy = (TimePeriodValues) super.clone();
copy.data = new ArrayList();
if (this.data.size() > 0) {
for (int index = start; index <= end; index++) {
TimePeriodValue item = (TimePeriodValue) this.data.get(index);
TimePeriodValue clone = (TimePeriodValue) item.clone();
try {
copy.add(clone);
}
catch (SeriesException e) {
System.err.println("Failed to add cloned item.");
}
}
}
return copy;
}
/**
* Returns the index of the time period with the minimum start milliseconds.
*
* @return The index.
*/
public int getMinStartIndex() {
return this.minStartIndex;
}
/**
* Returns the index of the time period with the maximum start milliseconds.
*
* @return The index.
*/
public int getMaxStartIndex() {
return this.maxStartIndex;
}
/**
* Returns the index of the time period with the minimum middle
* milliseconds.
*
* @return The index.
*/
public int getMinMiddleIndex() {
return this.minMiddleIndex;
}
/**
* Returns the index of the time period with the maximum middle
* milliseconds.
*
* @return The index.
*/
public int getMaxMiddleIndex() {
return this.maxMiddleIndex;
}
/**
* Returns the index of the time period with the minimum end milliseconds.
*
* @return The index.
*/
public int getMinEndIndex() {
return this.minEndIndex;
}
/**
* Returns the index of the time period with the maximum end milliseconds.
*
* @return The index.
*/
public int getMaxEndIndex() {
return this.maxEndIndex;
}
}
|
package io.javadog.cws.core.services;
import io.javadog.cws.api.common.ReturnCode;
import io.javadog.cws.api.requests.VerifyRequest;
import io.javadog.cws.api.responses.VerifyResponse;
import io.javadog.cws.core.enums.Permission;
import io.javadog.cws.core.model.Settings;
import io.javadog.cws.core.model.entities.SignatureEntity;
import javax.persistence.EntityManager;
import java.security.PublicKey;
import java.util.Date;
/**
* @author Kim Jensen
* @since CWS 1.0
*/
public final class VerifyService extends Serviceable<VerifyResponse, VerifyRequest> {
public VerifyService(final Settings settings, final EntityManager entityManager) {
super(settings, entityManager);
}
/**
* {@inheritDoc}
*/
@Override
public VerifyResponse perform(final VerifyRequest request) {
verifyRequest(request, Permission.VERIFY_SIGNATURE);
final String checksum = crypto.generateChecksum(request.getSignature());
final SignatureEntity entity = dao.findByChecksum(checksum);
final VerifyResponse response;
if (entity != null) {
final Date expires = entity.getExpires();
if ((expires != null) && expires.before(new Date())) {
response = new VerifyResponse(ReturnCode.SIGNATURE_WARNING, "The Signature has expired.");
} else {
final PublicKey publicKey = crypto.dearmoringPublicKey(entity.getPublicKey());
final boolean verified = crypto.verify(publicKey, request.getData(), request.getSignature());
if (verified) {
entity.setVerifications(entity.getVerifications() + 1);
dao.persist(entity);
}
response = new VerifyResponse();
response.setVerified(verified);
}
} else {
response = new VerifyResponse(ReturnCode.IDENTIFICATION_WARNING, "It was not possible to find the Signature.");
}
return response;
}
}
|
package org.pdxfinder.services;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.pdxfinder.dao.*;
import org.pdxfinder.repositories.*;
import org.pdxfinder.services.dto.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class DetailsService {
private SampleRepository sampleRepository;
private PatientRepository patientRepository;
private PatientSnapshotRepository patientSnapshotRepository;
private ModelCreationRepository modelCreationRepository;
private SpecimenRepository specimenRepository;
private MolecularCharacterizationRepository molecularCharacterizationRepository;
private PlatformRepository platformRepository;
private TreatmentSummaryRepository treatmentSummaryRepository;
private GraphService graphService;
private Map<String, List<String>> facets = new HashMap<>();
private PlatformService platformService;
private DrugService drugService;
private PatientService patientService;
private final String JAX_URL = "http://tumor.informatics.jax.org/mtbwi/pdxDetails.do?modelID=";
private final String JAX_URL_TEXT = "View data at JAX";
private final String IRCC_URL = "mailto:andrea.bertotti@unito.it?subject=";
private final String IRCC_URL_TEXT = "Contact IRCC here";
private final String PDMR_URL = "https://pdmdb.cancer.gov/pls/apex/f?p=101:41";
private final String PDMR_URL_TEXT = "View data at PDMR";
private final String HCI_URL = "";
private final String HCI_DS = "PDXNet-HCI-BCM";
private final String WISTAR_URL = "";
private final String WISTAR_DS = "PDXNet-Wistar-MDAnderson-Penn";
private final String MDA_URL = "";
private final String MDA_DS = "PDXNet-MDAnderson";
private final String WUSTL_URL = "";
private final String WUSTL_DS = "PDXNet-WUSTL";
private final static Logger log = LoggerFactory.getLogger(DetailsService.class);
public DetailsService(SampleRepository sampleRepository,
PatientRepository patientRepository,
PatientSnapshotRepository patientSnapshotRepository,
ModelCreationRepository modelCreationRepository,
SpecimenRepository specimenRepository,
MolecularCharacterizationRepository molecularCharacterizationRepository,
PlatformRepository platformRepository,
TreatmentSummaryRepository treatmentSummaryRepository,
GraphService graphService,
PlatformService platformService,
DrugService drugService,
PatientService patientService) {
this.sampleRepository = sampleRepository;
this.patientRepository = patientRepository;
this.patientSnapshotRepository = patientSnapshotRepository;
this.modelCreationRepository = modelCreationRepository;
this.molecularCharacterizationRepository = molecularCharacterizationRepository;
this.specimenRepository = specimenRepository;
this.platformRepository = platformRepository;
this.treatmentSummaryRepository = treatmentSummaryRepository;
this.graphService = graphService;
this.platformService = platformService;
this.drugService = drugService;
this.patientService = patientService;
}
public Set<String[]> getVariationDataCSV(String dataSrc, String modelId) {
Set<String[]> variationDataDTOSet = new LinkedHashSet<>();
int size = 50000, page = 0, draw=1;
String technology = "", passage="", filter="", sortDir="", sortCol="mAss.seqPosition";
//Retreive Diagnosis Information
String diagnosis = getModelDetails(dataSrc,modelId,page,size,technology,passage,filter).getDiagnosis();
// Retreive technology Information
List platforms = new ArrayList();
Map<String, Set<String>> modelTechAndPassages = findModelPlatformAndPassages(dataSrc,modelId,passage);
for (String tech : modelTechAndPassages.keySet()) {
platforms.add(tech);
}
// Retreive all Genomic Datasets
VariationDataDTO variationDataDTO = variationDataByPlatform(dataSrc,modelId,technology,passage,page,size,filter,draw,sortCol,sortDir);
for (String[] dData : variationDataDTO.moreData())
{
dData[2] = WordUtils.capitalize(diagnosis); //Histology
dData[3] = "Engrafted Tumor"; //Tumor type
variationDataDTOSet.add(dData);
}
return variationDataDTOSet;
}
public DetailsDTO getModelDetails(String dataSource, String modelId) {
return getModelDetails(dataSource, modelId, 0, 15000, "", "", "");
}
public DetailsDTO getModelDetails(String dataSource, String modelId, int page, int size, String technology, String passage, String searchFilter) {
Sample sample = sampleRepository.findByDataSourceAndPdxId(dataSource,modelId);
Patient patient = patientRepository.findByDataSourceAndModelId(dataSource,modelId);
ModelCreation pdx = modelCreationRepository.findByDataSourceAndSourcePdxId(dataSource, modelId);
List<Specimen> modelSpecimens = specimenRepository.findByDataSourceAndModelId(dataSource, modelId);
List<QualityAssurance> qa = pdx.getQualityAssurance();
int start = page;
Pageable pageable = new PageRequest(start,size);
Page<Specimen> specimens = null;
int totalRecords = 0;
totalRecords = specimenRepository.countBySearchParameterAndPlatform(dataSource,modelId,technology,passage,searchFilter);
specimens = specimenRepository.findSpecimenBySourcePdxIdAndPlatform(dataSource,modelId,technology,passage,searchFilter,pageable);
DetailsDTO dto = new DetailsDTO();
Set< List<MarkerAssociation> > markerAssociatonSet = new HashSet<>();
List<Specimen> specimenList = new ArrayList<>();
Set<MolecularCharacterization> molecularCharacterizations = new HashSet<>();
Set<Platform> platforms = new HashSet<>();
dto.setQualityAssurances(qa);
if (specimens != null) {
try {
double dSize = size;
dto.setTotalPages((int) Math.ceil(totalRecords/dSize) );
dto.setVariationDataCount(totalRecords);
}catch (Exception e){ }
}
dto.setPresentPage(page+1);
// "NOD SCID GAMA"=>"P1, P2"
Map<String, String> hostStrainMap = new HashMap<>();
for (Specimen specimen : specimens) {
try {
specimenList.add(specimen);
molecularCharacterizations.addAll(specimen.getSample().getMolecularCharacterizations());
for (MolecularCharacterization dMolkar : specimen.getSample().getMolecularCharacterizations()) {
markerAssociatonSet.add(dMolkar.getMarkerAssociations());
platforms.add(dMolkar.getPlatform());
}
}catch (Exception e){ }
}
dto.setMarkerAssociations(markerAssociatonSet);
dto.setMolecularCharacterizations(molecularCharacterizations);
dto.setPlatforms(platforms);
try {
dto.setSpecimens(specimenList);
}catch (Exception e){ }
if (sample != null && sample.getSourceSampleId() != null) {
dto.setExternalId(sample.getSourceSampleId());
}
if (patient != null && patient.getExternalId() != null) {
dto.setPatientId(patient.getExternalId());
}
if (patient != null && patient.getSex() != null) {
dto.setGender(patient.getSex());
}
if (patient != null && patient.getProviderGroup() != null) {
//dto.setContacts(patient.getExternalDataSource().getContact());
dto.setExternalDataSourceDesc(patient.getProviderGroup().getName());
}
if (patient != null && patient.getSnapshots() != null) {
for (PatientSnapshot patientSnapshot : patient.getSnapshots()) {
if (patientSnapshot != null && patientSnapshot.getAgeAtCollection() != null) {
dto.setAgeAtCollection(patientSnapshot.getAgeAtCollection());
}
}
}
if (patient != null && patient.getRace() != null) {
dto.setRace(patient.getRace());
}
if (patient != null && patient.getEthnicity() != null) {
dto.setEthnicity(patient.getEthnicity());
}
if (sample != null && sample.getDiagnosis() != null) {
dto.setDiagnosis(sample.getDiagnosis());
}
if (sample != null && sample.getType() != null) {
dto.setTumorType(sample.getType().getName());
}
if (sample != null && sample.getClassification() != null) {
dto.setClassification(sample.getClassification());
}
if (sample != null && sample.getStage() != null) {
dto.setStage( notEmpty(sample.getStage()) );
}
if (sample != null && sample.getStageClassification() != null) {
dto.setStageClassification( notEmpty(sample.getStageClassification()) );
}
if (sample != null && sample.getGrade() != null) {
dto.setGrade( notEmpty(sample.getGrade()) );
}
if (sample != null && sample.getGradeClassification() != null) {
dto.setGradeClassification( notEmpty(sample.getGradeClassification()) );
}
if (sample != null && sample.getOriginTissue() != null) {
dto.setOriginTissue(sample.getOriginTissue().getName());
}
if (sample != null && sample.getSampleSite() != null) {
dto.setSampleSite(notEmpty(sample.getSampleSite().getName()));
}
if (sample != null && sample.getSampleToOntologyRelationShip() != null) {
dto.setMappedOntology(sample.getSampleToOntologyRelationShip().getOntologyTerm().getLabel());
}
if (pdx != null && pdx.getSourcePdxId() != null) {
dto.setModelId(pdx.getSourcePdxId());
}
if(pdx!= null && pdx.getSpecimens() != null){
Set<Specimen> sp = pdx.getSpecimens();
Map<String, EngraftmentDataDTO> engraftmentDataMap = new HashMap<>();
// AGGREGATE THE ENGRAFTMENT DATA WITH CORRESPONDING PASSAGES
for(Specimen s:sp){
EngraftmentDataDTO pdxModel = new EngraftmentDataDTO();
if (s.getHostStrain() != null) {
pdxModel.setStrainName(
(s.getHostStrain() != null) ? notEmpty(s.getHostStrain().getName()) : "Not Specified"
);
pdxModel.setEngraftmentSite(
(s.getEngraftmentSite() != null) ? notEmpty(s.getEngraftmentSite().getName()) : "Not Specified"
);
pdxModel.setEngraftmentType(
(s.getEngraftmentType() != null) ? notEmpty(s.getEngraftmentType().getName()) : "Not Specified"
);
pdxModel.setEngraftmentMaterial(
(s.getEngraftmentMaterial() != null) ? notEmpty(s.getEngraftmentMaterial().getName()) : "Not Specified"
);
pdxModel.setEngraftmentMaterialState(
(s.getEngraftmentMaterial() != null) ? notEmpty(s.getEngraftmentMaterial().getState()) : "Not Specified"
);
pdxModel.setPassage(
(s.getPassage() != null) ? notEmpty(s.getPassage()) : "Not Specified"
);
String dataKey = pdxModel.getStrainName() + pdxModel.getEngraftmentSite() + pdxModel.getEngraftmentType() + pdxModel.getEngraftmentMaterial() + pdxModel.getEngraftmentMaterialState();
//if the datakey combination is found, then don't add new Engraftment data, but rather uodate the passage accordingly
if (engraftmentDataMap.containsKey(dataKey)) {
// Retrieve the existing Engraftment data fromthe Map
EngraftmentDataDTO edto = engraftmentDataMap.get(dataKey);
// Update the Passage of this existing engraftment data (and ensure no duplicate)
String newPassage = edto.getPassage().contains(pdxModel.getPassage()) ? edto.getPassage() : edto.getPassage() + "," + pdxModel.getPassage();
String[] passageArr = newPassage.split(",");
List<String> passages = new ArrayList<>(Arrays.asList(passageArr));
//order the passages:
Collections.sort(passages);
String passageString = StringUtils.join(passages, ',');
//Save the passage in the existing engraftment data AND update the Map
if(passageString.isEmpty()){
passageString = "";
}
edto.setPassage(passageString);
engraftmentDataMap.put(dataKey, edto);
} else {
// If new, save in the Map
engraftmentDataMap.put(dataKey, pdxModel);
}
}
}
// ITERATE THE "Map<String, EngraftmentDataDTO> engraftmentDataMap" MAP TO RETRIEVE THE EngraftmentDataDTO(s) into a Set
Set<EngraftmentDataDTO> pdxModels = new LinkedHashSet<>();
for (String key : engraftmentDataMap.keySet()) {
pdxModels.add(engraftmentDataMap.get(key));
}
dto.setPdxModelList(pdxModels);
}
// Unused Start:
String composedStrain = "";
if (hostStrainMap.size() > 1) {
composedStrain = hostStrainMap
.keySet()
.stream()
.map(x -> getHostStrainString(x, hostStrainMap))
.collect(Collectors.joining("; "));
} else if (hostStrainMap.size() == 1) {
for (String key : hostStrainMap.keySet()) {
composedStrain = key;
}
} else {
composedStrain = "Not Specified";
}
dto.setStrain(notEmpty(composedStrain));
// Unused Ends
if (sample != null && sample.getMolecularCharacterizations() != null) {
List<String> markerList = new ArrayList<>();
for (MolecularCharacterization mc : sample.getMolecularCharacterizations()) {
for (MarkerAssociation ma : mc.getMarkerAssociations()) {
/* if (ma.getDescription().equals("None")) {
markerList.add("None");
} else {
markerList.add(ma.getMarker().getName() + " status: " + ma.getDescription());
}*/
}
}
Collections.sort(markerList);
dto.setCancerGenomics(markerList);
}
if (pdx != null && pdx.getExternalUrls() != null) {
pdx.getExternalUrls().stream().forEach(extUrl ->{
if (extUrl.getType().equals(ExternalUrl.Type.SOURCE.getValue())){
dto.setExternalUrl(extUrl.getUrl());
}else{
dto.setContacts(extUrl.getUrl());
}
});
dto.setExternalUrlText("View Data at "+pdx.getDataSource());
}
else{
dto.setExternalUrl("
dto.setExternalUrlText("Unknown source");
}
Map<String, String> patientTech = findPatientPlatforms(dataSource, modelId);
dto.setPatientTech(patientTech);
Map<String, Set<String>> modelTechAndPassages = findModelPlatformAndPassages(dataSource, modelId, "");
dto.setModelTechAndPassages(modelTechAndPassages);
List<String> relatedModels = getModelsOriginatedFromSamePatient(dataSource, modelId);
dto.setRelatedModels(relatedModels);
List<DrugSummaryDTO> drugSummary = getDrugSummary(dataSource, modelId);
dto.setDrugSummary(drugSummary);
dto.setDrugSummaryRowNumber(drugSummary.size());
String drugProtocolUrl = drugService.getPlatformUrlByDataSource(dataSource);
dto.setDrugProtocolUrl(drugProtocolUrl);
List<VariationDataDTO> variationDataDTOList = new ArrayList<>();
dto.setVariationDataDTOList(variationDataDTOList);
Map<String, String> techNPassToSampleId = new HashMap<>();
List<Map> dataSummaryList = new ArrayList<>();
for (String tech : modelTechAndPassages.keySet()) {
//Retrieve the passages:
Set<String> passages = modelTechAndPassages.get(tech);
// Retrieve variation data by technology and passage
for (String dPassage : passages) {
VariationDataDTO variationDataDTO = variationDataByPlatform(dataSource, modelId, tech, dPassage, page, size, "", 1, "mAss.seqPosition", "");
variationDataDTOList.add(variationDataDTO);
// Aggregate sampleIds for this Technology and passage in a Set<String>, to remove duplicates
Set<String> sampleIDSet = new HashSet<>();
for (String[] data : variationDataDTO.getData()) {
sampleIDSet.add(data[0]);
}
// Turn the Set<String> to a comma seperated String
String sampleIDs = "";
for (String sampleID : sampleIDSet) {
sampleIDs += sampleID + ",";
Map<String, String> dataSummary = new HashMap<>();
dataSummary.put("sampleId", sampleID);
dataSummary.put("sampleType", "Engrafted Tumor");
dataSummary.put("xenograftPassage",dPassage);
dataSummary.put("dataAvailable","Mutation_"+tech);
dataSummary.put("platformUsed",tech);
dataSummary.put("rawData","Not Available");
dataSummaryList.add(dataSummary);
}
// Create a Key Value map of (Technology+Passage , sampleIDs) and Pass to DTO
techNPassToSampleId.put(tech + dPassage, StringUtils.stripEnd(sampleIDs, ","));
// SampleType - Engrafted Tumor
// XenograftPassage - dPassage
// DataAvailable -
// PlatformUsed - tech
// RawData -
}
}
dto.setDataSummary(dataSummaryList);
dto.setTechNPassToSampleId(techNPassToSampleId);
Set<String> autoSuggestList = graphService.getMappedNCITTerms();
dto.setAutoSuggestList(autoSuggestList);
Map<String, String> platformsAndUrls = platformService.getPlatformsWithUrls();
dto.setPlatformsAndUrls(platformsAndUrls);
Map<String, String> sorceDesc = new HashMap<>();
sorceDesc.put("JAX","The Jackson Laboratory");
sorceDesc.put("PDXNet-HCI-BCM","HCI-Baylor College of Medicine");
sorceDesc.put("PDXNet-Wistar-MDAnderson-Penn","Melanoma PDX established by the Wistar/MD Anderson/Penn");
sorceDesc.put("PDXNet-WUSTL","Washington University in St. Louis");
sorceDesc.put("PDXNet-MDAnderson","University of Texas MD Anderson Cancer Center");
sorceDesc.put("PDMR","NCI Patient-Derived Models Repository");
sorceDesc.put("IRCC","Candiolo Cancer Institute");
if (sample != null && sample.getDataSource() != null) {
dto.setDataSource(sample.getDataSource());
dto.setSourceDescription(sorceDesc.get(sample.getDataSource()));
}
// Retrive Patint Information:
PatientDTO patientDTO = patientService.getPatientDetails(dataSource, modelId);
dto.setPatient(patientDTO);
return dto;
}
/**
* Return a formatted string representing the host and passage
* @param hostStrain the key to the map of host strains
* @param hostStrainMap the map containing all the host strains associated to the model
* @return a formatted string representing the host strains
*/
private String getHostStrainString(String hostStrain, Map<String, String> hostStrainMap) {
String passage = hostStrainMap.get(hostStrain).equals("Not Specified") ? "" : "(" + hostStrainMap.get(hostStrain) + ")";
String formatted = String.format("%s%s", hostStrain, passage);
return formatted;
}
public Map findPatientPlatforms(String dataSource, String modelId){
Map<String, String> platformMap = new HashMap<>();
List<MolecularCharacterization> molecularCharacterizations = molecularCharacterizationRepository.findPatientPlatformByModelId(dataSource,modelId);
for (MolecularCharacterization mc : molecularCharacterizations) {
if(mc.getPlatform() != null){
platformMap.put(mc.getPlatform().getName(), mc.getPlatform().getName());
}
}
return platformMap;
}
public Map<String, Set<String>> findModelPlatformAndPassages(String dataSource, String modelId,String passage){
/**
* Used to store a technology String with their respective List of PDX Passages
*/
Map<String, Set<String>> platformMap = new HashMap<>();
/**
* Retrieve all the technologies for that mouse model
*/
List<Platform> platforms = platformRepository.findModelPlatformByModelId(dataSource,modelId);
/**
* For each of the technologies retrieve the list of PDX passages using the specimen repository
*/
for (Platform platform : platforms) {
List<Specimen> specimens = specimenRepository.findSpecimenBySourcePdxIdAndPlatform2(dataSource,modelId,platform.getName());
Set<String> passagesList = new HashSet<>();
for (Specimen specimen : specimens)
{
passagesList.add(specimen.getPassage()+"");
}
platformMap.put(platform.getName(), passagesList);
}
return platformMap;
}
public List<String> getModelsOriginatedFromSamePatient(String dataSource, String modelId) {
return patientRepository.getModelsOriginatedFromSamePatientByDataSourceAndModelId(dataSource, modelId);
}
public List<DrugSummaryDTO> getDrugSummary(String dataSource, String modelId) {
TreatmentSummary ts = treatmentSummaryRepository.findModelTreatmentByDataSourceAndModelId(dataSource, modelId);
List<DrugSummaryDTO> results = new ArrayList<>();
if (ts != null && ts.getTreatmentProtocols() != null) {
for (TreatmentProtocol tp : ts.getTreatmentProtocols()) {
DrugSummaryDTO dto = new DrugSummaryDTO();
dto.setDrugName(tp.getDrugString(true));
List<TreatmentComponent> components = tp.getComponents();
String dose = "";
if(components.size()>0){
for(TreatmentComponent tc : components){
if(!dose.equals("")){
dose += " / ";
}
dose += tc.getDose();
}
}
dto.setDose(dose);
if (tp.getResponse() != null && tp.getResponse().getDescription() != null) {
dto.setResponse(tp.getResponse().getDescription());
} else {
dto.setResponse("");
}
results.add(dto);
}
}
return results;
}
public VariationDataDTO patientVariationDataByPlatform(String dataSource, String modelId, String technology,
String searchParam, int draw, String sortColumn, String sortDir, int start, int size) {
//int recordsTotal = patientRepository.countByBySourcePdxIdAndPlatform(dataSource,modelId,technology,"");
int recordsTotal = modelCreationRepository.variationCountByDataSourceAndPdxIdAndPlatform(dataSource, modelId, technology, "");
int recordsFiltered = recordsTotal;
if (!searchParam.isEmpty()) {
recordsFiltered = modelCreationRepository.variationCountByDataSourceAndPdxIdAndPlatform(dataSource, modelId, technology, searchParam);
}
/**
* Retrieve the Records based on search parameter
*/
ModelCreation model = modelCreationRepository.findVariationBySourcePdxIdAndPlatform(dataSource, modelId, technology, searchParam, start, size);
VariationDataDTO variationDataDTO = new VariationDataDTO();
List<String[]> variationData = new ArrayList<>();
if (model != null && model.getSample() != null) {
variationData.addAll(buildUpDTO(model.getSample(), "", draw, recordsTotal, recordsFiltered));
}
variationDataDTO.setDraw(draw);
variationDataDTO.setRecordsTotal(recordsTotal);
variationDataDTO.setRecordsFiltered(recordsFiltered);
variationDataDTO.setData(variationData);
return variationDataDTO;
}
public VariationDataDTO variationDataByPlatform(String dataSource, String modelId, String technology, String passage, int start, int size,
String searchParam, int draw, String sortColumn, String sortDir) {
/**
* Set the Pagination parameters: start comes in as 0,10,20 e.t.c while pageable works in page batches 0,1,2,...
*/
Sort.Direction direction = getSortDirection(sortDir);
Pageable pageable = new PageRequest(start, size, direction, sortColumn);
/**
* 1st count all the records and set Total Records & Initialize Filtered Record as Total record
*/
//int recordsTotal = specimenRepository.countBySearchParameterAndPlatform(dataSource,modelId,technology,passage,"");
int recordsTotal = specimenRepository.countByPlatform(dataSource, modelId, technology, passage);
int recordsFiltered = recordsTotal;
/**
* If search Parameter is not empty: Count and Reset the value of filtered records based on search Parameter
*/
if (!searchParam.isEmpty()) {
recordsFiltered = specimenRepository.countBySearchParameterAndPlatform(dataSource, modelId, technology, passage, searchParam);
}
/**
* Retrieve the Records based on search parameter
*/
Page<Specimen> specimens = specimenRepository.findSpecimenBySourcePdxIdAndPlatform(dataSource, modelId, technology, passage, searchParam, pageable);
VariationDataDTO variationDataDTO = new VariationDataDTO();
List<String[]> variationData = new ArrayList();
if (specimens != null) {
for (Specimen specimen : specimens) {
variationData.addAll(buildUpDTO(specimen.getSample(), specimen.getPassage(), draw, recordsTotal, recordsFiltered));
}
}
variationDataDTO.setDraw(draw);
variationDataDTO.setRecordsTotal(recordsTotal);
variationDataDTO.setRecordsFiltered(recordsFiltered);
variationDataDTO.setData(variationData);
return variationDataDTO;
}
public List<String[]> buildUpDTO(Sample sample,String passage,int draw,int recordsTotal,int recordsFiltered){
List<String[]> variationData = new LinkedList<>();
/**
* Generate an equivalent 2-D array type of the Retrieved result Set, the Front end table must be a 2D JSON Array
*/
try {
for (MolecularCharacterization dMolChar : sample.getMolecularCharacterizations()) {
List<MarkerAssociation> markerAssociation = new ArrayList();// = dMolChar.getMarkerAssociations();
markerAssociation.addAll(dMolChar.getMarkerAssociations());
for (MarkerAssociation markerAssoc : markerAssociation) {
String[] markerAssocArray = new String[13];
markerAssocArray[0] = sample.getSourceSampleId();
markerAssocArray[1] = markerAssoc.getChromosome();
markerAssocArray[2] = markerAssoc.getSeqPosition();
markerAssocArray[3] = markerAssoc.getRefAllele();
markerAssocArray[4] = markerAssoc.getAltAllele();
markerAssocArray[5] = markerAssoc.getConsequence();
markerAssocArray[6] = markerAssoc.getMarker().getSymbol();
markerAssocArray[7] = markerAssoc.getAminoAcidChange();
markerAssocArray[8] = markerAssoc.getReadDepth();
markerAssocArray[9] = markerAssoc.getAlleleFrequency();
markerAssocArray[10] = markerAssoc.getRsVariants();
markerAssocArray[11] = dMolChar.getPlatform().getName();
markerAssocArray[12] = passage;
//markerAssocArray[13] = sample.getDiagnosis();
// markerAssocArray[14] = sample.getType().getName();
variationData.add(markerAssocArray);
}
}
}catch (Exception e) { }
return variationData;
}
public Sort.Direction getSortDirection(String sortDir){
Sort.Direction direction = Sort.Direction.ASC;
if (sortDir.equals("desc")){
direction = Sort.Direction.DESC;
}
return direction;
}
public String notEmpty(String incoming){
String result = (incoming == null) ? "Not Specified" : incoming;
result = result.equals("null") ? "Not Specified" : result;
result = result.length() == 0 ? "Not Specified" : result;
result = result.equals("Unknown") ? "Not Specified" : result;
return result;
}
}
|
package roart.client;
import roart.config.ConfigTreeMap;
import roart.model.GUISize;
import roart.model.ResultItemBytes;
import roart.model.ResultItemTable;
import roart.model.ResultItemTableRow;
import roart.model.ResultItemText;
import roart.model.ResultItem;
import roart.util.Constants;
import roart.service.ControlService;
import java.sql.Timestamp;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
//import roart.beans.session.misc.Unit;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.Image;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Link;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.InlineDateField;
import com.vaadin.ui.PopupDateField;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Container;
import com.vaadin.data.Container.ItemSetChangeListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TabSheet;
import com.vaadin.server.FileResource;
import com.vaadin.server.StreamResource;
import com.vaadin.server.StreamResource.StreamSource;
import com.vaadin.server.FileDownloader;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.themes.BaseTheme;
import com.vaadin.ui.Window;
import com.vaadin.annotations.Push;
import com.vaadin.shared.communication.PushMode;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.server.Sizeable;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.math3.util.Pair;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
@Push
//@Theme("mytheme")
@Theme("valo")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI
{
private static Logger log = LoggerFactory.getLogger(MyVaadinUI.class);
//private static final Logger log = LoggerFactory.getLogger(MyVaadinUI.class);
/*
horMisc.addComponent(getMove());
HorizontalLayout horMACD = new HorizontalLayout();
horMACD.setHeight("20%");
horMACD.setWidth("90%");
horMACD.addComponent(getMACD());
horMACD.addComponent(getMACDDelta());
horMACD.addComponent(getMACDHistogramDelta());
HorizontalLayout horRSI = new HorizontalLayout();
horRSI.setHeight("20%");
horRSI.setWidth("90%");
horRSI.addComponent(getRSI());
horRSI.addComponent(getRSIDelta());
*/
// not yet
/*
horMACD.addComponent(getCCI());
horMACD.addComponent(getCCIDelta());
horMACD.addComponent(getATR());
horMACD.addComponent(getATRDelta());
horMACD.addComponent(getSTOCH());
horMACD.addComponent(getSTOCHDelta());
horRSI.addComponent(getSTOCHRSI());
horRSI.addComponent(getSTOCHRSIDelta());
*/
HorizontalLayout horStat = new HorizontalLayout();
horStat.setHeight("20%");
horStat.setWidth("90%");
horStat.addComponent(new Label("b1"));
VerticalLayout v1 = new VerticalLayout();
horStat.addComponent(v1);
v1.addComponent(new Label("b2"));
HorizontalLayout h1 = new HorizontalLayout();
v1.addComponent(h1);
h1.addComponent(new Label("b3"));
VerticalLayout v2 = new VerticalLayout();
h1.addComponent(v2);
v2.addComponent(new Label("b4"));
//horStat.addComponent(getOverlapping());
HorizontalLayout horDb = new HorizontalLayout();
horDb.setHeight("20%");
horDb.setWidth("60%");
/*
tab.addComponent(getCleanup());
tab.addComponent(getCleanup2());
tab.addComponent(getCleanupfs());
*/
HorizontalLayout horTree = new HorizontalLayout();
ConfigTreeMap map2 = controlService.conf.configTreeMap;
componentMap = new HashMap<>();
print(map2, horTree);
tab.addComponent(horMisc);
//tab.addComponent(horMACD);
//tab.addComponent(horRSI);
tab.addComponent(horStat);
tab.addComponent(horDb);
tab.addComponent(horTree);
/*
HorizontalLayout bla2 = new HorizontalLayout();
tab.addComponent(bla2);
JFreeChart c = SvgUtil.bla();
//OutputStream out = null;
//InputStream in = null
StreamResource resource = SvgUtil.chartToResource(c, "/tmp/svg.svg");
SvgUtil.bla2(bla2, resource);
SvgUtil.bla3(tab, resource);
SvgUtil.bla4(tab);
SvgUtil.bla5(tab, resource);
*/
return tab;
}
Map<String, Component> componentMap ;
private void print(ConfigTreeMap map2, HorizontalLayout tab) {
Map<String, Object> map = controlService.conf.configValueMap;
String name = map2.getName();
System.out.println("name " + name);
Object object = map.get(name);
Component o = null;
String text = controlService.conf.text.get(name);
if (object == null) {
//System.out.println("null for " + name);
String labelname = name;
int last = name.lastIndexOf(".");
if (last >=0) {
labelname = name.substring(last + 1);
}
o = new Label(labelname + " ");
tab.addComponent(o);
componentMap.put(name, o);
} else {
switch (object.getClass().getName()) {
case "java.lang.String":
o = getStringField(text, name);
break;
case "java.lang.Double":
o = getDoubleField(text, name);
break;
case "java.lang.Integer":
o = getIntegerField(text, name);
break;
case "java.lang.Boolean":
o = getCheckbox(text, name);
break;
default:
System.out.println("unknown " + object.getClass().getName());
log.info("unknown " + object.getClass().getName());
}
tab.addComponent(o);
componentMap.put(name, o);
}
//System.out.print(space.substring(0, indent));
//System.out.println("map2 " + map2.name + " " + map2.enabled);
Map<String, ConfigTreeMap> map3 = map2.getConfigTreeMap();
if (!map3.keySet().isEmpty()) {
VerticalLayout h = new VerticalLayout();
tab.addComponent(h);
h.addComponent(new Label(">"));
HorizontalLayout n1 = new HorizontalLayout();
h.addComponent(n1);
n1.addComponent(new Label(">"));
VerticalLayout h1 = new VerticalLayout();
n1.addComponent(h1);
for (String key : map3.keySet()) {
System.out.println("key " + key);
HorizontalLayout n = new HorizontalLayout();
h1.addComponent(n);
print(map3.get(key), n);
//Object value = map.get(key);
//System.out.println("k " + key + " " + value + " " + value.getClass().getName());
}
}
}
private VerticalLayout getConfigTab() {
boolean isProductionMode = VaadinService.getCurrent()
.getDeploymentConfiguration().isProductionMode();
String DELIMITER = " = ";
VerticalLayout tab = new VerticalLayout();
tab.setCaption("Configuration");
HorizontalLayout hor = new HorizontalLayout();
hor.setHeight("20%");
hor.setWidth("90%");
/*
if (!isProductionMode) {
hor.addComponent(getDbEngine());
}
*/
tab.addComponent(hor);
return tab;
}
private VerticalLayout getSearchTab() {
//displayResults(new ControlService());
VerticalLayout tab = new VerticalLayout();
tab.setCaption("Search");
HorizontalLayout horNewInd = new HorizontalLayout();
horNewInd.setHeight("20%");
horNewInd.setWidth("90%");
HorizontalLayout horStat = new HorizontalLayout();
horStat.setHeight("20%");
horStat.setWidth("90%");
horStat.addComponent(getDate());
horStat.addComponent(getResetDate());
horStat.addComponent(getMarket());
horStat.addComponent(getStat());
//horStat.addComponent(getOverlapping());
HorizontalLayout horDb = new HorizontalLayout();
horDb.setHeight("20%");
horDb.setWidth("60%");
//horDb.addComponent(getDbItem());
horDb.addComponent(getMarkets());
HorizontalLayout horDb2 = new HorizontalLayout();
horDb2.setHeight("20%");
horDb2.setWidth("60%");
//horDb.addComponent(getDbItem());
/*
horDb2.addComponent(getDays());
horDb2.addComponent(getTableDays());
horDb2.addComponent(getTableIntervalDays());
horDb2.addComponent(getTopBottom());
HorizontalLayout horMACD = new HorizontalLayout();
horMACD.setHeight("20%");
horMACD.setWidth("90%");
horMACD.addComponent(getMACDDeltaDays());
horMACD.addComponent(getMACDHistogramDeltaDays());
*/
// not yet:
/*
horDb2.addComponent(getATRDeltaDays());
horDb2.addComponent(getCCIDeltaDays());
horDb2.addComponent(getSTOCHDeltaDays());
*/
/*
HorizontalLayout horRSI = new HorizontalLayout();
horRSI.setHeight("20%");
horRSI.setWidth("90%");
horRSI.addComponent(getRSIDeltaDays());
horRSI.addComponent(getSTOCHRSIDeltaDays());
HorizontalLayout horDb3 = new HorizontalLayout();
horDb3.setHeight("20%");
horDb3.setWidth("60%");
horDb3.addComponent(getTableMoveIntervalDays());
*/
/*
horDb3.addComponent(getTodayZero());
*/
//horDb3.addComponent(getEqualize());
VerticalLayout verManualList = new VerticalLayout();
verManualList.setHeight("20%");
verManualList.setWidth("60%");
HorizontalLayout horTester = new HorizontalLayout();
horTester.setHeight("20%");
horTester.setWidth("60%");
horTester.addComponent(getTestRecommender(false));
horTester.addComponent(getTestRecommender(true));
HorizontalLayout horManual = new HorizontalLayout();
horManual.setHeight("20%");
horManual.setWidth("60%");
//horDb.addComponent(getDbItem());
horManual.addComponent(getMarkets2(horManual, verManualList));
HorizontalLayout horChooseGraph = new HorizontalLayout();
horChooseGraph.setHeight("20%");
horChooseGraph.setWidth("60%");
//horDb.addComponent(getDbItem());
//horChooseGraph.addComponent(getEqualizeGraph());
//horChooseGraph.addComponent(getEqualizeUnify());
horChooseGraph.addComponent(getChooseGraph(verManualList));
//tab.addComponent(horNewInd);
tab.addComponent(horStat);
tab.addComponent(horDb);
tab.addComponent(horDb2);
//tab.addComponent(horDb3);
//tab.addComponent(horMACD);
//tab.addComponent(horRSI);
tab.addComponent(horManual);
tab.addComponent(verManualList);
tab.addComponent(horChooseGraph);
tab.addComponent(horTester);
return tab;
}
private InlineDateField getDate() {
InlineDateField tf = new InlineDateField("Set comparison date");
// Create a DateField with the default style
// Set the date and time to present
Date date = new Date();
// temp fix
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
tf.setValue(date);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
Date date = (Date) event.getProperty().getValue();
// Do something with the value
long time = date.getTime();
// get rid of millis garbage
time = time / 1000;
time = time * 1000;
date = new Date(time);
try {
controlService.conf.setdate(date);
Notification.show("Request sent");
//displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private Button getResetDate() {
Button button = new Button("Reset date");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
controlService.conf.setdate(null);
Notification.show("Request sent");
//displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
return button;
}
private Button getTestRecommender(boolean doSet) {
String set = "";
if (doSet) {
set = "and set";
}
Button button = new Button("Test recommender" + set);
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
Notification.show("Request sent");
List<ResultItem> list = controlService.getTestRecommender(doSet);
log.info("listsize " + list.size());
VerticalLayout layout = new VerticalLayout();
layout.setCaption("Results");
displayResultListsTab(layout, list);
tabsheet.addComponent(layout);
tabsheet.getTab(layout).setClosable(true);
if (doSet) {
VerticalLayout newComponent = getControlPanelTab();
tabsheet.replaceComponent(controlPanelTab, newComponent);
controlPanelTab = newComponent;
}
Notification.show("New result available");
//displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
return button;
}
private Button getMarket() {
Button button = new Button("Get market data");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
return button;
}
private Button getStat() {
Button button = new Button("Get stats");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
Notification.show("Request sent");
displayResultsStat();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
return button;
}
private ListSelect getMarkets() {
ListSelect ls = new ListSelect("Get market");
Set<String> marketSet = null;
try {
List<String> markets = controlService.getMarkets();
markets.remove(null);
marketSet = new TreeSet<String>(markets);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return ls;
}
log.info("languages " + marketSet);
if (marketSet == null ) {
return ls;
}
ls.addItems(marketSet);
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMarket(value);
Notification.show("Request sent");
//displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
Set<Pair<String, String>> chosen = new HashSet<>();
private Button getChooseGraph(VerticalLayout ver) {
Button button = new Button("Choose graph");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
Notification.show("Request sent");
displayResultsGraph(chosen);
chosen.clear();
ver.removeAllComponents();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
return button;
}
private ListSelect getMarkets2(HorizontalLayout horManual, VerticalLayout verManualList) {
ListSelect ls = new ListSelect("Market");
Set<String> marketSet = null;
try {
List<String> markets = controlService.getMarkets();
markets.remove(null);
marketSet = new TreeSet<String>(markets);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return ls;
}
log.info("languages " + marketSet);
if (marketSet == null ) {
return ls;
}
ls.addItems(marketSet);
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
ListSelect ls2 = getUnits(value, ls, verManualList);
horManual.addComponent(ls2);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
private ListSelect getUnits(String market, ListSelect ls2, VerticalLayout verManualList) {
ListSelect ls = new ListSelect("Units");
Set<String> stockSet = null;
System.out.println("m " + market);
final Map<String, String> stockMap = controlService.getStocks(market);
log.info("stocks " + stockSet);
if (stockSet == null ) {
return ls;
}
ls.addItems(stockSet);
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
String id = null;
for (String stockid : stockMap.keySet()) {
String stockname = stockMap.get(stockid);
if (value.equals(stockname)) {
id = stockid;
break;
}
}
Pair pair = new Pair(market, id);
chosen.add(pair);
verManualList.addComponent(new Label(market + " " + id + " " + value));
ComponentContainer parent = (ComponentContainer) ls.getParent();
parent.removeComponent(ls);
System.out.println("value " +value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
/*
private TextField getDays() {
TextField tf = new TextField("Single interval days");
tf.setValue("" + controlService.conf.getDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getMACDHistogramDeltaDays() {
TextField tf = new TextField("MACD histogram delta days");
tf.setValue("" + controlService.conf.getMACDHistogramDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMACDHistogramDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getMACDDeltaDays() {
TextField tf = new TextField("MACD delta days");
tf.setValue("" + controlService.conf.getMACDDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMACDDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getRSIDeltaDays() {
TextField tf = new TextField("RSI delta days");
tf.setValue("" + controlService.conf.getRSIDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setRSIDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getSTOCHRSIDeltaDays() {
TextField tf = new TextField("STOCH RSI delta days");
tf.setValue("" + controlService.conf.getSTOCHRSIDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHRSIDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getCCIDeltaDays() {
TextField tf = new TextField("CCI delta days");
tf.setValue("" + controlService.conf.getCCIDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setCCIDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getATRDeltaDays() {
TextField tf = new TextField("ATR delta days");
tf.setValue("" + controlService.conf.getATRDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setATRDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getSTOCHDeltaDays() {
TextField tf = new TextField("STOCH delta days");
tf.setValue("" + controlService.conf.getATRDeltaDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHDeltaDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getTableIntervalDays() {
TextField tf = new TextField("Table interval days");
tf.setValue("" + controlService.conf.getTableIntervalDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setTableIntervalDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getTableMoveIntervalDays() {
TextField tf = new TextField("Table move interval days");
tf.setValue("" + controlService.conf.getTableMoveIntervalDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setTableMoveIntervalDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getTableDays() {
TextField tf = new TextField("Table days");
tf.setValue("" + controlService.conf.getTableDays());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setTableDays(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getTopBottom() {
TextField tf = new TextField("Table top/bottom");
tf.setValue("" + controlService.conf.getTopBottom());
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setTopBottom(new Integer(value));
Notification.show("Request sent");
displayResults();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
*/
private void displayResults() {
controlService.getContent(this);
/*
log.info("listsize " + list.size());
VerticalLayout layout = new VerticalLayout();
layout.setCaption("Results");
displayResultListsTab(layout, list);
List listGraph = controlService.getContentGraph(guiSize);
displayResultListsTab(layout, listGraph);
tabsheet.addComponent(layout);
tabsheet.getTab(layout).setClosable(true);
Notification.show("New result available");
*/
}
private void displayResultsStat() {
List list = controlService.getContentStat();
VerticalLayout layout = new VerticalLayout();
layout.setCaption("Results");
displayResultListsTab(layout, list);
tabsheet.addComponent(layout);
tabsheet.getTab(layout).setClosable(true);
Notification.show("New result available");
}
private void displayResultsGraph(Set<Pair<String, String>> ids) {
VerticalLayout layout = new VerticalLayout();
layout.setCaption("Graph results");
tabsheet.addComponent(layout);
tabsheet.getTab(layout).setClosable(true);
List listGraph = controlService.getContentGraph(ids, guiSize);
displayResultListsTab(layout, listGraph);
tabsheet.addComponent(layout);
tabsheet.getTab(layout).setClosable(true);
Notification.show("New result available");
}
private StreamResource getStreamResource(byte[] bytes) {
//System.out.println("bytes " + bytes.length + " "+ new String(bytes));
//System.out.println("size " + (300 + 10 * xsize) + " " + (400 + 10 * ysize));
StreamResource resource = new StreamResource(new StreamSource() {
@Override
public InputStream getStream() {
try {
return new ByteArrayInputStream(bytes);
} catch (Exception e) {
//log.error(Constants.EXCEPTION, e);
return null;
}
}
}, "/tmp/svg3.svg");
return resource;
}
protected void addListStream(Layout layout, ResultItemBytes item) {
byte[] bytes = item.bytes;
//SvgUtil. bla3(layout, resource);
//SvgUtil. bla5(layout, resource);
//if (true) continue;
StreamResource resource = getStreamResource(bytes);
Image image = new Image ("Image", resource);
//Embedded image = new Embedded("1", img);
int xsize = 100 + 300 + 10 * 120 /*controlService.conf.getTableDays()*/;
int ysize = 200 + 400 + 10 * 10 /*controlService.conf.getTopBottom()*/;
//System.out.println("xys1 " + xsize + " " + ysize);
if (xsize + 100 > guiSize.x) {
xsize = guiSize.x - 100;
}
/*
if (ysize + 200 > y) {
ysize = y - 200;
}
*/
//System.out.println("xys2 " + xsize + " " + ysize);
/*
InputStream is = new ByteArrayInputStream(bytes);
try {
BufferedImage anImage = ImageIO.read(is);
if (anImage != null) {
xsize = anImage.getWidth();
ysize = anImage.getHeight();
}
System.out.println("sizeme " + xsize + " " + ysize);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
*/
// TODO matching svgutil change
xsize = 1024;
ysize = 768;
if (!item.fullsize) {
ysize = 384;
}
image.setHeight(ysize, Sizeable.Unit.PIXELS );
image.setWidth(xsize, Sizeable.Unit.PIXELS );
layout.addComponent(image);
}
/*
private CheckBox getEqualize() {
CheckBox cb = new CheckBox("Equalize sample sets");
cb.setValue(controlService.conf.isEqualize());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setEqualize(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
*/
private CheckBox getCheckbox(String text, String configKey) {
CheckBox cb = new CheckBox(text);
Boolean origValue = (Boolean) controlService.conf.configValueMap.get(configKey);
cb.setValue(origValue);
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.configValueMap.put(configKey, value );
// TODO handle hiding
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private TextField getStringField(String text, String configKey) {
TextField tf = new TextField(text);
String origValue = (String) controlService.conf.configValueMap.get(configKey);
tf.setValue(origValue);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.configValueMap.put(configKey, value );
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getIntegerField(String text, String configKey) {
TextField tf = new TextField(text);
Integer origValue = (Integer) controlService.conf.configValueMap.get(configKey);
tf.setValue("" + origValue);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.configValueMap.put(configKey, new Integer(value) );
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
private TextField getDoubleField(String text, String configKey) {
TextField tf = new TextField(text);
Double origValue = (Double) controlService.conf.configValueMap.get(configKey);
tf.setValue("" + origValue);
// Handle changes in the value
tf.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.configValueMap.put(configKey, new Double(value) );
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
tf.setImmediate(true);
return tf;
}
/*
private CheckBox getMove() {
CheckBox cb = new CheckBox("Enable chart move");
cb.setValue(controlService.conf.isMoveEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMoveEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getMACD() {
CheckBox cb = new CheckBox("Enable MACD");
cb.setValue(controlService.conf.isMACDEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMACDEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getMACDDelta() {
CheckBox cb = new CheckBox("Enable MACD delta");
cb.setValue(controlService.conf.isMACDDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMACDDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getMACDHistogramDelta() {
CheckBox cb = new CheckBox("Enable MACD histogram delta");
cb.setValue(controlService.conf.isMACDHistogramDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setMACDHistogramDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getRSIDelta() {
CheckBox cb = new CheckBox("Enable RSI delta");
cb.setValue(controlService.conf.isRSIDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setRSIDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getSTOCHRSIDelta() {
CheckBox cb = new CheckBox("Enable STOCH RSI delta (caution)");
cb.setValue(controlService.conf.isSTOCHRSIDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHRSIDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getCCIDelta() {
CheckBox cb = new CheckBox("Enable CCI delta");
cb.setValue(controlService.conf.isCCIDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setCCIDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getATRDelta() {
CheckBox cb = new CheckBox("Enable ATR delta");
cb.setValue(controlService.conf.isATRDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setATRDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getSTOCHDelta() {
CheckBox cb = new CheckBox("Enable STOCH delta");
cb.setValue(controlService.conf.isSTOCHDeltaEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHDeltaEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getRSI() {
CheckBox cb = new CheckBox("Enable RSI");
cb.setValue(controlService.conf.isRSIEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setRSIEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getSTOCHRSI() {
CheckBox cb = new CheckBox("Enable STOCH RSI");
cb.setValue(controlService.conf.isSTOCHRSIEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHRSIEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getCCI() {
CheckBox cb = new CheckBox("Enable CCI");
cb.setValue(controlService.conf.isCCIEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setCCIEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getATR() {
CheckBox cb = new CheckBox("Enable ATR");
cb.setValue(controlService.conf.isATREnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setATREnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getSTOCH() {
CheckBox cb = new CheckBox("Enable STOCH");
cb.setValue(controlService.conf.isSTOCHEnabled());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setSTOCHEnabled(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getEqualizeGraph() {
CheckBox cb = new CheckBox("Equalize graphic table");
cb.setValue(controlService.conf.isGraphEqualize());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setGraphEqualize(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private CheckBox getEqualizeUnify() {
CheckBox cb = new CheckBox("Equalize merge price and index table");
cb.setValue(controlService.conf.isGraphEqUnify());
// Handle changes in the value
cb.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
boolean value = (Boolean) event.getProperty().getValue();
// Do something with the value
try {
controlService.conf.setGraphEqUnify(value);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
cb.setImmediate(true);
return cb;
}
private ListSelect getDbEngine() {
ListSelect ls = new ListSelect("Select search engine");
String[] engines = ConfigConstants.dbvalues;
ls.addItems(engines);
ls.setNullSelectionAllowed(false);
// Show 5 items and a scrollbar if there are more
ls.setRows(5);
ls.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Assuming that the value type is a String
String value = (String) event.getProperty().getValue();
// Do something with the value
try {
System.out.println("new val " + value);
controlService.dbengine(value.equals(ConfigConstants.SPARK));
Notification.show("Request sent");
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
});
// Fire value changes immediately when the field loses focus
ls.setImmediate(true);
return ls;
}
*/
void addListText(VerticalLayout ts, ResultItemText str) {
ts.addComponent(new Label(str.text));
}
void addListTable(VerticalLayout ts, ResultItemTable strarr) {
if (strarr.size() <= 1) {
return;
}
Table table = new Table("Table");
table.setWidth("90%");
int columns = strarr.get(0).get().size();
int mdcolumn = 0;
for (int i=0; i<strarr.size(); i++) {
if (strarr.get(i).get().size() != columns) {
log.error("column differs " + columns + " found " + strarr.get(i).get().size());
System.out.println("column differs " + columns + " found " + strarr.get(i).get().size() + " " + i + " : " + strarr.get(i).get().get(1) + " " +strarr.get(i).get() );
break;
}
}
try {
log.info("arr " + 0 + " " + strarr.get(0).getarr().length + " " + Arrays.toString(strarr.get(0).getarr()));
for (int i = 0; i < columns; i++) {
Object object = null;
for (int j = 1; j < strarr.size(); j++) {
object = strarr.get(j).get().get(i);
if (object != null) {
break;
}
}
//Object object = strarr.get(1).get().get(i);
if (object == null) {
table.addContainerProperty(strarr.get(0).get().get(i), String.class, null);
continue;
}
switch (object.getClass().getName()) {
case "java.lang.String":
if (i == 0 && strarr.get(0).get().get(0).equals(Constants.IMG)) {
table.addContainerProperty(strarr.get(0).get().get(i), Button.class, null);
} else {
table.addContainerProperty(strarr.get(0).get().get(i), String.class, null);
}
break;
case "java.lang.Integer":
table.addContainerProperty(strarr.get(0).get().get(i), Integer.class, null);
break;
case "java.lang.Double":
table.addContainerProperty(strarr.get(0).get().get(i), Double.class, null);
break;
case "java.util.Date":
table.addContainerProperty(strarr.get(0).get().get(i), Date.class, null);
break;
case "java.sql.Timestamp":
table.addContainerProperty(strarr.get(0).get().get(i), Timestamp.class, null);
break;
default:
log.error("not found" + strarr.get(0).get().get(i).getClass().getName() + "|" + object.getClass().getName());
System.out.println("not found" + strarr.get(0).get().get(i).getClass().getName() + "|" + object.getClass().getName());
break;
}
//table.addContainerProperty(strarr.get(0).get().get(i), String.class, null);
}
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
log.info("strarr size " + strarr.size());
for (int i = 1; i < strarr.size(); i++) {
log.info("str arr " + i);
ResultItemTableRow str = strarr.get(i);
try {
if (strarr.get(0).get().get(0).equals(Constants.IMG)) {
String id = (String) str.get().get(0);
str.get().set(0, getImage(id));
//Object myid = table.addItem(str.getarr(), i);
//log.info("myid " + str.getarr().length + " " + myid);
}
Object myid = table.addItem(str.getarr(), i);
if (myid == null) {
log.error("addItem failed for" + Arrays.toString(str.getarr()));
}
} catch (Exception e) {
log.error("i " + i + " " + str.get().get(0));
log.error(Constants.EXCEPTION, e);
}
}
//table.setPageLength(table.size());
log.info("tabledata " + table.getColumnHeaders().length + " " + table.size() + " " + Arrays.toString(table.getColumnHeaders()));
ts.addComponent(table);
}
/*
void addListTable(VerticalLayout ts, ResultItemTable resulttable) {
log.info("t " + resulttable.size());
if (resulttable.size() <= 1) {
return;
}
Table table = new Table("Table");
table.setWidth("90%");
int columns = resulttable.get(0).get().size();
int mdcolumn = 0;
for (int i=0; i<resulttable.size(); i++) {
if (resulttable.get(i).get().size() != columns) {
log.error("column differs " + columns + " found " + resulttable.get(i).get().size());
System.out.println("column differs " + columns + " found " + resulttable.get(i).get().size() + " " + i + " : " + resulttable.get(i).get().get(1) + " " +resulttable.get(i).get() );
break;
}
}
for (int i = 0; i < columns; i++) {
Object object = null;
for (int j = 1; j < resulttable.size(); j++) {
object = resulttable.get(j).get().get(i);
if (object != null) {
break;
}
}
//Object object = strarr.get(1).get().get(i);
if (object == null) {
table.addContainerProperty(resulttable.get(0).get().get(i), String.class, null);
continue;
}
switch (object.getClass().getName()) {
case "java.lang.String":
if (i == 0 && resulttable.get(0).get().get(0).equals(Constants.IMG)) {
table.addContainerProperty(resulttable.get(0).get().get(i), Button.class, null);
} else {
table.addContainerProperty(resulttable.get(0).get().get(i), String.class, null);
}
break;
case "java.lang.Integer":
table.addContainerProperty(resulttable.get(0).get().get(i), Integer.class, null);
break;
case "java.lang.Double":
table.addContainerProperty(resulttable.get(0).get().get(i), Double.class, null);
break;
case "java.util.Date":
table.addContainerProperty(resulttable.get(0).get().get(i), Date.class, null);
break;
case "java.sql.Timestamp":
table.addContainerProperty(resulttable.get(0).get().get(i), Timestamp.class, null);
break;
default:
log.error("not found" + resulttable.get(0).get().get(i).getClass().getName() + "|" + object.getClass().getName());
System.out.println("not found" + resulttable.get(0).get().get(i).getClass().getName() + "|" + object.getClass().getName());
break;
}
//table.addContainerProperty(strarr.get(0).get().get(i), String.class, null);
}
for (int i = 1; i < resulttable.size(); i++) {
ResultItemTableRow str = resulttable.get(i);
try {
if (resulttable.get(0).get().get(0).equals(Constants.IMG)) {
String id = (String) str.get().get(0);
str.get().set(0, getImage(id));
table.addItem(str.getarr(), i);
}
table.addItem(str.getarr(), i);
} catch (Exception e) {
log.error("i " + i + " " + str.get().get(0));
log.error(Constants.EXCEPTION, e);
}
}
//table.setPageLength(table.size());
ts.addComponent(table);
}
*/
private Button getImage(final String id) {
Button button = new Button("Img");
button.setHtmlContentAllowed(true);
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
String idarr[] = id.split(",");
Set<Pair<String, String>> ids = new HashSet<>();
for (String id : idarr) {
ids.add(new Pair(controlService.conf.getMarket(), id));
}
displayResultsGraph(ids);
Notification.show("Request sent");
}
});
return button;
}
void addList(VerticalLayout ts, List<String> strarr) {
for (int i=0; i<strarr.size(); i++) {
String str = strarr.get(i);
ts.addComponent(new Label(str));
}
}
private VerticalLayout getResultTemplate() {
final Component content = getContent();
VerticalLayout res = new VerticalLayout();
res.addComponent(new Label("Search results"));
/*
Button button = new Button("Back to main page");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
setContent(content);
}
});
res.addComponent(button);
*/
return res;
}
@SuppressWarnings("rawtypes")
public void displayResultListsTab(Layout tab, List<ResultItem>/*<List>*/ lists) {
final String table = (new ResultItemTable()).getClass().getName();
final String text = (new ResultItemText()).getClass().getName();
final String stream = (new ResultItemBytes()).getClass().getName();
VerticalLayout result = getResultTemplate();
if (lists != null) {
for (ResultItem item : lists) {
if (table.equals(item.getClass().getName())) {
addListTable(result, (ResultItemTable) item);
}
if (text.equals(item.getClass().getName())) {
addListText(result, (ResultItemText) item);
}
if (stream.equals(item.getClass().getName())) {
addListStream(result, (ResultItemBytes) item);
}
}
}
tab.addComponent(result);
tabsheet.addComponent(tab);
tabsheet.getTab(tab).setClosable(true);
Notification.show("New result available");
}
public void notify(String text) {
Notification.show(text);
}
}
|
package com.intellij.debugger.ui;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.ui.EditorComboBoxEditor;
import com.intellij.ui.EditorComboBoxRenderer;
import org.jetbrains.annotations.NonNls;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author ven
*/
public class DebuggerExpressionComboBox extends DebuggerEditorImpl {
public static final Key<String> KEY = Key.create("DebuggerComboBoxEditor.KEY");
public static final int MAX_ROWS = 20;
private MyEditorComboBoxEditor myEditor;
private ComboBox myComboBox;
protected TextWithImports myItem;
private class MyEditorComboBoxEditor extends EditorComboBoxEditor{
public MyEditorComboBoxEditor(Project project, FileType fileType) {
super(project, fileType);
}
public Object getItem() {
Document document = (Document)super.getItem();
return createItem(document, getProject());
}
public void setItem(Object item) {
super.setItem(createDocument((TextWithImports)item));
/* Causes PSI being modified from PSI events. See IDEADEV-22102
final Editor editor = getEditor();
if (editor != null) {
DaemonCodeAnalyzer.getInstance(getProject()).updateVisibleHighlighters(editor);
}
*/
}
}
public void setText(TextWithImports item) {
final String itemText = item.getText().replace('\n', ' ');
item.setText(itemText);
if (!"".equals(itemText)) {
if(myComboBox.getItemCount() == 0 || !item.equals(myComboBox.getItemAt(0))) {
myComboBox.insertItemAt(item, 0);
}
}
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
if(myComboBox.isEditable()) {
myComboBox.getEditor().setItem(item);
}
else {
myItem = item;
}
}
public TextWithImports getText() {
return (TextWithImports)myComboBox.getEditor().getItem();
}
protected void updateEditor(TextWithImports item) {
if(!myComboBox.isEditable()) return;
boolean focusOwner = myEditor != null && myEditor.getEditorComponent().isFocusOwner();
int offset = 0;
TextWithImports oldItem = null;
if(focusOwner) {
offset = myEditor.getEditor().getCaretModel().getOffset();
oldItem = (TextWithImports)myEditor.getItem();
}
myEditor = new MyEditorComboBoxEditor(getProject(), myFactory.getFileType());
myComboBox.setEditor(myEditor);
myComboBox.setRenderer(new EditorComboBoxRenderer(myEditor));
myComboBox.setMaximumRowCount(MAX_ROWS);
myEditor.setItem(item);
if(focusOwner) {
myEditor.getEditorComponent().requestFocus();
if(oldItem.equals(item)) {
myEditor.getEditor().getCaretModel().moveToOffset(offset);
}
}
}
private void setRecents() {
boolean focusOwner = myEditor != null && myEditor.getEditorComponent().isFocusOwner();
myComboBox.removeAllItems();
if(getRecentsId() != null) {
LinkedList<TextWithImports> recents = DebuggerRecents.getInstance(getProject()).getRecents(getRecentsId());
ArrayList<TextWithImports> singleLine = new ArrayList<TextWithImports>();
for (TextWithImports evaluationText : recents) {
if (evaluationText.getText().indexOf('\n') == -1) {
singleLine.add(evaluationText);
}
}
addRecents(singleLine);
}
if(focusOwner) myEditor.getEditorComponent().requestFocus();
}
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.width = 100;
return size;
}
public void setEnabled(boolean enabled) {
if(myComboBox.isEditable() == enabled) return;
myComboBox.setEnabled(enabled);
myComboBox.setEditable(enabled);
if(enabled) {
setRecents();
updateEditor(myItem);
} else {
myItem = (TextWithImports)myComboBox.getEditor().getItem();
myComboBox.removeAllItems();
myComboBox.addItem(myItem);
}
}
public TextWithImports createText(String text, String importsString) {
return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, text, importsString);
}
private void addRecents(List<TextWithImports> expressions) {
for (final TextWithImports text : expressions) {
myComboBox.addItem(text);
}
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
}
public DebuggerExpressionComboBox(Project project, @NonNls String recentsId) {
this(project, null, recentsId, DefaultCodeFragmentFactory.getInstance());
}
public DebuggerExpressionComboBox(Project project, PsiElement context, @NonNls String recentsId, final CodeFragmentFactory factory) {
super(project, context, recentsId, factory);
myComboBox = new ComboBox(-1);
// Have to turn this off because when used in DebuggerTreeInplaceEditor, the combobox popup is hidden on every change of selection
// See comment to SynthComboBoxUI.FocusHandler.focusLost()
myComboBox.setLightWeightPopupEnabled(false);
setLayout(new BorderLayout());
add(myComboBox);
setText(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, ""));
myItem = createText("");
setEnabled(true);
}
public JComponent getPreferredFocusedComponent() {
return (JComponent)myComboBox.getEditor().getEditorComponent();
}
public void selectAll() {
myComboBox.getEditor().selectAll();
}
public Editor getEditor() {
return myEditor.getEditor();
}
public JComponent getEditorComponent() {
return (JComponent)myEditor.getEditorComponent();
}
public void addRecent(TextWithImports text) {
super.addRecent(text);
setRecents();
}
}
|
package gaia.cu9.ari.gaiaorbit.desktop.gui.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.JsonValue;
import gaia.cu9.ari.gaiaorbit.desktop.GaiaSkyDesktop;
import gaia.cu9.ari.gaiaorbit.desktop.gui.swing.callback.Callback;
import gaia.cu9.ari.gaiaorbit.desktop.gui.swing.callback.CallbackTask;
import gaia.cu9.ari.gaiaorbit.desktop.gui.swing.jsplash.GuiUtility;
import gaia.cu9.ari.gaiaorbit.desktop.gui.swing.jsplash.JSplashLabel;
import gaia.cu9.ari.gaiaorbit.desktop.gui.swing.version.VersionChecker;
import gaia.cu9.ari.gaiaorbit.event.EventManager;
import gaia.cu9.ari.gaiaorbit.event.Events;
import gaia.cu9.ari.gaiaorbit.interfce.KeyBindings;
import gaia.cu9.ari.gaiaorbit.interfce.KeyBindings.ProgramAction;
import gaia.cu9.ari.gaiaorbit.interfce.TextUtils;
import gaia.cu9.ari.gaiaorbit.util.ConfInit;
import gaia.cu9.ari.gaiaorbit.util.Constants;
import gaia.cu9.ari.gaiaorbit.util.GlobalConf;
import gaia.cu9.ari.gaiaorbit.util.I18n;
import gaia.cu9.ari.gaiaorbit.util.Logger;
import gaia.cu9.ari.gaiaorbit.util.math.MathUtilsd;
import net.miginfocom.swing.MigLayout;
import slider.RangeSlider;
/**
* The configuration dialog to set the resolution, the screen mode, etc.
*
* @author Toni Sagrista
*
*/
public class ConfigDialog extends I18nJFrame {
private static long fiveDaysMs = 5 * 24 * 60 * 60 * 1000;
private static ConfigDialog singleton = null;
public static void initialise(GaiaSkyDesktop gsd, boolean startup) {
if (singleton == null) {
singleton = new ConfigDialog(gsd, startup);
} else {
singleton.setVisible(true);
singleton.toFront();
}
}
JFrame frame;
JLabel checkLabel;
JPanel checkPanel;
Color darkgreen, darkred, transparent;
JButton cancelButton, okButton;
String vislistdata;
JTree visualisationsTree;
private DecimalFormat nf3;
public ConfigDialog(final GaiaSkyDesktop gsd, boolean startup) {
super(startup ? GlobalConf.getFullApplicationName() : txt("gui.settings"));
FontUtilities.setFontScale(GlobalConf.SCALE_FACTOR);
nf3 = new DecimalFormat("#.000");
// Initialize
initialize(gsd, startup);
if (startup) {
/** SPLASH IMAGE **/
URL url = this.getClass().getResource("/img/splash/splash-s.jpg");
JSplashLabel label = new JSplashLabel(url, txt("gui.build", GlobalConf.version.build) + " - " + txt("gui.version", GlobalConf.version.version), null, Color.lightGray);
JPanel imagePanel = new JPanel(new GridLayout(1, 1, 0, 0));
imagePanel.add(label);
imagePanel.setBackground(Color.black);
frame.add(imagePanel, BorderLayout.NORTH);
} else {
JPanel imagePanel = new JPanel(new GridLayout(1, 1, 0, 0));
imagePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JLabel buildtext = new JLabel("<html><font color='white'>" + GlobalConf.APPLICATION_NAME + " - " + txt("gui.build", GlobalConf.version.build) + " - " + txt("gui.version", GlobalConf.version.version) + "</font></html>");
buildtext.setHorizontalAlignment(JLabel.CENTER);
imagePanel.add(buildtext);
imagePanel.setBackground(Color.black);
frame.add(imagePanel, BorderLayout.NORTH);
}
frame.pack();
GuiUtility.centerOnScreen(frame);
frame.setVisible(true);
frame.setEnabled(true);
frame.setAutoRequestFocus(true);
// ESC closes the frame
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "closeTheDialog");
getRootPane().getActionMap().put("closeTheDialog", new AbstractAction() {
private static final long serialVersionUID = 8360999630557775801L;
@Override
public void actionPerformed(ActionEvent e) {
// This should be replaced by the action you want to
// perform
cancelButton.doClick();
}
});
// Window close hook
WindowListener exitListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
singleton = null;
}
};
frame.addWindowListener(exitListener);
// Request focus
frame.getRootPane().setDefaultButton(okButton);
okButton.requestFocus();
}
private void initialize(final GaiaSkyDesktop gsd, final boolean startup) {
frame = this;
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
darkgreen = new Color(0, .5f, 0);
darkred = new Color(.8f, 0, 0);
transparent = new Color(0f, 0f, 0f, 0f);
// Build content
frame.setLayout(new BorderLayout(0, 0));
/** BODY **/
JPanel body = new JPanel(new MigLayout("", "[grow,fill][]", ""));
/** VERSION CHECK **/
checkPanel = new JPanel(new MigLayout("", "[][]", "[]4[]"));
checkLabel = new JLabel("");
checkPanel.add(checkLabel);
if (GlobalConf.program.LAST_CHECKED == null || GlobalConf.program.LAST_VERSION.isEmpty() || new Date().getTime() - GlobalConf.program.LAST_CHECKED.getTime() > fiveDaysMs) {
// Check!
checkLabel.setText(txt("gui.newversion.checking"));
getCheckVersionThread().start();
} else {
// Inform latest
newVersionCheck(GlobalConf.program.LAST_VERSION);
}
/** TABBED PANEL **/
final JXTabbedPane tabbedPane = new JXTabbedPane(JTabbedPane.LEFT);
/** RESOLUTION **/
JPanel mode = new JPanel(new MigLayout("fillx", "[grow,fill][grow,fill]", ""));
mode.setBorder(new TitledBorder(txt("gui.resolutionmode")));
// Full screen mode resolutions
DisplayMode[] modes = LwjglApplicationConfiguration.getDisplayModes();
final JComboBox<DisplayMode> fullScreenResolutions = new JComboBox<DisplayMode>(modes);
DisplayMode selectedMode = null;
for (DisplayMode dm : modes) {
if (dm.width == GlobalConf.screen.FULLSCREEN_WIDTH && dm.height == GlobalConf.screen.FULLSCREEN_HEIGHT) {
selectedMode = dm;
break;
}
}
if (selectedMode != null)
fullScreenResolutions.setSelectedItem(selectedMode);
// Get current resolution
DisplayMode nativeMode = LwjglApplicationConfiguration.getDesktopDisplayMode();
// Windowed mode resolutions
JPanel windowedResolutions = new JPanel(new MigLayout("", "[][grow,fill][][grow,fill]", "[][]4[][]"));
final JSpinner widthField = new JSpinner(new SpinnerNumberModel(MathUtils.clamp(GlobalConf.screen.SCREEN_WIDTH, 100, nativeMode.width), 100, nativeMode.width, 1));
final JSpinner heightField = new JSpinner(new SpinnerNumberModel(MathUtils.clamp(GlobalConf.screen.SCREEN_HEIGHT, 100, nativeMode.height), 100, nativeMode.height, 1));
final JCheckBox resizable = new JCheckBox("Resizable", GlobalConf.screen.RESIZABLE);
final JLabel widthLabel = new JLabel(txt("gui.width") + ":");
final JLabel heightLabel = new JLabel(txt("gui.height") + ":");
windowedResolutions.add(widthLabel);
windowedResolutions.add(widthField);
windowedResolutions.add(heightLabel);
windowedResolutions.add(heightField, "wrap");
windowedResolutions.add(resizable, "span");
// Radio buttons
final JRadioButton fullscreen = new JRadioButton(txt("gui.fullscreen"));
fullscreen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GlobalConf.screen.FULLSCREEN = fullscreen.isSelected();
selectFullscreen(fullscreen.isSelected(), widthField, heightField, fullScreenResolutions, resizable, widthLabel, heightLabel);
}
});
fullscreen.setSelected(GlobalConf.screen.FULLSCREEN);
final JRadioButton windowed = new JRadioButton(txt("gui.windowed"));
windowed.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GlobalConf.screen.FULLSCREEN = !windowed.isSelected();
selectFullscreen(!windowed.isSelected(), widthField, heightField, fullScreenResolutions, resizable, widthLabel, heightLabel);
}
});
windowed.setSelected(!GlobalConf.screen.FULLSCREEN);
selectFullscreen(GlobalConf.screen.FULLSCREEN, widthField, heightField, fullScreenResolutions, resizable, widthLabel, heightLabel);
ButtonGroup modeButtons = new ButtonGroup();
modeButtons.add(fullscreen);
modeButtons.add(windowed);
mode.add(fullscreen);
mode.add(fullScreenResolutions, "wrap");
mode.add(windowed);
mode.add(windowedResolutions);
/** GRAPHICS **/
JPanel graphics = new JPanel(new MigLayout("", "[grow,fill][grow,fill][]", ""));
graphics.setBorder(new TitledBorder(txt("gui.graphicssettings")));
// Quality
JLabel gqTooltip = new JLabel(IconManager.get("config/info-tooltip"));
gqTooltip.setToolTipText(txt("gui.gquality.info"));
ComboBoxBean[] gqs = new ComboBoxBean[] { new ComboBoxBean(txt("gui.gquality.high"), 0), new ComboBoxBean(txt("gui.gquality.normal"), 1), new ComboBoxBean(txt("gui.gquality.low"), 2) };
final JComboBox<ComboBoxBean> gquality = new JComboBox<ComboBoxBean>(gqs);
int index = -1;
for (int i = 0; i < GlobalConf.data.OBJECTS_JSON_FILE_GQ.length; i++) {
if (GlobalConf.data.OBJECTS_JSON_FILE_GQ[i].equals(GlobalConf.data.OBJECTS_JSON_FILE)) {
index = i;
break;
}
}
int gqidx = index;
gquality.setSelectedItem(gqs[gqidx]);
JLabel aaTooltip = new JLabel(IconManager.get("config/info-tooltip"));
aaTooltip.setToolTipText(txt("gui.aa.info"));
//ComboBoxBean[] aas = new ComboBoxBean[] { new ComboBoxBean(txt("gui.aa.no"), 0), new ComboBoxBean(txt("gui.aa.fxaa"), -1), new ComboBoxBean(txt("gui.aa.nfaa"), -2), new ComboBoxBean(txt("gui.aa.msaa", 2), 2), new ComboBoxBean(txt("gui.aa.msaa", 4), 4), new ComboBoxBean(txt("gui.aa.msaa", 8), 8), new ComboBoxBean(txt("gui.aa.msaa", 16), 16) };
ComboBoxBean[] aas = new ComboBoxBean[] { new ComboBoxBean(txt("gui.aa.no"), 0), new ComboBoxBean(txt("gui.aa.fxaa"), -1), new ComboBoxBean(txt("gui.aa.nfaa"), -2) };
final JComboBox<ComboBoxBean> msaa = new JComboBox<ComboBoxBean>(aas);
msaa.setSelectedItem(aas[idxAa(2, GlobalConf.postprocess.POSTPROCESS_ANTIALIAS)]);
// Vsync
final JCheckBox vsync = new JCheckBox(txt("gui.vsync"), GlobalConf.screen.VSYNC);
// Line renderer
ComboBoxBean[] lineRenderers = new ComboBoxBean[] { new ComboBoxBean(txt("gui.linerenderer.normal"), 0), new ComboBoxBean(txt("gui.linerenderer.quad"), 1) };
final JComboBox<ComboBoxBean> lineRenderer = new JComboBox<ComboBoxBean>(lineRenderers);
lineRenderer.setSelectedItem(lineRenderers[GlobalConf.scene.LINE_RENDERER]);
// Add all
graphics.add(new JLabel(txt("gui.gquality") + ":"));
graphics.add(gquality);
graphics.add(gqTooltip, "wrap");
graphics.add(new JLabel(txt("gui.aa") + ":"));
graphics.add(msaa);
graphics.add(aaTooltip, "wrap");
graphics.add(new JLabel(txt("gui.linerenderer") + ":"));
graphics.add(lineRenderer, "span");
graphics.add(vsync, "span,wrap");
/** NOTICE **/
JPanel notice = new JPanel(new MigLayout("", "[]", ""));
JLabel noticeText = new JLabel(txt("gui.graphics.info"));
noticeText.setForeground(darkgreen);
notice.add(noticeText);
/** SUB TABBED PANE **/
// JTabbedPane graphicsTabbedPane = new JTabbedPane();
// graphicsTabbedPane.setTabPlacement(JTabbedPane.TOP);
// graphicsTabbedPane.addTab(txt("gui.resolutionmode"), mode);
// graphicsTabbedPane.addTab(txt("gui.graphicssettings"), graphics);
JPanel graphicsPanel = new JPanel(new MigLayout("", "[grow,fill][]", ""));
// graphicsPanel.add(graphicsTabbedPane, "wrap");
graphicsPanel.add(mode, "wrap");
graphicsPanel.add(graphics, "wrap");
if (!startup) {
graphicsPanel.add(notice, "wrap");
}
tabbedPane.addTab(txt("gui.graphics"), IconManager.get("config/graphics"), graphicsPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JPanel ui = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
ui.setBorder(new TitledBorder(txt("gui.ui.interfacesettings")));
File i18nfolder = new File(GaiaSkyDesktop.ASSETS_LOC + "i18n/");
String i18nname = "gsbundle";
String[] files = i18nfolder.list();
LangComboBoxBean[] langs = new LangComboBoxBean[files.length];
int i = 0;
for (String file : files) {
if (file.startsWith("gsbundle") && file.endsWith(".properties")) {
String locale = file.substring(i18nname.length(), file.length() - ".properties".length());
if (locale.length() != 0) {
// Remove underscore _
locale = locale.substring(1).replace("_", "-");
Locale loc = Locale.forLanguageTag(locale);
langs[i] = new LangComboBoxBean(loc);
} else {
langs[i] = new LangComboBoxBean(I18n.bundle.getLocale());
}
}
i++;
}
Arrays.sort(langs);
final JComboBox<LangComboBoxBean> lang = new JComboBox<LangComboBoxBean>(langs);
lang.setSelectedItem(langs[idxLang(GlobalConf.program.LOCALE, langs)]);
// Theme sample image
JPanel sampleImagePanel = new JPanel(new MigLayout("", "push[]", ""));
// final JLabel sampleImage = new JLabel();
// sampleImagePanel.add(sampleImage);
// Theme chooser
String[] themes = new String[] { "dark-orange", "dark-orange-large", "dark-green", "light-blue", "HiDPI" };
final JComboBox<String> theme = new JComboBox<String>(themes);
// theme.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// String selected = (String) theme.getSelectedItem();
// ImageIcon icon = new ImageIcon(GaiaSandboxDesktop.ASSETS_LOC +
// "img/themes/" + selected + ".png");
// sampleImage.setIcon(icon);
theme.setSelectedItem(GlobalConf.program.UI_THEME);
ui.add(new JLabel(txt("gui.ui.language") + ":"));
ui.add(lang, "wrap");
ui.add(new JLabel(txt("gui.ui.theme") + ":"));
ui.add(theme, "wrap");
ui.add(sampleImagePanel, "span, wrap");
/** NOTICE **/
JPanel uiNotice = new JPanel(new MigLayout("", "[]", ""));
JLabel uinoticeText = new JLabel(txt("gui.ui.info"));
uinoticeText.setForeground(darkgreen);
uiNotice.add(uinoticeText);
JPanel uiPanel = new JPanel(new MigLayout("", "[grow,fill][]", ""));
uiPanel.add(ui, "wrap");
if (!startup) {
uiPanel.add(uiNotice, "wrap");
}
tabbedPane.addTab(txt("gui.ui.interface"), IconManager.get("config/interface"), uiPanel);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
/** MULTITHREAD **/
JPanel multithread = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
multithread.setBorder(new TitledBorder(txt("gui.multithreading")));
int maxthreads = Runtime.getRuntime().availableProcessors();
ComboBoxBean[] cbs = new ComboBoxBean[maxthreads + 1];
cbs[0] = new ComboBoxBean(txt("gui.letdecide"), 0);
for (i = 1; i <= maxthreads; i++) {
cbs[i] = new ComboBoxBean(txt("gui.thread", i), i);
}
final JComboBox<ComboBoxBean> numThreads = new JComboBox<ComboBoxBean>(cbs);
numThreads.setSelectedIndex(GlobalConf.performance.NUMBER_THREADS);
final JCheckBox multithreadCb = new JCheckBox(txt("gui.thread.enable"));
multithreadCb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
numThreads.setEnabled(multithreadCb.isSelected());
}
});
multithreadCb.setSelected(GlobalConf.performance.MULTITHREADING);
numThreads.setEnabled(multithreadCb.isSelected());
multithread.add(multithreadCb, "span");
multithread.add(new JLabel(txt("gui.thread.number") + ":"));
multithread.add(numThreads);
/** LEVELS OF DETAIL **/
JPanel lod = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
lod.setBorder(new TitledBorder(txt("gui.lod")));
// LOD fade
final JCheckBox lodFadeCb = new JCheckBox(txt("gui.lod.fade"), GlobalConf.scene.OCTREE_PARTICLE_FADE);
final JLabel lod0 = new JLabel(nf3.format(GlobalConf.scene.OCTANT_THRESHOLD_0));
final JLabel lod1 = new JLabel(nf3.format(GlobalConf.scene.OCTANT_THRESHOLD_1));
JPanel lodInfo = new JPanel();
lodInfo.add(new JLabel("Min: "));
lodInfo.add(lod0);
lodInfo.add(new JLabel(" Max: "));
lodInfo.add(lod1);
// LOD transitions
final RangeSlider lodTransitions = new RangeSlider((int) Constants.MIN_SLIDER, (int) Constants.MAX_SLIDER);
lodTransitions.setUpperValue(Math.round(MathUtilsd.lint(GlobalConf.scene.OCTANT_THRESHOLD_1, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE, Constants.MIN_SLIDER, Constants.MAX_SLIDER)));
lodTransitions.setValue(Math.round(MathUtilsd.lint(GlobalConf.scene.OCTANT_THRESHOLD_0, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE, Constants.MIN_SLIDER, Constants.MAX_SLIDER)));
lodTransitions.setUpperValue(Math.round(MathUtilsd.lint(GlobalConf.scene.OCTANT_THRESHOLD_1, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE, Constants.MIN_SLIDER, Constants.MAX_SLIDER)));
lodTransitions.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
RangeSlider slider = (RangeSlider) e.getSource();
lod0.setText(nf3.format(MathUtilsd.lint(slider.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE)));
lod1.setText(nf3.format(MathUtilsd.lint(slider.getUpperValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE)));
}
});
lod.add(lodFadeCb, "span");
lod.add(new JLabel(txt("gui.lod.thresholds") + ":"));
lod.add(lodTransitions, "wrap");
lod.add(lodInfo, "span");
JPanel performancePanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
performancePanel.add(multithread, "wrap");
performancePanel.add(lod, "wrap");
tabbedPane.addTab(txt("gui.performance"), IconManager.get("config/performance"), performancePanel);
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
JPanel controls = new JPanel(new MigLayout("", "[grow,fill][]", ""));
controls.setBorder(new TitledBorder(txt("gui.keymappings")));
Map<TreeSet<Integer>, ProgramAction> maps = KeyBindings.instance.getSortedMappings();
Set<TreeSet<Integer>> keymaps = maps.keySet();
String[] headers = new String[] { txt("gui.keymappings.action"), txt("gui.keymappings.keys") };
String[][] data = new String[maps.size()][2];
i = 0;
for (TreeSet<Integer> keys : keymaps) {
ProgramAction action = maps.get(keys);
data[i][0] = action.actionName;
data[i][1] = keysToString(keys);
i++;
}
JTable table = new JTable(data, headers);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setRowHeight(scale(table.getRowHeight()));
JScrollPane controlsScrollPane = new JScrollPane(table);
controlsScrollPane.setPreferredSize(new Dimension(0, scale(180)));
// JLabel lab = new JLabel(txt("gui.noteditable"));
// lab.setForeground(darkred);
// controls.add(lab, "wrap");
controls.add(controlsScrollPane, "wrap");
JPanel controlsPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
controlsPanel.add(controls, "wrap");
tabbedPane.addTab(txt("gui.controls"), IconManager.get("config/controls"), controlsPanel);
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
/** SCREENSHOTS CONFIG **/
JPanel screenshots = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
screenshots.setBorder(new TitledBorder(txt("gui.screencapture")));
JTextArea screenshotsInfo = new JTextArea(txt("gui.screencapture.info")) {
@Override
public void setBorder(Border border) {
}
};
screenshotsInfo.setEditable(false);
screenshotsInfo.setBackground(transparent);
screenshotsInfo.setForeground(darkgreen);
// SCREENSHOTS LOCATION
JLabel screenshotsLocationLabel = new JLabel(txt("gui.screenshots.save") + ":");
final File currentLocation = new File(GlobalConf.screenshot.SCREENSHOT_FOLDER);
String dirText = txt("gui.screenshots.directory.choose");
final Label screenshotsTextContainer = new Label(currentLocation.getAbsolutePath());
if (currentLocation.exists() && currentLocation.isDirectory()) {
dirText = currentLocation.getName();
}
final JButton screenshotsDir = new JButton(dirText);
screenshotsDir.addActionListener(new ActionListener() {
JFileChooser chooser = null;
@Override
public void actionPerformed(ActionEvent e) {
SecurityManager sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File f = new File(screenshotsTextContainer.getText());
if (f.exists() && f.isDirectory()) {
chooser.setCurrentDirectory(f);
chooser.setSelectedFile(f);
}
chooser.setDialogTitle(txt("gui.directory.chooseany"));
int v = chooser.showOpenDialog(null);
switch (v) {
case JFileChooser.APPROVE_OPTION:
File choice = null;
if (chooser.getSelectedFile() != null && chooser.getSelectedFile().isDirectory()) {
choice = chooser.getSelectedFile();
} else if (chooser.getCurrentDirectory() != null) {
choice = chooser.getCurrentDirectory();
}
screenshotsTextContainer.setText(choice.getAbsolutePath());
screenshotsDir.setText(choice.getName());
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
}
});
// SCREENSHOT WIDTH AND HEIGHT
final JLabel screenshotsSizeLabel = new JLabel(txt("gui.screenshots.size") + ":");
final JLabel xLabel = new JLabel("\u2715");
final JSpinner sswidthField = new JSpinner(new SpinnerNumberModel(GlobalConf.screenshot.SCREENSHOT_WIDTH, 50, 25000, 1));
final JSpinner ssheightField = new JSpinner(new SpinnerNumberModel(GlobalConf.screenshot.SCREENSHOT_HEIGHT, 50, 25000, 1));
// SCREENSHOTS MODE
ComboBoxBean[] screenshotModes = new ComboBoxBean[] { new ComboBoxBean(txt("gui.screenshots.mode.simple"), 0), new ComboBoxBean(txt("gui.screenshots.mode.redraw"), 1) };
final JComboBox<ComboBoxBean> screenshotsMode = new JComboBox<ComboBoxBean>(screenshotModes);
screenshotsMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (((ComboBoxBean) screenshotsMode.getSelectedItem()).value == 0) {
// Simple
enableComponents(false, sswidthField, ssheightField, screenshotsSizeLabel, xLabel);
} else {
// Redraw
enableComponents(true, sswidthField, ssheightField, screenshotsSizeLabel, xLabel);
}
}
});
screenshotsMode.setSelectedItem(screenshotModes[GlobalConf.screenshot.SCREENSHOT_MODE.ordinal()]);
JLabel screenshotsModeTooltip = new JLabel(IconManager.get("config/info-tooltip"));
screenshotsModeTooltip.setToolTipText(txt("gui.tooltip.screenshotmode"));
JPanel screenshotsModePanel = new JPanel(new MigLayout("", "[grow,fill][]", ""));
screenshotsModePanel.add(screenshotsMode);
screenshotsModePanel.add(screenshotsModeTooltip, "wrap");
screenshots.add(screenshotsInfo, "span,wrap");
screenshots.add(screenshotsLocationLabel);
screenshots.add(screenshotsDir, "span,wrap");
screenshots.add(new JLabel(txt("gui.screenshots.mode") + ":"));
screenshots.add(screenshotsModePanel, "span,wrap");
screenshots.add(screenshotsSizeLabel);
screenshots.add(sswidthField);
screenshots.add(xLabel);
screenshots.add(ssheightField);
JPanel screenshotsPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
screenshotsPanel.add(screenshots, "wrap");
tabbedPane.addTab(txt("gui.screenshots"), IconManager.get("config/screenshots"), screenshotsPanel);
tabbedPane.setMnemonicAt(4, KeyEvent.VK_5);
/** IMAGE OUTPUT CONFIG **/
JPanel imageOutput = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
imageOutput.setBorder(new TitledBorder(txt("gui.frameoutput")));
JTextArea frameInfo = new JTextArea(txt("gui.frameoutput.info")) {
@Override
public void setBorder(Border border) {
}
};
frameInfo.setEditable(false);
frameInfo.setBackground(transparent);
frameInfo.setForeground(darkgreen);
// FRAME SAVE LOCATION
final File currentFrameLocation = new File(GlobalConf.frame.RENDER_FOLDER);
String dirFrameText = txt("gui.frameoutput.directory.choose");
final Label frameTextContainer = new Label(currentFrameLocation.getAbsolutePath());
if (currentFrameLocation.exists() && currentFrameLocation.isDirectory()) {
dirText = currentFrameLocation.getName();
}
final JButton frameDir = new JButton(dirText);
frameDir.addActionListener(new ActionListener() {
JFileChooser chooser = null;
@Override
public void actionPerformed(ActionEvent e) {
SecurityManager sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File f = new File(frameTextContainer.getText());
if (f.exists() && f.isDirectory()) {
chooser.setCurrentDirectory(f);
chooser.setSelectedFile(f);
}
chooser.setDialogTitle(txt("gui.directory.chooseany"));
int v = chooser.showOpenDialog(null);
switch (v) {
case JFileChooser.APPROVE_OPTION:
File choice = null;
if (chooser.getSelectedFile() != null && chooser.getSelectedFile().isDirectory()) {
choice = chooser.getSelectedFile();
} else if (chooser.getCurrentDirectory() != null) {
choice = chooser.getCurrentDirectory();
}
frameTextContainer.setText(choice.getAbsolutePath());
frameDir.setText(choice.getName());
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
}
});
// NAME
final JTextField frameFileName = new JTextField();
frameFileName.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
String text = frameFileName.getText();
// Only word characters
if (!text.matches("^\\w+$")) {
frameFileName.setForeground(Color.red);
} else {
frameFileName.setForeground(Color.black);
}
}
});
frameFileName.setText(GlobalConf.frame.RENDER_FILE_NAME);
// TARGET FPS
final JSpinner targetFPS = new JSpinner(new SpinnerNumberModel(GlobalConf.frame.RENDER_TARGET_FPS, 1, 60, 1));
// FRAME OUTPUT WIDTH AND HEIGHT
final JLabel frameSizeLabel = new JLabel(txt("gui.frameoutput.size") + ":");
final JLabel frameXLabel = new JLabel("\u2715");
final JSpinner frameWidthField = new JSpinner(new SpinnerNumberModel(GlobalConf.frame.RENDER_WIDTH, 50, 25000, 1));
final JSpinner frameHeightField = new JSpinner(new SpinnerNumberModel(GlobalConf.frame.RENDER_HEIGHT, 50, 25000, 1));
// FRAME OUTPUT MODE
ComboBoxBean[] frameModesBean = new ComboBoxBean[] { new ComboBoxBean(txt("gui.screenshots.mode.simple"), 0), new ComboBoxBean(txt("gui.screenshots.mode.redraw"), 1) };
final JComboBox<ComboBoxBean> frameMode = new JComboBox<ComboBoxBean>(frameModesBean);
frameMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (((ComboBoxBean) frameMode.getSelectedItem()).value == 0) {
// Simple
enableComponents(false, frameWidthField, frameHeightField, frameSizeLabel, frameXLabel);
} else {
// Redraw
enableComponents(true, frameWidthField, frameHeightField, frameSizeLabel, frameXLabel);
}
}
});
frameMode.setSelectedItem(frameModesBean[GlobalConf.frame.FRAME_MODE.ordinal()]);
JLabel frameModeTooltip = new JLabel(IconManager.get("config/info-tooltip"));
frameModeTooltip.setToolTipText(txt("gui.tooltip.screenshotmode"));
JPanel frameModePanel = new JPanel(new MigLayout("", "[grow,fill][]", ""));
frameModePanel.add(frameMode);
frameModePanel.add(frameModeTooltip, "wrap");
// FRAME OUTPUT CHECKBOX
imageOutput.add(frameInfo, "span");
imageOutput.add(new JLabel(txt("gui.frameoutput.location") + ":"));
imageOutput.add(frameDir, "wrap, span");
imageOutput.add(new JLabel(txt("gui.frameoutput.prefix") + ":"));
imageOutput.add(frameFileName, "wrap, span");
imageOutput.add(new JLabel(txt("gui.frameoutput.fps") + ":"));
imageOutput.add(targetFPS, "span");
imageOutput.add(new JLabel(txt("gui.screenshots.mode") + ":"));
imageOutput.add(frameModePanel, "span,wrap");
imageOutput.add(frameSizeLabel);
imageOutput.add(frameWidthField);
imageOutput.add(frameXLabel);
imageOutput.add(frameHeightField, "wrap");
JPanel imageOutputPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
imageOutputPanel.add(imageOutput, "wrap");
tabbedPane.addTab(txt("gui.frameoutput.title"), IconManager.get("config/frameoutput"), imageOutputPanel);
tabbedPane.setMnemonicAt(5, KeyEvent.VK_6);
JPanel cameraRec = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
cameraRec.setBorder(new TitledBorder(txt("gui.camerarec")));
// TARGET FPS
final JSpinner targetFPScamera = new JSpinner(new SpinnerNumberModel(GlobalConf.frame.CAMERA_REC_TARGET_FPS, 1, 60, 1));
// AUTOMATICALLY ENABLE FRAME OUTPUT WHEN PLAYING CAMERA
final JCheckBox autoFrameOutput = new JCheckBox(txt("gui.camerarec.frameoutput"), GlobalConf.frame.AUTO_FRAME_OUTPUT_CAMERA_PLAY);
autoFrameOutput.setToolTipText(txt("gui.tooltip.playcamera.frameoutput"));
JLabel afoTooltip = new JLabel(IconManager.get("config/info-tooltip"));
afoTooltip.setToolTipText(txt("gui.tooltip.playcamera.frameoutput"));
cameraRec.add(new JLabel(txt("gui.camerarec.fps") + ":"));
cameraRec.add(targetFPScamera, "span,wrap");
cameraRec.add(autoFrameOutput);
cameraRec.add(afoTooltip);
JPanel cameraRecPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
cameraRecPanel.add(cameraRec, "wrap");
tabbedPane.addTab(txt("gui.camerarec.title"), IconManager.get("config/camera"), cameraRecPanel);
tabbedPane.setMnemonicAt(6, KeyEvent.VK_7);
JTextArea mode360Info = new JTextArea(txt("gui.360.info")) {
@Override
public void setBorder(Border border) {
}
};
mode360Info.setEditable(false);
mode360Info.setBackground(transparent);
mode360Info.setForeground(darkgreen);
JPanel mode360 = new JPanel(new MigLayout("", "[grow,fill][grow,fill]", ""));
mode360.setBorder(new TitledBorder(txt("gui.360")));
// CUBEMAP RESOLUTION
final JSpinner cubemapResolution = new JSpinner(new SpinnerNumberModel(GlobalConf.scene.CUBEMAP_FACE_RESOLUTION, 20, 15000, 1));
mode360.add(mode360Info, "span");
mode360.add(new JLabel(txt("gui.360.resolution") + ":"));
mode360.add(cubemapResolution, "span");
JPanel mode360Panel = new JPanel(new MigLayout("", "[grow,fill]", ""));
mode360Panel.add(mode360, "wrap");
tabbedPane.addTab(txt("gui.360.title"), IconManager.get("config/360"), mode360Panel);
tabbedPane.setMnemonicAt(7, KeyEvent.VK_8);
JPanel datasource = new JPanel(new MigLayout("", "[][grow,fill][]", ""));
datasource.setBorder(new TitledBorder(txt("gui.data.source")));
// HYG
final JRadioButton hyg = new JRadioButton(txt("gui.data.hyg"));
hyg.setSelected(GlobalConf.data.CATALOG_JSON_FILE.equals(GlobalConf.data.HYG_JSON_FILE));
// TGAS
final JRadioButton tgas = new JRadioButton(txt("gui.data.tgas"));
tgas.setSelected(GlobalConf.data.CATALOG_JSON_FILE.equals(GlobalConf.data.TGAS_JSON_FILE));
ButtonGroup dataButtons = new ButtonGroup();
dataButtons.add(hyg);
dataButtons.add(tgas);
datasource.add(hyg, "span,wrap");
datasource.add(tgas, "span,wrap");
final JPanel dataPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
dataPanel.add(datasource, "wrap");
tabbedPane.addTab(txt("gui.data"), IconManager.get("config/data"), dataPanel);
tabbedPane.setMnemonicAt(8, KeyEvent.VK_9);
JPanel gaia = new JPanel(new MigLayout("", "[][grow,fill][]", ""));
gaia.setBorder(new TitledBorder(txt("gui.gaia.attitude")));
// REAL OR NSL attitude
final JRadioButton real = new JRadioButton(txt("gui.gaia.real"));
real.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GlobalConf.data.REAL_GAIA_ATTITUDE = real.isSelected();
}
});
real.setSelected(GlobalConf.data.REAL_GAIA_ATTITUDE);
final JRadioButton nsl = new JRadioButton(txt("gui.gaia.nsl"));
nsl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GlobalConf.data.REAL_GAIA_ATTITUDE = !nsl.isSelected();
}
});
nsl.setSelected(!GlobalConf.data.REAL_GAIA_ATTITUDE);
ButtonGroup gaiaButtons = new ButtonGroup();
gaiaButtons.add(real);
gaiaButtons.add(nsl);
gaia.add(real, "span,wrap");
gaia.add(nsl, "span,wrap");
final JPanel gaiaPanel = new JPanel(new MigLayout("", "[grow,fill]", ""));
gaiaPanel.add(gaia, "wrap");
tabbedPane.addTab(txt("gui.gaia"), IconManager.get("config/gaia"), gaiaPanel);
/** SHOW AGAIN? **/
// Do not show again
final JCheckBox showAgain = new JCheckBox(txt("gui.showatstartup"));
showAgain.setSelected(GlobalConf.program.SHOW_CONFIG_DIALOG);
showAgain.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
GlobalConf.program.SHOW_CONFIG_DIALOG = showAgain.isSelected();
}
});
body.add(tabbedPane, "wrap");
body.add(checkPanel, "wrap");
body.add(showAgain, "wrap");
/** BUTTONS **/
JPanel buttons = new JPanel(new MigLayout("", "push[][]", ""));
okButton = new JButton(startup ? txt("gui.launchapp") : txt("gui.saveprefs"));
okButton.addActionListener(new ActionListener() {
boolean goahead;
@Override
public void actionPerformed(ActionEvent evt) {
goahead = true;
if (goahead) {
// Add all properties to GlobalConf.instance
GlobalConf.screen.FULLSCREEN = fullscreen.isSelected();
// Fullscreen options
GlobalConf.screen.FULLSCREEN_WIDTH = ((DisplayMode) fullScreenResolutions.getSelectedItem()).width;
GlobalConf.screen.FULLSCREEN_HEIGHT = ((DisplayMode) fullScreenResolutions.getSelectedItem()).height;
// Windowed options
GlobalConf.screen.SCREEN_WIDTH = ((Integer) widthField.getValue());
GlobalConf.screen.SCREEN_HEIGHT = ((Integer) heightField.getValue());
GlobalConf.screen.RESIZABLE = resizable.isSelected();
// Graphics
ComboBoxBean bean = (ComboBoxBean) gquality.getSelectedItem();
GlobalConf.data.OBJECTS_JSON_FILE = GlobalConf.data.OBJECTS_JSON_FILE_GQ[bean.value];
GlobalConf.scene.GRAPHICS_QUALITY = bean.value;
bean = (ComboBoxBean) msaa.getSelectedItem();
GlobalConf.postprocess.POSTPROCESS_ANTIALIAS = bean.value;
EventManager.instance.post(Events.ANTIALIASING_CMD, bean.value);
GlobalConf.screen.VSYNC = vsync.isSelected();
// Line renderer
bean = (ComboBoxBean) lineRenderer.getSelectedItem();
GlobalConf.scene.LINE_RENDERER = bean.value;
// Interface
LangComboBoxBean lbean = (LangComboBoxBean) lang.getSelectedItem();
GlobalConf.program.LOCALE = lbean.locale.toLanguageTag();
I18n.forceinit(Gdx.files.internal("i18n/gsbundle"));
GlobalConf.program.UI_THEME = (String) theme.getSelectedItem();
if (GlobalConf.program.UI_THEME.equalsIgnoreCase("hidpi")) {
GlobalConf.updateScaleFactor(Math.max(GlobalConf.SCALE_FACTOR, 1.6f));
}
// Performance
bean = (ComboBoxBean) numThreads.getSelectedItem();
GlobalConf.performance.NUMBER_THREADS = bean.value;
GlobalConf.performance.MULTITHREADING = multithreadCb.isSelected();
GlobalConf.scene.OCTREE_PARTICLE_FADE = lodFadeCb.isSelected();
GlobalConf.scene.OCTANT_THRESHOLD_0 = MathUtilsd.lint(lodTransitions.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE);
GlobalConf.scene.OCTANT_THRESHOLD_1 = MathUtilsd.lint(lodTransitions.getUpperValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_LOD_TRANS_ANGLE, Constants.MAX_LOD_TRANS_ANGLE);
// Data
if (hyg.isSelected())
GlobalConf.data.CATALOG_JSON_FILE = GlobalConf.data.HYG_JSON_FILE;
else if (tgas.isSelected())
GlobalConf.data.CATALOG_JSON_FILE = GlobalConf.data.TGAS_JSON_FILE;
else if (GlobalConf.data.CATALOG_JSON_FILE == null || GlobalConf.data.CATALOG_JSON_FILE.length() == 0)
Logger.error(this.getClass().getSimpleName(), "No catalog file selected!");
// Screenshots
File ssfile = new File(screenshotsTextContainer.getText());
if (ssfile.exists() && ssfile.isDirectory())
GlobalConf.screenshot.SCREENSHOT_FOLDER = ssfile.getAbsolutePath();
GlobalConf.screenshot.SCREENSHOT_MODE = GlobalConf.ScreenshotMode.values()[screenshotsMode.getSelectedIndex()];
GlobalConf.screenshot.SCREENSHOT_WIDTH = ((Integer) sswidthField.getValue());
GlobalConf.screenshot.SCREENSHOT_HEIGHT = ((Integer) ssheightField.getValue());
EventManager.instance.post(Events.SCREENSHOT_SIZE_UDPATE, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT);
// Frame output
File fofile = new File(frameTextContainer.getText());
if (fofile.exists() && fofile.isDirectory())
GlobalConf.frame.RENDER_FOLDER = fofile.getAbsolutePath();
String text = frameFileName.getText();
if (text.matches("^\\w+$")) {
GlobalConf.frame.RENDER_FILE_NAME = text;
}
GlobalConf.frame.FRAME_MODE = GlobalConf.ScreenshotMode.values()[frameMode.getSelectedIndex()];
GlobalConf.frame.RENDER_WIDTH = ((Integer) frameWidthField.getValue());
GlobalConf.frame.RENDER_HEIGHT = ((Integer) frameHeightField.getValue());
GlobalConf.frame.RENDER_TARGET_FPS = ((Integer) targetFPS.getValue());
EventManager.instance.post(Events.FRAME_SIZE_UDPATE, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT);
// Camera recording
GlobalConf.frame.CAMERA_REC_TARGET_FPS = (Integer) targetFPScamera.getValue();
GlobalConf.frame.AUTO_FRAME_OUTPUT_CAMERA_PLAY = (Boolean) autoFrameOutput.isSelected();
// Cube map resolution
GlobalConf.scene.CUBEMAP_FACE_RESOLUTION = (Integer) cubemapResolution.getValue();
// Save configuration
ConfInit.instance.persistGlobalConf(new File(System.getProperty("properties.file")));
EventManager.instance.post(Events.PROPERTIES_WRITTEN);
if (startup) {
gsd.launchMainApp();
}
frame.dispose();
singleton = null;
}
}
});
okButton.setMinimumSize(new Dimension(100, 20));
cancelButton = new JButton(txt("gui.cancel"));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (frame.isDisplayable()) {
frame.dispose();
singleton = null;
if (startup) {
gsd.terminate();
}
}
}
});
cancelButton.setMinimumSize(new Dimension(100, 20));
buttons.add(okButton);
buttons.add(cancelButton);
frame.add(body, BorderLayout.CENTER);
frame.add(buttons, BorderLayout.SOUTH);
}
private void enableComponents(boolean enabled, JComponent... components) {
for (JComponent c : components) {
if (c != null)
c.setEnabled(enabled);
}
}
private void selectFullscreen(boolean fullscreen, JSpinner widthField, JSpinner heightField, JComboBox<DisplayMode> fullScreenResolutions, JCheckBox resizable, JLabel widthLabel, JLabel heightLabel) {
if (fullscreen) {
GlobalConf.screen.SCREEN_WIDTH = ((DisplayMode) fullScreenResolutions.getSelectedItem()).width;
GlobalConf.screen.SCREEN_HEIGHT = ((DisplayMode) fullScreenResolutions.getSelectedItem()).height;
} else {
GlobalConf.screen.SCREEN_WIDTH = (Integer) widthField.getValue();
GlobalConf.screen.SCREEN_HEIGHT = (Integer) heightField.getValue();
}
enableComponents(!fullscreen, widthField, heightField, resizable, widthLabel, heightLabel);
enableComponents(fullscreen, fullScreenResolutions);
}
private int idxAa(int base, int x) {
if (x == -1)
return 1;
if (x == -2)
return 2;
if (x == 0)
return 0;
return (int) (Math.log(x) / Math.log(2) + 1e-10) + 2;
}
private int idxLang(String code, LangComboBoxBean[] langs) {
if (code.isEmpty()) {
code = I18n.bundle.getLocale().toLanguageTag();
}
for (int i = 0; i < langs.length; i++) {
if (langs[i].locale.toLanguageTag().equals(code)) {
return i;
}
}
return -1;
}
private class ComboBoxBean {
public String name;
public int value;
public ComboBoxBean(String name, int samples) {
super();
this.name = name;
this.value = samples;
}
@Override
public String toString() {
return name;
}
}
private class LangComboBoxBean implements Comparable<LangComboBoxBean> {
public Locale locale;
public String name;
public LangComboBoxBean(Locale locale) {
super();
this.locale = locale;
this.name = TextUtils.capitalise(locale.getDisplayName(locale));
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(LangComboBoxBean o) {
return this.name.compareTo(o.name);
}
}
private Thread getCheckVersionThread() {
return new Thread(new CallbackTask(new VersionChecker(GlobalConf.program.VERSION_CHECK_URL), new Callback() {
@Override
public void complete(Object result) {
checkPanel.removeAll();
checkPanel.add(checkLabel);
if (result instanceof String) {
// Error
checkLabel.setText("Error checking version: " + (String) result);
checkLabel.setForeground(Color.RED);
} else if (result instanceof JsonValue) {
JsonValue json = (JsonValue) result;
JsonValue last = json.get(0);
String version = last.getString("name");
if (version.matches("^(\\D{1})?\\d+.\\d+(\\D{1})?(.\\d+)?$")) {
GlobalConf.program.LAST_VERSION = new String(version);
GlobalConf.program.LAST_CHECKED = new Date();
newVersionCheck(version);
}
checkPanel.validate();
}
}
}));
}
/**
* Checks the given version against the current version and:
* <ul>
* <li>Displays a "new version available" message if the given version is
* newer than the current.</li>
* <li>Display a "you have the latest version" message and a "check now"
* button if the given version is older.</li>
* </ul>
*
* @param version
* The version to check.
*/
private void newVersionCheck(String version) {
int[] majmin = GlobalConf.VersionConf.getMajorMinorRevFromString(version);
if (majmin[0] > GlobalConf.version.major || (majmin[0] == GlobalConf.version.major && majmin[1] > GlobalConf.version.minor) || (majmin[0] == GlobalConf.version.major && majmin[1] == GlobalConf.version.minor) && majmin[2] > GlobalConf.version.rev) {
// There's a new version!
checkLabel.setText(txt("gui.newversion.available", GlobalConf.version, version));
try {
final URI uri = new URI(GlobalConf.WEBPAGE);
JButton button = new JButton();
button.setText(txt("gui.newversion.getit"));
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setToolTipText(uri.toString());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException ex) {
}
} else {
}
}
});
checkPanel.add(button);
} catch (URISyntaxException e1) {
}
} else {
checkLabel.setText(txt("gui.newversion.nonew", GlobalConf.program.getLastCheckedString()));
// Add check now button
JButton button = new JButton();
button.setText(txt("gui.newversion.checknow"));
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setToolTipText(txt("gui.newversion.checknow.tooltip"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getCheckVersionThread().start();
}
});
checkPanel.add(button);
}
checkLabel.setForeground(darkgreen);
}
private String keysToString(TreeSet<Integer> keys) {
String s = "";
int i = 0;
int n = keys.size();
for (Integer key : keys) {
s += Keys.toString(key).toUpperCase();
if (i < n - 1) {
s += " + ";
}
i++;
}
return s;
}
class JXTabbedPane extends JTabbedPane {
private ITabRenderer tabRenderer = new DefaultTabRenderer();
public JXTabbedPane() {
super();
}
public JXTabbedPane(int tabPlacement) {
super(tabPlacement);
}
public JXTabbedPane(int tabPlacement, int tabLayoutPolicy) {
super(tabPlacement, tabLayoutPolicy);
}
public ITabRenderer getTabRenderer() {
return tabRenderer;
}
public void setTabRenderer(ITabRenderer tabRenderer) {
this.tabRenderer = tabRenderer;
}
@Override
public void addTab(String title, Component component) {
this.addTab(title, null, component, null);
}
@Override
public void addTab(String title, Icon icon, Component component) {
this.addTab(title, icon, component, null);
}
@Override
public void addTab(String title, Icon icon, Component component, String tip) {
super.addTab(title, icon, component, tip);
int tabIndex = getTabCount() - 1;
Component tab = tabRenderer.getTabRendererComponent(this, title, icon, tabIndex);
super.setTabComponentAt(tabIndex, tab);
}
}
interface ITabRenderer {
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex);
}
abstract class AbstractTabRenderer implements ITabRenderer {
private String prototypeText = "";
private Icon prototypeIcon = UIManager.getIcon("OptionPane.informationIcon");
private int horizontalTextAlignment = SwingConstants.CENTER;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public AbstractTabRenderer() {
super();
}
public void setPrototypeText(String text) {
String oldText = this.prototypeText;
this.prototypeText = text;
firePropertyChange("prototypeText", oldText, text);
}
public String getPrototypeText() {
return prototypeText;
}
public Icon getPrototypeIcon() {
return prototypeIcon;
}
public void setPrototypeIcon(Icon icon) {
Icon oldIcon = this.prototypeIcon;
this.prototypeIcon = icon;
firePropertyChange("prototypeIcon", oldIcon, icon);
}
public int getHorizontalTextAlignment() {
return horizontalTextAlignment;
}
public void setHorizontalTextAlignment(int horizontalTextAlignment) {
this.horizontalTextAlignment = horizontalTextAlignment;
}
public PropertyChangeListener[] getPropertyChangeListeners() {
return propertyChangeSupport.getPropertyChangeListeners();
}
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return propertyChangeSupport.getPropertyChangeListeners(propertyName);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
PropertyChangeListener[] listeners = getPropertyChangeListeners();
for (int i = listeners.length - 1; i >= 0; i
listeners[i].propertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
}
}
}
class DefaultTabRenderer extends AbstractTabRenderer implements PropertyChangeListener {
private Component prototypeComponent;
public DefaultTabRenderer() {
super();
prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(), getHorizontalTextAlignment());
addPropertyChangeListener(this);
}
private Component generateRendererComponent(String text, Icon icon, int horizontalTabTextAlignmen) {
JPanel rendererComponent = new JPanel(new GridBagLayout());
rendererComponent.setOpaque(false);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(scale(2), scale(4), scale(2), scale(4));
c.fill = GridBagConstraints.HORIZONTAL;
rendererComponent.add(new JLabel(icon), c);
c.gridx = 1;
c.weightx = 1;
rendererComponent.add(new JLabel(text, horizontalTabTextAlignmen), c);
return rendererComponent;
}
@Override
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex) {
Component rendererComponent = generateRendererComponent(text, icon, getHorizontalTextAlignment());
int prototypeWidth = prototypeComponent.getPreferredSize().width;
int prototypeHeight = prototypeComponent.getPreferredSize().height;
float fontsize = new JLabel().getFont().getSize();
prototypeWidth = scale(Math.min(250, Math.round(150 * fontsize / 12f)));
prototypeHeight = scale(Math.min(30, Math.round(20 * fontsize / 12f)));
rendererComponent.setPreferredSize(new Dimension(prototypeWidth, prototypeHeight));
return rendererComponent;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("prototypeText".equals(propertyName) || "prototypeIcon".equals(propertyName)) {
this.prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(), getHorizontalTextAlignment());
}
}
}
private int scale(int value) {
return Math.round(value * GlobalConf.SCALE_FACTOR);
}
}
|
package nl.mpi.kinnate.export;
import java.util.ArrayList;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter;
import nl.mpi.kinnate.kintypestrings.ParserHighlight;
import nl.mpi.kinnate.svg.DataStoreSvg;
public class PedigreePackageExport {
private String getSimpleId(ArrayList<String> allIdArray, String entityIdentifier) {
// String entityIdentifier = entityData.getUniqueIdentifier();
if (!allIdArray.contains(entityIdentifier)) {
allIdArray.add(entityIdentifier);
}
return Integer.toString(allIdArray.indexOf(entityIdentifier));
}
private String getFirstMatchingParent(EntityData entityData, EntityData.SymbolType symbolType) {
for (EntityRelation entityRelation : entityData.getDistinctRelateNodes()) {
if (entityRelation.relationType.equals(DataTypes.RelationType.ancestor)) {
if (entityRelation.getAlterNode().getSymbolType().equals(symbolType.name())) {
return entityRelation.getAlterNode().getUniqueIdentifier();
}
}
}
return "orphan";
}
private int getIntegerGender(EntityData entityData) {
// Gender of individual noted in `id'. Character("male","female","unknown", "terminated") or numeric (1="male", 2="female", 3="unknown", 4="terminated") allowed.
String symbolName = entityData.getSymbolType();
if (symbolName.equals(EntityData.SymbolType.triangle.name())) {
return 1;
}
if (symbolName.equals(EntityData.SymbolType.circle.name())) {
return 2;
}
return 3;
}
public String createCsvContents(EntityData[] entityDataArray) {
ArrayList<String> allIdArray = new ArrayList<String>();
allIdArray.add("orphan"); // in the pedigree package a non existet entity has the id of 0 so we must keep that free
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("id\tmomid\tdadid\tsex\taffected\n"); // todo: add remaining elements: \tstatus\trelations\n");
for (EntityData entityData : entityDataArray) {
// prime the IDs so that the sequence matches the line sequence
getSimpleId(allIdArray, entityData.getUniqueIdentifier());
}
for (EntityData entityData : entityDataArray) {
stringBuilder.append(getSimpleId(allIdArray, entityData.getUniqueIdentifier()));
stringBuilder.append("\t");
// momid
stringBuilder.append(getSimpleId(allIdArray, getFirstMatchingParent(entityData, EntityData.SymbolType.circle)));
stringBuilder.append("\t");
// dadid
stringBuilder.append(getSimpleId(allIdArray, getFirstMatchingParent(entityData, EntityData.SymbolType.triangle)));
stringBuilder.append("\t");
// sex
stringBuilder.append(getIntegerGender(entityData));
stringBuilder.append("\t");
// affected
// One variable, or a matrix, indicating affection status. Assumed that 1="unaffected", 2="affected", NA or 0 = "unknown".
// todo: this could use an xquery on the xml data of the entity or the imdi etc.
if (entityData.isEgo) {
stringBuilder.append("2");
} else {
stringBuilder.append("1");
}
// stringBuilder.append("\t");
// status Status (0="censored", 1="dead")
// stringBuilder.append("\t");
// relations A matrix with 3 columns (id1, id2, code) specifying special relationship between pairs of individuals. Codes: 1=Monozygotic twin, 2=Dizygotic twin, 3=Twin of unknown zygosity, 4=Spouse and no children in pedigree
stringBuilder.append("\n");
}
return stringBuilder.toString();
}
static public void main(String[] argsArray) {
KinTypeStringConverter graphData = new KinTypeStringConverter();
// // todo: an addition to KinTypeStringConverter: EmB does not have any parents but it could however just take the parnents of Em: String kinTypes = "EmB|EmZ|EmM|EmF|EmS|EmD";
//String kinTypes = "EmM|EmF|EmS|EmD";
String kinTypes = "EmB|EmZ|EmM|EmF|EmS|EmD";
String[] kinTypeStrings = kinTypes.split("\\|");
graphData.readKinTypes(kinTypeStrings, /*graphPanel.getkinTermGroups()*/ new KinTermGroup[]{}, new DataStoreSvg(), new ParserHighlight[kinTypeStrings.length]);
System.out.println(new PedigreePackageExport().createCsvContents(graphData.getDataNodes()));
}
}
|
package cx2x.xcodeml.xnode;
import cx2x.xcodeml.helper.XelementHelper;
import cx2x.xcodeml.xelement.XbaseElement;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.List;
/**
* XcodeML AST node.
*
* @author clementval
*/
public class Xnode {
private final Element _baseElement;
public Xnode(Element element){
_baseElement = element;
}
/**
* Get the element opcode.
* @return Opcode.
*/
public Xcode Opcode(){
return Xcode.valueOf(_baseElement.getTagName());
}
/**
* Check whether the element has the corresponding attribute.
* @param attrCode Attribute code.
* @return True if the element has the corresponding attribute.
*/
public boolean hasAttribute(Xattr attrCode){
return _baseElement != null
&& _baseElement.hasAttribute(attrCode.toString());
}
/**
* Get the attribute's value.
* @param attrCode Attribute code.
* @return Attribute's value.
*/
public String getAttribute(Xattr attrCode){
return _baseElement.getAttribute(attrCode.toString());
}
/**
* Get the element's value.
* @return Element value.
*/
public String getValue(){
return _baseElement.getTextContent();
}
/**
* Set attribute value.
* @param attrCode Attribute code.
* @param value Value of the attribute.
*/
public void setAttribute(Xattr attrCode, String value){
_baseElement.setAttribute(attrCode.toString(), value);
}
/**
* Get the list of child elements.
* @return List of children of the current element.
*/
public List<Xnode> getChildren(){
List<Xnode> nodes = new ArrayList<>();
NodeList children = _baseElement.getChildNodes();
for(int i = 0; i < children.getLength(); ++i){
Node child = children.item(i);
if(child.getNodeType() == Node.ELEMENT_NODE){
nodes.add(new Xnode((Element)child));
}
}
return nodes;
}
/**
* Check whether the current element has a body element.
* @return True if the element has a body. False otherwise.
*/
public boolean hasBody(){
switch (Opcode()){
case FDOSTATEMENT:
case FFUNCTIONDEFINITION:
return true;
}
return false;
}
/**
* Get the inner body element.
* @return The body element if found. Null otherwise.
*/
public Xnode getBody(){
return findNode(Xcode.BODY);
}
/**
* Find first child with the given opcode.
* @param opcode Code of the element to be found.
* @return The found element. Null if nothing found.
*/
public Xnode findNode(Xcode opcode){
List<Xnode> children = getChildren();
for(Xnode child : children){
if(child.Opcode() == opcode){
return child;
}
}
return null;
}
/**
* Get child at position.
* @param pos Position of the child.
* @return Child at the corresponding position.
*/
public Xnode getChild(int pos){
List<Xnode> children = getChildren();
if(pos < 0 || pos > children.size() - 1){
return null;
}
return children.get(pos);
}
/**
* Set the element value.
* @param value The element value.
*/
public void setValue(String value){
_baseElement.setTextContent(value);
}
/**
* Delete the stored root element and all its children.
*/
public void delete(){
XelementHelper.delete(_baseElement);
}
/**
* Get the base element.
* @return Element.
*/
public Element getElement(){
return _baseElement;
}
/**
* Create an identical copy of the element and its children.
* @return A node representing the root element of the clone.
*/
public Node cloneNode(){
return _baseElement.cloneNode(true);
}
/**
* Append an element ot the children of this element.
* @param node The element to append.
* @param clone If true, the element is cloned before being appened. If
* false, the element is directly appened.
*/
public void appendToChildren(Xnode node, boolean clone){
if(node != null){
if(clone){
_baseElement.appendChild(node.cloneNode());
} else {
_baseElement.appendChild(node.getElement());
}
}
}
}
|
package vvk.numbers;
import java.util.Arrays;
public final class PAdic {
private static final int len;
private static final boolean[] isPrime;
private static int precalculatedPrimes;
private final int base;
private final int digits[];
private final int order;
private static enum Operation {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION
}
static {
len = (1 << 6);
precalculatedPrimes = (1 << 16);
isPrime = new boolean[precalculatedPrimes];
doEratostheneSieve();
}
/**
* Constructs p-adic number from integer value.
* @param value integer value in base 10.
* @param base base of field of p-adic numbers.
* Notice that base must be a prime number.
*/
public PAdic(final long value, final int base) {
PAdic.checkForPrime(base);
this.digits = new int[PAdic.len];
this.base = base;
final boolean isNegative = (value < 0);
long current = Math.abs(value);
int pos = 0;
while (current != 0) {
digits[pos] = (int) current % base;
current /= base;
++pos;
}
if (isNegative) {
toNegative();
}
int order = 0;
while (order < PAdic.len && digits[order] == 0) {
++order;
}
this.order = order < PAdic.len ? order : 0;
}
/**
* Constructs p-adic number from its string representation.
* @param value string that represents p-adic number.
* It can be either integer value or floating point value.
* Notice that point can be defined by '.' symbol only.
* @param base base of field of p-adic numbers.
* Notice that base must be a prime number.
*/
public PAdic(final String value, final int base) {
PAdic.checkForPrime(base);
this.digits = new int[PAdic.len];
this.base = base;
final int pointAt = value.lastIndexOf('.');
int posInString = value.length() - 1;
int posInDigits = 0;
while (posInString >= 0) {
if (posInString == pointAt) {
--posInString;
continue;
}
if (!Character.isDigit(value.charAt(posInString))) {
throw new RuntimeException("There must be only digits in the number, no letters or spectial symbols except of one floating point");
}
digits[posInDigits] = value.charAt(posInString) - '0';
--posInString;
++posInDigits;
}
int pos = 0;
while (pos < PAdic.len && digits[pos] == 0) {
++pos;
}
int order;
if (pointAt != -1 ) {
order = -(value.length() - pointAt - 1);
if (order < 0 ) {
final int offset = Math.min(-order, pos);
for (int i = 0; i + offset < PAdic.len; ++i) {
digits[i] = digits[i + offset];
}
order += offset;
}
} else {
if (pos == PAdic.len) {
pos = 0;
}
order = pos;
}
this.order = order;
}
/**
* Constructs p-adic number from rational fraction.
* @param numerator numerator of the fraction in base 10. Must be integer value.
* @param denominator denominator of the fracture in base 10. Denominator must be positive.
* @param base base of field of p-adic numbers.
* Notice that base must be a prime number.
*/
public PAdic(final int numerator, final int denominator, final int base) {
PAdic.checkForPrime(base);
final int g = gcd(Math.abs(numerator), Math.abs(denominator));
final int actualNumerator = numerator / g;
final int actualDenominator = denominator / g;
final PAdic pAdicNumerator = new PAdic(actualNumerator, base);
final PAdic pAdicDenominator = new PAdic(actualDenominator, base);
final PAdic pAdicResult = pAdicNumerator.divide(pAdicDenominator);
this.digits = Arrays.copyOfRange(pAdicResult.digits, 0, PAdic.len);
this.order = pAdicResult.order;
this.base = pAdicResult.base;
}
private PAdic(final int[] digits, final int order, final int base) {
PAdic.checkForPrime(base);
this.base = base;
this.digits = Arrays.copyOfRange(digits, 0, PAdic.len);
this.order = order;
}
private void toNegative() {
int pos = 0;
while (pos < PAdic.len && digits[pos] == 0) {
++pos;
}
if (pos < PAdic.len) {
digits[pos] = base - digits[pos];
}
for (int i = pos + 1; i < PAdic.len; ++i) {
digits[i] = base - digits[i] - 1;
}
}
/**
* Returns result of sum this p-adic number with <code>added</code>.
* @param added p-adic number to be added.
* @return p-adic number that is result of sum.
*/
public PAdic add(final PAdic added) {
PAdic.checkForBaseEquality(this, added);
if (this.getOrder() < 0 || added.getOrder() < 0) {
final int leftOperandOrder = Math.min(this.getOrder(), 0);
final int rightOperandOrder = Math.min(added.getOrder(), 0);
final int diff = leftOperandOrder - rightOperandOrder;
final int offset = Math.abs(diff);
return diff < 0 ? this.add(added, offset) : added.add(this, offset);
}
return add(added, 0);
}
private PAdic add(final PAdic added, int offset) {
PAdic.checkForBaseEquality(this, added);
final int[] result = new int[PAdic.len];
int toNext = 0;
for (int i = 0; i < offset; ++i) {
result[i] = digits[i];
}
for (int i = 0; i + offset < PAdic.len; ++i) {
final int next = digits[i + offset] + added.digits[i] + toNext;
toNext = next / base;
result[i + offset] = next % base;
}
final int order = PAdic.calculateOrder(result, this.getOrder(), added.getOrder(), Operation.ADDITION);
return new PAdic(result, order, this.base);
}
/**
* Returns difference of p-adic number and <code>subtracted</code> value.
* @param subtracted p-adic number to be subtracted.
* @return p-adic number that is result of subtraction.
*/
public PAdic subtract(final PAdic subtracted) {
PAdic.checkForBaseEquality(this, subtracted);
PAdic actual = null;
final int[] digits = new int[PAdic.len];
boolean haveActual = false;
if (subtracted.getOrder() < 0 && subtracted.getOrder() < this.getOrder()) {
final int diff = Math.abs(subtracted.getOrder() - Math.min(this.getOrder(), 0));
for (int i = PAdic.len - 1; i - diff >= 0; --i) {
final int idx = i - diff;
digits[i] = this.digits[idx];
}
final int newOrder = Math.min(this.getOrder(), 0) - diff;
actual = new PAdic(digits, newOrder, this.base);
haveActual = true;
}
if (!haveActual) {
actual = (PAdic) this.clone();
}
if (actual.getOrder() < 0 && subtracted.getOrder() >= 0) {
return actual.subtract(subtracted, -actual.getOrder());
}
final int offset;
if (actual.getOrder() < 0 || subtracted.getOrder() < 0) {
// Need to shift digits in such way that point was exactly under point.
// Example:
// _12345.67890 => _12345.67890 _ 100000 => _100000.00000
// 123.45 => 123.45000 OR 12345.12345 => 12345.12345
final int leftOperandOrder = Math.min(actual.getOrder(), 0);
final int rightOperandOrder = Math.min(subtracted.getOrder(), 0);
offset = Math.abs(leftOperandOrder - rightOperandOrder);
} else {
offset = 0;
}
return actual.subtract(subtracted, offset);
}
private PAdic subtract(final PAdic subtracted, final int offset) {
PAdic.checkForBaseEquality(this, subtracted);
final int[] result = new int[PAdic.len];
boolean takeOne;
for (int i = 0; i < offset; ++i) {
result[i] = digits[i];
}
for (int i = 0; i + offset < PAdic.len; ++i) {
final int idx = i + offset;
if (digits[idx] < subtracted.digits[i]) {
takeOne = true;
int j = idx + 1;
while (j < PAdic.len && takeOne) {
if (digits[j] == 0) {
digits[j] = base - 1;
} else {
--digits[j];
takeOne = false;
}
++j;
}
digits[idx] += base;
}
result[idx] = digits[idx] - subtracted.digits[i];
}
final int order = PAdic.calculateOrder(result, this.getOrder(), subtracted.getOrder(), Operation.SUBTRACTION);
return new PAdic(result, order, this.base);
}
/**
* Returns result of multiplication of this p-adic number by <code>multiplier</code> value.
* @param multiplier value to multiply this p-adic number by.
* @return p-adic number that is result of multiplication.
*/
public PAdic multiply(final PAdic multiplier) {
PAdic.checkForBaseEquality(this, multiplier);
PAdic result = new PAdic("0", this.base);
for (int i = 0; i < PAdic.len; ++i) {
final int temp[] = multiplyToInteger(digits, multiplier.digits[i]);
final PAdic adder = new PAdic(temp, 0, this.base);
result = result.add(adder, i);
}
// In some cases when we multiply numbers, it may happens that
// real index of the most right non-zero coefficient gets greater than it must be.
// For example, multiplying ...00000.1 (order = -1) by ...000010 (order = 1)
// we will get ...0000010 (order = 1) that's incorrect, because its order must be zero.
// So, the order calculated correctly, but we need to shift the result a little to the right.
final int minOrder = Math.min(this.getOrder(), multiplier.getOrder());
final int maxOrder = Math.max(this.getOrder(), multiplier.getOrder());
if (minOrder < 0 && 0 < maxOrder) {
int pos = 0;
while (pos < -minOrder && result.digits[pos] == 0) {
++pos;
}
for (int i = 0; i + pos < PAdic.len; ++i) {
result.digits[i] = result.digits[i + pos];
}
}
final int order = PAdic.calculateOrder(result.digits, this.getOrder(), multiplier.getOrder(), Operation.MULTIPLICATION);
return new PAdic(result.digits, order, this.base);
}
/**
* Returns result of division of this p-adic number by <code>divisor</code> value.
* @param divisor value to divide this p-adic number by.
* @return p-adic number that is result of division.
*/
public PAdic divide(final PAdic divisor) {
PAdic.checkForBaseEquality(this, divisor);
final int[] result = new int[PAdic.len];
PAdic divided = new PAdic(this.digits, 0, this.base);
int pos = 0;
while (pos < PAdic.len && divisor.digits[pos] == 0) {
++pos;
}
final int[] temp = new int[PAdic.len];
for (int i = 0; i + pos < PAdic.len; ++i) {
temp[i] = divisor.digits[i + pos];
}
for (int i = PAdic.len - pos; i < PAdic.len; ++i) {
temp[i] = temp[PAdic.len - pos - 1];
}
final PAdic actualDivisor = new PAdic(temp, divisor.getOrder() - pos, this.base);
for (int i = 0; i < PAdic.len; ++i) {
final int digit = findMultiplier(divided.digits[i], actualDivisor.digits[0]);
if (digit == -1) {
throw new RuntimeException("Bullshit, that shouldn't happened.");
}
final int[] tmp = multiplyToInteger(actualDivisor.digits, digit);
result[i] = digit;
divided = divided.subtract(new PAdic(tmp, 0, this.base), i);
}
final int order = PAdic.calculateOrder(result, this.getOrder() - pos, actualDivisor.getOrder(), Operation.DIVISION);
return new PAdic(result, order, this.base);
}
/**
* Returns order of p-adic number.
* Order of p-adic number is maximal power <i>n</i> of <i>p</i> so <i>p</i> in power <i>n</i> divides the number.
* @return order of the number.
*/
public int getOrder() {
return order;
}
private static int calculateOrder(final int[] digits, final int firstOrder, final int secondOrder, Operation operation) {
int order = 0;
if (operation == Operation.ADDITION || operation == Operation.SUBTRACTION){
order = Math.min(firstOrder, secondOrder);
}
if (operation == Operation.MULTIPLICATION) {
order = firstOrder + secondOrder;
}
if (operation == Operation.DIVISION) {
order = firstOrder - secondOrder;
}
int pos = 0;
while (pos < PAdic.len && digits[pos] == 0) {
++pos;
}
if (pos == PAdic.len) {
return 0;
}
if (0 <= order && order < pos) {
order = pos;
}
if (order < 0) {
final int min = Math.min(-order, pos);
for (int i = 0; i + min < PAdic.len; ++i) {
digits[i] = digits[i + min];
}
order += pos;
}
return order;
}
private int[] multiplyToInteger(final int[] number, final int multiplier) {
int toNext = 0;
final int[] result = new int[PAdic.len];
for (int i = 0; i < number.length; ++i) {
final int next = number[i] * multiplier + toNext;
toNext = next / base;
result[i] = next % base;
}
return result;
}
private int findMultiplier(final int mod, final int multiplier) {
for (int i = 0; i < base; ++i) {
if ((multiplier * i) % base == mod) {
return i;
}
}
return -1;
}
private static void doEratostheneSieve() {
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < precalculatedPrimes; ++i) {
if (!isPrime[i]) {
continue;
}
for (int j = i + i; j < precalculatedPrimes; j += i) {
isPrime[j] = false;
}
}
}
private static void checkForPrime(final int base) {
final boolean isPrimeBase = (base < precalculatedPrimes && isPrime[base]);
if (!isPrimeBase) {
throw new RuntimeException("Base " + base + " is not prime. Base must be a prime number.");
}
}
private static void checkForBaseEquality(final PAdic first, final PAdic second) {
final boolean areEqual = (first.base == second.base);
if (!areEqual) {
throw new RuntimeException("Mathematical operations can be done only with p-adic numbers that have the same base.");
}
}
private int gcd(final int a, final int b) {
return b == 0 ? a : gcd(b, a % b);
}
@Override
protected Object clone(){
return new PAdic(this.digits, this.order, this.base);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(PAdic.len);
int pos = PAdic.len - 1;
while (pos >= 0 && digits[pos] == 0) {
--pos;
}
if (pos == -1) {
++pos;
}
for (int i = pos; i >= 0; --i) {
result.append(digits[i]);
}
if (order < 0) {
while (result.length() < -order) {
result.insert(0, '0');
}
result.insert(result.length() + order, '.');
}
if (result.charAt(0) == '.') {
result.insert(0, '0');
}
return result.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof PAdic)) {
return false;
}
PAdic number = (PAdic) obj;
if (this.base != number.base) {
return false;
}
if (this.order != number.order) {
return false;
}
for (int i = 0; i < PAdic.len; ++i) {
if (this.digits[i] != number.digits[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = 0;
final int prime = 31;
for (int i = 0; i < PAdic.len; ++i) {
hash = hash * prime + digits[i];
}
hash = hash * prime + order;
hash = hash * prime + base;
return hash;
}
}
|
package com.intellij.util.xml.ui;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomUtil;
import com.intellij.util.xml.GenericDomValue;
import com.intellij.util.xml.highlighting.DomElementAnnotationsManager;
import com.intellij.util.xml.reflect.DomChildrenDescription;
import com.intellij.util.xml.reflect.DomCollectionChildDescription;
import com.intellij.util.xml.reflect.DomFixedChildDescription;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public abstract class BasicDomElementComponent<T extends DomElement> extends AbstractDomElementComponent<T> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.ui.editors.BasicDomElementComponent");
private final Map<JComponent, DomUIControl> myBoundComponents = new HashMap<JComponent, DomUIControl>();
public BasicDomElementComponent(T domElement) {
super(domElement);
}
protected final void bindProperties() {
bindProperties(getDomElement());
}
protected boolean commitOnEveryChange(GenericDomValue element) {
return false;
}
protected final void bindProperties(final DomElement domElement) {
if (domElement == null) return;
DomElementAnnotationsManager.getInstance(domElement.getManager().getProject()).addHighlightingListener(new DomElementAnnotationsManager.DomHighlightingListener() {
public void highlightingFinished(@NotNull final DomFileElement element) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (getComponent().isShowing() && element.isValid()) {
updateHighlighting();
}
}
});
}
}, this);
for (final DomChildrenDescription description : domElement.getGenericInfo().getChildrenDescriptions()) {
final JComponent boundComponent = getBoundComponent(description);
if (boundComponent != null) {
if (description instanceof DomFixedChildDescription && DomUtil.isGenericValueType(description.getType())) {
if ((description.getValues(domElement)).size() == 1) {
final GenericDomValue element = domElement.getManager().createStableValue(new Factory<GenericDomValue>() {
public GenericDomValue create() {
return domElement.isValid() ? (GenericDomValue)description.getValues(domElement).get(0) : null;
}
});
doBind(DomUIFactory.createControl(element, commitOnEveryChange(element)), boundComponent);
}
else {
//todo not bound
}
}
else if (description instanceof DomCollectionChildDescription) {
doBind(DomUIFactory.getDomUIFactory().createCollectionControl(domElement, (DomCollectionChildDescription)description), boundComponent);
}
}
}
reset();
}
protected void doBind(final DomUIControl control, final JComponent boundComponent) {
myBoundComponents.put(boundComponent, control);
control.bind(boundComponent);
addComponent(control);
}
private JComponent getBoundComponent(final DomChildrenDescription description) {
for (Field field : getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (convertFieldName(field.getName(), description).equals(description.getXmlElementName()) && field.get(this) instanceof JComponent)
{
return (JComponent)field.get(this);
}
}
catch (IllegalAccessException e) {
LOG.error(e);
}
}
return null;
}
private String convertFieldName(String propertyName, final DomChildrenDescription description) {
if (propertyName.startsWith("my")) propertyName = propertyName.substring(2);
String convertedName = description.getDomNameStrategy(getDomElement()).convertName(propertyName);
if (description instanceof DomCollectionChildDescription) {
final String unpluralizedStr = StringUtil.unpluralize(convertedName);
if (unpluralizedStr != null) return unpluralizedStr;
}
return convertedName;
}
public final Project getProject() {
return getDomElement().getManager().getProject();
}
public final Module getModule() {
return getDomElement().getModule();
}
protected final DomUIControl getDomControl(JComponent component) {
return myBoundComponents.get(component);
}
}
|
package org.drools.marshalling;
import java.io.ByteArrayOutputStream;
import org.drools.KnowledgeBase;
import org.drools.ProviderInitializationException;
/**
* <p>
* The MarshallerFactory is used to marshal and unmarshal StatefulKnowledgeSessions. At the simplest it can be used as follows:
* </p>
* <pre>
* // ksession is the StatefulKnowledgeSession
* // kbase is the KnowledgeBase
* ByteArrayOutputStream baos = new ByteArrayOutputStream();
* Marshaller marshaller = MarshallerFactory.newMarshaller( kbase );
* marshaller.marshall( baos, ksession );
* baos.close();
* </pre>
*
* <p>
* However with marshalling you need more flexibility when dealing with referenced user data. To achieve this we have the
* ObjectMarshallingStrategy interface. Two implementations are provided, but the user can implement their own. The two
* supplied are IdentityMarshallingStrategy and SerializeMarshallingStrategy. SerializeMarshallingStrategy is the default, as used
* in the example above and it just calls the Serializable or Externalizable methods on a user instance. IdentityMarshallingStrategy
* instead creates an int id for each user object and stores them in a Map the id is written to the stream. When unmarshalling
* it simply looks to the IdentityMarshallingStrategy map to retrieve the instance. This means that if you use the IdentityMarshallingStrategy
* it's stateful for the life of the Marshaller instance and will create ids and keep references to all objects that it attempts to marshal.
* Here is he code to use a IdentityMarshallingStrategy.
* </p>
* <pre>
* ByteArrayOutputStream baos = new ByteArrayOutputStream();
* Marshaller marshaller = MarshallerFactory.newMarshaller( kbase, new ObjectMarshallingStrategy[] { MarshallerFactory.newIdentityMarshallingStrategy() } );
* marshaller.marshall( baos, ksession );
* baos.close();
* </pre>
* <p>
* For added flexability we can't assume that a single strategy is suitable for this we have added the ObjectMarshallingStrategyAcceptor interface that each
* ObjectMarshallingStrategy has. The Marshaller has a chain of strategies and when it attempts to read or write a user object it iterates the strategies asking
* if they accept responsability for marshalling the user object. One one implementation is provided the ClassFilterAcceptor. This allows strings and wild cards
* to be used to match class names. The default is "*.*", so in the above the IdentityMarshallingStrategy is used which has a default "*.*" acceptor.
* </p>
*
* <p>
* But lets say we want to serialise all classes except for one given package, where we will use identity lookup, we could do the following:
* </p>
* <pre>
* ByteArrayOutputStream baos = new ByteArrayOutputStream();
* ObjectMarshallingStrategyAcceptor identityAceceptor = MarshallerFactory.newClassFilterAcceptor( new String[] { "org.domain.pkg1.*" } );
* ObjectMarshallingStrategy identityStratetgy = MarshallerFactory.newIdentityMarshallingStrategy( identityAceceptor );
* Marshaller marshaller = MarshallerFactory.newMarshaller( kbase, new ObjectMarshallingStrategy[] { identityStratetgy, MarshallerFactory.newSerializeMarshallingStrategy() } );
* marshaller.marshall( baos, ksession );
* baos.close();
* </pre>
*
* <p>
* Not that the acceptance checking order is in the natural order of the supplied array.
* </p>
*
*/
public class MarshallerFactory {
private static volatile MarshallerProvider provider;
public static ObjectMarshallingStrategyAcceptor newClassFilterAcceptor(String[] patterns) {
return getMarshallerProvider().newClassFilterAcceptor( patterns );
}
public static ObjectMarshallingStrategy newIdentityMarshallingStrategy() {
return getMarshallerProvider().newIdentityMarshallingStrategy();
}
public static ObjectMarshallingStrategy newIdentityMarshallingStrategy(ObjectMarshallingStrategyAcceptor acceptor) {
return getMarshallerProvider().newIdentityMarshallingStrategy( acceptor );
}
public static ObjectMarshallingStrategy newSerializeMarshallingStrategy() {
return getMarshallerProvider().newSerializeMarshallingStrategy();
}
public static ObjectMarshallingStrategy newSerializeMarshallingStrategy(ObjectMarshallingStrategyAcceptor acceptor) {
return getMarshallerProvider().newSerializeMarshallingStrategy( acceptor );
}
/**
* Default uses the serialise marshalling strategy.
* @return
*/
public static Marshaller newMarshaller(KnowledgeBase kbase) {
return getMarshallerProvider().newMarshaller( kbase );
}
public static Marshaller newMarshaller(KnowledgeBase kbase,
ObjectMarshallingStrategy[] strategies) {
return getMarshallerProvider().newMarshaller( kbase,
strategies );
}
private static synchronized void setMarshallerProvider(MarshallerProvider provider) {
MarshallerFactory.provider = provider;
}
private static synchronized MarshallerProvider getMarshallerProvider() {
if ( provider == null ) {
loadProvider();
}
return provider;
}
private static void loadProvider() {
try {
Class<MarshallerProvider> cls = (Class<MarshallerProvider>) Class.forName( "org.drools.marshalling.impl.MarshallerProviderImpl" );
setMarshallerProvider( cls.newInstance() );
} catch ( Exception e2 ) {
throw new ProviderInitializationException( "Provider org.drools.marshalling.impl.MarshallerProviderImpl could not be set.",
e2 );
}
}
}
|
package org.opencds.cqf.dstu3.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.entity.ContentType;
import org.cqframework.cql.elm.execution.Library;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.PlanDefinition;
import org.opencds.cqf.cds.discovery.DiscoveryResolutionStu3;
import org.opencds.cqf.cds.evaluation.EvaluationContext;
import org.opencds.cqf.cds.evaluation.Stu3EvaluationContext;
import org.opencds.cqf.cds.hooks.Hook;
import org.opencds.cqf.cds.hooks.HookFactory;
import org.opencds.cqf.cds.hooks.Stu3HookEvaluator;
import org.opencds.cqf.cds.providers.ProviderConfiguration;
import org.opencds.cqf.cds.request.JsonHelper;
import org.opencds.cqf.cds.request.Request;
import org.opencds.cqf.cds.response.CdsCard;
import org.opencds.cqf.common.config.HapiProperties;
import org.opencds.cqf.common.exceptions.InvalidRequestException;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.common.retrieve.JpaFhirRetrieveProvider;
import org.opencds.cqf.cql.engine.data.CompositeDataProvider;
import org.opencds.cqf.cql.engine.debug.DebugMap;
import org.opencds.cqf.cql.engine.exception.CqlException;
import org.opencds.cqf.cql.engine.execution.Context;
import org.opencds.cqf.cql.engine.execution.LibraryLoader;
import org.opencds.cqf.cql.engine.fhir.exception.DataProviderException;
import org.opencds.cqf.cql.engine.fhir.model.Dstu3FhirModelResolver;
import org.opencds.cqf.dstu3.helpers.LibraryHelper;
import org.opencds.cqf.dstu3.providers.PlanDefinitionApplyProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.cql.dstu3.provider.JpaTerminologyProvider;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
@WebServlet(name = "cds-services")
public class CdsHooksServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private FhirVersionEnum version = FhirVersionEnum.DSTU3;
private static final Logger logger = LoggerFactory.getLogger(CdsHooksServlet.class);
private org.opencds.cqf.dstu3.providers.PlanDefinitionApplyProvider planDefinitionProvider;
private LibraryResolutionProvider<org.hl7.fhir.dstu3.model.Library> libraryResolutionProvider;
private JpaFhirRetrieveProvider fhirRetrieveProvider;
private JpaTerminologyProvider jpaTerminologyProvider;
private ProviderConfiguration providerConfiguration;
@SuppressWarnings("unchecked")
@Override
public void init() {
// System level providers
ApplicationContext appCtx = (ApplicationContext) getServletContext()
.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
this.providerConfiguration = appCtx.getBean(ProviderConfiguration.class);
this.planDefinitionProvider = appCtx.getBean(PlanDefinitionApplyProvider.class);
this.libraryResolutionProvider = (LibraryResolutionProvider<org.hl7.fhir.dstu3.model.Library>)appCtx.getBean(LibraryResolutionProvider.class);
this.fhirRetrieveProvider = appCtx.getBean(JpaFhirRetrieveProvider.class);
this.jpaTerminologyProvider = appCtx.getBean(JpaTerminologyProvider.class);
}
protected ProviderConfiguration getProviderConfiguration() {
return this.providerConfiguration;
}
// CORS Pre-flight
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
setAccessControlHeaders(resp);
resp.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
resp.setHeader("X-Content-Type-Options", "nosniff");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.info(request.getRequestURI());
if (!request.getRequestURL().toString().endsWith("cds-services")) {
logger.error(request.getRequestURI());
throw new ServletException("This servlet is not configured to handle GET requests.");
}
this.setAccessControlHeaders(response);
response.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
response.getWriter().println(new GsonBuilder().setPrettyPrinting().create().toJson(getServices()));
}
@Override
@SuppressWarnings("deprecation")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info(request.getRequestURI());
try {
// validate that we are dealing with JSON
if (request.getContentType() == null || !request.getContentType().startsWith("application/json")) {
throw new ServletException(String.format("Invalid content type %s. Please use application/json.", request.getContentType()));
}
String baseUrl = HapiProperties.getServerAddress();
String service = request.getPathInfo().replace("/", "");
JsonParser parser = new JsonParser();
JsonObject requestJson = parser.parse(request.getReader()).getAsJsonObject();
logger.info(requestJson.toString());
Request cdsHooksRequest = new Request(service, requestJson, JsonHelper.getObjectRequired(getService(service), "prefetch"));
Hook hook = HookFactory.createHook(cdsHooksRequest);
String hookName = hook.getRequest().getHook();
logger.info("cds-hooks hook: " + hookName);
logger.info("cds-hooks hook instance: " + hook.getRequest().getHookInstance());
logger.info("cds-hooks maxCodesPerQuery: " + this.getProviderConfiguration().getMaxCodesPerQuery());
logger.info("cds-hooks expandValueSets: " + this.getProviderConfiguration().getExpandValueSets());
logger.info("cds-hooks searchStyle: " + this.getProviderConfiguration().getSearchStyle());
logger.info("cds-hooks prefetch maxUriLength: " + this.getProviderConfiguration().getMaxUriLength());
logger.info("cds-hooks local server address: " + baseUrl);
logger.info("cds-hooks fhir server address: " + hook.getRequest().getFhirServerUrl());
PlanDefinition planDefinition = planDefinitionProvider.getDao().read(new IdType(hook.getRequest().getServiceName()));
AtomicBoolean planDefinitionHookMatchesRequestHook = new AtomicBoolean(false);
planDefinition.getAction().forEach(action -> {
action.getTriggerDefinition().forEach(triggerDefn -> {
if(hookName.equals(triggerDefn.getEventName())){
planDefinitionHookMatchesRequestHook.set(true);
return;
}
});
if(planDefinitionHookMatchesRequestHook.get()){
return;
}
});
if(!planDefinitionHookMatchesRequestHook.get()){
throw new ServletException("ERROR: Request hook does not match the service called.");
}
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(libraryResolutionProvider);
Library library = LibraryHelper.resolvePrimaryLibrary(planDefinition, libraryLoader, libraryResolutionProvider);
Dstu3FhirModelResolver resolver = new Dstu3FhirModelResolver();
CompositeDataProvider provider = new CompositeDataProvider(resolver, fhirRetrieveProvider);
Context context = new Context(library);
DebugMap debugMap = new DebugMap();
debugMap.setIsLoggingEnabled(true);
context.setDebugMap(debugMap);
context.registerDataProvider("http://hl7.org/fhir", provider); // TODO make sure tooling handles remote
// provider case
context.registerTerminologyProvider(jpaTerminologyProvider);
context.registerLibraryLoader(libraryLoader);
context.setContextValue("Patient", hook.getRequest().getContext().getPatientId().replace("Patient/", ""));
context.setExpressionCaching(true);
EvaluationContext<PlanDefinition> evaluationContext = new Stu3EvaluationContext(hook, version, FhirContext.forDstu3().newRestfulGenericClient(baseUrl),
jpaTerminologyProvider, context, library,
planDefinition, this.getProviderConfiguration());
this.setAccessControlHeaders(response);
response.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
Stu3HookEvaluator evaluator = new Stu3HookEvaluator();
String jsonResponse = toJsonResponse(evaluator.evaluate(evaluationContext));
logger.info(jsonResponse);
response.getWriter().println(jsonResponse);
} catch (BaseServerResponseException e) {
this.setAccessControlHeaders(response);
response.setStatus(500); // This will be overwritten with the correct status code downstream if needed.
response.getWriter().println("ERROR: Exception connecting to remote server.");
this.printMessageAndCause(e, response);
this.handleServerResponseException(e, response);
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (DataProviderException e) {
this.setAccessControlHeaders(response);
response.setStatus(500); // This will be overwritten with the correct status code downstream if needed.
response.getWriter().println("ERROR: Exception in DataProvider.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
}
catch (CqlException e) {
this.setAccessControlHeaders(response);
response.setStatus(500); // This will be overwritten with the correct status code downstream if needed.
response.getWriter().println("ERROR: Exception in CQL Execution.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (Exception e) {
logger.error(e.toString());
throw new ServletException("ERROR: Exception in cds-hooks processing.", e);
}
}
private void handleServerResponseException(BaseServerResponseException e, HttpServletResponse response)
throws IOException {
switch (e.getStatusCode()) {
case 401:
case 403:
response.getWriter().println("Precondition Failed. Remote FHIR server returned: " + e.getStatusCode());
response.getWriter().println("Ensure that the fhirAuthorization token is set or that the remote server allows unauthenticated access.");
response.setStatus(412);
break;
case 404:
response.getWriter().println("Precondition Failed. Remote FHIR server returned: " + e.getStatusCode());
response.getWriter().println("Ensure the resource exists on the remote server.");
response.setStatus(412);
break;
default:
response.getWriter().println("Unhandled Error in Remote FHIR server: " + e.getStatusCode());
}
}
private void printMessageAndCause(Exception e, HttpServletResponse response) throws IOException {
if (e.getMessage() != null) {
response.getWriter().println(e.getMessage());
}
if (e.getCause() != null && e.getCause().getMessage() != null) {
response.getWriter().println(e.getCause().getMessage());
}
}
private void printStackTrack(Exception e, HttpServletResponse response) throws IOException {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
response.getWriter().println(exceptionAsString);
}
private JsonObject getService(String service) {
JsonArray services = getServices().get("services").getAsJsonArray();
List<String> ids = new ArrayList<>();
for (JsonElement element : services) {
if (element.isJsonObject() && element.getAsJsonObject().has("id")) {
ids.add(element.getAsJsonObject().get("id").getAsString());
if (element.isJsonObject() && element.getAsJsonObject().get("id").getAsString().equals(service)) {
return element.getAsJsonObject();
}
}
}
throw new InvalidRequestException(
"Cannot resolve service: " + service + "\nAvailable services: " + ids.toString());
}
private JsonObject getServices() {
DiscoveryResolutionStu3 discoveryResolutionStu3 = new DiscoveryResolutionStu3(
FhirContext.forDstu3().newRestfulGenericClient(HapiProperties.getServerAddress()));
discoveryResolutionStu3.setMaxUriLength(this.getProviderConfiguration().getMaxUriLength());
return discoveryResolutionStu3.resolve()
.getAsJson();
}
private String toJsonResponse(List<CdsCard> cards) {
JsonObject ret = new JsonObject();
JsonArray cardArray = new JsonArray();
for (CdsCard card : cards) {
cardArray.add(card.toJson());
}
ret.add("cards", cardArray);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(ret);
}
private void setAccessControlHeaders(HttpServletResponse resp) {
if (HapiProperties.getCorsEnabled()) {
resp.setHeader("Access-Control-Allow-Origin", HapiProperties.getCorsAllowedOrigin());
resp.setHeader("Access-Control-Allow-Methods",
String.join(", ", Arrays.asList("GET", "HEAD", "POST", "OPTIONS")));
resp.setHeader("Access-Control-Allow-Headers", String.join(", ", Arrays.asList("x-fhir-starter", "Origin",
"Accept", "X-Requested-With", "Content-Type", "Authorization", "Cache-Control")));
resp.setHeader("Access-Control-Expose-Headers",
String.join(", ", Arrays.asList("Location", "Content-Location")));
resp.setHeader("Access-Control-Max-Age", "86400");
}
}
}
|
package mergedoc.encoding;
import org.eclipse.jface.dialogs.IPageChangeProvider;
import org.eclipse.jface.dialogs.IPageChangedListener;
import org.eclipse.jface.dialogs.PageChangedEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import mergedoc.encoding.document.ActiveDocument;
import mergedoc.encoding.document.ClassFileJarDocument;
import mergedoc.encoding.document.ClassFileSingleDocument;
import mergedoc.encoding.document.ExternalFileDocument;
import mergedoc.encoding.document.NonOpenedDocument;
import mergedoc.encoding.document.NullDocument;
import mergedoc.encoding.document.StorageFileDocument;
import mergedoc.encoding.document.WorkspaceFileDocument;
/**
* This agent tries to provide the encoding of the document of the active editor.
* It also provides method to set the encoding of the document.
* @author Tsoi Yat Shing
* @author Shinji Kashihara
*/
public class ActiveDocumentAgent implements IPropertyListener, IPartListener, IPageChangedListener {
// Callback for this agent.
private IActiveDocumentAgentCallback callback;
// The current document for the agent.
private ActiveDocument currentDocument;
// Indicate whether the agent has started monitoring the encoding of the active document.
private boolean isStarted = false;
// The IWorkbenchWindow to work on.
IWorkbenchWindow window;
public ActiveDocumentAgent(IActiveDocumentAgentCallback callback) {
if (callback == null) throw new IllegalArgumentException("Please provide a callback.");
this.callback = callback;
// Initialize the current handler to a dummy handler, so that we do not need to check whether it is null.
setCurrentDocument(getDocument(null));
}
/**
* Get the active editor.
* @return the active editor, or null if there is no active editor.
*/
private IEditorPart getActiveEditor() {
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
return page.getActiveEditor();
}
}
return null;
}
/**
* Check whether the active document is dirty or not.
* @return true/false
*/
public boolean isDocumentDirty() {
return currentDocument != null && currentDocument.getEditor() != null && currentDocument.getEditor().isDirty();
}
public ActiveDocument getDocument() {
return currentDocument;
}
/**
* Get a handler for an editor.
* @return a specific handler, or NullDocument if there is no specific handler for an editor.
*/
private ActiveDocument getDocument(IEditorPart editor) {
if (editor == null) {
// No opened editor in workspace
return new NonOpenedDocument();
}
else if (editor.getAdapter(IEncodingSupport.class) != null) {
// Get MultiPartEditor active tab
if (editor instanceof FormEditor) {
IEditorPart e = ((FormEditor) editor).getActiveEditor();
if (e instanceof ITextEditor) {
editor = e;
}
}
IEditorInput editorInput = editor.getEditorInput();
if (editorInput instanceof IFileEditorInput) {
return new WorkspaceFileDocument(editor, callback);
}
else if (editorInput instanceof FileStoreEditorInput) {
// Decompiled class file in bin directory
if (editorInput.getClass().getSimpleName().equals("DecompilerClassEditorInput")) {
return new ClassFileSingleDocument(editor, callback);
}
return new ExternalFileDocument(editor, callback);
}
else if (editorInput instanceof IStorageEditorInput) {
// Non class file resources in jar
// pom editor Effective pom tab
StorageFileDocument doc = new StorageFileDocument(editor, callback);
if (doc.hasContent()) {
return doc;
}
// Fallback
Activator.info("No Content: " + editorInput.getClass().getName());
return new ActiveDocument(editor, callback);
} else if (editorInput.getClass().getSimpleName().equals("InternalClassFileEditorInput")) {
// Class file in jar (with source and without source)
return new ClassFileJarDocument(editor, callback);
}
}
// MultiPageEditor no document tab
return new NullDocument(editor);
}
/**
* Start to monitor the encoding of the active document, if not started yet.
* @param window The IWorkbenchWindow to work on.
*/
public void start(IWorkbenchWindow window) {
if (!isStarted && window != null) {
isStarted = true;
this.window = window;
// Update the current handler.
// Not invoke the callback during start.
setCurrentDocument(getDocument(getActiveEditor()));
// Add listeners.
window.getPartService().addPartListener(this);
}
}
/**
* Stop to monitor the encoding of the active document, if started.
*/
public void stop() {
if (isStarted) {
// Remove listeners.
window.getPartService().removePartListener(this);
// Reset the current handler to a dummy handler, which will remove IPropertyListener if added.
setCurrentDocument(getDocument(null));
window = null;
isStarted = false;
}
}
/**
* Change the current handler.
* This method helps to add/remove IPropertyListener as needed.
* @param document
*/
private void setCurrentDocument(ActiveDocument document) {
if (document == null) throw new IllegalArgumentException("handler must not be null.");
// Remove IPropertyListener from the old editor.
if (currentDocument != null) {
IEditorPart editor = currentDocument.getEditor();
if (editor != null) {
editor.removePropertyListener(this);
}
}
currentDocument = document;
// Add IPropertyListener to the new editor.
IEditorPart editor = currentDocument.getEditor();
if (editor != null) {
editor.addPropertyListener(this);
}
}
/**
* Check whether the active editor is changed.
*/
private void checkActiveEditor() {
IEditorPart activeEditor = getActiveEditor();
if (activeEditor != currentDocument.getEditor()) {
// Get a new handler for the active editor, and invoke the callback.
setCurrentDocument(getDocument(activeEditor));
callback.statusChanged();
}
}
@Override
public void propertyChanged(Object source, int propId) {
if (propId == IEditorPart.PROP_INPUT) {
// The current handler may not be able to handle the new editor input,
// so get a new handler for the active editor, and invoke the callback.
setCurrentDocument(getDocument(getActiveEditor()));
callback.statusChanged();
}
else {
// Pass the event to the handler.
currentDocument.propertyChanged(source, propId);
}
}
@Override
public void partActivated(IWorkbenchPart part) {
if (part instanceof IPageChangeProvider) {
((IPageChangeProvider) part).addPageChangedListener(this);
}
checkActiveEditor();
}
@Override
public void partDeactivated(IWorkbenchPart part) {
if (part instanceof IPageChangeProvider) {
((IPageChangeProvider) part).removePageChangedListener(this);
}
// Unnecessary: Call partActivated after this
//checkActiveEditor();
}
@Override
public void partBroughtToTop(IWorkbenchPart part) {
checkActiveEditor();
}
@Override
public void partOpened(IWorkbenchPart part) {
checkActiveEditor();
}
@Override
public void partClosed(IWorkbenchPart part) {
checkActiveEditor();
}
/**
* MultiPageEditorPart tab changed.
*/
@Override
public void pageChanged(PageChangedEvent event) {
setCurrentDocument(getDocument(getActiveEditor()));
callback.statusChanged();
}
public void fireEncodingChanged() {
callback.statusChanged();
}
}
|
package org.k3.language.ui.tools;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.k3.language.ui.Activator;
public class FileUtils {
static String lineSeparator = System.getProperty("line.separator");
public static String getFileTypeK3(String namePackage) {
StringBuffer buffer= new StringBuffer();
buffer.append("package " + namePackage + "\n\n");
buffer.append("class HelloWorld { \n\n");
buffer.append("\tdef static void main(String[] args) {\n");
buffer.append("\t\tprintln('Hello world by Kermeta 3 programm!')\n");
buffer.append("\t}\n");
buffer.append("}\n");
return buffer.toString();
}
public static String manifestMFPlugin (String projectName, List<String> requiredBundles, List<String> exportedPackages) {
StringBuffer buffer= new StringBuffer();
buffer.append("Manifest-Version: 1.0" + lineSeparator);
buffer.append("Bundle-ManifestVersion: 2" + lineSeparator);
buffer.append("Bundle-Name: " + projectName + lineSeparator);
buffer.append("Bundle-SymbolicName: " + projectName + "; singleton:=true" + lineSeparator);
buffer.append("Bundle-Version: 1.0.0" + lineSeparator);
buffer.append("Require-Bundle: ");
buffer.append("org.k3.core.plugin;bundle-version=\"1.0.0\""+ lineSeparator);
buffer.append("Bundle-ClassPath: .,");
buffer.append("resources/k3-3.0-SNAPSHOT.jar,");
buffer.append("resources/org.eclipse.xtend.lib-2.4.3-SNAPSHOT.jar,");
buffer.append("resources/org.eclipse.xtext.xbase.lib-2.4.3-SNAPSHOT.jar" + lineSeparator);
return buffer.toString();
}
public static String pluginbasisXML() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?eclipse version=\"3.4\"?>\n" + "<plugin>\n" + "</plugin>";
}
public static String pluginXml(String nameProject) {
StringBuffer buffer= new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buffer.append("<?eclipse version=\"3.4\"?>\n");
buffer.append("<plugin>\n\n");
buffer.append("\t<extension\n");
buffer.append("\t\t\tpoint=\"org.eclipse.ui.actionSets\">\n");
buffer.append("\t\t<actionSet\n");
buffer.append("\t\t\t\tlabel=\"Sample Action Set\"\n");
buffer.append("\t\t\t\tvisible=\"true\"\n");
buffer.append("\t\t\t\tid=\"" + nameProject + ".actionSet\">\n");
buffer.append("\t\t\t<menu\n");
buffer.append("\t\t\t\t\tlabel=\"Sample &Menu\"\n");
buffer.append("\t\t\t\t\tid=\"sampleMenu\">\n");
buffer.append("\t\t\t\t<separator\n");
buffer.append("\t\t\t\t\t\tname=\"sampleGroup\">\n");
buffer.append("\t\t\t\t</separator>\n");
buffer.append("\t\t\t</menu>\n");
buffer.append("\t\t\t<action\n");
buffer.append("\t\t\t\t\tlabel=\"&Sample Action\"\n");
buffer.append("\t\t\t\t\ticon=\"icons/sample.gif\"\n");
buffer.append("\t\t\t\t\tclass=\"" + nameProject + ".actions.SampleAction\"\n");
buffer.append("\t\t\t\t\ttooltip=\"Hello, Eclipse world\"\n");
buffer.append("\t\t\t\t\tmenubarPath=\"sampleMenu/sampleGroup\"\n");
buffer.append("\t\t\t\t\ttoolbarPath=\"sampleGroup\"\n");
buffer.append("\t\t\t\t\tid=\"" + nameProject + ".actions.SampleAction\">\n");
buffer.append("\t\t\t</action>\n");
buffer.append("\t\t</actionSet>\n");
buffer.append("\t</extension>\n\n");
buffer.append("</plugin>");
return buffer.toString();
}
public static String buildProperties () {
StringBuffer buffer= new StringBuffer();
buffer.append("source.. = src/"+lineSeparator);
buffer.append("output.. = bin/"+lineSeparator);
buffer.append("bin.includes = plugin.xml,\\"+lineSeparator);
buffer.append("\t\t\t\tMETA-INF/,\\"+lineSeparator);
buffer.append("\t\t\t\t.,\\"+lineSeparator);
buffer.append("\t\t\t\tlibrary/k3-3.0-SNAPSHOT.jar,\\"+lineSeparator);
buffer.append("\t\t\t\tlibrary/org.eclipse.xtend.lib-2.4.3-SNAPSHOT.jar,\\"+lineSeparator);
buffer.append("\t\t\t\tlibrary/org.eclipse.xtext.xbase.lib-2.4.3-SNAPSHOT.jar"+lineSeparator);
return buffer.toString();
}
public static String pomXmlK3(String nameProject, String groupID, String artifactID, String version) {
StringBuffer buffer= new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buffer.append("<project xmlns=\"http:
buffer.append("\txsi:schemaLocation=\"http:
buffer.append("\t<modelVersion>4.0.0</modelVersion>\n");
buffer.append("\t<groupId>"+ groupID + "</groupId>\n");
buffer.append("\t<artifactId>"+ artifactID + "</artifactId>\n");
buffer.append("\t<version>"+ version + "</version>\n");
buffer.append("\t<name>"+ nameProject + "</name>\n");
buffer.append("\t<properties>\n");
buffer.append("\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n");
buffer.append("\t\t<xtend.version>2.4.3-SNAPSHOT</xtend.version>\n");
buffer.append("\t</properties>\n");
buffer.append("\t<build>\n");
buffer.append("\t\t<plugins>\n");
buffer.append("\t\t\t<plugin>\n");
buffer.append("\t\t\t\t<groupId>org.eclipse.xtend</groupId>\n");
buffer.append("\t\t\t\t<artifactId>xtend-maven-plugin</artifactId>\n");
buffer.append("\t\t\t\t<version>${xtend.version}</version>\n");
buffer.append("\t\t\t\t<executions>\n");
buffer.append("\t\t\t\t\t<execution>\n");
buffer.append("\t\t\t\t\t\t<goals>\n");
buffer.append("\t\t\t\t\t\t\t<goal>compile</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>testCompile</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>xtend-install-debug-info</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>xtend-test-install-debug-info</goal>\n");
buffer.append("\t\t\t\t\t\t</goals>\n");
buffer.append("\t\t\t\t\t</execution>\n");
buffer.append("\t\t\t\t</executions>\n");
buffer.append("\t\t\t</plugin>\n");
buffer.append("\t\t\t<plugin>\n");
buffer.append("\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n");
buffer.append("\t\t\t\t<version>3.0</version>\n");
buffer.append("\t\t\t\t<configuration>\n");
buffer.append("\t\t\t\t\t<source>1.5</source>\n");
buffer.append("\t\t\t\t\t<target>1.5</target>\n");
buffer.append("\t\t\t\t</configuration>\n");
buffer.append("\t\t\t</plugin>\n");
buffer.append("\t\t</plugins>\n");
buffer.append("\t</build>\n");
buffer.append("\t<dependencies>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.xtend</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.xtend.lib</artifactId>\n");
buffer.append("\t\t\t<version>${xtend.version}</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>fr.inria.triskell</groupId>\n");
buffer.append("\t\t\t<artifactId>k3</artifactId>\n");
buffer.append("\t\t\t<version>3.0-SNAPSHOT</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.ecore.xmi</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.ecore</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.common</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t</dependencies>\n");
buffer.append("\t<repositories>\n");
buffer.append("\t\t<repository>\n");
buffer.append("\t\t\t<id>xtext.snapshots</id>\n");
buffer.append("\t\t\t<url>http://dev.nightlabs.org/maven-repository/repo/</url>\n");
buffer.append("\t\t</repository>\n");
buffer.append("\t</repositories>\n");
buffer.append("\t<pluginRepositories>\n");
buffer.append("\t\t<pluginRepository>\n");
buffer.append("\t\t\t<id>xtext.oss.snapshots</id>\n");
buffer.append("\t\t\t<url>http://dev.nightlabs.org/maven-repository/repo/</url>\n");
buffer.append("\t\t</pluginRepository>\n");
buffer.append("\t</pluginRepositories>\n");
buffer.append("</project>\n");
return buffer.toString();
}
public static String pomXmlK3Ecore(String nameProject, String groupID, String artifactID, String version, String eGroupID, String eArtifactID, String eVersion) {
StringBuffer buffer= new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buffer.append("<project xmlns=\"http:
buffer.append("\txsi:schemaLocation=\"http:
buffer.append("\t<modelVersion>4.0.0</modelVersion>\n");
buffer.append("\t<groupId>"+ groupID + "</groupId>\n");
buffer.append("\t<artifactId>"+ artifactID + "</artifactId>\n");
buffer.append("\t<version>"+ version + "</version>\n");
buffer.append("\t<name>"+ nameProject + "</name>\n");
buffer.append("\t<properties>\n");
buffer.append("\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n");
buffer.append("\t\t<xtend.version>2.4.3-SNAPSHOT</xtend.version>\n");
buffer.append("\t</properties>\n");
buffer.append("\t<build>\n");
buffer.append("\t\t<plugins>\n");
buffer.append("\t\t\t<plugin>\n");
buffer.append("\t\t\t\t<groupId>org.eclipse.xtend</groupId>\n");
buffer.append("\t\t\t\t<artifactId>xtend-maven-plugin</artifactId>\n");
buffer.append("\t\t\t\t<version>${xtend.version}</version>\n");
buffer.append("\t\t\t\t<executions>\n");
buffer.append("\t\t\t\t\t<execution>\n");
buffer.append("\t\t\t\t\t\t<goals>\n");
buffer.append("\t\t\t\t\t\t\t<goal>compile</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>testCompile</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>xtend-install-debug-info</goal>\n");
buffer.append("\t\t\t\t\t\t\t<goal>xtend-test-install-debug-info</goal>\n");
buffer.append("\t\t\t\t\t\t</goals>\n");
buffer.append("\t\t\t\t\t</execution>\n");
buffer.append("\t\t\t\t</executions>\n");
buffer.append("\t\t\t</plugin>\n");
buffer.append("\t\t\t<plugin>\n");
buffer.append("\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n");
buffer.append("\t\t\t\t<version>3.0</version>\n");
buffer.append("\t\t\t\t<configuration>\n");
buffer.append("\t\t\t\t\t<source>1.5</source>\n");
buffer.append("\t\t\t\t\t<target>1.5</target>\n");
buffer.append("\t\t\t\t</configuration>\n");
buffer.append("\t\t\t</plugin>\n");
buffer.append("\t\t</plugins>\n");
buffer.append("\t</build>\n");
buffer.append("\t<dependencies>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.xtend</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.xtend.lib</artifactId>\n");
buffer.append("\t\t\t<version>${xtend.version}</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>fr.inria.triskell</groupId>\n");
buffer.append("\t\t\t<artifactId>k3</artifactId>\n");
buffer.append("\t\t\t<version>3.0-SNAPSHOT</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.ecore.xmi</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.ecore</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.common</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>" + eGroupID + "</groupId>\n");
buffer.append("\t\t\t<artifactId>" + eArtifactID + "</artifactId>\n");
buffer.append("\t\t\t<version>" + eVersion + "</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t</dependencies>\n");
buffer.append("\t<repositories>\n");
buffer.append("\t\t<repository>\n");
buffer.append("\t\t\t<id>xtext.snapshots</id>\n");
buffer.append("\t\t\t<url>http://dev.nightlabs.org/maven-repository/repo/</url>\n");
buffer.append("\t\t</repository>\n");
buffer.append("\t</repositories>\n");
buffer.append("\t<pluginRepositories>\n");
buffer.append("\t\t<pluginRepository>\n");
buffer.append("\t\t\t<id>xtext.oss.snapshots</id>\n");
buffer.append("\t\t\t<url>http://dev.nightlabs.org/maven-repository/repo/</url>\n");
buffer.append("\t\t</pluginRepository>\n");
buffer.append("\t</pluginRepositories>\n");
buffer.append("</project>\n");
return buffer.toString();
}
public static String pomXmlMetamodel(String nameProject, String groupID, String artifactID, String version) {
StringBuffer buffer= new StringBuffer();
buffer.append("<project xmlns=\"http:
buffer.append("\t <modelVersion>4.0.0</modelVersion>\n");
buffer.append("\t<groupId>"+ groupID + "</groupId>\n");
buffer.append("\t<artifactId>"+ artifactID + "</artifactId>\n");
buffer.append("\t<version>"+ version + "</version>\n");
buffer.append("\t<name>"+ nameProject + "</name>\n");
buffer.append("\t<build>\n");
buffer.append("\t\t<sourceDirectory>src</sourceDirectory>\n");
buffer.append("\t\t<plugins>\n");
buffer.append("\t\t\t<plugin>\n");
buffer.append("\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n");
buffer.append("\t\t\t\t<version>3.0</version>\n");
buffer.append("\t\t\t\t<configuration>\n");
buffer.append("\t\t\t\t\t<source/>\n");
buffer.append("\t\t\t\t\t<target/>\n");
buffer.append("\t\t\t\t</configuration>\n");
buffer.append("\t\t\t</plugin>\n");
buffer.append("\t\t</plugins>\n");
buffer.append("\t</build>\n");
buffer.append("\t<dependencies>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.core</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.core.runtime</artifactId>\n");
buffer.append("\t\t\t<version>3.6.0.v20100505</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.ecore</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t\t<dependency>\n");
buffer.append("\t\t\t<groupId>org.eclipse.emf</groupId>\n");
buffer.append("\t\t\t<artifactId>org.eclipse.emf.common</artifactId>\n");
buffer.append("\t\t\t<version>2.8.0-v20120911-0500</version>\n");
buffer.append("\t\t</dependency>\n");
buffer.append("\t</dependencies>\n");
buffer.append("</project>\n");
return buffer.toString();
}
public static void copy(final InputStream inStream, final OutputStream outStream, final int bufferSize) throws IOException {
final byte[] buffer = new byte[bufferSize];
int nbRead;
while ((nbRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, nbRead);
}
}
public static void copyDirectory(final File from, final File to) throws IOException {
if (! to.exists()) {
to.mkdir();
}
final File[] inDir = from.listFiles();
for (int i = 0; i < inDir.length; i++) {
final File file = inDir[i];
copy(file, new File(to, file.getName()));
}
}
public static void copyFile(final File from, final File to) throws IOException {
final InputStream inStream = new FileInputStream(from);
final OutputStream outStream = new FileOutputStream(to);
copy(inStream, outStream, (int) Math.min(from.length(), 4*1024));
inStream.close();
outStream.close();
}
public static void copy(final File from, final File to) throws IOException {
if (from.isFile()) {
copyFile(from, to);
} else if (from.isDirectory()){
copyDirectory(from, to);
} else {
throw new FileNotFoundException(from.toString() + " does not exist" );
}
}
public static void unZip(IProject project, ProjectDescriptor projectDesc) {
try {
URL interpreterZipUrl = FileLocator.find(Platform.getBundle(projectDesc.getBundleName()), new Path(projectDesc.getZipLocation()), null);
// We make sure that the project is created from this point forward.
ZipInputStream zipFileStream = new ZipInputStream(interpreterZipUrl.openStream());
ZipEntry zipEntry = zipFileStream.getNextEntry();
// We derive a regexedProjectName so that the dots don't end up being
// interpreted as the dot operator in the regular expression language.
//String regexedProjectName = projectName.replaceAll("\\.", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
while (zipEntry != null) {
// We will construct the new file but we will strip off the project
// directory from the beginning of the path because we have already
// created the destination project for this zip.
File file = new File(project.getLocation().toString(), zipEntry.getName());
if (false == zipEntry.isDirectory()) {
/*
* Copy files (and make sure parent directory exist)
*/
File parentFile = file.getParentFile();
if (null != parentFile && false == parentFile.exists()) {
parentFile.mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
byte[] buffer = new byte[102400];
while (true) {
int len = zipFileStream.read(buffer);
if (zipFileStream.available() == 0)
break;
os.write(buffer, 0, len);
}
} finally {
if (null != os) {
os.close();
}
}
}
zipFileStream.closeEntry();
zipEntry = zipFileStream.getNextEntry();
}
} catch (IOException exception) {
Activator.logErrorMessage(exception.getMessage(), exception);
}
}
}
|
package BluebellAdventures.Characters;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.imageio.ImageIO;
import BluebellAdventures.Characters.GameMap;
import Megumin.Actions.Action;
import Megumin.Actions.Effect;
import Megumin.Nodes.Sprite;
import Megumin.Point;
public class Character extends Sprite {
private int hp;
private int mp;
private int chargeBar;
private int speed;
private int unlockSpeed;
private int attackScore;
private int snackScore;
private int key;
// Constructors //
public Character(String filename) throws IOException {
super(filename, new Point(0, 0));
}
public Character(String filename, Point position) throws IOException {
super(ImageIO.read(new File(filename)), position);
}
public Character(BufferedImage image) {
super(image, new Point(0, 0));
}
public Character(BufferedImage image, Point position) {
super(image, position);
}
public void render(Graphics2D g) {
if (getVisible()) {
g.setFont(new Font("TimesRoman", Font.BOLD, 35));
String hpString = "";
g.setColor(Color.white);
g.drawString("Health: ", 100, 50);
g.setColor(Color.red);
g.drawString(hpString.substring(0, hp), 250, 50);
String keyString = "";
g.setColor(Color.white);
g.drawString("key: ", 400, 50);
g.setColor(Color.yellow);
g.drawString(keyString.substring(0, key), 500, 50);
g.setColor(Color.white);
g.drawString("Score: " + snackScore, 700, 50);
super.render(g);
}
}
@Override
public boolean checkCrash(CopyOnWriteArrayList<Sprite> sprites, Action action) {
boolean crash = false;
GameMap map = GameMap.getInstance();
int x1 = getPosition().getX();
int y1 = getPosition().getY();
int w1 = getSize().getX();
int h1 = getSize().getY();
Iterator it = sprites.iterator();
while (it.hasNext()) {
Sprite sprite = (Sprite)it.next();
int x2 = map.getPosition().getX() + sprite.getPosition().getX();
int y2 = map.getPosition().getY() + sprite.getPosition().getY();
int w2 = sprite.getSize().getX();
int h2 = sprite.getSize().getY();
if (Math.max(Math.abs(x2 - (x1 + w1)), Math.abs(x2 + w2 - x1)) < w1 + w2 &&
Math.max(Math.abs(y2 - (y1 + h1)), Math.abs(y2 + h2 - y1)) < h1 + h2) {
((Effect)action).setSprite(sprite);
runAction(action);
crash = true;
}
}
return crash;
}
// Get and Sets //
public Character setHp(int hp) {
this.hp = hp;
return this;
}
public int getHp() {
return hp;
}
public Character setMp(int mp) {
this.mp = mp;
return this;
}
public int getMp(){
return mp;
}
public Character setChargeBar(int chargeBar) {
this.chargeBar = chargeBar;
return this;
}
public int getChargeBar() {
return chargeBar;
}
public Character setSpeed(int speed) {
this.speed = speed;
return this;
}
public int getSpeed() {
return speed;
}
public Character setUnlockSpeed(int unlockSpeed) {
this.unlockSpeed = unlockSpeed;
return this;
}
public int getUnlockSpeed() {
return unlockSpeed;
}
public Character setAttackScore(int attackScore) {
this.attackScore = attackScore;
return this;
}
public int getAttackScore() {
return attackScore;
}
public Character setSnackScore(int snackScore) {
this.snackScore = snackScore;
return this;
}
public void addSnackScore(int snackScore) {
this.snackScore += snackScore;
}
public int getSnackScore() {
return snackScore;
}
public Character setKey(int key) {
this.key = key;
return this;
}
public int getKey() {
return key;
}
public void addKey(int key) {
this.key += key;
}
public void useKey(int key) {
this.key -= key;
}
}
|
package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.Animation.AnimationType;
import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.Camera;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.Collider.Collision;
import com.ezardlabs.dethsquare.Collider.CollisionLocation;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Input;
import com.ezardlabs.dethsquare.Input.OnKeyListener;
import com.ezardlabs.dethsquare.Input.OnTouchListener;
import com.ezardlabs.dethsquare.Renderer;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.dethsquare.util.Utils;
import com.ezardlabs.lostsector.objects.warframes.Warframe;
import java.util.ArrayList;
import java.util.HashMap;
public class Player extends Script {
public static GameObject player;
public int jumpCount = 0;
private int x = 0;
public boolean landing = false;
public boolean melee = false;
private float speed = 12.5f;
@Override
public void start() {
player = gameObject;
switch (Utils.PLATFORM) {
case ANDROID:
Input.addOnTouchListener(new OnTouchListener() {
final HashMap<Integer, Vector2> map = new HashMap<>();
@Override
public void onTouchDown(int id, float x, float y) {
if (x < Screen.width / 6f) {
Player.this.x = -1;
} else if (x < Screen.width / 2f) {
Player.this.x = 1;
}
map.put(id, new Vector2(x, y));
}
@Override
public void onTouchMove(int id, float x, float y) {
if (map.containsKey(id) && map.get(id).x > Screen.width / 2f) {
if (x < Screen.width / 2f) {
onTouchUp(id, Screen.width / 2f, y);
}
} else {
if (x > Screen.width / 2f) {
onTouchUp(id, Screen.width / 2f, y);
} else if (x < Screen.width / 6f) {
Player.this.x = -1;
} else if (x < Screen.width / 2f) {
Player.this.x = 1;
}
}
}
@SuppressWarnings("ConstantConditions")
@Override
public void onTouchUp(int id, float x, float y) {
Vector2 v = map.get(id);
map.remove(id);
if (v != null) {
if (v.x < Screen.width / 2f) {
Player.this.x = 0;
} else {
v.x = x - v.x;
v.y = y - v.y;
Warframe w = (Warframe) gameObject
.getComponentOfType(Warframe.class);
if (v.x < -150 * Screen.scale) { // left
if (w.hasEnergy(25)) {
w.removeEnergy(25);
w.ability3();
}
} else if (v.x > 150 * Screen.scale) { // right
if (w.hasEnergy(5)) {
w.removeEnergy(5);
w.ability1();
}
} else if (v.y < -150 * Screen.scale) {
if (w.hasEnergy(50)) {
w.removeEnergy(50);
w.ability4();
}
} else if (v.y > 150 * Screen.scale) { // down
if (w.hasEnergy(10)) {
w.removeEnergy(10);
w.ability2();
}
} else {
jump();
}
}
}
}
@Override
public void onTouchCancel(int id) {
map.remove(id);
}
@Override
public void onTouchOutside(int id) {
map.remove(id);
}
});
break;
case DESKTOP:
Input.addOnKeyListener(new OnKeyListener() {
private boolean leftDown = false;
private boolean rightDown = false;
private ArrayList<Character> down = new ArrayList<>();
@Override
public void onKeyTyped(char keyChar) {
}
@SuppressWarnings("ConstantConditions")
@Override
public void onKeyDown(char keyChar) {
if (down.contains(keyChar)) return;
else down.add(keyChar);
Warframe w = (Warframe) gameObject.getComponentOfType(Warframe.class);
switch (keyChar) {
case 'a':
leftDown = true;
if (rightDown) x = 0;
else x = -1;
break;
case 'd':
rightDown = true;
if (leftDown) x = 0;
else x = 1;
break;
case 'w':
case ' ':
case 'j':
if (!landing && !melee) jump();
break;
case '1':
if (w.hasEnergy(5)) {
w.removeEnergy(5);
w.ability1();
}
break;
case '2':
if (w.hasEnergy(10)) {
w.removeEnergy(10);
w.ability2();
}
break;
case '3':
if (w.hasEnergy(25)) {
w.removeEnergy(25);
w.ability3();
}
break;
case '4':
if (w.hasEnergy(50)) {
w.removeEnergy(50);
w.ability4();
}
break;
case '\n':
case 'k':
if (!landing) melee();
break;
}
}
@Override
public void onKeyUp(char keyChar) {
if (down.contains(keyChar)) down.remove((Character) keyChar);
switch (keyChar) {
case 'a':
leftDown = false;
if (rightDown) x = 1;
else x = 0;
break;
case 'd':
rightDown = false;
if (leftDown) x = -1;
else x = 0;
break;
}
}
});
break;
}
}
@Override
public void update() {
if (landing) return;
if (x < 0) {
gameObject.renderer.hFlipped = true;
} else if (x > 0) {
gameObject.renderer.hFlipped = false;
}
if (melee) return;
transform.translate(x * speed, 0);
if (jumpCount > 0 && gameObject.rigidbody.velocity.y > 0) {
gameObject.animator.play("fall");
}
if (jumpCount == 0) {
if (gameObject.rigidbody.velocity.y > 2) {
gameObject.animator.play("fall");
} else if (x != 0) {
gameObject.animator.play("run");
} else {
gameObject.animator.play("idle");
}
}
}
public void jump() {
if (!landing && jumpCount++ < 2) {
gameObject.rigidbody.velocity.y = -25f;
gameObject.animator.play(jumpCount == 1 ? "jump" : "doublejump");
}
}
public void melee() {
melee = true;
//noinspection ConstantConditions
gameObject.animator
.play(((Warframe) gameObject.getComponentOfType(Warframe.class)).meleeWeapon
.getNextAnimation(x));
}
@Override
public void onCollision(Collider other, Collision collision) {
if (collision.location == CollisionLocation.BOTTOM) {
jumpCount = 0;
if (collision.speed > 37) {
landing = true;
gameObject.renderer.setSize(200, 200);
gameObject.renderer.setOffsets(0, 0);
gameObject.animator.play("land");
//noinspection ConstantConditions
Camera.main.gameObject.getComponent(CameraMovement.class).startQuake(100, 0.3f);
TextureAtlas ta = new TextureAtlas("images/effects/dust.png",
"images/effects/dust.txt");
GameObject.destroy(GameObject.instantiate(
new GameObject("Dust", new Renderer(ta, ta.getSprite("dust0"), 700, 50),
new Animator(new Animation("dust",
new Sprite[]{ta.getSprite("dust0"),
ta.getSprite("dust1"),
ta.getSprite("dust2")}, AnimationType.ONE_SHOT,
100))),
new Vector2(transform.position.x - 262, transform.position.y + 150)), 300);
new Thread() {
@Override
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
}
landing = false;
}
}.start();
}
}
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_MASK = 0xC0;
private byte [] name;
private long offsets;
private int hashcode;
private static final byte [] emptyLabel = new byte[] {(byte)0};
private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'};
/** The root name */
public static final Name root;
/** The maximum length of a Name */
private static final int MAXNAME = 255;
/** The maximum length of labels a label a Name */
private static final int MAXLABEL = 63;
/** The maximum number of labels in a Name */
private static final int MAXLABELS = 128;
/** The maximum number of cached offsets */
private static final int MAXOFFSETS = 7;
/* Used for printing non-printable characters */
private static final DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static final byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static final Name wild;
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
root = new Name();
wild = new Name();
root.appendSafe(emptyLabel, 0, 1);
wild.appendSafe(wildLabel, 0, 1);
}
private
Name() {
}
private final void
dump(String prefix) {
String s;
try {
s = toString();
} catch (Exception e) {
s = "<unprintable>";
}
System.out.println(prefix + ": " + s);
byte labels = labels();
for (int i = 0; i < labels; i++)
System.out.print(offset(i) + " ");
System.out.println("");
for (int i = 0; name != null && i < name.length; i++)
System.out.print((name[i] & 0xFF) + " ");
System.out.println("");
}
private final void
setoffset(int n, int offset) {
if (n >= MAXOFFSETS)
return;
int shift = 8 * (7 - n);
offsets &= (~(0xFFL << shift));
offsets |= ((long)offset << shift);
}
private final int
offset(int n) {
if (n < 0 || n >= getlabels())
throw new IllegalArgumentException("label out of range");
if (n < MAXOFFSETS) {
int shift = 8 * (7 - n);
return ((int)(offsets >>> shift) & 0xFF);
} else {
int pos = offset(MAXOFFSETS - 1);
for (int i = MAXOFFSETS - 1; i < n; i++)
pos += (name[pos] + 1);
return (pos);
}
}
private final void
setlabels(byte labels) {
offsets &= ~(0xFF);
offsets |= labels;
}
private final byte
getlabels() {
return (byte)(offsets & 0xFF);
}
private static final void
copy(Name src, Name dst) {
dst.name = src.name;
dst.offsets = src.offsets;
}
private final void
append(byte [] array, int start, int n) throws NameTooLongException {
int length = (name == null ? 0 : (name.length - offset(0)));
int alength = 0;
for (int i = 0, pos = start; i < n; i++) {
int len = array[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
len++;
pos += len;
alength += len;
}
int newlength = length + alength;
if (newlength > MAXNAME)
throw new NameTooLongException();
byte labels = getlabels();
int newlabels = labels + n;
if (newlabels > MAXLABELS)
throw new IllegalStateException("too many labels");
byte [] newname = new byte[newlength];
if (length != 0)
System.arraycopy(name, offset(0), newname, 0, length);
System.arraycopy(array, start, newname, length, alength);
name = newname;
for (int i = 0, pos = length; i < n; i++) {
setoffset(labels + i, pos);
pos += (newname[pos] + 1);
}
setlabels((byte) newlabels);
}
private final void
appendFromString(byte [] array, int start, int n) throws TextParseException {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
throw new TextParseException("Name too long");
}
}
private final void
appendSafe(byte [] array, int start, int n) {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer(s);
if (origin != null)
sb.append("." + origin);
sb.append(": "+ e.getMessage());
System.err.println(sb.toString());
return;
}
if (!n.isAbsolute() && !Options.check("pqdn") &&
n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1)
{
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
n.appendSafe(emptyLabel, 0, 1);
}
copy(n, this);
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw new TextParseException("empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw new TextParseException
("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1) {
name.appendFromString(emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(origin.name, 0, origin.getlabels());
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, pos, currentpos;
Name name2;
boolean done = false;
byte [] label = new byte[MAXLABEL + 1];
int savedpos = -1;
while (!done) {
len = in.readUnsignedByte();
switch (len & LABEL_MASK) {
case LABEL_NORMAL:
if (getlabels() >= MAXLABELS)
throw new WireParseException("too many labels");
if (len == 0) {
append(emptyLabel, 0, 1);
done = true;
} else {
label[0] = (byte)len;
in.readArray(label, 1, len);
append(label, 0, 1);
}
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
currentpos = in.getPos();
if (pos >= currentpos)
throw new WireParseException("bad compression");
if (savedpos == -1)
savedpos = currentpos;
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
continue;
}
}
if (savedpos != -1)
in.setPos(savedpos);
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param src An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
public
Name(Name src, int n) {
byte slabels = src.labels();
if (n > slabels)
throw new IllegalArgumentException("attempted to remove too " +
"many labels");
name = src.name;
setlabels((byte)(slabels - n));
for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++)
setoffset(i, src.offset(i + n));
}
/**
* Creates a new name by concatenating two existing names.
* @param prefix The prefix name.
* @param suffix The suffix name.
* @return The concatenated name.
* @throws NameTooLongException The name is too long.
*/
public static Name
concatenate(Name prefix, Name suffix) throws NameTooLongException {
if (prefix.isAbsolute())
return (prefix);
Name newname = new Name();
copy(prefix, newname);
newname.append(suffix.name, suffix.offset(0), suffix.getlabels());
return newname;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
if (n < 1)
throw new IllegalArgumentException("must replace 1 or more " +
"labels");
try {
Name newname = new Name();
copy(wild, newname);
newname.append(name, offset(n), getlabels() - n);
return newname;
}
catch (NameTooLongException e) {
throw new IllegalStateException
("Name.wild: concatenate failed");
}
}
/**
* Generates a new Name to be used when following a DNAME.
* @param dname The DNAME record to follow.
* @return The constructed name.
* @throws NameTooLongException The resulting name is too long.
*/
public Name
fromDNAME(DNAMERecord dname) throws NameTooLongException {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
if (!subdomain(dnameowner))
return null;
int plabels = labels() - dnameowner.labels();
int plength = length() - dnameowner.length();
int pstart = offset(0);
int dlabels = dnametarget.labels();
int dlength = dnametarget.length();
if (plength + dlength > MAXNAME)
throw new NameTooLongException();
Name newname = new Name();
newname.setlabels((byte)(plabels + dlabels));
newname.name = new byte[plength + dlength];
System.arraycopy(name, pstart, newname.name, 0, plength);
System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength);
for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) {
newname.setoffset(i, pos);
pos += (newname.name[pos] + 1);
}
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels() == 0)
return false;
return (name[0] == (byte)1 && name[1] == (byte)'*');
}
/**
* Is this name fully qualified (that is, absolute)?
* @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>.
*/
public boolean
isQualified() {
return (isAbsolute());
}
/**
* Is this name absolute?
*/
public boolean
isAbsolute() {
if (labels() == 0)
return false;
return (name[name.length - 1] == 0);
}
/**
* The length of the name.
*/
public short
length() {
return (short)(name.length - offset(0));
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return getlabels();
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
byte labels = labels();
byte dlabels = domain.labels();
if (dlabels > labels)
return false;
if (dlabels == labels)
return equals(domain);
return domain.equals(name, offset(labels - dlabels));
}
private String
byteString(byte [] array, int pos) {
StringBuffer sb = new StringBuffer();
int len = array[pos++];
for (int i = pos; i < pos + len; i++) {
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
byte labels = labels();
if (labels == 0)
return "@";
else if (labels == 1 && name[offset(0)] == 0)
return ".";
StringBuffer sb = new StringBuffer();
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
if (len == 0)
break;
sb.append(byteString(name, pos));
sb.append('.');
pos += (1 + len);
}
if (!isAbsolute())
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public byte []
getLabel(int n) {
int pos = offset(n);
byte len = (byte)(name[pos] + 1);
byte [] label = new byte[len];
System.arraycopy(name, pos, label, 0, len);
return label;
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public String
getLabelString(int n) {
int pos = offset(n);
return byteString(name, pos);
}
public void
toWire(DataByteOutputStream out, Compression c) {
if (!isAbsolute())
throw new IllegalArgumentException("toWire() called on " +
"non-absolute name");
byte labels = labels();
for (int i = 0; i < labels - 1; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null)
pos = c.get(tname);
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
} else {
if (c != null)
c.add(out.getPos(), tname);
out.writeString(name, offset(i));
}
}
out.writeByte(0);
}
public byte []
toWire() {
DataByteOutputStream out = new DataByteOutputStream();
toWire(out, null);
return out.toByteArray();
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @param out The output stream to which the message is written.
*/
public void
toWireCanonical(DataByteOutputStream out) {
byte [] b = toWireCanonical();
out.writeArray(b);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public byte []
toWireCanonical() {
byte labels = labels();
if (labels == 0)
return (new byte[0]);
byte [] b = new byte[name.length - offset(0)];
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
b[pos] = name[pos++];
for (int j = 0; j < len; j++)
b[pos] = lowercase[name[pos++]];
}
return b;
}
void
toWire(DataByteOutputStream out, Compression c, boolean canonical) {
if (canonical)
toWireCanonical(out);
else
toWire(out, c);
}
private final boolean
equals(byte [] b, int bpos) {
byte labels = labels();
for (int i = 0, pos = offset(0); i < labels; i++) {
if (name[pos] != b[bpos])
return false;
int len = name[pos++];
bpos++;
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
for (int j = 0; j < len; j++)
if (lowercase[name[pos++]] != lowercase[b[bpos++]])
return false;
}
return true;
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels() != labels())
return false;
return equals(d.name, d.offset(0));
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = 0;
for (int i = offset(0); i < name.length; i++)
code += ((code << 3) + lowercase[name[i]]);
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
if (this == arg)
return (0);
byte labels = labels();
byte alabels = arg.labels();
int compares = labels > alabels ? alabels : labels;
for (int i = 1; i <= compares; i++) {
int start = offset(labels - i);
int astart = arg.offset(alabels - i);
int length = name[start];
int alength = arg.name[astart];
for (int j = 0; j < length && j < alength; j++) {
int n = lowercase[name[j + start]] -
lowercase[arg.name[j + astart]];
if (n != 0)
return (n);
}
if (length != alength)
return (length - alength);
}
return (labels - alabels);
}
}
|
// JS.java
package ed.js;
import java.io.*;
import java.util.*;
import ed.lang.*;
import ed.js.engine.*;
import ed.appserver.jxp.JxpSource;
import ed.appserver.adapter.AdapterType;
import ed.appserver.AppContext;
import ed.appserver.JSFileLibrary;
public class JS extends Language {
public JS(){
super( "js" );
}
public JSFunction compileLambda( String source ){
return Convert.makeAnon( source , true );
}
public JxpSource getAdapter(AdapterType type, File f, AppContext context, JSFileLibrary lib) {
// TODO - fix me
return null;
}
public Object eval( Scope scope , String code , boolean[] hasReturn ){
return scope.eval( code , "eval" , hasReturn );
}
public static boolean JNI = false;
public static final boolean DI = false;
public static final boolean RAW_EXCPETIONS = ed.util.Config.get().getBoolean( "RAWE" );
public static void _debugSI( String name , String place ){
if ( ! DI )
return;
System.err.println( "Static Init : " + name + " \t " + place );
}
public static void _debugSIStart( String name ){
if ( ! DI )
return;
System.err.println( "Static Init : " + name + " Start" );
}
public static void _debugSIDone( String name ){
if ( ! DI )
return;
System.err.println( "Static Init : " + name + " Done" );
}
/** Critical method.
* @return 17. Seriously, the only thing this method does is return 17.
*/
public static final int fun(){
return 17;
}
public static boolean bool( Object o ){
return JSInternalFunctions.JS_evalToBool( o );
}
public static final Object eval( String js ){
JNI = true;
try {
Scope s = Scope.getAScope().child();
Object ret = s.eval( js );
return ret;
}
catch ( Throwable t ){
t.printStackTrace();
return null;
}
}
/** Returns a short description of an object.
* @param o object to be stringified.
* @return string version of the object, or null if the object is null.
*/
public static final String toString( Object o ){
if ( o == null )
return null;
return o.toString();
}
public static boolean isBaseObject( Object o ){
if ( o == null )
return false;
return isBaseObject( o.getClass() );
}
public static boolean isBaseObject( Class c ){
return c == JSObjectBase.class || c == JSDict.class;
}
public static boolean isPrimitive( Object o ){
return
o instanceof Number ||
o instanceof JSNumber ||
o instanceof Boolean ||
o instanceof JSBoolean ||
o instanceof String ||
o instanceof JSString;
}
public static JSArray getArray( JSObject o , String name ){
List l = getList( o , name );
if ( l instanceof JSArray )
return (JSArray)l;
return null;
}
public static List getList( JSObject o , String name ){
if ( o == null )
return null;
Object v = o.get( name );
if ( v == null )
return null;
if ( v instanceof List )
return (List)v;
return null;
}
public static Object path( JSObject o , String path ){
if ( o == null )
return null;
if ( path == null )
return o;
while ( path.length() > 0 ){
int idx = path.indexOf( "." );
if ( idx < 0 )
return o.get( path );
Object next = o.get( path.substring( 0 , idx ) );
if ( next == null )
return null;
if ( ! ( next instanceof JSObject ) )
return null;
o = (JSObject)next;
path = path.substring( idx + 1 );
}
return o;
}
public static Object eval( JSObject o , String funcName , Object ... args ){
if ( o == null )
throw new NullPointerException( "null object" );
JSFunction f = o.getFunction( funcName );
if ( f == null )
throw new NullPointerException( "no function named [" + funcName + "]" );
return f.callAndSetThis( null , o , args );
}
public static JSDict build( String[] names , Object[] values ){
JSDict d = new JSDict();
for ( int i=0; i<names.length; i++ )
d.set( names[i] , values != null && i < values.length ? values[i] : null );
return d;
}
public static void main( String args[] )
throws Exception {
for ( String s : args ){
s = s.trim();
if ( s.length() == 0 )
continue;
System.out.println( "
System.out.println( s );
Convert c = new Convert( new File( s ) );
c.get().call( Scope.newGlobal().child() );
}
}
}
|
// JS.java
package ed.js;
import java.io.*;
import ed.js.engine.*;
public class JS {
public static final boolean RAW_EXCPETIONS = Boolean.getBoolean( "RAWE" );
public static final String toString( Object o ){
if ( o == null )
return null;
return o.toString();
}
public static void main( String args[] )
throws Exception {
for ( String s : args ){
System.out.println( "
System.out.println( s );
Convert c = new Convert( new File( s ) );
c.get().call( Scope.GLOBAL.child() );
}
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class NPD {
public String Id;
public String Name;
public Date LaunchDate;
public String Plant;
public String PlantCode;
public String ProjectName;
public String ProjectType;
public String accId;
public Account account;
public ArrayList<FG> listFG;
public NPD(ResultSet rs)
{
LoadData(rs);
}
public NPD(String NPDId)
{
ResultSet rs = DataManager.Query("SELECT * FROM salesforce.NPD__c where Account_Name__c='" + NPDId + "'");
try {
if(rs.next())
{
LoadData(rs);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void LoadData(ResultSet rs)
{
try {
Id = rs.getString("SFID");
Name = rs.getString("Name");
LaunchDate = rs.getDate("Launching_Date__c");
Plant = rs.getString("Plant__c");
PlantCode = Plant.substring(0, 4);
ProjectName = rs.getString("Project_Name__c");
ProjectType = rs.getString("Project_Type__c");
accId = rs.getString("Account__c");
listFG = new ArrayList<FG>();
LoadFG();
}
catch (SQLException e) {}
}
public void linkAccount(Account acc)
{
if(accId == acc.Id)
{
account = acc;
}
}
private void LoadFG()
{
try
{
ResultSet rs = DataManager.Query("SELECT * FROM salesforce.Sourcing__c where NPD__c = '" + Id + "'");
while (rs.next())
{
FG newFG = new FG(rs);
newFG.linkNPD(this);
listFG.add(newFG);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
import java.util.*;
/**
* Basic Yut 11.13
*/
public class Yut {
private String[] yutMatrix;
private String[] yut = {"DOE", "GAE", "GIRL", "YUT", "MOE"};
private String typeOfPlayer = "o ";
private final int playerNum = 2;
private final int raceRoom = 10;
private String[] board = new String[17];
Device user =new Device();
Device com = new Device();
// Initialize Yut Matrix
public Yut() {
yutMatrix = new String[raceRoom]; // Basic 2 Line 10 room Yut race
for (int i = 0 ; i < yutMatrix.length ; i++)
yutMatrix[i] = "__";
yutMatrix[0] = "ox";
}
// Game start
public void start() {
clean();
System.out.println("Play Game of Yut !!");
int turn=0, userPreIndex=0, comPreIndex=0;
Scanner in = new Scanner(System.in);
for(int i=1; i<=16; i++) board[i]="_";
System.out.println("pick num>0 and put to throw Yut for you!");
while(in.nextInt()!=0){
if(turn%2==0) {
user.input(throwYut());
if(user.getIndex()>16){
System.out.println("user win!\n");
break;
}
if(turn!=0) board[userPreIndex]="_";
userPreIndex=user.getIndex();
showBoard(turn);
//board[user.getIndex()]="u";
System.out.println("pick num>0 and put to throw Yut for enermy!");
}
else if(turn%2==1){
com.input(throwYut());
if(user.getIndex()>16){
System.out.println("com win!\n");
break;
}
if(turn!=1) board[comPreIndex]="_";
comPreIndex=com.getIndex();
showBoard(turn);
//board[com.getIndex()]="c";
System.out.println("pick num>0 and put to throw Yut for you!");
}
// for(int i=1; i<17; i++) System.out.print(board[i]);
// System.out.println();
turn++;
}
}
private void showBoard(int who) {
if(user.getIndex()!=com.getIndex()){
board[user.getIndex()]="u";
board[com.getIndex()]="c";
}
else{
//catchYou(who);
}
// for(int i=1; i<17; i++) System.out.print(board[i]);
// System.out.println();
for(int i=0; i<3 ; i++){
if(i==0){
reversePrint(9);
System.out.println();
}
else if(i==1){
int n=10;
for(int j=0; j!=6; j+=2) {
System.out.println(board[n] + " \t" + board[n - 6-j]);
n++;
}
}
else{
for(int j=13; j<17; j++) System.out.print(board[j]);
System.out.println(board[1]);
}
}
}
private void reversePrint(int n){
if(n<=4) return;
System.out.print(board[n]);
reversePrint(n-1);
}
public int throwYut() {
Random r = new Random();
System.out.println("Throws Yut!");
int result = r.nextInt(5);
System.out.println("Resulit is " + yut[result]);
return result;
}
// Move hores
public void moveHorse() {
}
public void catchWho(int who){
}
public void clean() {
for (int i=0; i<30; i++)
System.out.println();
}
}
|
package soot.jimple.spark.ondemand;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.AnySubType;
import soot.ArrayType;
import soot.Context;
import soot.G;
import soot.Local;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.RefType;
import soot.Scene;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.jimple.spark.ondemand.genericutil.ArraySet;
import soot.jimple.spark.ondemand.genericutil.HashSetMultiMap;
import soot.jimple.spark.ondemand.genericutil.ImmutableStack;
import soot.jimple.spark.ondemand.genericutil.Predicate;
import soot.jimple.spark.ondemand.genericutil.Propagator;
import soot.jimple.spark.ondemand.genericutil.Stack;
import soot.jimple.spark.ondemand.pautil.AssignEdge;
import soot.jimple.spark.ondemand.pautil.ContextSensitiveInfo;
import soot.jimple.spark.ondemand.pautil.OTFMethodSCCManager;
import soot.jimple.spark.ondemand.pautil.SootUtil;
import soot.jimple.spark.ondemand.pautil.ValidMatches;
import soot.jimple.spark.ondemand.pautil.SootUtil.FieldToEdgesMap;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.GlobalVarNode;
import soot.jimple.spark.pag.LocalVarNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.EmptyPointsToSet;
import soot.jimple.spark.sets.EqualsSupportingPointsToSet;
import soot.jimple.spark.sets.HybridPointsToSet;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetEqualsWrapper;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.VirtualCalls;
import soot.toolkits.scalar.Pair;
import soot.util.NumberedString;
/**
* Tries to find imprecision in points-to sets from a previously run analysis.
* Requires that all sub-results of previous analysis were cached.
*
* @author Manu Sridharan
*
*/
public final class DemandCSPointsTo implements PointsToAnalysis {
@SuppressWarnings("serial")
protected static final class AllocAndContextCache extends
HashMap<AllocAndContext, Map<VarNode, CallingContextSet>> {
}
protected static final class CallingContextSet extends
ArraySet<ImmutableStack<Integer>> {
}
protected final static class CallSiteAndContext extends
Pair<Integer, ImmutableStack<Integer>> {
public CallSiteAndContext(Integer callSite,
ImmutableStack<Integer> callingContext) {
super(callSite, callingContext);
}
}
protected static final class CallSiteToTargetsMap extends
HashSetMultiMap<CallSiteAndContext, SootMethod> {
}
protected static abstract class IncomingEdgeHandler {
public abstract void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext);
public abstract void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine);
abstract Object getResult();
abstract void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge);
abstract boolean shouldHandleSrc(VarNode src);
boolean terminate() {
return false;
}
}
protected static class VarAndContext {
final ImmutableStack<Integer> context;
final VarNode var;
public VarAndContext(VarNode var, ImmutableStack<Integer> context) {
assert var != null;
assert context != null;
this.var = var;
this.context = context;
}
public boolean equals(Object o) {
if (o != null && o.getClass() == VarAndContext.class) {
VarAndContext other = (VarAndContext) o;
return var.equals(other.var) && context.equals(other.context);
}
return false;
}
public int hashCode() {
return var.hashCode() + context.hashCode();
}
public String toString() {
return var + " " + context;
}
}
protected final static class VarContextAndUp extends VarAndContext {
final ImmutableStack<Integer> upContext;
public VarContextAndUp(VarNode var, ImmutableStack<Integer> context,
ImmutableStack<Integer> upContext) {
super(var, context);
this.upContext = upContext;
}
public boolean equals(Object o) {
if (o != null && o.getClass() == VarContextAndUp.class) {
VarContextAndUp other = (VarContextAndUp) o;
return var.equals(other.var) && context.equals(other.context)
&& upContext.equals(other.upContext);
}
return false;
}
public int hashCode() {
return var.hashCode() + context.hashCode() + upContext.hashCode();
}
public String toString() {
return var + " " + context + " up " + upContext;
}
}
public static boolean DEBUG = false;
protected static final int DEBUG_NESTING = 15;
protected static final int DEBUG_PASS = -1;
protected static final boolean DEBUG_VIRT = DEBUG && true;
protected static final int DEFAULT_MAX_PASSES = 10;
protected static final int DEFAULT_MAX_TRAVERSAL = 75000;
/**
* if <code>true</code>, refine the pre-computed call graph
*/
private boolean refineCallGraph = true;
protected static final ImmutableStack<Integer> EMPTY_CALLSTACK = ImmutableStack.<Integer> emptyStack();
/**
* Make a default analysis. Assumes Spark has already run.
*
* @return
*/
public static DemandCSPointsTo makeDefault() {
return makeWithBudget(DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES);
}
public static DemandCSPointsTo makeWithBudget(int maxTraversal,
int maxPasses) {
PAG pag = (PAG) Scene.v().getPointsToAnalysis();
ContextSensitiveInfo csInfo = new ContextSensitiveInfo(pag);
return new DemandCSPointsTo(csInfo, pag, maxTraversal, maxPasses);
}
protected final AllocAndContextCache allocAndContextCache = new AllocAndContextCache();
protected Stack<Pair<Integer, ImmutableStack<Integer>>> callGraphStack = new Stack<Pair<Integer, ImmutableStack<Integer>>>();
protected final CallSiteToTargetsMap callSiteToResolvedTargets = new CallSiteToTargetsMap();
protected HashMap<List<Object>, Set<SootMethod>> callTargetsArgCache = new HashMap<List<Object>, Set<SootMethod>>();
protected final Stack<VarAndContext> contextForAllocsStack = new Stack<VarAndContext>();
protected Map<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>> contextsForAllocsCache = new HashMap<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>>();
protected final ContextSensitiveInfo csInfo;
/**
* if <code>true</code>, compute full points-to set for queried
* variable
*/
protected boolean doPointsTo;
protected FieldCheckHeuristic fieldCheckHeuristic;
protected HeuristicType heuristicType;
protected final FieldToEdgesMap fieldToLoads;
protected final FieldToEdgesMap fieldToStores;
protected final int maxNodesPerPass;
protected final int maxPasses;
protected int nesting = 0;
protected int numNodesTraversed;
protected int numPasses = 0;
protected final PAG pag;
protected AllocAndContextSet pointsTo = null;
protected final Set<CallSiteAndContext> queriedCallSites = new HashSet<CallSiteAndContext>();
protected int recursionDepth = -1;
protected boolean refiningCallSite = false;
protected OTFMethodSCCManager sccManager;
protected Map<VarContextAndUp, Map<AllocAndContext, CallingContextSet>> upContextCache = new HashMap<VarContextAndUp, Map<AllocAndContext, CallingContextSet>>();
protected final ValidMatches vMatches;
protected Map<Local,PointsToSet> reachingObjectsCache, reachingObjectsCacheNoCGRefinement;
protected boolean useCache;
public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag) {
this(csInfo, pag, DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES);
}
public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag,
int maxTraversal, int maxPasses) {
this.csInfo = csInfo;
this.pag = pag;
this.fieldToStores = SootUtil.storesOnField(pag);
this.fieldToLoads = SootUtil.loadsOnField(pag);
this.vMatches = new ValidMatches(pag, fieldToStores);
this.maxPasses = maxPasses;
this.maxNodesPerPass = maxTraversal / maxPasses;
this.heuristicType = HeuristicType.INCR;
this.reachingObjectsCache = new HashMap<Local, PointsToSet>();
this.reachingObjectsCacheNoCGRefinement = new HashMap<Local, PointsToSet>();
this.useCache = true;
}
/**
* {@inheritDoc}
*/
public PointsToSet reachingObjects(Local l) {
PointsToSet result;
Map<Local, PointsToSet> cache;
if(refineCallGraph) { //we use different caches for different settings
cache = reachingObjectsCache;
} else {
cache = reachingObjectsCacheNoCGRefinement;
}
result = cache.get(l);
if(result==null) {
result = computeReachingObjects(l);
if(useCache) {
cache.put(l, result);
}
}
assert consistentResult(l,result);
return result;
}
/**
* Returns <code>false</code> if an inconsistent computation occurred, i.e. if result
* differs from the result computed by {@link #computeReachingObjects(Local)} on l.
*/
private boolean consistentResult(Local l, PointsToSet result) {
PointsToSet result2 = computeReachingObjects(l);
if(!(result instanceof EqualsSupportingPointsToSet) || !(result2 instanceof EqualsSupportingPointsToSet)) {
//cannot compare, assume everything is fine
return true;
}
EqualsSupportingPointsToSet eq1 = (EqualsSupportingPointsToSet) result;
EqualsSupportingPointsToSet eq2 = (EqualsSupportingPointsToSet) result2;
return new PointsToSetEqualsWrapper(eq1).equals(new PointsToSetEqualsWrapper(eq2));
}
/**
* Computes the possibly refined set of reaching objects for l.
*/
protected PointsToSet computeReachingObjects(Local l) {
VarNode v = pag.findLocalVarNode(l);
if (v == null) {
//no reaching objects
return EmptyPointsToSet.v();
}
PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v);
if(contextSensitiveResult == null ) {
//had to abort; return Spark's points-to set in a wrapper
return new WrappedPointsToSet(v.getP2Set());
} else {
return contextSensitiveResult;
}
}
/**
* Computes the refined set of reaching objects for l.
* Returns <code>null</code> if refinement failed.
*/
protected PointsToSet computeRefinedReachingObjects(VarNode v) {
// must reset the refinement heuristic for each query
this.fieldCheckHeuristic = HeuristicType.getHeuristic(
heuristicType, pag.getTypeManager(), getMaxPasses());
doPointsTo = true;
numPasses = 0;
PointsToSet contextSensitiveResult = null;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
break;
}
if (numPasses > maxPasses) {
break;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
pointsTo = new AllocAndContextSet();
try {
refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null);
contextSensitiveResult = pointsTo;
} catch (TerminateEarlyException e) {
}
if (!fieldCheckHeuristic.runNewPass()) {
break;
}
}
return contextSensitiveResult;
}
protected boolean callEdgeInSCC(AssignEdge assignEdge) {
boolean sameSCCAlready = false;
assert assignEdge.isCallEdge();
// assert assignEdge.getSrc() instanceof LocalVarNode :
// assignEdge.getSrc() + " not LocalVarNode";
if (!(assignEdge.getSrc() instanceof LocalVarNode)
|| !(assignEdge.getDst() instanceof LocalVarNode)) {
return false;
}
LocalVarNode src = (LocalVarNode) assignEdge.getSrc();
LocalVarNode dst = (LocalVarNode) assignEdge.getDst();
if (sccManager.inSameSCC(src.getMethod(), dst.getMethod())) {
sameSCCAlready = true;
}
return sameSCCAlready;
}
protected CallingContextSet checkAllocAndContextCache(
AllocAndContext allocAndContext, VarNode targetVar) {
if (allocAndContextCache.containsKey(allocAndContext)) {
Map<VarNode, CallingContextSet> m = allocAndContextCache
.get(allocAndContext);
if (m.containsKey(targetVar)) {
return m.get(targetVar);
}
} else {
allocAndContextCache.put(allocAndContext,
new HashMap<VarNode, CallingContextSet>());
}
return null;
}
protected PointsToSetInternal checkContextsForAllocsCache(
VarAndContext varAndContext, AllocAndContextSet ret,
PointsToSetInternal locs) {
PointsToSetInternal retSet = null;
if (contextsForAllocsCache.containsKey(varAndContext)) {
for (AllocAndContext allocAndContext : contextsForAllocsCache.get(
varAndContext).getO2()) {
if (locs.contains(allocAndContext.alloc)) {
ret.add(allocAndContext);
}
}
final PointsToSetInternal oldLocs = contextsForAllocsCache.get(
varAndContext).getO1();
final PointsToSetInternal tmpSet = new HybridPointsToSet(locs
.getType(), pag);
locs.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (!oldLocs.contains(n)) {
tmpSet.add(n);
}
}
});
retSet = tmpSet;
oldLocs.addAll(tmpSet, null);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(locs
.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache.put(varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, new AllocAndContextSet()));
retSet = locs;
}
return retSet;
}
/**
* check the computed points-to set of a variable against some predicate
*
* @param v
* the variable
* @param heuristic
* how to refine match edges
* @param p2setPred
* the predicate on the points-to set
* @return true if the p2setPred holds for the computed points-to set, or if
* a points-to set cannot be computed in the budget; false otherwise
*/
protected boolean checkP2Set(VarNode v, HeuristicType heuristic,
Predicate<Set<AllocAndContext>> p2setPred) {
doPointsTo = true;
// DEBUG = v.getNumber() == 150;
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return true;
}
if (numPasses > maxPasses) {
return true;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
pointsTo = new AllocAndContextSet();
boolean success = false;
try {
success = refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK),
null);
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
if (p2setPred.test(pointsTo)) {
return false;
}
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return true;
}
}
}
}
// protected boolean upContextsSane(CallingContextSet ret, AllocAndContext
// allocAndContext, VarContextAndUp varContextAndUp) {
// for (ImmutableStack<Integer> context : ret) {
// ImmutableStack<Integer> fixedContext = fixUpContext(context,
// allocAndContext, varContextAndUp);
// if (!context.equals(fixedContext)) {
// return false;
// return true;
// protected CallingContextSet fixAllUpContexts(CallingContextSet contexts,
// AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) {
// if (DEBUG) {
// debugPrint("fixing up contexts");
// CallingContextSet ret = new CallingContextSet();
// for (ImmutableStack<Integer> context : contexts) {
// ret.add(fixUpContext(context, allocAndContext, varContextAndUp));
// return ret;
// protected ImmutableStack<Integer> fixUpContext(ImmutableStack<Integer>
// context, AllocAndContext allocAndContext, VarContextAndUp
// varContextAndUp) {
// return null;
protected CallingContextSet checkUpContextCache(
VarContextAndUp varContextAndUp, AllocAndContext allocAndContext) {
if (upContextCache.containsKey(varContextAndUp)) {
Map<AllocAndContext, CallingContextSet> allocAndContextMap = upContextCache
.get(varContextAndUp);
if (allocAndContextMap.containsKey(allocAndContext)) {
return allocAndContextMap.get(allocAndContext);
}
} else {
upContextCache.put(varContextAndUp,
new HashMap<AllocAndContext, CallingContextSet>());
}
return null;
}
protected void clearState() {
allocAndContextCache.clear();
callGraphStack.clear();
callSiteToResolvedTargets.clear();
queriedCallSites.clear();
contextsForAllocsCache.clear();
contextForAllocsStack.clear();
upContextCache.clear();
callTargetsArgCache.clear();
sccManager = new OTFMethodSCCManager();
numNodesTraversed = 0;
nesting = 0;
recursionDepth = -1;
}
/**
* compute a flows-to set for an allocation site. for now, we use a simple
* refinement strategy; just refine as much as possible, maintaining the
* smallest set of flows-to vars
*
* @param alloc
* @param heuristic
* @return
*/
protected Set<VarNode> computeFlowsTo(AllocNode alloc,
HeuristicType heuristic) {
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
Set<VarNode> smallest = null;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return smallest;
}
if (numPasses > maxPasses) {
return smallest;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
Set<VarNode> result = null;
try {
result = getFlowsToHelper(new AllocAndContext(alloc,
EMPTY_CALLSTACK));
} catch (TerminateEarlyException e) {
}
if (result != null) {
if (smallest == null || result.size() < smallest.size()) {
smallest = result;
}
}
if (!fieldCheckHeuristic.runNewPass()) {
return smallest;
}
}
}
protected void debugPrint(String str) {
if (nesting <= DEBUG_NESTING) {
if (DEBUG_PASS == -1 || DEBUG_PASS == numPasses) {
G.v().out.println(":" + nesting + " " + str);
}
}
}
/*
* (non-Javadoc)
*
* @see AAA.summary.Refiner#dumpPathForBadLoc(soot.jimple.spark.pag.VarNode,
* soot.jimple.spark.pag.AllocNode)
*/
protected void dumpPathForLoc(VarNode v, final AllocNode badLoc,
String filePrefix) {
final HashSet<VarNode> visited = new HashSet<VarNode>();
final DotPointerGraph dotGraph = new DotPointerGraph();
final class Helper {
boolean handle(VarNode curNode) {
assert curNode.getP2Set().contains(badLoc);
visited.add(curNode);
Node[] newEdges = pag.allocInvLookup(curNode);
for (int i = 0; i < newEdges.length; i++) {
AllocNode alloc = (AllocNode) newEdges[i];
if (alloc.equals(badLoc)) {
dotGraph.addNew(alloc, curNode);
return true;
}
}
for (AssignEdge assignEdge : csInfo.getAssignEdges(curNode)) {
VarNode other = assignEdge.getSrc();
if (other.getP2Set().contains(badLoc)
&& !visited.contains(other) && handle(other)) {
if (assignEdge.isCallEdge()) {
dotGraph.addCall(other, curNode, assignEdge
.getCallSite());
} else {
dotGraph.addAssign(other, curNode);
}
return true;
}
}
Node[] loadEdges = pag.loadInvLookup(curNode);
for (int i = 0; i < loadEdges.length; i++) {
FieldRefNode frNode = (FieldRefNode) loadEdges[i];
SparkField field = frNode.getField();
VarNode base = frNode.getBase();
PointsToSetInternal baseP2Set = base.getP2Set();
for (Pair<VarNode, VarNode> store : fieldToStores
.get(field)) {
if (store.getO2().getP2Set().hasNonEmptyIntersection(
baseP2Set)) {
VarNode matchSrc = store.getO1();
if (matchSrc.getP2Set().contains(badLoc)
&& !visited.contains(matchSrc)
&& handle(matchSrc)) {
dotGraph.addMatch(matchSrc, curNode);
return true;
}
}
}
}
return false;
}
}
Helper h = new Helper();
h.handle(v);
// G.v().out.println(dotGraph.numEdges() + " edges on path");
dotGraph.dump("tmp/" + filePrefix + v.getNumber() + "_"
+ badLoc.getNumber() + ".dot");
}
protected Collection<AssignEdge> filterAssigns(final VarNode v,
final ImmutableStack<Integer> callingContext, boolean forward,
boolean refineVirtCalls) {
Set<AssignEdge> assigns = forward ? csInfo.getAssignEdges(v) : csInfo
.getAssignBarEdges(v);
Collection<AssignEdge> realAssigns;
boolean exitNode = forward ? SootUtil.isParamNode(v) : SootUtil
.isRetNode(v);
final boolean backward = !forward;
if (exitNode && !callingContext.isEmpty()) {
Integer topCallSite = callingContext.peek();
realAssigns = new ArrayList<AssignEdge>();
for (AssignEdge assignEdge : assigns) {
assert (forward && assignEdge.isParamEdge())
|| (backward && assignEdge.isReturnEdge()) : assignEdge;
Integer assignEdgeCallSite = assignEdge.getCallSite();
assert csInfo.getCallSiteTargets(assignEdgeCallSite).contains(
((LocalVarNode) v).getMethod()) : assignEdge;
if (topCallSite.equals(assignEdgeCallSite)
|| callEdgeInSCC(assignEdge)) {
realAssigns.add(assignEdge);
}
}
// assert realAssigns.size() == 1;
} else {
if (assigns.size() > 1) {
realAssigns = new ArrayList<AssignEdge>();
for (AssignEdge assignEdge : assigns) {
boolean enteringCall = forward ? assignEdge.isReturnEdge()
: assignEdge.isParamEdge();
if (enteringCall) {
Integer callSite = assignEdge.getCallSite();
if (csInfo.isVirtCall(callSite) && refineVirtCalls) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), callingContext);
LocalVarNode nodeInTargetMethod = forward ? (LocalVarNode) assignEdge
.getSrc()
: (LocalVarNode) assignEdge.getDst();
if (targets
.contains(nodeInTargetMethod.getMethod())) {
realAssigns.add(assignEdge);
}
} else {
realAssigns.add(assignEdge);
}
} else {
realAssigns.add(assignEdge);
}
}
} else {
realAssigns = assigns;
}
}
return realAssigns;
}
protected AllocAndContextSet findContextsForAllocs(
final VarAndContext varAndContext, PointsToSetInternal locs) {
if (contextForAllocsStack.contains(varAndContext)) {
// recursion; check depth
// we're fine for x = x.next
int oldIndex = contextForAllocsStack.indexOf(varAndContext);
if (oldIndex != contextForAllocsStack.size() - 1) {
if (recursionDepth == -1) {
recursionDepth = oldIndex + 1;
if (DEBUG) {
debugPrint("RECURSION depth = " + recursionDepth);
}
} else if (contextForAllocsStack.size() - oldIndex > 5) {
// just give up
throw new TerminateEarlyException();
}
}
}
contextForAllocsStack.push(varAndContext);
final AllocAndContextSet ret = new AllocAndContextSet();
final PointsToSetInternal realLocs = checkContextsForAllocsCache(
varAndContext, ret, locs);
if (realLocs.isEmpty()) {
if (DEBUG) {
debugPrint("cached result " + ret);
}
contextForAllocsStack.pop();
return ret;
}
nesting++;
if (DEBUG) {
debugPrint("finding alloc contexts for " + varAndContext);
}
try {
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varAndContext);
IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() {
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
if (realLocs.contains(allocNode)) {
if (DEBUG) {
debugPrint("found alloc " + allocNode);
}
ret.add(new AllocAndContext(allocNode,
origVarAndContext.context));
}
}
@Override
public void handleMatchSrc(final VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
if (DEBUG) {
debugPrint("handling src " + matchSrc);
debugPrint("intersection " + intersection);
}
if (!refine) {
p.prop(new VarAndContext(matchSrc, EMPTY_CALLSTACK));
return;
}
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(loadBase,
origVarAndContext.context), intersection);
if (DEBUG) {
debugPrint("alloc contexts " + allocContexts);
}
for (AllocAndContext allocAndContext : allocContexts) {
if (DEBUG) {
debugPrint("alloc and context " + allocAndContext);
}
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(
storeBase, EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
// ret
// .add(new Pair<AllocNode,
// ImmutableStack<Integer>>(
// (AllocNode) n,
// matchSrcContext));
// ret.addAll(findContextsForAllocs(matchSrc,
// matchSrcContext, locs));
p
.prop(new VarAndContext(matchSrc,
matchSrcContext));
}
}
}
@Override
Object getResult() {
return ret;
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
p.prop(newVarAndContext);
}
@Override
boolean shouldHandleSrc(VarNode src) {
return realLocs.hasNonEmptyIntersection(src.getP2Set());
}
};
processIncomingEdges(edgeHandler, worklist);
// update the cache
if (recursionDepth != -1) {
// if we're beyond recursion, don't cache anything
if (contextForAllocsStack.size() > recursionDepth) {
if (DEBUG) {
debugPrint("REMOVING " + varAndContext);
debugPrint(contextForAllocsStack.toString());
}
contextsForAllocsCache.remove(varAndContext);
} else {
assert contextForAllocsStack.size() == recursionDepth : recursionDepth
+ " " + contextForAllocsStack;
recursionDepth = -1;
if (contextsForAllocsCache.containsKey(varAndContext)) {
contextsForAllocsCache.get(varAndContext).getO2()
.addAll(ret);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(
locs.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache
.put(
varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, ret));
}
}
} else {
if (contextsForAllocsCache.containsKey(varAndContext)) {
contextsForAllocsCache.get(varAndContext).getO2().addAll(
ret);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(locs
.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache.put(varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, ret));
}
}
nesting
return ret;
} catch (CallSiteException e) {
contextsForAllocsCache.remove(varAndContext);
throw e;
} finally {
contextForAllocsStack.pop();
}
}
protected CallingContextSet findUpContextsForVar(
AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) {
final AllocNode alloc = allocAndContext.alloc;
final ImmutableStack<Integer> allocContext = allocAndContext.context;
CallingContextSet tmpSet = checkUpContextCache(varContextAndUp,
allocAndContext);
if (tmpSet != null) {
return tmpSet;
}
final CallingContextSet ret = new CallingContextSet();
upContextCache.get(varContextAndUp).put(allocAndContext, ret);
nesting++;
if (DEBUG) {
debugPrint("finding up context for " + varContextAndUp + " to "
+ alloc + " " + allocContext);
}
try {
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varContextAndUp);
class UpContextEdgeHandler extends IncomingEdgeHandler {
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
if (allocNode == alloc) {
if (allocContext.topMatches(contextAndUp.context)) {
ImmutableStack<Integer> reverse = contextAndUp.upContext
.reverse();
ImmutableStack<Integer> toAdd = allocContext
.popAll(contextAndUp.context).pushAll(
reverse);
if (DEBUG) {
debugPrint("found up context " + toAdd);
}
ret.add(toAdd);
} else if (contextAndUp.context
.topMatches(allocContext)) {
ImmutableStack<Integer> toAdd = contextAndUp.upContext
.reverse();
if (DEBUG) {
debugPrint("found up context " + toAdd);
}
ret.add(toAdd);
}
}
}
@Override
public void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
if (DEBUG) {
debugPrint("CHECKING " + alloc);
}
PointsToSetInternal tmp = new HybridPointsToSet(alloc
.getType(), pag);
tmp.add(alloc);
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(matchSrc, EMPTY_CALLSTACK), tmp);
// Set allocContexts = Collections.singleton(new Object());
if (!refine) {
if (!allocContexts.isEmpty()) {
ret.add(contextAndUp.upContext.reverse());
}
} else {
if (!allocContexts.isEmpty()) {
for (AllocAndContext t : allocContexts) {
ImmutableStack<Integer> discoveredAllocContext = t.context;
if (!allocContext
.topMatches(discoveredAllocContext)) {
continue;
}
ImmutableStack<Integer> trueAllocContext = allocContext
.popAll(discoveredAllocContext);
AllocAndContextSet allocAndContexts = findContextsForAllocs(
new VarAndContext(storeBase,
trueAllocContext), intersection);
for (AllocAndContext allocAndContext : allocAndContexts) {
// if (DEBUG)
// G.v().out.println("alloc context "
// + newAllocContext);
// CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
ret
.addAll(findUpContextsForVar(
allocAndContext,
new VarContextAndUp(
loadBase,
contextAndUp.context,
contextAndUp.upContext)));
} else {
CallingContextSet tmpContexts = findVarContextsFromAlloc(
allocAndContext, loadBase);
// upContexts = new CallingContextSet();
for (ImmutableStack<Integer> tmpContext : tmpContexts) {
if (tmpContext
.topMatches(contextAndUp.context)) {
ImmutableStack<Integer> reverse = contextAndUp.upContext
.reverse();
ImmutableStack<Integer> toAdd = tmpContext
.popAll(
contextAndUp.context)
.pushAll(reverse);
ret.add(toAdd);
}
}
}
}
}
}
}
}
@Override
Object getResult() {
return ret;
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
ImmutableStack<Integer> upContext = contextAndUp.upContext;
ImmutableStack<Integer> newUpContext = upContext;
if (assignEdge.isParamEdge()
&& contextAndUp.context.isEmpty()) {
if (upContext.size() < ImmutableStack.getMaxSize()) {
newUpContext = pushWithRecursionCheck(upContext,
assignEdge);
}
;
}
p.prop(new VarContextAndUp(newVarAndContext.var,
newVarAndContext.context, newUpContext));
}
@Override
boolean shouldHandleSrc(VarNode src) {
if (src instanceof GlobalVarNode) {
// TODO properly handle case of global here; rare
// but possible
// reachedGlobal = true;
// // for now, just give up
throw new TerminateEarlyException();
}
return src.getP2Set().contains(alloc);
}
}
;
UpContextEdgeHandler edgeHandler = new UpContextEdgeHandler();
processIncomingEdges(edgeHandler, worklist);
nesting
// if (edgeHandler.reachedGlobal) {
// return fixAllUpContexts(ret, allocAndContext, varContextAndUp);
// } else {
// assert upContextsSane(ret, allocAndContext, varContextAndUp);
// return ret;
return ret;
} catch (CallSiteException e) {
upContextCache.remove(varContextAndUp);
throw e;
}
}
protected CallingContextSet findVarContextsFromAlloc(
AllocAndContext allocAndContext, VarNode targetVar) {
CallingContextSet tmpSet = checkAllocAndContextCache(allocAndContext,
targetVar);
if (tmpSet != null) {
return tmpSet;
}
CallingContextSet ret = new CallingContextSet();
allocAndContextCache.get(allocAndContext).put(targetVar, ret);
try {
HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
Stack<VarAndContext> worklist = new Stack<VarAndContext>();
Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked,
worklist);
AllocNode alloc = allocAndContext.alloc;
ImmutableStack<Integer> allocContext = allocAndContext.context;
Node[] newBarNodes = pag.allocLookup(alloc);
for (int i = 0; i < newBarNodes.length; i++) {
VarNode v = (VarNode) newBarNodes[i];
p.prop(new VarAndContext(v, allocContext));
}
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
if (curVar == targetVar) {
ret.add(curContext);
}
// assign
Collection<AssignEdge> assignEdges = filterAssigns(curVar,
curContext, false, true);
for (AssignEdge assignEdge : assignEdges) {
VarNode dst = assignEdge.getDst();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isReturnEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek()) : assignEdge + " "
+ curContext;
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
}
} else if (assignEdge.isParamEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge
// .getCallSite());
newContext = pushWithRecursionCheck(curContext,
assignEdge);
}
if (assignEdge.isReturnEdge() && curContext.isEmpty()
&& csInfo.isVirtCall(assignEdge.getCallSite())) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), newContext);
if (!targets.contains(((LocalVarNode) assignEdge
.getDst()).getMethod())) {
continue;
}
}
if (dst instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
p.prop(new VarAndContext(dst, newContext));
}
// putfield_bars
Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar);
Node[] pfTargets = pag.storeLookup(curVar);
for (int i = 0; i < pfTargets.length; i++) {
FieldRefNode frNode = (FieldRefNode) pfTargets[i];
final VarNode storeBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode,
// FieldRefNode>(curVar, frNode);
for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) {
final VarNode loadBase = load.getO2();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final VarNode matchTgt = load.getO1();
if (matchTargets.contains(matchTgt)) {
if (DEBUG) {
debugPrint("match source " + matchTgt);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkField = fieldCheckHeuristic
.validateMatchesForField(field);
if (checkField) {
AllocAndContextSet sharedAllocContexts = findContextsForAllocs(
new VarAndContext(storeBase, curContext),
intersection);
for (AllocAndContext curAllocAndContext : sharedAllocContexts) {
CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
upContexts = findUpContextsForVar(
curAllocAndContext,
new VarContextAndUp(loadBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
upContexts = findVarContextsFromAlloc(
curAllocAndContext, loadBase);
}
for (ImmutableStack<Integer> upContext : upContexts) {
p.prop(new VarAndContext(matchTgt,
upContext));
}
}
} else {
p.prop(new VarAndContext(matchTgt,
EMPTY_CALLSTACK));
}
// h.handleMatchSrc(matchSrc, intersection,
// storeBase,
// loadBase, varAndContext, checkGetfield);
// if (h.terminate())
// return;
}
}
}
}
return ret;
} catch (CallSiteException e) {
allocAndContextCache.remove(allocAndContext);
throw e;
}
}
@SuppressWarnings("unchecked")
protected Set<SootMethod> getCallTargets(PointsToSetInternal p2Set,
NumberedString methodStr, Type receiverType,
Set<SootMethod> possibleTargets) {
List<Object> args = Arrays.asList(p2Set, methodStr, receiverType,
possibleTargets);
if (callTargetsArgCache.containsKey(args)) {
return callTargetsArgCache.get(args);
}
Set<Type> types = p2Set.possibleTypes();
Set<SootMethod> ret = new HashSet<SootMethod>();
for (Type type : types) {
ret.addAll(getCallTargetsForType(type, methodStr, receiverType,
possibleTargets));
}
callTargetsArgCache.put(args, ret);
return ret;
}
protected Set<SootMethod> getCallTargetsForType(Type type,
NumberedString methodStr, Type receiverType,
Set<SootMethod> possibleTargets) {
if (!pag.getTypeManager().castNeverFails(type, receiverType))
return Collections.<SootMethod> emptySet();
if (type instanceof AnySubType) {
AnySubType any = (AnySubType) type;
RefType refType = any.getBase();
if (pag.getTypeManager().getFastHierarchy().canStoreType(
receiverType, refType)
|| pag.getTypeManager().getFastHierarchy().canStoreType(
refType, receiverType)) {
return possibleTargets;
} else {
return Collections.<SootMethod> emptySet();
}
}
if (type instanceof ArrayType) {
// we'll invoke the java.lang.Object method in this
// case
// Assert.chk(varNodeType.toString().equals("java.lang.Object"));
type = Scene.v().getSootClass("java.lang.Object").getType();
}
RefType refType = (RefType) type;
SootMethod targetMethod = null;
targetMethod = VirtualCalls.v().resolveNonSpecial(refType, methodStr);
return Collections.<SootMethod> singleton(targetMethod);
}
protected Set<VarNode> getFlowsToHelper(AllocAndContext allocAndContext) {
Set<VarNode> ret = new ArraySet<VarNode>();
try {
HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
Stack<VarAndContext> worklist = new Stack<VarAndContext>();
Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked,
worklist);
AllocNode alloc = allocAndContext.alloc;
ImmutableStack<Integer> allocContext = allocAndContext.context;
Node[] newBarNodes = pag.allocLookup(alloc);
for (int i = 0; i < newBarNodes.length; i++) {
VarNode v = (VarNode) newBarNodes[i];
ret.add(v);
p.prop(new VarAndContext(v, allocContext));
}
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
ret.add(curVar);
// assign
Collection<AssignEdge> assignEdges = filterAssigns(curVar,
curContext, false, true);
for (AssignEdge assignEdge : assignEdges) {
VarNode dst = assignEdge.getDst();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isReturnEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek()) : assignEdge + " "
+ curContext;
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
}
} else if (assignEdge.isParamEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge
// .getCallSite());
newContext = pushWithRecursionCheck(curContext,
assignEdge);
}
if (assignEdge.isReturnEdge() && curContext.isEmpty()
&& csInfo.isVirtCall(assignEdge.getCallSite())) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), newContext);
if (!targets.contains(((LocalVarNode) assignEdge
.getDst()).getMethod())) {
continue;
}
}
if (dst instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
p.prop(new VarAndContext(dst, newContext));
}
// putfield_bars
Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar);
Node[] pfTargets = pag.storeLookup(curVar);
for (int i = 0; i < pfTargets.length; i++) {
FieldRefNode frNode = (FieldRefNode) pfTargets[i];
final VarNode storeBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode,
// FieldRefNode>(curVar, frNode);
for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) {
final VarNode loadBase = load.getO2();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final VarNode matchTgt = load.getO1();
if (matchTargets.contains(matchTgt)) {
if (DEBUG) {
debugPrint("match source " + matchTgt);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkField = fieldCheckHeuristic
.validateMatchesForField(field);
if (checkField) {
AllocAndContextSet sharedAllocContexts = findContextsForAllocs(
new VarAndContext(storeBase, curContext),
intersection);
for (AllocAndContext curAllocAndContext : sharedAllocContexts) {
CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
upContexts = findUpContextsForVar(
curAllocAndContext,
new VarContextAndUp(loadBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
upContexts = findVarContextsFromAlloc(
curAllocAndContext, loadBase);
}
for (ImmutableStack<Integer> upContext : upContexts) {
p.prop(new VarAndContext(matchTgt,
upContext));
}
}
} else {
p.prop(new VarAndContext(matchTgt,
EMPTY_CALLSTACK));
}
// h.handleMatchSrc(matchSrc, intersection,
// storeBase,
// loadBase, varAndContext, checkGetfield);
// if (h.terminate())
// return;
}
}
}
}
return ret;
} catch (CallSiteException e) {
allocAndContextCache.remove(allocAndContext);
throw e;
}
}
protected int getMaxPasses() {
return maxPasses;
}
protected void incrementNodesTraversed() {
numNodesTraversed++;
if (numNodesTraversed > maxNodesPerPass) {
throw new TerminateEarlyException();
}
}
@SuppressWarnings("unused")
protected boolean isRecursive(ImmutableStack<Integer> context,
AssignEdge assignEdge) {
boolean sameSCCAlready = callEdgeInSCC(assignEdge);
if (sameSCCAlready) {
return true;
}
Integer callSite = assignEdge.getCallSite();
if (context.contains(callSite)) {
Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>();
int callSiteInd = 0;
for (; callSiteInd < context.size()
&& !context.get(callSiteInd).equals(callSite); callSiteInd++)
;
for (; callSiteInd < context.size(); callSiteInd++) {
toBeCollapsed.add(csInfo.getInvokingMethod(context
.get(callSiteInd)));
}
sccManager.makeSameSCC(toBeCollapsed);
return true;
}
return false;
}
protected boolean isRecursiveCallSite(Integer callSite) {
SootMethod invokingMethod = csInfo.getInvokingMethod(callSite);
SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
return sccManager.inSameSCC(invokingMethod, invokedMethod);
}
@SuppressWarnings("unused")
protected Set<VarNode> nodesPropagatedThrough(final VarNode source,
final PointsToSetInternal allocs) {
final Set<VarNode> marked = new HashSet<VarNode>();
final Stack<VarNode> worklist = new Stack<VarNode>();
Propagator<VarNode> p = new Propagator<VarNode>(marked, worklist);
p.prop(source);
while (!worklist.isEmpty()) {
VarNode curNode = worklist.pop();
Node[] assignSources = pag.simpleInvLookup(curNode);
for (int i = 0; i < assignSources.length; i++) {
VarNode assignSrc = (VarNode) assignSources[i];
if (assignSrc.getP2Set().hasNonEmptyIntersection(allocs)) {
p.prop(assignSrc);
}
}
Set<VarNode> matchSources = vMatches.vMatchInvLookup(curNode);
for (VarNode matchSrc : matchSources) {
if (matchSrc.getP2Set().hasNonEmptyIntersection(allocs)) {
p.prop(matchSrc);
}
}
}
return marked;
}
protected ImmutableStack<Integer> popRecursiveCallSites(
ImmutableStack<Integer> context) {
ImmutableStack<Integer> ret = context;
while (!ret.isEmpty() && isRecursiveCallSite(ret.peek())) {
ret = ret.pop();
}
return ret;
}
protected void processIncomingEdges(IncomingEdgeHandler h,
Stack<VarAndContext> worklist) {
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext varAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + varAndContext);
}
VarNode v = varAndContext.var;
ImmutableStack<Integer> callingContext = varAndContext.context;
Node[] newEdges = pag.allocInvLookup(v);
for (int i = 0; i < newEdges.length; i++) {
AllocNode allocNode = (AllocNode) newEdges[i];
h.handleAlloc(allocNode, varAndContext);
if (h.terminate()) {
return;
}
}
Collection<AssignEdge> assigns = filterAssigns(v, callingContext,
true, true);
for (AssignEdge assignEdge : assigns) {
VarNode src = assignEdge.getSrc();
// if (DEBUG) {
// G.v().out.println("assign src " + src);
if (h.shouldHandleSrc(src)) {
ImmutableStack<Integer> newContext = callingContext;
if (assignEdge.isParamEdge()) {
if (!callingContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
callingContext.peek()) : assignEdge
+ " " + callingContext;
newContext = callingContext.pop();
} else {
newContext = popRecursiveCallSites(callingContext);
}
}
// } else if (refiningCallSite) {
// if (!fieldCheckHeuristic.aggressiveVirtCallRefine())
// // throw new CallSiteException();
} else if (assignEdge.isReturnEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(callingContext, assignEdge)) {
// newContext = callingContext.push(assignEdge
// .getCallSite());
newContext = pushWithRecursionCheck(callingContext,
assignEdge);
}
if (assignEdge.isParamEdge()) {
Integer callSite = assignEdge.getCallSite();
if (csInfo.isVirtCall(callSite) && !weirdCall(callSite)) {
Set<SootMethod> targets = refineCallSite(callSite,
newContext);
if (DEBUG) {
debugPrint(targets.toString());
}
SootMethod targetMethod = ((LocalVarNode) assignEdge
.getDst()).getMethod();
if (!targets.contains(targetMethod)) {
if (DEBUG) {
debugPrint("skipping call because of call graph");
}
continue;
}
}
}
if (src instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
h.handleAssignSrc(new VarAndContext(src, newContext),
varAndContext, assignEdge);
if (h.terminate()) {
return;
}
}
}
Set<VarNode> matchSources = vMatches.vMatchInvLookup(v);
Node[] loads = pag.loadInvLookup(v);
for (int i = 0; i < loads.length; i++) {
FieldRefNode frNode = (FieldRefNode) loads[i];
final VarNode loadBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> getfield = new Pair<VarNode,
// FieldRefNode>(v, frNode);
for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) {
final VarNode storeBase = store.getO2();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final VarNode matchSrc = store.getO1();
if (matchSources.contains(matchSrc)) {
if (h.shouldHandleSrc(matchSrc)) {
if (DEBUG) {
debugPrint("match source " + matchSrc);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkGetfield = fieldCheckHeuristic
.validateMatchesForField(field);
h.handleMatchSrc(matchSrc, intersection, loadBase,
storeBase, varAndContext, field,
checkGetfield);
if (h.terminate())
return;
}
}
}
}
}
}
protected ImmutableStack<Integer> pushWithRecursionCheck(
ImmutableStack<Integer> context, AssignEdge assignEdge) {
boolean foundRecursion = callEdgeInSCC(assignEdge);
if (!foundRecursion) {
Integer callSite = assignEdge.getCallSite();
if (context.contains(callSite)) {
foundRecursion = true;
if (DEBUG) {
debugPrint("RECURSION!!!");
}
// TODO properly collapse recursive methods
if (true) {
throw new TerminateEarlyException();
}
Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>();
int callSiteInd = 0;
for (; callSiteInd < context.size()
&& !context.get(callSiteInd).equals(callSite); callSiteInd++)
;
// int numToPop = 0;
for (; callSiteInd < context.size(); callSiteInd++) {
toBeCollapsed.add(csInfo.getInvokingMethod(context
.get(callSiteInd)));
// numToPop++;
}
sccManager.makeSameSCC(toBeCollapsed);
// ImmutableStack<Integer> poppedContext = context;
// for (int i = 0; i < numToPop; i++) {
// poppedContext = poppedContext.pop();
// if (DEBUG) {
// debugPrint("new stack " + poppedContext);
// return poppedContext;
}
}
if (foundRecursion) {
ImmutableStack<Integer> popped = popRecursiveCallSites(context);
if (DEBUG) {
debugPrint("popped stack " + popped);
}
return popped;
} else {
return context.push(assignEdge.getCallSite());
}
}
protected boolean refineAlias(VarNode v1, VarNode v2,
PointsToSetInternal intersection, HeuristicType heuristic) {
if (refineAliasInternal(v1, v2, intersection, heuristic))
return true;
if (refineAliasInternal(v2, v1, intersection, heuristic))
return true;
return false;
}
protected boolean refineAliasInternal(VarNode v1, VarNode v2,
PointsToSetInternal intersection, HeuristicType heuristic) {
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return false;
}
if (numPasses > maxPasses) {
return false;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
boolean success = false;
try {
AllocAndContextSet allocAndContexts = findContextsForAllocs(
new VarAndContext(v1, EMPTY_CALLSTACK), intersection);
boolean emptyIntersection = true;
for (AllocAndContext allocAndContext : allocAndContexts) {
CallingContextSet upContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(v2,
EMPTY_CALLSTACK, EMPTY_CALLSTACK));
if (!upContexts.isEmpty()) {
emptyIntersection = false;
break;
}
}
success = emptyIntersection;
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
G.v().out.println("took " + numPasses + " passes");
return true;
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return false;
}
}
}
}
protected Set<SootMethod> refineCallSite(Integer callSite,
ImmutableStack<Integer> origContext) {
CallSiteAndContext callSiteAndContext = new CallSiteAndContext(
callSite, origContext);
if (queriedCallSites.contains(callSiteAndContext)) {
// if (DEBUG_VIRT) {
// final SootMethod invokedMethod =
// csInfo.getInvokedMethod(callSite);
// final VarNode receiver =
// csInfo.getReceiverForVirtCallSite(callSite);
// debugPrint("call of " + invokedMethod + " on " + receiver + " "
// + origContext + " goes to "
// + callSiteToResolvedTargets.get(callSiteAndContext));
return callSiteToResolvedTargets.get(callSiteAndContext);
}
if (callGraphStack.contains(callSiteAndContext)) {
return Collections.<SootMethod> emptySet();
} else {
callGraphStack.push(callSiteAndContext);
}
final VarNode receiver = csInfo.getReceiverForVirtCallSite(callSite);
final Type receiverType = receiver.getType();
final SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
final NumberedString methodSig = invokedMethod
.getNumberedSubSignature();
final Set<SootMethod> allTargets = csInfo.getCallSiteTargets(callSite);
if (!refineCallGraph) {
callGraphStack.pop();
return allTargets;
}
if (DEBUG_VIRT) {
debugPrint("refining call to " + invokedMethod + " on " + receiver
+ " " + origContext);
}
final HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final class Helper {
void prop(VarAndContext varAndContext) {
if (marked.add(varAndContext)) {
worklist.push(varAndContext);
}
}
}
;
final Helper h = new Helper();
h.prop(new VarAndContext(receiver, origContext));
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG_VIRT) {
debugPrint("virt looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
// Set<SootMethod> curVarTargets = getCallTargets(curVar.getP2Set(),
// methodSig, receiverType, allTargets);
// if (curVarTargets.size() <= 1) {
// for (SootMethod method : curVarTargets) {
// callSiteToResolvedTargets.put(callSiteAndContext, method);
// continue;
Node[] newNodes = pag.allocInvLookup(curVar);
for (int i = 0; i < newNodes.length; i++) {
AllocNode allocNode = (AllocNode) newNodes[i];
for (SootMethod method : getCallTargetsForType(allocNode
.getType(), methodSig, receiverType, allTargets)) {
callSiteToResolvedTargets.put(callSiteAndContext, method);
}
}
Collection<AssignEdge> assigns = filterAssigns(curVar, curContext,
true, true);
for (AssignEdge assignEdge : assigns) {
VarNode src = assignEdge.getSrc();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isParamEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek());
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
} else {
callSiteToResolvedTargets.putAll(callSiteAndContext,
allTargets);
// if (DEBUG) {
// debugPrint("giving up on virt");
continue;
}
} else if (assignEdge.isReturnEdge()) {
// if (DEBUG)
// G.v().out.println("entering call site "
// + assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge.getCallSite());
newContext = pushWithRecursionCheck(curContext, assignEdge);
} else if (src instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
h.prop(new VarAndContext(src, newContext));
}
// TODO respect heuristic
Set<VarNode> matchSources = vMatches.vMatchInvLookup(curVar);
final boolean oneMatch = matchSources.size() == 1;
Node[] loads = pag.loadInvLookup(curVar);
for (int i = 0; i < loads.length; i++) {
FieldRefNode frNode = (FieldRefNode) loads[i];
final VarNode loadBase = frNode.getBase();
SparkField field = frNode.getField();
for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) {
final VarNode storeBase = store.getO2();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final VarNode matchSrc = store.getO1();
if (matchSources.contains(matchSrc)) {
// optimize for common case of constructor init
boolean skipMatch = false;
if (oneMatch) {
PointsToSetInternal matchSrcPTo = matchSrc
.getP2Set();
Set<SootMethod> matchSrcCallTargets = getCallTargets(
matchSrcPTo, methodSig, receiverType,
allTargets);
if (matchSrcCallTargets.size() <= 1) {
skipMatch = true;
for (SootMethod method : matchSrcCallTargets) {
callSiteToResolvedTargets.put(
callSiteAndContext, method);
}
}
}
if (!skipMatch) {
final PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
AllocAndContextSet allocContexts = null;
boolean oldRefining = refiningCallSite;
int oldNesting = nesting;
try {
refiningCallSite = true;
allocContexts = findContextsForAllocs(
new VarAndContext(loadBase, curContext),
intersection);
} catch (CallSiteException e) {
callSiteToResolvedTargets.putAll(
callSiteAndContext, allTargets);
continue;
} finally {
refiningCallSite = oldRefining;
nesting = oldNesting;
}
for (AllocAndContext allocAndContext : allocContexts) {
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext,
new VarContextAndUp(storeBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
VarAndContext newVarAndContext = new VarAndContext(
matchSrc, matchSrcContext);
h.prop(newVarAndContext);
}
}
}
}
}
}
}
if (DEBUG_VIRT) {
debugPrint("call of " + invokedMethod + " on " + receiver + " "
+ origContext + " goes to "
+ callSiteToResolvedTargets.get(callSiteAndContext));
}
callGraphStack.pop();
queriedCallSites.add(callSiteAndContext);
return callSiteToResolvedTargets.get(callSiteAndContext);
}
protected boolean refineP2Set(VarAndContext varAndContext,
final PointsToSetInternal badLocs) {
nesting++;
if (DEBUG) {
debugPrint("refining " + varAndContext);
}
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varAndContext);
IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() {
boolean success = true;
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
if (doPointsTo && pointsTo != null) {
pointsTo.add(new AllocAndContext(allocNode,
origVarAndContext.context));
} else {
if (badLocs.contains(allocNode)) {
success = false;
}
}
}
@Override
public void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(loadBase, origVarAndContext.context),
intersection);
for (AllocAndContext allocAndContext : allocContexts) {
if (DEBUG) {
debugPrint("alloc and context " + allocAndContext);
}
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(storeBase,
EMPTY_CALLSTACK, EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
if (DEBUG)
debugPrint("match source context "
+ matchSrcContext);
VarAndContext newVarAndContext = new VarAndContext(
matchSrc, matchSrcContext);
p.prop(newVarAndContext);
}
}
}
Object getResult() {
return Boolean.valueOf(success);
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
p.prop(newVarAndContext);
}
@Override
boolean shouldHandleSrc(VarNode src) {
if (doPointsTo) {
return true;
} else {
return src.getP2Set().hasNonEmptyIntersection(badLocs);
}
}
boolean terminate() {
return !success;
}
};
processIncomingEdges(edgeHandler, worklist);
nesting
return (Boolean) edgeHandler.getResult();
}
/*
* (non-Javadoc)
*
* @see AAA.summary.Refiner#refineP2Set(soot.jimple.spark.pag.VarNode,
* soot.jimple.spark.sets.PointsToSetInternal)
*/
protected boolean refineP2Set(VarNode v, PointsToSetInternal badLocs,
HeuristicType heuristic) {
// G.v().out.println(badLocs);
this.doPointsTo = false;
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
try {
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return false;
}
if (numPasses > maxPasses) {
return false;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
boolean success = false;
try {
success = refineP2Set(
new VarAndContext(v, EMPTY_CALLSTACK), badLocs);
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
return true;
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return false;
}
}
}
} finally {
}
}
protected boolean weirdCall(Integer callSite) {
SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
return SootUtil.isThreadStartMethod(invokedMethod)
|| SootUtil.isNewInstanceMethod(invokedMethod);
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Context c, Local l) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Context c, Local l, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Local l, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(PointsToSet s, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) {
throw new UnsupportedOperationException();
}
/**
* @return returns the (SPARK) pointer assignment graph
*/
public PAG getPAG() {
return pag;
}
/**
* @return <code>true</code> is caching is enabled
*/
public boolean usesCache() {
return useCache;
}
/**
* enables caching
*/
public void enableCache() {
useCache = true;
}
/**
* disables caching
*/
public void disableCache() {
useCache = false;
}
/**
* clears the cache
*/
public void clearCache() {
reachingObjectsCache.clear();
reachingObjectsCacheNoCGRefinement.clear();
}
public boolean isRefineCallGraph() {
return refineCallGraph;
}
public void setRefineCallGraph(boolean refineCallGraph) {
this.refineCallGraph = refineCallGraph;
}
public HeuristicType getHeuristicType() {
return heuristicType;
}
public void setHeuristicType(HeuristicType heuristicType) {
this.heuristicType = heuristicType;
clearCache();
}
}
|
package com.poseidon;
import com.poseidon.controller.PoseidonApplicationTests;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import static org.junit.Assert.fail;
public class FunctionalTest extends PoseidonApplicationTests {
private WebDriver driver;
private String userAdmin = "admin";
private String passwordAdmin = "admin";
private String user = "user";
private String passwordUser = "user";
private String newDoctor = "Gregory House";
private String newPacient = "Maria";
private String newBorn = "test";
private String newBornPassword = "test";
private String homeTitle = "Home";
private String patientTitle = "Paciente";
private String consultTitle = "Consulta";
private String doctorTitle = "Médico";
private String accountTitle = "Conta";
private String aboutTitle = "Sobre";
private String loginTitle = "Login";
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
@Test
public void adminAccess() {
accessAsAdmin();
Assert.assertEquals(homeTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Cadastrar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Deletar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Pesquisar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Consultas")).click();
driver.findElement(By.linkText("Cadastrar Consulta")).click();
Assert.assertEquals(consultTitle, driver.getTitle());
driver.findElement(By.linkText("Consultas")).click();
driver.findElement(By.linkText("Deletar Consulta")).click();
Assert.assertEquals(consultTitle, driver.getTitle());
driver.findElement(By.linkText("Consultas")).click();
driver.findElement(By.linkText("Editar Consulta")).click();
Assert.assertEquals(consultTitle, driver.getTitle());
driver.findElement(By.linkText("Consultas")).click();
driver.findElement(By.linkText("Exibir calendário de Consultas")).click();
Assert.assertEquals(consultTitle, driver.getTitle());
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Cadastrar Médico")).click();
Assert.assertEquals(doctorTitle, driver.getTitle());
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Pesquisar Médico")).click();
Assert.assertEquals(doctorTitle, driver.getTitle());
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Deletar Médico")).click();
Assert.assertEquals(doctorTitle, driver.getTitle());
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Editar Médico")).click();
Assert.assertEquals(doctorTitle, driver.getTitle());
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Exibir todos Médicos")).click();
Assert.assertEquals(doctorTitle, driver.getTitle());
driver.findElement(By.linkText("Contas")).click();
driver.findElement(By.linkText("Criar Conta")).click();
Assert.assertEquals(accountTitle, driver.getTitle());
driver.findElement(By.linkText("Contas")).click();
driver.findElement(By.linkText("Editar Conta")).click();
Assert.assertEquals(accountTitle, driver.getTitle());
driver.findElement(By.linkText("Contas")).click();
driver.findElement(By.linkText("Deletar Conta")).click();
Assert.assertEquals(accountTitle, driver.getTitle());
driver.findElement(By.linkText("Contas")).click();
driver.findElement(By.linkText("Exibir todas Contas")).click();
Assert.assertEquals(accountTitle, driver.getTitle());
driver.findElement(By.linkText("Sobre")).click();
Assert.assertEquals(aboutTitle, driver.getTitle());
driver.findElement(By.linkText("Logout")).click();
Assert.assertEquals(loginTitle, driver.getTitle());
}
@Test
public void addDoctorAsAdmin() {
accessAsAdmin();
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Cadastrar Médico")).click();
driver.findElement(By.id("user.create")).sendKeys(newDoctor);
driver.findElement(By.id("cadastrarMedico.submit")).click();
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Exibir todos Médicos")).click();
List<WebElement> TRs = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newDoctor, TRs) == true) { return; }
fail("Não encontrado o médico " + newDoctor + "!");
}
@Test
public void deleteDoctorAsAdmin() {
accessAsAdmin();
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Cadastrar Médico")).click();
driver.findElement(By.id("user.create")).sendKeys(newDoctor);
driver.findElement(By.id("cadastrarMedico.submit")).click();
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Exibir todos Médicos")).click();
List<WebElement> TR = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newDoctor, TR) == true){
driver.findElement(By.linkText("Médico")).click();
driver.findElement(By.linkText("Deletar Médico")).click();
driver.findElement(By.id("id.medico")).sendKeys(TR.toString());
return;
}
fail("Não foi encontrado o médico " + newDoctor + " !");
}
@Test
public void addConsultAsAdmin() {
accessAsAdmin();
driver.findElement(By.linkText("Consultas")).click();
driver.findElement(By.linkText("Cadastrar Consulta")).click();
}
@Test
public void addPacientAsAdmin() {
String address = "Padre Chagas, 6969, Moinhos de Vento";
String surmane = "Silva";
String meansOfPayment = "250,00";
String cep = "123456789";
String cpf = "0166239969";
String birthDate = "20022000";
String email = "maria@gmail.com";
String lastConsult = "12122012";
String telephone = "32125415";
String phone = "84541212";
accessAsAdmin();
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Cadastrar Paciente")).click();
driver.findElement(By.id("nomecadastro")).sendKeys(newPacient);
driver.findElement(By.id("enderecocadastro")).sendKeys(address);
driver.findElement(By.id("sobrenomecadastro")).sendKeys(surmane);
driver.findElement(By.id("cepcadastro")).sendKeys(cep);
driver.findElement(By.id("cpfcadastro")).sendKeys(cpf);
driver.findElement(By.id("datanscimentocadastro")).sendKeys(birthDate);
driver.findElement(By.id("emailcadastro")).sendKeys(email);
driver.findElement(By.id("dataultimaconsultacadastro")).sendKeys(lastConsult);
driver.findElement(By.id("telefonecadastro")).sendKeys(telephone);
driver.findElement(By.id("formadepagamentocadastro")).sendKeys(meansOfPayment);
driver.findElement(By.id("celularcadastro")).sendKeys(phone);
driver.findElement(By.id("submitcadastrarpaciente")).click();
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Pesquisar Paciente")).click();
driver.findElement(By.id("nome")).sendKeys(newPacient);
driver.findElement(By.id("idpesquisar")).click();
List<WebElement> TR = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newPacient, TR) == true){ return; }
fail("Não foi encontrado o paciente " + newPacient + " !");
}
@Test
public void deletePacientAsAdmin() {
String idPacient = "76";
addPacientAsAdmin();
List<WebElement> TR = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newPacient, TR) == true){
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Deletar Paciente")).click();
driver.findElement(By.id("id.paciente")).sendKeys(idPacient);
driver.findElement(By.id("id.nome")).sendKeys(newPacient);
driver.findElement(By.id("submitdeletar")).click();
return;
}
fail("Não foi encontrado o paciente " + newPacient + " !");
}
@Test
public void aboutAccessAsAdmin() {
accessAsAdmin();
driver.findElement(By.linkText("Sobre")).click();
WebElement txt = driver.findElement(By.id("about"));
String str = txt.getText();
String merge = "Criamos está aplicação com o Objetivo de suprir as necessidades do mercado de clinicas de quiropaxia. Criado por Guilherme Matuella, Jader Cunha, Pedro Henrique, Rafael Ahrons e William Ahrons";
Assert.assertEquals(merge, str);
}
@Test
public void UserAccess() {
accessAsUser();
Assert.assertEquals(homeTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Cadastrar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Deletar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Pesquisar Paciente")).click();
Assert.assertEquals(patientTitle, driver.getTitle());
driver.findElement(By.linkText("Sobre")).click();
Assert.assertEquals(aboutTitle, driver.getTitle());
driver.findElement(By.linkText("Logout")).click();
Assert.assertEquals(loginTitle, driver.getTitle());
}
@Test
public void addPacientAsUser() {
String address = "Lucas de Oliveira, 6969, Rio Branco";
String surmane = "Carvalho";
String meansOfPayment = "350,00";
String cep = "98764321";
String cpf = "0166236969";
String birthDate = "26922000";
String email = "maria@gmail.com";
String lastConsult = "12122012";
String telephone = "32125415";
String phone = "84541212";
accessAsUser();
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Cadastrar Paciente")).click();
driver.findElement(By.id("nomecadastro")).sendKeys(newPacient);
driver.findElement(By.id("enderecocadastro")).sendKeys(address);
driver.findElement(By.id("sobrenomecadastro")).sendKeys(surmane);
driver.findElement(By.id("cepcadastro")).sendKeys(cep);
driver.findElement(By.id("cpfcadastro")).sendKeys(cpf);
driver.findElement(By.id("datanscimentocadastro")).sendKeys(birthDate);
driver.findElement(By.id("emailcadastro")).sendKeys(email);
driver.findElement(By.id("dataultimaconsultacadastro")).sendKeys(lastConsult);
driver.findElement(By.id("telefonecadastro")).sendKeys(telephone);
driver.findElement(By.id("formadepagamentocadastro")).sendKeys(meansOfPayment);
driver.findElement(By.id("celularcadastro")).sendKeys(phone);
driver.findElement(By.id("submitcadastrarpaciente")).click();
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Pesquisar Paciente")).click();
driver.findElement(By.id("nome")).sendKeys(newPacient);
driver.findElement(By.id("idpesquisar")).click();
List<WebElement> TR = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newPacient, TR) == true){ return; }
fail("Não foi encontrado o paciente " + newPacient + " !");
}
@Test
public void deletePacientAsUser() {
String idPacient = "76";
addPacientAsUser();
List<WebElement> TR = driver.findElements(By.tagName("tr"));
if (verifyIFaTextInTdIsEqual(newPacient, TR) == true){
driver.findElement(By.linkText("Paciente")).click();
driver.findElement(By.linkText("Deletar Paciente")).click();
driver.findElement(By.id("id.paciente")).sendKeys(idPacient);
driver.findElement(By.id("id.nome")).sendKeys(newPacient);
driver.findElement(By.id("submitdeletar")).click();
return;
}
fail("Não foi encontrado o paciente " + newPacient + " !");
}
@Test
public void aboutAccessAsUser() {
accessAsUser();
driver.findElement(By.linkText("Sobre")).click();
WebElement txt = driver.findElement(By.id("about"));
String str = txt.getText();
String merge = "Criamos está aplicação com o Objetivo de suprir as necessidades do mercado de clinicas de quiropaxia. Criado por Guilherme Matuella, Jader Cunha, Pedro Henrique, Rafael Ahrons e William Ahrons";
Assert.assertEquals(merge, str);
}
@Test
public void createAnUser() {
driver.findElement(By.id("btn-newuser")).click();
driver.findElement(By.id("user.create")).sendKeys(newBorn);
driver.findElement(By.id("pass.create")).sendKeys(newBornPassword);
driver.findElement(By.id("createUser.submit")).click();
fail("Não foi possível criar o usuário " + newBorn + " !");
}
public void accessAsAdmin(){
driver.get("http://localhost:8081/");
driver.findElement(By.id("user.login")).sendKeys(userAdmin);
driver.findElement(By.id("password.login")).sendKeys(passwordAdmin);
driver.findElement(By.id("submit.login")).click();
}
public void accessAsUser(){
driver.get("http://localhost:8081/");
driver.findElement(By.id("user.login")).sendKeys(user);
driver.findElement(By.id("password.login")).sendKeys(passwordUser);
driver.findElement(By.id("submit.login")).click();
}
private boolean verifyIFaTextInTdIsEqual(String toEqual, List<WebElement> trList) {
for (int i = 1; i < trList.size(); i++) {
List<WebElement> td = trList.get(i).findElements(By.tagName("td"));
for (int j = 0; j < td.size(); j++) {
if (td.get(j).getText().equals(toEqual)) {
return true;
}
}
}
return false;
}
@After
public void tearDown() throws Exception {
driver.quit();
}
}
|
package cn.dataprocess.cfzk;
import java.io.IOException;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.zookeeper.KeeperException;
/**
*
* @author lfh
*/
@CommonsLog
public class ZkWatcherTest implements Runnable {
private final ConfigFromZk CFZK = ConfigFromZk.getInstance();
TestBean wob = null;
public ZkWatcherTest(String hosts, int timeout, String path) throws IOException, KeeperException, InterruptedException, InstantiationException, IllegalAccessException {
wob = CFZK.getConfig(hosts, path, TestBean.class);
}
public static void main(String args[]) throws InterruptedException, IOException, KeeperException, InstantiationException, IllegalAccessException {
String host = "192.168.2.215:2181,192.168.2.216:2181,192.168.2.217:2181";
int timeout = 3000;
String path = "/testzk";
ZkWatcherTest zkw = new ZkWatcherTest(host, timeout, path);
TestBean tb = zkw.get();
Thread th = new Thread(zkw);
th.start();
while (true) {
Thread.sleep(1000);
System.out.println(" ext tb=" + tb);
}
}
public TestBean get() {
return wob;
}
@Override
public void run() {
while (true) {
System.out.println(" runner wob=" + wob);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
log.error(ex);
}
}
}
}
|
package com.jcabi.github;
import com.jcabi.aspects.Tv;
import javax.json.Json;
import javax.json.JsonObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test case for {@link RtContents}.
* @author Andres Candal (andres.candal@rollasolution.com)
* @version $Id$
* @since 0.8
* @todo #119 RtContents should be able to get the readme file
* from a real Github repository, fetch files, create, update and remove
* files.
* When done, remove this puzzle and Ignore annotation from the method.
* @checkstyle MultipleStringLiterals (300 lines)
*/
public final class RtContentsITCase {
/**
* RtContents can fetch readme file.
* @throws Exception If some problem inside
*/
@Test
@Ignore
public void canFetchReadmeFiles() throws Exception {
// to be implemented
}
/**
* RtContents can create file content.
* @throws Exception If some problem inside
*/
@Test
public void canCreateFileContent() throws Exception {
final Repos repos = github().repos();
final Repo repo = repos.create(
Json.createObjectBuilder().add(
"name", RandomStringUtils.randomAlphanumeric(Tv.TEN)
).build()
);
try {
final String path = RandomStringUtils.randomAlphabetic(Tv.TEN);
MatcherAssert.assertThat(
repos.get(repo.coordinates()).contents().create(
this.jsonObject(
path, new String(
Base64.encodeBase64("some content".getBytes())
), "theMessage"
)
).path(),
Matchers.equalTo(path)
);
} finally {
repos.remove(repo.coordinates());
}
}
/**
* RtContents can get content.
* @throws Exception If some problem inside
*/
@Test
public void getContent() throws Exception {
final Repos repos = github().repos();
final Repo repo = repos.create(
Json.createObjectBuilder().add(
"name", RandomStringUtils.randomAlphanumeric(Tv.TEN)
).build()
);
try {
final String path = RandomStringUtils.randomAlphanumeric(Tv.TEN);
final String message = String.format("testMessage");
final String cont = new String(
Base64.encodeBase64(
String.format("content%d", System.currentTimeMillis())
.getBytes()
)
);
final Contents contents = repos.get(repo.coordinates()).contents();
contents.create(this.jsonObject(path, cont, message));
final Content content = contents.get(path, "master");
MatcherAssert.assertThat(
content.path(),
Matchers.equalTo(path)
);
MatcherAssert.assertThat(
new Content.Smart(content).content(),
Matchers.equalTo(String.format("%s\n", cont))
);
} finally {
repos.remove(repo.coordinates());
}
}
/**
* Create and return JsonObject of content.
* @param path Content's path
* @param cont Content's Base64 string
* @param message Message
* @return JsonObject
*/
private JsonObject jsonObject(
final String path, final String cont, final String message
) {
return Json.createObjectBuilder()
.add("path", path)
.add("message", message)
.add("content", cont)
.build();
}
/**
* Create and return repo to test.
*
* @return Repo
* @throws Exception If some problem inside
*/
private static Github github() throws Exception {
final String key = System.getProperty("failsafe.github.key");
Assume.assumeThat(key, Matchers.notNullValue());
return new RtGithub(key);
}
}
|
package com.qiniu.qbox.testing;
import junit.framework.TestCase;
import com.qiniu.qbox.Config;
import com.qiniu.qbox.auth.AuthPolicy;
import com.qiniu.qbox.auth.CallRet;
import com.qiniu.qbox.auth.DigestAuthClient;
import com.qiniu.qbox.fileop.ImageExif;
import com.qiniu.qbox.fileop.ImageInfo;
import com.qiniu.qbox.fileop.ImageMogrify;
import com.qiniu.qbox.fileop.ImageView;
import com.qiniu.qbox.rs.GetRet;
import com.qiniu.qbox.rs.PutFileRet;
import com.qiniu.qbox.rs.RSClient;
import com.qiniu.qbox.rs.RSService;
public class FileopTest extends TestCase {
public void setUp() {
Config.ACCESS_KEY = System.getenv("QINIU_ACCESS_KEY");
Config.SECRET_KEY = System.getenv("QINIU_SECRET_KEY");
Config.UP_HOST = System.getenv("QINIU_UP_HOST") ;
Config.RS_HOST = System.getenv("QINIU_RS_HOST") ;
Config.IO_HOST = System.getenv("QINIU_IO_HOST") ;
String bucketName = System.getenv("QINIU_TEST_BUCKET") ;
assertNotNull(Config.ACCESS_KEY) ;
assertNotNull(Config.SECRET_KEY) ;
assertNotNull(Config.UP_HOST) ;
assertNotNull(Config.RS_HOST) ;
assertNotNull(Config.IO_HOST) ;
assertNotNull(bucketName) ;
}
public void testUploadWithToken() throws Exception {
String key = "upload.jpg" ;
String bucketName = System.getenv("QINIU_TEST_BUCKET") ;
String expectHash = "FnM8Lt3Mk6yCcYPaosvnAOwWZqyM" ;
String dir = System.getProperty("user.dir") ;
String absFilePath = dir + "/res/" + key ;
AuthPolicy policy = new AuthPolicy(bucketName, 3600);
String token = policy.makeAuthTokenString();
PutFileRet putRet = RSClient.putFileWithToken(token, bucketName, key, absFilePath, "", "", "", "") ;
String hash = putRet.getHash() ;
assertTrue(putRet.ok() && (expectHash.equals(hash))) ;
}
public GetRet rsGet() throws Exception {
String key = "upload.jpg" ;
String bucketName = System.getenv("QINIU_TEST_BUCKET") ;
DigestAuthClient conn = new DigestAuthClient();
RSService rs = new RSService(conn, bucketName);
GetRet getRet = rs.get(key, key);
return getRet ;
}
public void testImageInfo() throws Exception {
GetRet getRet = this.rsGet() ;
assertTrue(getRet.ok()) ;
String url = getRet.getUrl() ;
CallRet callRet = ImageInfo.call(url) ;
assertTrue("ImageInfo " + url + " failed!", callRet.ok()) ;
}
public void testImageExif() throws Exception {
GetRet getRet = this.rsGet() ;
assertTrue(getRet.ok()) ;
String url = getRet.getUrl() ;
CallRet callRet = ImageExif.call(url) ;
assertTrue("ImageExif " + url + " failed!", callRet.ok()) ;
}
public void testImageView() throws Exception {
GetRet getRet = this.rsGet() ;
assertTrue(getRet.ok()) ;
String url = getRet.getUrl() ;
ImageView imgView = new ImageView() ;
imgView.mode = 1 ;
imgView.width = 100 ;
imgView.height = 200 ;
imgView.quality = 1 ;
imgView.format = "jpg" ;
imgView.sharpen = 100 ;
CallRet imgViewRet = imgView.call(url) ;
assertTrue("ImageView " + url + " failed!", imgViewRet.ok()) ;
}
public void testImageMogrify() throws Exception {
GetRet getRet = this.rsGet() ;
assertTrue(getRet.ok()) ;
String url = getRet.getUrl() ;
ImageMogrify imgMogr = new ImageMogrify() ;
imgMogr.thumbnail = "!120x120r" ;
imgMogr.gravity = "center" ;
imgMogr.crop = "!120x120a0a0" ;
imgMogr.quality = 85 ;
imgMogr.rotate = 45 ;
imgMogr.format = "jpg" ;
imgMogr.autoOrient = true ;
CallRet imgMogrRet = imgMogr.call(url) ;
assertTrue("ImageMogr " + url + " failed!", imgMogrRet.ok()) ;
}
public void testImageViewMakeRequest() {
String testUrl = "http://iovip.qbox.me/file/xyz==" ;
ImageView imgView = new ImageView() ;
imgView.mode = 2 ;
String url = imgView.makeRequest(testUrl) ;
assertEquals(testUrl + "?imageView/2", url) ;
imgView.height = 200 ;
url = imgView.makeRequest(testUrl) ;
assertEquals(testUrl + "?imageView/2/h/200", url) ;
imgView.sharpen = 10 ;
url = imgView.makeRequest(testUrl) ;
assertEquals(testUrl + "?imageView/2/h/200/sharpen/10", url) ;
}
public void testImageMogrifyMakeRequest() {
String testUrl = "http://iovip.qbox.me/file/xyz==" ;
ImageMogrify imgMogr = new ImageMogrify() ;
imgMogr.format = "jpg" ;
String url = imgMogr.makeRequest(testUrl) ;
assertEquals(testUrl+"?imageMogr/format/jpg", url) ;
imgMogr.autoOrient = true ;
url = imgMogr.makeRequest(testUrl) ;
assertEquals(testUrl+"?imageMogr/format/jpg/auto-orient", url) ;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.