answer
stringlengths 17
10.2M
|
|---|
package de.fau.osr.gui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import de.fau.osr.bl.Tracker;
import de.fau.osr.core.db.DataSource;
import de.fau.osr.core.vcs.base.CommitFile;
import de.fau.osr.core.vcs.base.VcsController;
public class DataRetriever {
Logger logger = LoggerFactory.getLogger(DataRetriever.class);
Tracker tracker;
VcsController vcsController;
DataSource dataSource;
public DataRetriever(VcsController vcsController,Tracker tracker, DataSource dataSource){
this.vcsController = vcsController;
this.tracker = tracker;
this.dataSource = dataSource;
}
/*
* added a parameter 'requirementPattern' to easily change the pattern in runtime
* have to ask the author of this method to extend the method in the master
*/
public List<Integer> parse(String latestCommitMessage,String requirementPattern) {
final Pattern REQUIREMENT_PATTERN = Pattern.compile(requirementPattern);
Matcher m = REQUIREMENT_PATTERN.matcher(latestCommitMessage);
List<Integer> found_reqids = new ArrayList<Integer>();
while(m.find()) {
found_reqids.add(Integer.valueOf(m.group(1)));
}
return found_reqids;
}
/*
* Req-4 + Req-5 + Req-6 + Req-7
* Responsibility: Flo
*/
public ArrayList<CommitFile> getCommitFilesForRequirementID(String requirementID,String requirementPattern){
ArrayList<CommitFile> commitFilesList = new ArrayList<CommitFile>();
Iterator<String> commits = vcsController.getCommitList();
while(commits.hasNext())
{
String currentCommit = commits.next();
if(parse(vcsController.getCommitMessage(currentCommit),requirementPattern).contains(Integer.valueOf(requirementID)))
{
commitFilesList.addAll(vcsController.getCommitFiles(currentCommit));
}
}
return commitFilesList;
}
/*
* Req-13
* Responsibility: Taleh
*/
public void addRequirementCommitRelation(Integer requirementID, String commitID) {
try {
dataSource.addReqCommitRelation(requirementID, commitID);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Req-13
* Responsibility: Taleh
*/
public ArrayList<String> getRequirementCommitRelationFromDB(Integer requirementID) {
// TODO programm to an interface ==> ArrayList to Iterable
ArrayList<String> rvalue = null;
try {
rvalue = Lists.newArrayList(dataSource.getCommitRelationByReq(requirementID));
} catch (Exception e) {
e.printStackTrace();
}
return rvalue;
}
/*
* Req-8
* Responsibility: Gayathery
*/
public List<Integer> getRequirementIDsForFile(String filePath){
logger.info("Start call :: getRequirementIDsForFile()"+filePath);
List<Integer> requirementIDlist = new ArrayList<Integer>();
requirementIDlist = tracker.getAllRequirementsforFile(filePath);
return requirementIDlist;
}
/*
* Req-12
* Responsibility: Rajab
*/
public ArrayList<String> getRequirementIDs(){
ArrayList<String> requirements = new ArrayList<String>();
requirements.add("0");
requirements.add("1");
requirements.add("2");
requirements.add("3");
requirements.add("4");
requirements.add("5");
requirements.add("6");
requirements.add("7");
return requirements;
}
}
|
package dispatching;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.logging.Logger;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.Variable;
import org.metacsp.multi.allenInterval.AllenIntervalConstraint;
import org.metacsp.time.Bounds;
import org.metacsp.utility.logging.MetaCSPLogging;
import fluentSolver.Fluent;
import fluentSolver.FluentNetworkSolver;
import sensing.FluentConstraintNetworkAnimator;
public class FluentDispatcher extends Thread {
public static enum ACTIVITY_STATE {PLANNED, STARTED, FINISHING, FINISHED, SKIP_BECAUSE_UNIFICATION, FAILED};
private ConstraintNetwork cn;
private FluentNetworkSolver fns;
private long period;
private HashMap<Fluent,ACTIVITY_STATE> acts;
private HashMap<Fluent,AllenIntervalConstraint> overlapFutureConstraints;
private HashMap<String,FluentDispatchingFunction> dfs;
private Fluent future;
private transient Logger logger = MetaCSPLogging.getLogger(this.getClass());
public FluentDispatcher(FluentNetworkSolver fns, long period, Fluent future) {
this.fns = fns;
cn = fns.getConstraintNetwork();
this.period = period;
acts = new HashMap<Fluent, ACTIVITY_STATE>();
overlapFutureConstraints = new HashMap<Fluent, AllenIntervalConstraint>();
dfs = new HashMap<String, FluentDispatchingFunction>();
this.future = future;
}
@Override
public void run() {
while (! isInterrupted()) {
try { Thread.sleep(period); } // TODO put this to the end to prevent sleeping right at the beginning?
catch (InterruptedException e) {
interrupt();
}
synchronized(fns) {
for (String component : dfs.keySet()) {
// go through all activity fluents
Variable[] vars = cn.getVariables(component);
Arrays.sort(vars, new Comparator<Variable>() {
@Override
public int compare(Variable o1, Variable o2) {
if (o1 instanceof Fluent && o2 instanceof Fluent) {
long o1_est = ((Fluent) o1).getAllenInterval().getEST();
long o2_est = ((Fluent) o2).getAllenInterval().getEST();
int c = Long.compare(o1_est, o2_est);
if (c == 0) {
c = o1.compareTo(o2);
}
return c;
} else {
return o1.compareTo(o2);
}
}
});
for (Variable var : vars) {
if (var instanceof Fluent) {
Fluent act = (Fluent)var;
if (dfs.get(component).skip(act)) continue;
//New act, tag as not dispatched
if (!acts.containsKey(act)) {
boolean skip = false;
//... but test if activity is a unification - if so, ignore it!
Constraint[] outgoing = fns.getConstraintNetwork().getOutgoingEdges(act);
for (Constraint con : outgoing) {
if (con instanceof AllenIntervalConstraint) {
AllenIntervalConstraint aic = (AllenIntervalConstraint)con;
Fluent to = (Fluent)aic.getTo();
if (to.getComponent().equals(act.getComponent()) &&
to.getCompoundSymbolicVariable().getName().equals(act.getCompoundSymbolicVariable().getName()) &&
aic.getTypes()[0].equals(AllenIntervalConstraint.Type.Equals)) {
skip = true;
logger.info("IGNORED UNIFICATION " + aic);
break;
}
}
}
if (!skip) acts.put(act, ACTIVITY_STATE.PLANNED);
else acts.put(act, ACTIVITY_STATE.SKIP_BECAUSE_UNIFICATION);
}
//Not dispatched, check if need to dispatch
if (acts.get(act).equals(ACTIVITY_STATE.PLANNED)) {
//time to dispatch, do it!
if (act.getTemporalVariable().getEST() < future.getTemporalVariable().getEST()) {
acts.put(act, ACTIVITY_STATE.STARTED);
AllenIntervalConstraint overlapsFuture = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Overlaps);
overlapsFuture.setFrom(act);
overlapsFuture.setTo(future);
boolean ret = fns.addConstraint(overlapsFuture);
if(!ret){
logger.info("IGNORED: " + act);
// System.out.println(" CONSTRAINTS IN: " + Arrays.toString(fns.getConstraintNetwork().getIncidentEdges(act)));
// System.out.println(" CONSTRAINTS OUT: " + Arrays.toString(fns.getConstraintNetwork().getOutgoingEdges(act)));
// CopyOfTestProblemParsing.extractPlan(fns);
}
else {
overlapFutureConstraints.put(act, overlapsFuture);
this.dfs.get(component).dispatch(act);
}
}
}
//If finished, tag as finished
else if (acts.get(act).equals(ACTIVITY_STATE.FINISHING)) {
acts.put(act, ACTIVITY_STATE.FINISHED);
fns.removeConstraint(overlapFutureConstraints.get(act));
AllenIntervalConstraint deadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(future.getTemporalVariable().getEST(),future.getTemporalVariable().getEST()));
deadline.setFrom(act);
deadline.setTo(act);
if (!fns.addConstraint(deadline)) {
AllenIntervalConstraint defaultDeadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(act.getTemporalVariable().getEET(),act.getTemporalVariable().getEET()));
defaultDeadline.setFrom(act);
defaultDeadline.setTo(act);
fns.addConstraint(defaultDeadline);
//System.out.println("++++++++++++++++++++ SHIT: " + act + " DAEDLINE AT " + future.getTemporalVariable().getEST());
}
}
}
}
}
}
synchronized(this) {
if (this.isFinished()) {
logger.info("dispatching finished: notifying all waiting threads");
this.notifyAll();
}
if (this.failed()) {
logger.info("dispatching failed: notifying all waiting threads");
this.notifyAll();
}
}
}
}
/**
* Check if all activities have been finished.
* @return true if all activities have been finished, i.e., no started or planned activites exist, otherwise false
*/
public boolean isFinished() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.PLANNED) || state.equals(ACTIVITY_STATE.STARTED) || state.equals(ACTIVITY_STATE.FINISHING)) {
return false;
}
}
logger.fine("Acts.size: " + acts.size());
return true;
}
/**
* Check if any activity has failed.
* @return true if any activity has failed, otherwise false
*/
public boolean failed() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.FAILED)) {
return true;
}
}
return false;
}
public void addDispatchingFunction(String component, FluentDispatchingFunction df) {
df.registerDispatcher(this);
this.dfs.put(component, df);
}
public void finish(Fluent act) { acts.put(act, ACTIVITY_STATE.FINISHING); }
public void fail(Fluent act) {acts.put(act, ACTIVITY_STATE.FAILED); }
public ConstraintNetwork getConstraintNetwork() {
return fns.getConstraintNetwork();
}
}
|
package gr.phaistosnetworks.tank;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TankClient implementation for java.
*/
public class TankClient {
/**
* Constructor for the TankClient object.
* Upon initialization TankClient will attempt to connect to server.
* Upon success, it will check for ping response from server.
* If it's unsuccesful an error will be logged, and it will retry indefinately.
*/
public TankClient(String tankHost, int tankPort) {
this.tankHost = tankHost;
this.tankPort = tankPort;
clientReqId = 0;
log = Logger.getLogger("tankClient");
try {
clientId = ByteManipulator.getStr8("JC01");
} catch (TankException | UnsupportedEncodingException te) {
log.severe("Cannot generate default clientID str8. " + te.getMessage());
System.exit(1);
}
try {
while (true) {
try {
client = new Socket(tankHost, tankPort);
} catch (IOException ioe) {
log.severe(ioe.getMessage());
log.log(Level.FINEST, "ERROR opening socket", ioe);
Thread.sleep(TankClient.RETRY_INTERVAL);
continue;
}
//client.setSoTimeout(1000);
client.setTcpNoDelay(true);
client.setKeepAlive(true);
client.setReuseAddress(true);
log.config("Connected to " + client.getRemoteSocketAddress());
log.config(" + recv buffer size: " + client.getReceiveBufferSize());
log.config(" + send buffer size: " + client.getSendBufferSize());
log.config(" + timeout: " + client.getSoTimeout());
log.config(" + soLinger: " + client.getSoLinger());
log.config(" + nodelay: " + client.getTcpNoDelay());
log.config(" + keepalive: " + client.getKeepAlive());
log.config(" + oobinline: " + client.getOOBInline());
log.config(" + reuseAddress: " + client.getReuseAddress());
bis = new BufferedInputStream(client.getInputStream());
socketOutputStream = client.getOutputStream();
break;
}
while (true) {
if (!getPing(bis)) {
log.severe("ERROR: No Ping Received");
} else {
log.fine("PING OK");
break;
}
}
} catch (IOException | InterruptedException ioe) {
log.log(Level.SEVERE, "ERROR opening Streams", ioe);
System.exit(1);
}
}
/**
* get a valid ping response from server.
*
* @param bis BufferedInputStream to read from
* @return true if valid ping response is received.
*/
private boolean getPing(BufferedInputStream bis) {
try {
int av = bis.available();
if (av == 0) {
return false;
}
byte readByte = (byte)bis.read();
if (readByte != PING_REQ) {
return false;
}
// payload size:u32 is 0 for ping
bis.skip(U32);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR getting ping", ioe);
return false;
}
return true;
}
/**
* tries to get data from the network socket.
* It will loop and retry if there's no data.
* If the data is incomplete, i.e. available less than payload,
* then it will loop and append until payload size is reached.
*/
private List<TankResponse> poll(short requestType, TankRequest request) throws TankException {
ByteManipulator input = new ByteManipulator(null);
int remainder = 0;
int toRead = 0;
while (true) {
int av = 0;
try {
av = bis.available();
} catch (IOException ioe) {
log.log(Level.SEVERE, "Unable to read from socket", ioe);
}
log.finest("bytes available: " + av);
if (av == 0) {
try {
Thread.sleep(TankClient.RETRY_INTERVAL);
} catch (InterruptedException ie) {
log.warning("Cmon, lemme get some sleep ! " + ie.getCause());
} finally {
continue;
}
}
if (remainder >= 0) {
toRead = av;
} else {
toRead = remainder;
}
byte [] ba = new byte[toRead];
try {
bis.read(ba, 0, toRead);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Unable to read from socket", ioe);
}
if (remainder > 0) {
input.append(ba);
} else {
input = new ByteManipulator(ba);
}
byte resp = (byte)input.deSerialize(U8);
long payloadSize = input.deSerialize(U32);
if (resp != requestType) {
log.severe("Bad Response type. Expected " + requestType + ", got " + resp);
throw new TankException("Bad Response type. Expected " + requestType + ", got " + resp);
}
if (payloadSize > input.getRemainingLength()) {
log.finer("Received packet incomplete ");
remainder = (int)(payloadSize - input.getRemainingLength());
input.resetOffset();
continue;
} else {
remainder = 0;
}
log.fine("resp: " + resp);
log.fine("payload size: " + payloadSize);
if (requestType == CONSUME_REQ) {
return processConsumeResponse(input, request);
} else if (requestType == PUBLISH_REQ) {
return getPubResponse(input, request);
}
for (Handler h : log.getHandlers()) {
h.flush();
}
break;
}
return new ArrayList<TankResponse>();
}
/**
* Send consume request to broker.
*/
public List<TankResponse> consume(TankRequest request) throws TankException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.fine("Issuing consume with " + request.getTopicsCount() + " topics");
try {
baos.write((byte)CONSUME_REQ);
baos.write(ByteManipulator.serialize(0, U32));
//clientVersion not implemented
baos.write(ByteManipulator.serialize(0L, U16));
baos.write(ByteManipulator.serialize(clientReqId++, U32));
baos.write(clientId);
baos.write(ByteManipulator.serialize(maxWait, U64));
baos.write(ByteManipulator.serialize(minBytes, U32));
baos.write(ByteManipulator.serialize(request.getTopicsCount(), U8));
baos.write(request.serialize());
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR creating consume request", ioe);
System.exit(1);
}
byte [] req = baos.toByteArray();
byte [] rsize = (ByteManipulator.serialize(req.length - 5, U32));
log.fine("consume request size is " + req.length);
for (int i = 0; i < U32; i++) {
req[i + 1] = rsize[i];
}
try {
socketOutputStream.write(req);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR writing publish request to socket", ioe);
System.exit(1);
}
return poll(CONSUME_REQ, request);
}
/**
* Processes a response from tank server after we issue a publish request.
*
* @param input a ByteManipulator object containing the data received from server.
*/
private List<TankResponse> getConsumeResponse(ByteManipulator input, TankRequest request) {
List<TankResponse> response = processConsumeResponse(input, request);
return response;
}
/**
* Processes the headers of the input received from tank server.
*
* @param input the ByteManipulator object that contains the bytes received from server.
* @param topics the request topics. Used to crosscheck between request and response.
*/
private List<TankResponse> processConsumeResponse(ByteManipulator input, TankRequest request) {
ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
ArrayList<TankResponse> response = new ArrayList<TankResponse>();
// Headers
long headerSize = input.deSerialize(U32);
long requestId = input.deSerialize(U32);
long totalTopics = input.deSerialize(U8);
log.fine("header size: " + headerSize);
log.fine("reqid: " + requestId);
log.fine(String.format("topics count: %d", totalTopics));
for (int t = 0; t < totalTopics; t++) {
String topic = input.getStr8();
long totalPartitions = input.deSerialize(U8);
log.fine("topic name: " + topic);
log.fine("Total Partitions: " + totalPartitions);
int partition = (int)input.deSerialize(U16);
if (partition == U16_MAX) {
log.warning("Topic " + topic + " Not Found ");
continue;
} else {
// Partitions
for (int p = 0; p < totalPartitions; p++) {
if (p != 0) {
partition = (int)input.deSerialize(U16);
}
byte errorOrFlags = (byte)input.deSerialize(U8);
log.fine("Partition : " + partition);
log.fine(String.format("ErrorOrFlags : %x", errorOrFlags));
if ((errorOrFlags & U8_MAX) == U8_MAX) {
log.warning("Unknown Partition");
continue;
}
long baseAbsSeqNum = 0L;
if ((errorOrFlags & U8_MAX) != 0xFE) {
baseAbsSeqNum = input.deSerialize(U64);
log.fine("Base Abs Seq Num : " + baseAbsSeqNum);
}
long highWaterMark = input.deSerialize(U64);
long chunkLength = input.deSerialize(U32);
log.fine("High Watermark : " + highWaterMark);
log.fine("Chunk Length : " + chunkLength);
if (errorOrFlags == 0x1) {
long firstAvailSeqNum = input.deSerialize(U64);
long requestedSeqNum = request.getSequenceNum(topic, p);
log.warning(
"Sequence "
+ requestedSeqNum
+ " out of bounds. Range: "
+ firstAvailSeqNum + " - " + highWaterMark);
TankResponse blankResponse = new TankResponse(topic, partition, errorOrFlags);
blankResponse.setHighWaterMark(highWaterMark);
blankResponse.setFirstAvailSeqNum(firstAvailSeqNum);
blankResponse.setRequestSeqNum(requestedSeqNum);
/*
if (requestedSeqNum < firstAvailSeqNum) {
blankResponse.setRequestSeqNum(firstAvailSeqNum);
} else {
blankResponse.setRequestSeqNum(highWaterMark);
}
*/
response.add(blankResponse);
continue;
}
chunkList.add(
new Chunk(topic, partition, errorOrFlags, baseAbsSeqNum, highWaterMark, chunkLength));
}
}
}
return processChunks(requestId, input, request, chunkList, response);
}
/**
* Processes the chunks of the input received from tank server.
*
* @param input the ByteManipulator object that contains the bytes received from server.
* @param topics the request topics. Used to crosscheck between request and response.
* @param chunkList the chunkList as read from headers.
*/
private List<TankResponse> processChunks(
long requestId,
ByteManipulator input,
TankRequest request,
ArrayList<Chunk> chunkList,
ArrayList<TankResponse> response) {
for (Chunk c : chunkList) {
long bundleLength = 0;
long requestedSeqNum = request.getSequenceNum(c.topic, c.partition);
log.fine("Chunk for " + c.topic + ":" + c.partition
+ " @" + requestedSeqNum
+ " with baseSeqNum: " + c.baseAbsSeqNum);
TankResponse topicPartition = new TankResponse(c.topic, c.partition, c.errorOrFlags);
topicPartition.setRequestSeqNum(requestedSeqNum);
if (c.length == 0) {
response.add(topicPartition);
continue;
}
long firstMessageNum = c.baseAbsSeqNum;
long remainingChunkBytes = c.length;
input.flushOffset();
while (remainingChunkBytes > 0) {
log.fine("Remaining Length: " + input.getRemainingLength());
try {
bundleLength = input.getVarInt();
} catch (ArrayIndexOutOfBoundsException aioobe) {
log.info("Bundle length varint incomplete");
break;
}
log.fine("Bundle length : " + bundleLength);
if (bundleLength > topicPartition.getFetchSize()) {
//Add extra 5 bytes which is max 32bit varint can use up.
topicPartition.setFetchSize(bundleLength + 5);
}
if (bundleLength > input.getRemainingLength()) {
log.fine("Bundle Incomplete (remaining bytes: " + input.getRemainingLength() + ")");
break;
}
if (bundleLength > remainingChunkBytes) {
log.fine("Bundle Incomplete (remaining chunk bytes: " + remainingChunkBytes + ")");
} else {
remainingChunkBytes -= bundleLength;
}
remainingChunkBytes -= input.getOffset();
input.flushOffset();
byte flags = (byte)input.deSerialize(U8);
// See TANK tank_encoding.md for flags
long messageCount = (flags >> 2) & 0xF;
long compressed = flags & 0x3;
long sparse = (flags >> 6) & 0xF;
log.finer("Bundle compressed : " + compressed);
log.finer("Bundle SPARSE : " + sparse);
if (messageCount == 0) {
messageCount = input.getVarInt();
}
log.finer("Messages in set : " + messageCount);
long lastMessageNum = 0L;
if (sparse == 1) {
firstMessageNum = input.deSerialize(U64);
log.finer("First message: " + firstMessageNum);
if (messageCount > 1) {
lastMessageNum = input.getVarInt() + 1 + firstMessageNum;
log.finer("Last message: " + lastMessageNum);
}
}
ByteManipulator chunkMsgs;
if (compressed == 1) {
log.finer("Snappy uncompression");
try {
chunkMsgs = new ByteManipulator(
input.snappyUncompress(
bundleLength - input.getOffset()));
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR uncompressing", ioe);
return response;
}
} else {
chunkMsgs = input;
}
long timestamp = 0L;
long prevSeqNum = firstMessageNum;
long curSeqNum = firstMessageNum;
for (int i = 0; i < messageCount; i++) {
log.finer("
flags = (byte)chunkMsgs.deSerialize(U8);
log.finer(String.format("flags : %d", flags));
if (sparse == 1) {
if (i == 0) {
//do nothing. curSeqNum is already set.
} else if ((flags & SEQ_NUM_PREV_PLUS_ONE) != 0) {
log.fine("SEQ_NUM_PREV_PLUS_ONE");
curSeqNum = prevSeqNum + 1;
} else if (i != (messageCount - 1)) {
curSeqNum = (chunkMsgs.getVarInt() + 1 + prevSeqNum);
} else {
curSeqNum = lastMessageNum;
}
log.finer("sparse msg: " + i + " seq num: " + curSeqNum);
prevSeqNum = curSeqNum;
}
log.finer("cur seq num: " + curSeqNum);
if ((flags & USE_LAST_SPECIFIED_TS) == 0) {
timestamp = chunkMsgs.deSerialize(U64);
log.finer("New Timestamp : " + timestamp);
} else {
log.finer("Using last Timestamp : " + timestamp);
}
String key = new String();
if ((flags & HAVE_KEY) != 0) {
key = chunkMsgs.getStr8();
log.finer("We have a key and it is : " + key);
}
long contentLength = chunkMsgs.getVarInt();
log.finer("Content Length: " + contentLength);
byte [] message = chunkMsgs.getNextBytes((int)contentLength);
log.finest(new String(message));
// Don't save the message if it has a sequence number lower than we requested.
if (curSeqNum >= requestedSeqNum) {
topicPartition.addMessage(new TankMessage(
curSeqNum, timestamp, key.getBytes(), message));
}
curSeqNum++;
firstMessageNum++;
}
}
response.add(topicPartition);
}
return response;
}
/**
* Send publish request to broker.
*/
public List<TankResponse> publish(TankRequest request) throws TankException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.info("Issuing publish with " + request.getTopicsCount() + " topics");
try {
baos.write((byte)PUBLISH_REQ);
baos.write(ByteManipulator.serialize(0, U32));
//clientVersion not implemented
baos.write(ByteManipulator.serialize(0L, U16));
baos.write(ByteManipulator.serialize(clientReqId++, U32));
baos.write(clientId);
//requestAcks not implemented
baos.write(ByteManipulator.serialize(0L, U8));
//ackTimeout not implemented
baos.write(ByteManipulator.serialize(0L, U32));
baos.write(ByteManipulator.serialize(request.getTopicsCount(), U8));
baos.write(request.serialize());
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR creating publish request", ioe);
System.exit(1);
}
byte [] req = baos.toByteArray();
byte [] rsize = (ByteManipulator.serialize(req.length - 5, U32));
log.fine("Publish request size is " + req.length);
for (int i = 0; i < U32; i++) {
req[i + 1] = rsize[i];
}
try {
socketOutputStream.write(req);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR writing publish request to socket", ioe);
System.exit(1);
}
return poll(PUBLISH_REQ, request);
}
/**
* Processes a response from tank server after we issue a publish request.
*
* @param input a ByteManipulator object containing the data received from server.
*/
private List<TankResponse> getPubResponse(ByteManipulator input, TankRequest tr) {
ArrayList<TankResponse> response = new ArrayList<TankResponse>();
log.fine("Getting response for Request id: " + input.deSerialize(U32));
long error = 0L;
String noTopic = new String();
for (SimpleEntry<String, Long> tuple : tr.getTopicPartitions()) {
log.fine("Processing response for " + tuple.getKey() + ":" + tuple.getValue());
if (tuple.getKey().equals(noTopic)) {
//No such topic. No errors encoded for further partitions
} else {
error = input.deSerialize(U8);
}
if (error == ERROR_NO_SUCH_TOPIC) {
noTopic = tuple.getKey();
}
response.add(
new TankResponse(
tuple.getKey(),
tuple.getValue(),
error));
}
return response;
}
/**
* see tank_protocol.md for chunk details.
*/
private class Chunk {
/**
* constructor.
*
* @param eof errorOrFlags
* @param basn base absolute sequence number.
* @param hwm high water mark
*/
public Chunk(String topic, int partition, byte eof, long basn, long hwm, long length) {
this.topic = topic;
this.partition = partition;
this.errorOrFlags = eof;
this.baseAbsSeqNum = basn;
this.highWaterMark = hwm;
this.length = length;
}
private String topic;
private long partition;
private byte errorOrFlags;
private long highWaterMark;
private long length;
private long baseAbsSeqNum;
}
/**
* See TANK tank_protocol.md for maxWait semantics.
*
* @return the maxWait to wait for (ms) (default 5s)
*/
public long getFetchRespMaxWaitMs() {
return maxWait;
}
/**
* See TANK tank_protocol.md for maxWait semantics.
*
* @param maxWaitMs the maxWait to wait for (ms)
*/
public void setFetchRespMaxWait(long maxWaitMs) {
this.maxWait = maxWaitMs;
}
/**
* See TANK tank_protocol.md for minBytes semantics.
*
* @return the minBytes to wait for (default 20k)
*/
public long getFetchRespMinBytes() {
return minBytes;
}
/**
* See TANK tank_protocol.md for minBytes semantics.
*
* @param byteCount the minBytes to wait for
*/
public void setFetchRespMinBytes(long byteCount) {
this.minBytes = byteCount;
}
/**
* Set the client identification string (optional) for requests.
* See tank_protocol.md for details
*
* @param clientId the client id (max 255 chars)
*/
public void setClientId(String clientId) {
try {
this.clientId = ByteManipulator.getStr8(clientId);
} catch (TankException | UnsupportedEncodingException te) {
log.warning("Unable to set requested clientId. Ignoring." + te.getMessage());
}
}
private String tankHost;
private int tankPort;
private int reqSeqNum;
private Socket client;
private BufferedInputStream bis;
private OutputStream socketOutputStream;
private Logger log;
private int clientReqId;
private long maxWait = 5000L;
private long minBytes = 0L;
private byte [] clientId;
public static final long U64_MAX = -1L;
public static final int U16_MAX = 65535;
public static final int U8_MAX = 255;
public static final int U4_MAX = 15;
public static final byte HAVE_KEY = 1;
public static final byte USE_LAST_SPECIFIED_TS = 2;
public static final byte SEQ_NUM_PREV_PLUS_ONE = 4;
private static final long RETRY_INTERVAL = 50;
public static final short PUBLISH_REQ = 1;
public static final short CONSUME_REQ = 2;
private static final short PING_REQ = 3;
public static final byte U8 = 1;
public static final byte U16 = 2;
public static final byte U32 = 4;
public static final byte U64 = 8;
public static final long ERROR_NO_SUCH_TOPIC = 255;
public static final long ERROR_NO_SUCH_PARTITION = 1;
public static final long ERROR_INVALID_SEQNUM = 2;
public static final long ERROR_OUT_OF_BOUNDS = 1;
public static final long COMPRESS_MIN_SIZE = 1024;
}
|
package dk.itu.kelvin.util;
public class HashTable<K, V> extends DynamicHashArray implements Map<K, V> {
/**
* UID for identifying serialized objects.
*/
private static final long serialVersionUID = 55;
/**
* Internal key storage.
*/
private K[] keys;
/**
* Internal value storage.
*/
private V[] values;
/**
* The hash collision resolver to use.
*/
private transient HashResolver resolver = new QuadraticProbe();
/**
* Initialize a tbale with the specified initial capacity.
*
* @param capacity The initial capacity of the table.
*/
@SuppressWarnings("unchecked")
public HashTable(final int capacity) {
super(
capacity,
0.5f, // Upper load factor
2f, // Upper resize factor
0.125f, // Lower load factor
0.5f // Lower resize factor
);
this.keys = (K[]) new Object[this.capacity()];
this.values = (V[]) new Object[this.capacity()];
}
/**
* Initialize a hash table with the default initial capacity.
*/
public HashTable() {
this(16);
}
/**
* Resize the internal storage of the table to the specified capacity.
*
* @param capacity The new capacity of the internal storage of the table.
*/
protected final void resize(final int capacity) {
HashTable<K, V> temp = new HashTable<>(capacity);
// For each of the entries in the current store, put them in the temporary
// store, effectively recomputing their hashes.
for (int i = 0; i < this.capacity(); i++) {
if (this.keys[i] != null) {
temp.put(this.keys[i], this.values[i]);
}
}
// Point the entries of the current store to the entries of the temporary,
// rehashed store.
this.keys = temp.keys;
this.values = temp.values;
}
/**
* Return the index of the specified key.
*
* @param key The key to look up the index of.
* @return The index of the specified key.
*/
private int indexOf(final Object key) {
return this.resolver.resolve(this.hash(key), key, this.keys);
}
/**
* Get a value by key from the table.
*
* @param key The key of the value to get.
* @return The value if found.
*/
public final V get(final Object key) {
return this.values[this.indexOf(key)];
}
/**
* Check if the specified key exists within the table.
*
* @param key The key to check for.
* @return A boolean indicating whether or not the table contains the
* specified key.
*/
public final boolean containsKey(final Object key) {
return this.get(key) != null;
}
/**
* Check if the specified value exists within the table.
*
* @param value The value to check for.
* @return A boolean indicating whether or not the table contains the
* specified value.
*/
public final boolean containsValue(final Object value) {
for (V found: this.values) {
if (value.equals(found)) {
return true;
}
}
return false;
}
/**
* Put a key/value pair in the table.
*
* @param key The key to put in the table.
* @param value The value to put in the table.
* @return The previous value associated with the key if found.
*/
public final V put(final K key, final V value) {
if (value == null) {
this.remove(key);
return null;
}
int i = this.indexOf(key);
if (this.keys[i] != null && this.keys[i].equals(key)) {
V old = this.values[i];
this.values[i] = value;
return old;
}
else {
this.keys[i] = key;
this.values[i] = value;
this.grow();
return null;
}
}
/**
* Remove a key/value pair from the table.
*
* @param key The key of the value to remove.
* @return The removed value if fonund.
*/
public final V remove(final Object key) {
if (!this.containsKey(key)) {
return null;
}
int i = this.indexOf(key);
V old = this.values[i];
this.keys[i] = null;
this.values[i] = null;
this.shrink();
return old;
}
/**
* Get a collection of the values contained within the table.
*
* @return A collection of the values contained within the table.
*/
public final Collection<V> values() {
List<V> values = new ArrayList<>(this.size());
for (V value: this.values) {
values.add(value);
}
return values;
}
}
|
package com.opengamma.financial.analytics.model.future;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.time.calendar.Clock;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.position.Trade;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.Security;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.conversion.FixedIncomeConverterDataProvider;
import com.opengamma.financial.analytics.conversion.InterestRateFutureSecurityConverter;
import com.opengamma.financial.analytics.conversion.InterestRateFutureTradeConverter;
import com.opengamma.financial.analytics.ircurve.InterpolatedYieldCurveSpecificationWithSecurities;
import com.opengamma.financial.analytics.ircurve.YieldCurveFunction;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.financial.security.future.InterestRateFutureSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
public abstract class InterestRateFutureCurveSpecificFunction extends AbstractFunction.NonCompiledInvoker {
private final String _valueRequirement;
private InterestRateFutureTradeConverter _converter;
private FixedIncomeConverterDataProvider _dataConverter;
public InterestRateFutureCurveSpecificFunction(final String valueRequirement) {
ArgumentChecker.notNull(valueRequirement, "value requirement");
_valueRequirement = valueRequirement;
}
@Override
public void init(final FunctionCompilationContext context) {
final HolidaySource holidaySource = OpenGammaCompilationContext.getHolidaySource(context);
final RegionSource regionSource = OpenGammaCompilationContext.getRegionSource(context);
final ConventionBundleSource conventionSource = OpenGammaCompilationContext.getConventionBundleSource(context);
_converter = new InterestRateFutureTradeConverter(new InterestRateFutureSecurityConverter(holidaySource, conventionSource, regionSource));
_dataConverter = new FixedIncomeConverterDataProvider(conventionSource);
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final Clock snapshotClock = executionContext.getValuationClock();
final ZonedDateTime now = snapshotClock.zonedDateTime();
final HistoricalTimeSeriesSource dataSource = OpenGammaExecutionContext.getHistoricalTimeSeriesSource(executionContext);
final Trade trade = target.getTrade();
final ValueRequirement desiredValue = desiredValues.iterator().next();
final String forwardCurveName = desiredValue.getConstraint(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
final String fundingCurveName = desiredValue.getConstraint(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
final String curveCalculationMethod = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_METHOD);
final YieldCurveBundle data = getYieldCurves(target, inputs, forwardCurveName, fundingCurveName, curveCalculationMethod);
final ValueRequirement curveSpecRequirement = getCurveSpecRequirement(target, curveName);
final Object curveSpecObject = inputs.getValue(curveSpecRequirement);
if (curveSpecObject == null) {
throw new OpenGammaRuntimeException("Could not get " + curveSpecRequirement);
}
final InterpolatedYieldCurveSpecificationWithSecurities curveSpec = (InterpolatedYieldCurveSpecificationWithSecurities) curveSpecObject;
final InstrumentDefinition<InstrumentDerivative> irFutureDefinition = _converter.convert(trade);
final InstrumentDerivative irFuture = _dataConverter.convert(trade.getSecurity(), irFutureDefinition, now, new String[] {fundingCurveName, forwardCurveName}, dataSource);
final ValueSpecification spec = new ValueSpecification(_valueRequirement, target.toSpecification(),
createValueProperties(target, curveName, forwardCurveName, fundingCurveName, curveCalculationMethod));
return getResults(irFuture, curveName, curveSpec, data, spec);
}
protected abstract Set<ComputedValue> getResults(final InstrumentDerivative irFuture, final String curveName, final InterpolatedYieldCurveSpecificationWithSecurities curveSpec,
final YieldCurveBundle curves, final ValueSpecification resultSpec);
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.TRADE;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.TRADE) {
return false;
}
return target.getTrade().getSecurity() instanceof InterestRateFutureSecurity;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties properties = createValueProperties(target);
return Collections.singleton(new ValueSpecification(_valueRequirement, target.toSpecification(), properties));
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
if (curveName == null) {
throw new OpenGammaRuntimeException("Must specify a curve against which to calculate the desired value " + _valueRequirement);
}
final Set<String> forwardCurves = desiredValue.getConstraints().getValues(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
if (forwardCurves == null || forwardCurves.size() != 1) {
return null;
}
final Set<String> fundingCurves = desiredValue.getConstraints().getValues(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
if (fundingCurves == null || fundingCurves.size() != 1) {
return null;
}
final Set<String> calculationMethodNames = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE_CALCULATION_METHOD);
if (calculationMethodNames == null || calculationMethodNames.size() != 1) {
return null;
}
final String forwardCurveName = forwardCurves.iterator().next();
final String fundingCurveName = fundingCurves.iterator().next();
if (!curveName.equals(forwardCurveName) && !curveName.equals(fundingCurveName)) {
throw new OpenGammaRuntimeException("Asked for sensitivities to a curve (" + curveName + ") to which this interest rate future is not sensitive " +
"(allowed " + forwardCurveName + " and " + fundingCurveName + ")");
}
final String calculationMethod = calculationMethodNames.iterator().next();
final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>();
if (forwardCurveName.equals(fundingCurveName)) {
requirements.add(getCurveRequirement(target, curveName, null, null, calculationMethod));
requirements.add(getCurveSpecRequirement(target, curveName));
return requirements;
}
requirements.add(getCurveRequirement(target, forwardCurveName, forwardCurveName, fundingCurveName, calculationMethod));
requirements.add(getCurveRequirement(target, fundingCurveName, forwardCurveName, fundingCurveName, calculationMethod));
requirements.add(getCurveSpecRequirement(target, curveName));
return requirements;
}
private static ValueRequirement getCurveRequirement(final ComputationTarget target, final String curveName, final String advisoryForward, final String advisoryFunding,
final String curveCalculationMethod) {
return YieldCurveFunction.getCurveRequirement(FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity()), curveName, advisoryForward, advisoryFunding,
curveCalculationMethod);
}
private static ValueRequirement getCurveSpecRequirement(final ComputationTarget target, final String curveName) {
final Currency currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity());
final ValueProperties.Builder properties = ValueProperties.builder().with(ValuePropertyNames.CURVE, curveName);
return new ValueRequirement(ValueRequirementNames.YIELD_CURVE_SPEC, ComputationTargetType.PRIMITIVE, currency.getUniqueId(), properties.get());
}
private static YieldCurveBundle getYieldCurves(final ComputationTarget target, final FunctionInputs inputs, final String forwardCurveName, final String fundingCurveName,
final String curveCalculationMethod) {
final ValueRequirement forwardCurveRequirement = getCurveRequirement(target, forwardCurveName, null, null, curveCalculationMethod);
final Object forwardCurveObject = inputs.getValue(forwardCurveRequirement);
if (forwardCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get " + forwardCurveRequirement);
}
Object fundingCurveObject = null;
if (!forwardCurveName.equals(fundingCurveName)) {
final ValueRequirement fundingCurveRequirement = getCurveRequirement(target, fundingCurveName, null, null, curveCalculationMethod);
fundingCurveObject = inputs.getValue(fundingCurveRequirement);
if (fundingCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get " + fundingCurveRequirement);
}
}
final YieldAndDiscountCurve forwardCurve = (YieldAndDiscountCurve) forwardCurveObject;
final YieldAndDiscountCurve fundingCurve = fundingCurveObject == null ? forwardCurve : (YieldAndDiscountCurve) fundingCurveObject;
return new YieldCurveBundle(new String[] {fundingCurveName, forwardCurveName}, new YieldAndDiscountCurve[] {fundingCurve, forwardCurve});
}
private ValueProperties createValueProperties(final ComputationTarget target) {
final Security security = target.getTrade().getSecurity();
final String currency = FinancialSecurityUtils.getCurrency(security).getCode();
final ValueProperties.Builder properties = createValueProperties()
.with(ValuePropertyNames.CURRENCY, currency)
.with(ValuePropertyNames.CURVE_CURRENCY, currency)
.withAny(ValuePropertyNames.CURVE_CALCULATION_METHOD)
.withAny(ValuePropertyNames.CURVE)
.withAny(YieldCurveFunction.PROPERTY_FORWARD_CURVE)
.withAny(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
return properties.get();
}
private ValueProperties createValueProperties(final ComputationTarget target, final String curveName, final String forwardCurveName,
final String fundingCurveName, final String curveCalculationMethod) {
final Security security = target.getTrade().getSecurity();
final String currency = FinancialSecurityUtils.getCurrency(security).getCode();
final ValueProperties.Builder properties = createValueProperties()
.with(ValuePropertyNames.CURRENCY, currency)
.with(ValuePropertyNames.CURVE_CURRENCY, currency)
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, curveCalculationMethod)
.with(ValuePropertyNames.CURVE, curveName)
.with(YieldCurveFunction.PROPERTY_FORWARD_CURVE, forwardCurveName)
.with(YieldCurveFunction.PROPERTY_FUNDING_CURVE, fundingCurveName);
return properties.get();
}
}
|
package edu.cmu.sv.ws.ssnoc.data;
/**
* This class contains all the SQL related code that is used by the project.
* Note that queries are grouped by their purpose and table associations for
* easy maintenance.
*
*/
public class SQL {
public static final String SSN_USERS = "SSN_USERS";
public static final String SSN_STATUS_CRUMBS = "SSN_STATUS_CRUMBS";
public static final String SSN_LOCATION_CRUMBS = "SSN_LOCATION_CRUMBS";
public static final String SSN_MESSAGES = "SSN_MESSAGES";
public static final String SSN_MEMORY_CRUMBS = "SSN_MEMORY_CRUMBS";
/**
* Query to check if a given table exists in the H2 database.
*/
public static final String CHECK_TABLE_EXISTS_IN_DB = "SELECT count(1) as rowCount "
+ " FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = SCHEMA() "
+ " AND UPPER(TABLE_NAME) = UPPER(?)";
// All queries related to USERS
/**
* Query to create the USERS table.
*/
public static final String CREATE_USERS = "create table IF NOT EXISTS "
+ SSN_USERS + " ( user_id IDENTITY PRIMARY KEY,"
+ " user_name VARCHAR(100)," + " password VARCHAR(512),"
+ " salt VARCHAR(512),"
+ " last_status_code_id BIGINT, last_location_id BIGINT, "
+ " created_at TIMESTAMP," + " modified_at TIMESTAMP )";
/**
* Query to drop the USERS table.
*/
public static final String DROP_USERS = "drop table if exists "
+ SSN_USERS;
/**
* Query to load all users in the system.
*/
public static final String FIND_ALL_USERS = "select u.user_id, u.user_name, u.password,"
+ " u.salt, u.last_status_code_id, ssc.status, ssc.created_at, u.last_location_id, slc.location, u.created_at, u.modified_at "
+ " from "
+ SSN_USERS
+ " u "
+ " left outer join "
+ SSN_STATUS_CRUMBS
+ " ssc on u.last_status_code_id = ssc.status_crumb_id "
+ " left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on u.last_location_id = slc.location_crumb_id "
+ " order by user_name";
/**
* Query to find a user details depending on his name. Note that this query
* does a case insensitive search with the user name.
*/
public static final String FIND_USER_BY_NAME = "select user_id, user_name, password,"
+ " salt, last_status_code_id, last_location_id, created_at, modified_at "
+ " from " + SSN_USERS + " where UPPER(user_name) = UPPER(?)";
/**
* Query to find a user id depending on his name. Note that this query does
* a case insensitive search with the user name.
*/
public static final String FIND_USER_ID_BY_NAME = "select user_id "
+ " from " + SSN_USERS + " where UPPER(user_name) = UPPER(?)";
/**
* Query to find a user name depending on his id.
*/
public static final String FIND_USER_NAME_BY_ID = "select user_name "
+ " from " + SSN_USERS + " where user_id = ?";
/**
* Query to insert a row into the users table.
*/
public static final String INSERT_USER = "insert into "
+ SSN_USERS
+ " (user_name, password, salt, created_at) values (?, ?, ?, CURRENT_TIMESTAMP() )";
/**
* Query to update a row in the users table.
*/
public static final String UPDATE_USER_BY_ID = "update "
+ SSN_USERS
+ " set last_status_code_id = ?, last_location_id = ?, modified_at = CURRENT_TIMESTAMP()"
+ " where user_id = ?";
/**
* Query to update a row in the users table.
*/
public static final String UPDATE_USER_BY_NAME = "update "
+ SSN_USERS
+ " set last_status_code_id = ?, last_location_id = ?, modified_at = CURRENT_TIMESTAMP()"
+ " where UPPER(user_name) = UPPER(?)";
// All queries related to STATUS_CRUMBS
/**
* Query to create the STATUS_CRUMBS table.
*/
public static final String CREATE_STATUS_CRUMBS = "create table IF NOT EXISTS "
+ SSN_STATUS_CRUMBS
+ " ( status_crumb_id IDENTITY PRIMARY KEY,"
+ " user_id BIGINT,"
+ " status VARCHAR(10), location_crumb_id BIGINT, "
+ " created_at TIMESTAMP )";
/**
* Query to drop the STATUS_CRUMBS table.
*/
public static final String DROP_STATUS_CRUMBS = "drop table if exists "
+ SSN_STATUS_CRUMBS;
/**
* Query to load all status crumbs in the system.
*/
public static final String FIND_ALL_STATUS_CRUMBS = "select ssc.status_crumb_id, ssc.user_id, u.user_name, ssc.status, ssc.location_crumb_id, slc.location, "
+ " ssc.created_at "
+ " from "
+ SSN_STATUS_CRUMBS
+ " ssc "
+ " left outer join "
+ SSN_USERS
+ " u on ssc.user_id = u.user_id "
+ " left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on ssc.location_crumb_id = slc.location_crumb_id "
+ "order by created_at DESC";
/**
* Query to find a status_crumb depending on the user_id.
*/
public static final String FIND_STATUS_CRUMB_FOR_USER_ID = "select status_crumb_id, user_id, status, location_crumb_id, "
+ " created_at "
+ " from "
+ SSN_STATUS_CRUMBS
+ " where user_id = ?";
/**
* Query to insert a row into the status_crumbs table.
*/
public static final String INSERT_STATUS_CRUMB = "insert into "
+ SSN_STATUS_CRUMBS
+ " (user_id, status, location_crumb_id, created_at) values (?, ?, ?, CURRENT_TIMESTAMP())";
// All queries related to LOCATION_CRUMBS
/**
* Query to create the LOCATION_CRUMBS table.
*/
public static final String CREATE_LOCATION_CRUMBS = "create table IF NOT EXISTS "
+ SSN_LOCATION_CRUMBS
+ " ( location_crumb_id IDENTITY PRIMARY KEY,"
+ " user_id BIGINT,"
+ " location VARCHAR(50)," + " created_at TIMESTAMP )";
/**
* Query to drop the LOCATION_CRUMBS table.
*/
public static final String DROP_LOCATION_CRUMBS = "drop table if exists "
+ SSN_LOCATION_CRUMBS;
/**
* Query to load all location crumbs in the system.
*/
public static final String FIND_ALL_LOCATION_CRUMBS = "select location_crumb_id, user_id, location,"
+ " created_at "
+ " from "
+ SSN_LOCATION_CRUMBS
+ " order by created_at DESC";
/**
* Query to find a location_crumb depending on the user_id.
*/
public static final String FIND_LOCATION_CRUMB_FOR_USER_ID = "select Location_crumb_id, user_id, location,"
+ " created_at "
+ " from "
+ SSN_LOCATION_CRUMBS
+ " where user_id = ?";
/**
* Query to insert a row into the location_crumbs table.
*/
public static final String INSERT_LOCATION_CRUMB = "insert into "
+ SSN_LOCATION_CRUMBS
+ " (user_id, location, created_at) values (?, ?, CURRENT_TIMESTAMP())";
// All queries related to MESSAGES
/**
* Query to create the MESSAGES table.
*/
public static final String CREATE_MESSAGES = "create table IF NOT EXISTS "
+ SSN_MESSAGES + " ( message_id IDENTITY PRIMARY KEY,"
+ " author_id BIGINT, target_id BIGINT, location_id BIGINT,"
+ " content VARCHAR(1024), message_type VARCHAR(10),"
+ " created_at TIMESTAMP )";
/**
* Query to drop the MESSAGES table.
*/
public static final String DROP_MESSAGES = "drop table if exists "
+ SSN_MESSAGES;
/**
* Query to load message by the specific message ID
*/
public static final String FIND_MESSAGE_BY_ID = "select ssm.message_id, ssm.author_id, sa.user_name, ssm.target_id, sb.user_name, ssm.location_id, slc.location, ssm.content, ssm.message_type, ssm.created_at "
+ "from "
+ SSN_MESSAGES
+ " ssm "
+ "left outer join "
+ SSN_USERS
+ " sa on ssm.author_id=sa.user_id "
+ "left outer join "
+ SSN_USERS
+ " sb on ssm.target_id=sa.user_id "
+ "left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on sa.last_location_id=slc.location_crumb_id "
+ "where ssm.message_id = ? "
+ "order by ssm.created_at DESC";
/**
* Query to load all messages in the system.
*/
public static final String FIND_ALL_MESSAGES = "select ssm.message_id, ssm.author_id, sa.user_name, ssm.target_id,"
+ " sb.user_name, ssm.location_id, slc.location, "
+ " ssm.content, ssm.message_type, ssm.created_at "
+ " from "
+ SSN_MESSAGES
+ " ssm "
+ " left outer join "
+ SSN_USERS
+ " sa on ssm.author_id=sa.user_id "
+ " left outer join "
+ SSN_USERS
+ " sb on ssm.target_id=sa.user_id "
+ " left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on ssm.location_id=slc.location_crumb_id"
+ " order by ssm.created_at DESC";
/**
* Query to load all chat messages in the system.
*/
public static final String FIND_ALL_CHAT_MESSAGES = "select ssm.message_id, ssm.author_id, sa.user_name, ssm.target_id,"
+ " sb.user_name, ssm.location_id, slc.location, "
+ " ssm.content, ssm.message_type, ssm.created_at "
+ " from "
+ SSN_MESSAGES
+ " ssm "
+ " left outer join "
+ SSN_USERS
+ " sa on ssm.author_id=sa.user_id "
+ " left outer join "
+ SSN_USERS
+ " sb on ssm.target_id=sa.user_id "
+ " left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on ssm.location_id=slc.location_crumb_id"
+ " where ssm.message_type=\'CHAT\'"
+ " order by ssm.created_at DESC";
/**
* Query to load all wall messages in the system.
*/
public static final String FIND_ALL_WALL_MESSAGES = "select ssm.message_id, ssm.author_id, sa.user_name, ssm.target_id,"
+ " sb.user_name, ssm.location_id, slc.location, "
+ " ssm.content, ssm.message_type, ssm.created_at "
+ " from "
+ SSN_MESSAGES
+ " ssm "
+ " left outer join "
+ SSN_USERS
+ " sa on ssm.author_id=sa.user_id "
+ " left outer join "
+ SSN_USERS
+ " sb on ssm.target_id=sa.user_id "
+ " left outer join "
+ SSN_LOCATION_CRUMBS
+ " slc on ssm.location_id=slc.location_crumb_id"
+ " where ssm.message_type=\'WALL\'"
+ " order by ssm.created_at DESC";
/**
* Query to insert a new chat message into the chat_messages table.
*/
public static final String INSERT_CHAT_MESSAGE = "insert into "
+ SSN_MESSAGES
+ " (author_id, target_id, content, message_type, location_id, created_at) values (?, ?, ?, ?, ?,CURRENT_TIMESTAMP())";
/**
* Query to insert a new chat message into the chat_messages table.
*/
public static final String INSERT_WALL_MESSAGE = "insert into "
+ SSN_MESSAGES
+ " (author_id, target_id, content, message_type, location_id, created_at) values (?, ?, ?, ?, ?, CURRENT_TIMESTAMP())";
/**
* Query to fetch chat buddies
*/
public static final String FETCH_CHAT_BUDDIES = "select u.user_id, user_name, created_at, modified_at, last_status_code_id "
+ "from SSN_USERS u "
+ "join "
+ "(select distinct target_id as user_id "
+ "from SSN_MESSAGES m1 "
+ "join SSN_USERS u1 on m1.author_id = u1.user_id "
+ "where u1.user_name = ? "
+ "and m1.message_type = \'CHAT\' "
+ "union "
+ "select distinct author_id as user_id "
+ "from SSN_MESSAGES m2 "
+ "join SSN_USERS u2 on m2.target_id = u2.user_id "
+ "where u2.user_name = ? "
+ "and m2.message_type = \'CHAT\' "
+ ") m "
+ "on u.user_id = m.user_id ";
public static final String FIND_PEER_CHAT_MESSAGES = "select * from SSN_MESSAGES";
// All queries related to MEMORY_CRUMBS
/**
* Query to create the MEMORY_CRUMBS table.
*/
public static final String CREATE_MEMORY_CRUMBS = "create table IF NOT EXISTS "
+ SSN_MEMORY_CRUMBS
+ " ( memory_crumb_id IDENTITY PRIMARY KEY,"
+ " used_volatile_memory BIGINT,"
+ " remaining_volatile_memory BIGINT,"
+ " used_persistent_memory BIGINT,"
+ " remaining_persistent_memory BIGINT,"
+ " online_users BIGINT,"
+ " created_at TIMESTAMP )";
/**
* Query to drop the MEMORY_CRUMBS table.
*/
public static final String DROP_MEMORY_CRUMBS = "drop table if exists "
+ SSN_MEMORY_CRUMBS;
/**
* Query to load all memory crumbs in the system.
*/
public static final String FIND_ALL_MEMORY_CRUMBS = "select memory_crumb_id, used_volatile_memory, remaining_volatile_memory, "
+ " used_persistent_memory, remaining_persistent_memory, online_users, created_at "
+ " from "
+ SSN_MEMORY_CRUMBS
+ " order by created_at DESC";
/**
* Query to load all memory crumbs in the specified time interval.
*/
public static final String FIND_ALL_MEMORY_CRUMBS_IN_INTERVAL = "select memory_crumb_id, used_volatile_memory, remaining_volatile_memory, "
+ " used_persistent_memory, remaining_persistent_memory, online_users, created_at "
+ " from "
+ SSN_MEMORY_CRUMBS
+ " where created_at between DATEADD(hh, ?, current_timestamp()) and current_timestamp()"
+ " order by created_at DESC";
/**
* Query to delete all memory crumbs in the system.
*/
public static final String DELETE_ALL_MEMORY_CRUMBS = "delete from "
+ SSN_MEMORY_CRUMBS;
/**
* Query to insert a row into the memory_crumbs table.
*/
public static final String INSERT_MEMORY_CRUMB = "insert into "
+ SSN_MEMORY_CRUMBS
+ " (used_volatile_memory, remaining_volatile_memory, used_persistent_memory, remaining_persistent_memory, "
+ " online_users, created_at) values (?, ?, ?, ?, ?, CURRENT_TIMESTAMP())";
}
|
package servlets;
import helperClasses.Const;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.Date;
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.spoledge.audao.db.dao.DaoException;
import database.DataSourceConnector;
import database.dao.BrugerDao;
import database.dao.CtKontrastKontrolskemaDao;
import database.dao.MRKontrolskemaDao;
import database.dao.ModalitetDao;
import database.dao.PETCTKontrolskemaDao;
import database.dao.PatientDao;
import database.dao.RekvisitionDao;
import database.dao.UndersoegelsesTypeDao;
import database.dao.mysql.BrugerDaoImpl;
import database.dao.mysql.CtKontrastKontrolskemaDaoImpl;
import database.dao.mysql.MRKontrolskemaDaoImpl;
import database.dao.mysql.ModalitetDaoImpl;
import database.dao.mysql.PETCTKontrolskemaDaoImpl;
import database.dao.mysql.PatientDaoImpl;
import database.dao.mysql.RekvisitionDaoImplExt;
import database.dao.mysql.UndersoegelsesTypeDaoImpl;
import database.dto.Bruger;
import database.dto.CtKontrastKontrolskema;
import database.dto.MRKontrolskema;
import database.dto.Modalitet;
import database.dto.PETCTKontrolskema;
import database.dto.Patient;
import database.dto.RekvisitionExtended;
import database.dto.MRKontrolskema.MRBoern;
import database.dto.MRKontrolskema.MRVoksen;
import database.dto.PETCTKontrolskema.Formaal;
import database.dto.PETCTKontrolskema.KemoOgStraale;
import database.dto.RekvisitionExtended.AmbulantKoersel;
import database.dto.RekvisitionExtended.HenvistTil;
import database.dto.RekvisitionExtended.HospitalOenske;
import database.dto.RekvisitionExtended.IndlaeggelseTransport;
import database.dto.RekvisitionExtended.Prioritering;
import database.dto.RekvisitionExtended.Samtykke;
import database.dto.UndersoegelsesType;
import database.interfaces.IDataSourceConnector.ConnectionException;
/**
* Servlet implementation class NyRekvisitionServlet
*/
@SuppressWarnings("serial")
@WebServlet("/NyRekvisitionServlet")
public class NyRekvisitionServlet extends HttpServlet
{
private static final String HENV_AFD = "henv_afd";
private static final String PATIENT_TLF = "patient_tlf";
private static final String PATIENT_NAVN = "patient_navn";
private static final String PATIENT_ADRESSE = "patient_adresse";
private static final String PATIENT_CPR = "patient_cpr";
private static final boolean DEBUG = false;
/**
* @see HttpServlet#HttpServlet()
*/
public NyRekvisitionServlet()
{
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Getting List of modalities - first create connection
Connection conn = null;
try {
conn = DataSourceConnector.getConnection();
} catch (ConnectionException e) {
//Connection Fails TODO message to user
e.printStackTrace();
}
//And DAO
ModalitetDao modDao = new ModalitetDaoImpl(conn);
//Getting Modalities
Modalitet[] modList = modDao.findDynamic(null, 0, -1, null);
request.setAttribute(Const.MODALITY_LIST, modList);
if (Const.DEBUG) System.out.println(modList);
request.getRequestDispatcher(Const.NEW_REKVISITION_PAGE).forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Getting active user
Bruger activeBruger = (Bruger) request.getSession().getAttribute(Const.ACTIVE_USER);
//Checking if activeUser
if (activeBruger == null) response.sendRedirect(Const.MAIN_SERVLET);
request.setCharacterEncoding("UTF-8");
//Getting a database connection....
Connection conn = null;
try {
conn = DataSourceConnector.getConnection();
} catch (ConnectionException e1) {
e1.printStackTrace();
}
//Getting active user
//Storing patient data.
Integer ptId = storePatient(request, conn, activeBruger);
//Making Rekvisition DTO
RekvisitionExtended rek = new RekvisitionExtended();
rek.setPaaroerende(request.getParameter("paaroerende"));
rek.setSamtykke(convertSamtykke(request)); //TODO validate samtykke.
rek.setTriage(request.getParameter("triage"));
rek.setCave(request.getParameter("cave"));//TODO validate
try {
rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent_id")));
} catch (NumberFormatException e){
//Should never happen TODO - Now handles by setting rekvirent to null - should give backend exception
rek.setRekvirentId(null);
e.printStackTrace();
}
rek.setRekvirentId(activeBruger.getBrugerId());
rek.setHenvAfd(request.getParameter(HENV_AFD));
rek.setHenvLaege(request.getParameter("henv_laege"));
rek.setKontaktTlf(request.getParameter("kontakt_tlf"));
rek.setUdfIndlagt(Boolean.valueOf(request.getParameter("udf_indlagt")));
rek.setAmbulant(!rek.getUdfIndlagt());
rek.setHenvistTil(convertHenvistTil(request));
rek.setHospitalOenske(convertHospitalOenske(request));
rek.setPrioritering(convertPrioritering(request));
Integer USTypeID = -1;
UndersoegelsesType USType = new UndersoegelsesType();
USType.setModalitetId(Integer.valueOf(request.getParameter("modalitet_navn")));
USType.setUndersoegelsesNavn(request.getParameter("undersoegelses_type"));
UndersoegelsesTypeDao usTypeDao = new UndersoegelsesTypeDaoImpl(conn) ;
try {
USTypeID = usTypeDao.insert(USType);
} catch (DaoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
rek.setUndersoegelsesTypeId(USTypeID); //TODO FIXXX!!!
rek.setKliniskProblemstilling(request.getParameter("klinisk_problemstilling"));
rek.setAmbulantKoersel(convertAmbulantKoersel(request));
rek.setIndlaeggelseTransport(convertIndlaeggelseTransport(request));
rek.setDatoForslag(request.getParameter("dato_forslag"));
rek.setGraviditet(Boolean.valueOf(request.getParameter("graviditet")));
rek.setHoerehaemmet(getBoolFromCheckbox(request,"hoerehaemmet"));
rek.setSynshaemmet(getBoolFromCheckbox(request, "synshaemmet"));
rek.setAmputeret(getBoolFromCheckbox(request, "amputeret"));
rek.setKanIkkeStaa(getBoolFromCheckbox(request, "kan_ikke_staa"));
rek.setDement(getBoolFromCheckbox(request, "dement"));
rek.setAfasi(getBoolFromCheckbox(request, "afasi"));
try {
rek.setIltLiterPrmin(Integer.valueOf(request.getParameter("ilt")));
} catch (NumberFormatException e){
rek.setIltLiterPrmin(null);
}
rek.setTolkSprog(request.getParameter("tolk"));
rek.setIsolation(request.getParameter("isolation"));
try {
rek.setCytostatikaDato(java.sql.Date.valueOf(request.getParameter("cytostatika")));
System.out.println(rek.getCytostatikaDato());
} catch (IllegalArgumentException e) {
rek.setCytostatikaDato(null);
}
rek.setTidlBilledDiagnostik(request.getParameter("tidl_billed_diagnostik"));
rek.setPatientId(ptId);
rek.setStatus(RekvisitionExtended.Status.PENDING);
rek.setAfsendtDato(new Date());
System.out.println(rek);
//Check Modalitet
String modalitet = request.getParameter("modalitet_navn");
// can not switch on null - makes empty string instead should not happen
modalitet = modalitet == null ? "" : modalitet;
switch (modalitet) {
case "invasiv_UL":
Integer ULSkemaID = storeULInvKontrolSkema(request,response);
rek.setInvasivULKontrolskemaId(ULSkemaID);
break;
case "MR":
Integer MRSkemaID = null;
try {
MRSkemaID = storeMRSkema(request, response);
} catch (DaoException e1) {
// TODO Error page???
e1.printStackTrace();
}
rek.setMRKontrolskemaId(MRSkemaID);
break;
case "CT_kontrast":
Integer CTKSkemaID = null;
try {
CTKSkemaID = storeCTKSkema(request, response);
} catch (DaoException e1) {
// TODO Error page???
e1.printStackTrace();
}
rek.setCTKontrastKontrolskemaId(CTKSkemaID);
break;
case "PETCT":
Integer PETCTSkemaID = null;
try {
PETCTSkemaID = storePETCTSkema(request,response);
} catch (DaoException e1) {
// TODO Error page???
e1.printStackTrace();
}
rek.setPETCTKontrolskemaId(PETCTSkemaID);
break;
default:
//Now store the requisition
RekvisitionDao rekDao = new RekvisitionDaoImplExt(conn);
try {
rekDao.insert(rek);
} catch (DaoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HopeFully it went well ;)
//TODO - real page
PrintWriter out = response.getWriter();
out.println("<HTML><BODY>Tak for din henvendelse - du kan følge med i status for din rekvisition i oversigten <BR>");
out.println("<A HREF='RekvisitionServlet'>Tilbage til rekvisitioner</A></BODY><HTML>");
break;
}
}
private Integer storePatient(HttpServletRequest request, Connection conn,
Bruger activeBruger) {
Patient pt = new Patient();
// pt.setFoedselsdag(Timestamp.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR))));
pt.setFoedselsdag(java.sql.Date.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR))));
pt.setPatientCpr(request.getParameter(PATIENT_CPR));
pt.setPatientAdresse(request.getParameter(PATIENT_ADRESSE));
pt.setPatientNavn(request.getParameter(PATIENT_NAVN));
pt.setPatientTlf(request.getParameter(PATIENT_TLF));
pt.setStamafdeling(activeBruger.getBrugerNavn());
if (Const.DEBUG)System.out.println(pt);
//Time to store patient
Integer ptId = null;
PatientDao ptDao = new PatientDaoImpl(conn);
try {
ptId = ptDao.insert(pt);
} catch (DaoException e1) {
e1.printStackTrace();
}
return ptId;
}
private Integer storePETCTSkema(HttpServletRequest request,
HttpServletResponse response) throws DaoException {
Connection conn = null;
try {
conn = DataSourceConnector.getConnection();
} catch (ConnectionException e1) {
e1.printStackTrace();
}
PETCTKontrolskema pck = new PETCTKontrolskema();
pck.setFormaal(convertFormaalMetode(request));
pck.setFormaalTekst(request.getParameter("formaal_text"));
pck.setKanPtLiggeStille30(Boolean.valueOf(request.getParameter("kanPtLiggeStille30")));
pck.setPtTaalerFaste(Boolean.valueOf(request.getParameter("ptTaalerFaste")));
pck.setDiabetes(Boolean.valueOf(request.getParameter("diabetes")));
pck.setDMBeh(request.getParameter("DM_Beh"));
pck.setSmerter(Boolean.valueOf(request.getParameter("smerter")));
pck.setRespInsuff(Boolean.valueOf(request.getParameter("respInsuff")));
pck.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi")));
pck.setAllergi(Boolean.valueOf(request.getParameter("allergi")));
pck.setAllergiTekst(request.getParameter("allergi_tekst"));
pck.setFedme(Boolean.valueOf(request.getParameter("fedme")));
pck.setVaegt(Integer.valueOf(request.getParameter("vaegt")));
pck.setBiopsi(Boolean.valueOf(request.getParameter("biopsi")));
pck.setBiopsiTekst(request.getParameter("biopsi_tekst"));
pck.setOperation(Boolean.valueOf(request.getParameter("operation")));
pck.setOperationTekst(request.getParameter("operation_tekst"));
pck.setKemoOgStraale(convertKemostraale(request));
pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("straaleDato")));
pck.setNedsatNyreFkt(Boolean.valueOf(request.getParameter("nedsatNyreFkt")));
pck.setSidstePKreatinin(Integer.valueOf(request.getParameter("sidstePKreatinin")));
pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("sidstePKreatTimestamp")));
PETCTKontrolskemaDao petctkDao = new PETCTKontrolskemaDaoImpl(conn);
return petctkDao.insert(pck);
}
private Integer storeCTKSkema(HttpServletRequest request,
HttpServletResponse response) throws DaoException {
Connection conn = null;
try {
conn = DataSourceConnector.getConnection();
} catch (ConnectionException e1) {
e1.printStackTrace();
}
// Making CTTKontrolskema dto
CtKontrastKontrolskema ctk = new CtKontrastKontrolskema();
ctk.setDiabetes(Boolean.valueOf(request.getParameter("diabetes")));
ctk.setNyrefunktion(Boolean.valueOf(request.getParameter("nyrefunktion")));
ctk.setNyreopereret(Boolean.valueOf(request.getParameter("nyreopereret")));
ctk.setHjertesygdom(Boolean.valueOf(request.getParameter("hjertesygdom")));
ctk.setMyokardieinfarkt(Boolean.valueOf(request.getParameter("myokardieinfarkt")));
ctk.setProteinuri(Boolean.valueOf(request.getParameter("proteinuri")));
ctk.setUrinsyregigt(Boolean.valueOf(request.getParameter("urinsyregigt")));
ctk.setOver70(Boolean.valueOf(request.getParameter("over70")));
ctk.setHypertension(Boolean.valueOf(request.getParameter("hypertension")));
ctk.setNsaidPraeparat(Boolean.valueOf(request.getParameter("NSAIDpræparat")));
ctk.setAllergi(Boolean.valueOf(request.getParameter("alergi")));
ctk.setKontraststofreaktion(Boolean.valueOf(request.getParameter("konstrastofreaktion")));
ctk.setAstma(Boolean.valueOf(request.getParameter("astma")));
ctk.setHyperthyreoidisme(Boolean.valueOf(request.getParameter("hyperthyreoidisme")));
ctk.setMetformin(Boolean.valueOf(request.getParameter("metformin")));
ctk.setInterleukin2(Boolean.valueOf(request.getParameter("interleukin")));
ctk.setBetaBlokkere(Boolean.valueOf(request.getParameter("betaBlokkere")));
ctk.setPKreatininVaerdi(request.getParameter("Værdi"));
// setPKreatininTimestamp???
ctk.setPtHoejde(Integer.valueOf(request.getParameter("Højde")));
ctk.setPtVaegt(Integer.valueOf(request.getParameter("Vægt")));
CtKontrastKontrolskemaDao ctkDao = new CtKontrastKontrolskemaDaoImpl(conn);
return ctkDao.insert(ctk);
}
private Integer storeMRSkema(HttpServletRequest request,
HttpServletResponse response) throws DaoException {
Connection conn = null;
try {
conn = DataSourceConnector.getConnection();
} catch (ConnectionException e1) {
e1.printStackTrace();
}
MRKontrolskema mrk = new MRKontrolskema();
mrk.setPacemaker(Boolean.valueOf(request.getParameter("pacemaker")));
mrk.setMetalImplantater(Boolean.valueOf(request.getParameter("metal_implantater")));
mrk.setMetalImplantaterBeskrivelse(request.getParameter("metal_implantater_beskrivelse"));
mrk.setAndetMetalisk(Boolean.valueOf(request.getParameter("andet_metalisk")));
mrk.setAndetMetaliskBeskrivelse(request.getParameter("andet_metalisk_beskrivelse"));
mrk.setNyresygdom(Boolean.valueOf(request.getParameter("nyresygdom")));
mrk.setNyresygdomKreatinin(Integer.valueOf(request.getParameter("nyresygdom_kreatinin")));
mrk.setGraviditet(Boolean.valueOf(request.getParameter("graviditet")));
mrk.setGraviditetUge(Integer.valueOf(request.getParameter("graviditet_uge")));
mrk.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi")));
mrk.setHoejde(Integer.valueOf(request.getParameter("hoejde")));
mrk.setVaegt(Integer.valueOf(request.getParameter("vaegt")));
mrk.setMRBoern(convertSederingBoern(request));
mrk.setMRVoksen(convertSederingVoksen(request));
mrk.setPraepForsyn(request.getParameter("praep_forsyn"));
MRKontrolskemaDao mrkDao = new MRKontrolskemaDaoImpl(conn);
return mrkDao.insert(mrk);
}
private Integer storeULInvKontrolSkema(HttpServletRequest request,
HttpServletResponse response) {
// TODO Auto-generated method stub
return -1;
}
private String parseCPRBirthday(String foedselsdagString) {
// String = request.getParameter(PATIENT_CPR);
Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6));
String digit7String = foedselsdagString.substring(6,7);
if (digit7String.equalsIgnoreCase("-") ) digit7String = foedselsdagString.substring(7, 8);
Integer digit7 = Integer.valueOf(digit7String);
if (digit7 <= 3 ){
foedeaar = 1900 + foedeaar;
} else {
if ((digit7 == 4 || digit7 == 9) && foedeaar >=37){
foedeaar = 1900 + foedeaar;
} else {
if (foedeaar >=58 && (digit7 !=4||digit7!=9)){
foedeaar = 1800 + foedeaar;
} else {
foedeaar = 2000 + foedeaar;
}
}
}
foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2);
System.out.println("birthday from cpr: " + foedselsdagString);
// Date d = new Date();
// System.out.println("Date format: " + d.toString());
// Timestamp t = Timestamp.valueOf(foedselsdagString);
// new Date(foedselsdagString);
// new Date(123);
// System.out.println("come on: " + Date.parse(foedselsdagString));
// System.out.println("new format: " + java.sql.Date.valueOf(d.toString()));
// System.out.println("second fomrat: " + Date.parse(d.toString()));
// foedselsdagString = foedselsdagString + " 00:00:00.000000000";
return foedselsdagString;
}
private Boolean getBoolFromCheckbox(HttpServletRequest request,
String boxname) {
if("on".equals(request.getParameter(boxname))){
// check box is selected
return true;
} else{
// check box is not selected
return false;
}
}
private IndlaeggelseTransport convertIndlaeggelseTransport(
HttpServletRequest request) {
IndlaeggelseTransport indlTrans;
String transString = request.getParameter("indlagt_transport");
if (transString==null) return null;
switch (transString) {
case "selv":
indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_UDEN_PORTOER;
break;
case "portoer":
indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_MED_PORTOER;
break;
case "koerestol":
indlTrans = RekvisitionExtended.IndlaeggelseTransport.KOERESTOL;
break;
case "seng":
indlTrans = RekvisitionExtended.IndlaeggelseTransport.SENG;
break;
default:
indlTrans=null;
break;
}
return indlTrans;
}
private AmbulantKoersel convertAmbulantKoersel(HttpServletRequest request) {
AmbulantKoersel ambuTrans;
String transString = request.getParameter("ambulant_transport");
if (transString==null) return null;
switch (transString) {
case "ingen":
ambuTrans = RekvisitionExtended.AmbulantKoersel.INGEN;
break;
case "siddende":
ambuTrans = RekvisitionExtended.AmbulantKoersel.SIDDENDE;
break;
case "liggende":
ambuTrans = RekvisitionExtended.AmbulantKoersel.LIGGENDE;
break;
default:
ambuTrans = null;
break;
}
return ambuTrans;
}
private Prioritering convertPrioritering(HttpServletRequest request) {
Prioritering prio;
String prioString = request.getParameter("prioriterings_oenske");
if (prioString==null)return null;
switch (prioString) {
case "haste":
prio = RekvisitionExtended.Prioritering.HASTE;
break;
case "fremskyndet":
prio = RekvisitionExtended.Prioritering.FREMSKYNDET;
break;
case "rutine":
prio = RekvisitionExtended.Prioritering.RUTINE;
break;
case "pakke":
prio = RekvisitionExtended.Prioritering.PAKKEFORLOEB;
break;
default:
prio = null;
break;
}
return prio;
}
private HospitalOenske convertHospitalOenske(HttpServletRequest request) {
HospitalOenske hospOensk;
String hospOenskString = request.getParameter("hospitals_oenske");
if (hospOenskString==null) return null;
switch (hospOenskString) {
case "hilleroed":
hospOensk = RekvisitionExtended.HospitalOenske.HILLEROED;
break;
case "frederikssund":
hospOensk = RekvisitionExtended.HospitalOenske.FREDERIKSSUND;
break;
case "helsingoer":
hospOensk = RekvisitionExtended.HospitalOenske.HELSINGOER;
break;
default:
hospOensk=null;
break;
}
return hospOensk;
}
private HenvistTil convertHenvistTil(HttpServletRequest request) {
HenvistTil henv;
String henvString = request.getParameter("henvist_til");
if (henvString==null) return null;
switch (henvString) {
case "radiologisk":
henv = RekvisitionExtended.HenvistTil.RADIOLOGISK;
break;
case "klinfys":
henv = RekvisitionExtended.HenvistTil.KLINISK;
break;
default:
henv = null;
break;
}
return henv;
}
private Samtykke convertSamtykke(HttpServletRequest request) {
Samtykke samtykke;
String samtykkeString = request.getParameter("samtykke");
if (samtykkeString == null) return null;
switch (samtykkeString) {
case "ja":
samtykke = RekvisitionExtended.Samtykke.JA;
break;
case "nej":
samtykke = RekvisitionExtended.Samtykke.NEJ;
break;
default:
samtykke = RekvisitionExtended.Samtykke.UDEN_SAMTYKKE;
break;
}
return samtykke;
}
private MRBoern convertSederingBoern(HttpServletRequest request){
MRBoern mrboern;
String mrboernString = request.getParameter("sederingBoern");
if (mrboernString == null) return null;
switch (mrboernString) {
case "uden_sedering":
mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING;
break;
case "i_generel_anaestesi":
mrboern = MRKontrolskema.MRBoern.I_GENEREL_ANAESTESI;
break;
default:
mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING;
break;
}
return mrboern;
}
private MRVoksen convertSederingVoksen(HttpServletRequest request){
MRVoksen mrvoksen;
String mrvoksenString = request.getParameter("sederingVoksne");
if (mrvoksenString == null) return null;
switch (mrvoksenString) {
case "uden_sedering":
mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING;
break;
case "i_generel_anaestesi":
mrvoksen = MRKontrolskema.MRVoksen.I_GENEREL_ANAESTESI;
break;
default:
mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING;
break;
}
return mrvoksen;
}
private KemoOgStraale convertKemostraale(HttpServletRequest request){
KemoOgStraale kemoOgStraale;
String kemiOgStraaleString = request.getParameter("aldrigGivetKemo");
if (kemiOgStraaleString == null) return null;
switch (kemiOgStraaleString) {
case "aldrigGivetKemoJa":
kemoOgStraale = PETCTKontrolskema.KemoOgStraale.ALDRIGGIVET;
break;
case "kemoterapiJa":
case "stråleterapiNej":
kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMOTERAPI;
break;
case "kemoterapiNej":
case "stråleterapiJa":
kemoOgStraale = PETCTKontrolskema.KemoOgStraale.STRAALETERAPI;
break;
default:
kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMO_OG_STRAALE;
break;
}
return kemoOgStraale;
}
private Formaal convertFormaalMetode(HttpServletRequest request){
Formaal formaal = null;
String formaalString = request.getParameter("formaal");
if (formaalString == null) return null;
switch (formaalString) {
case "primardiag":
formaal = PETCTKontrolskema.Formaal.PRIMAERDIAG;
break;
case "kontrolbeh":
formaal = PETCTKontrolskema.Formaal.KONTROLBEH;
break;
case "kontrolremission":
formaal = PETCTKontrolskema.Formaal.KONTROLREMISSION;
break;
case "kontrolrecidiv":
formaal = PETCTKontrolskema.Formaal.KONTROLRECIDIV;
break;
}
return formaal;
}
}
|
package com.evolveum.midpoint.provisioning.ucf.impl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.annotation.PostConstruct;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.SchemaViolationException;
import javax.xml.namespace.QName;
import org.apache.commons.configuration.Configuration;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.framework.api.ConnectorInfo;
import org.identityconnectors.framework.api.ConnectorInfoManager;
import org.identityconnectors.framework.api.ConnectorInfoManagerFactory;
import org.identityconnectors.framework.api.ConnectorKey;
import org.identityconnectors.framework.api.RemoteFrameworkConnectionInfo;
import org.identityconnectors.framework.common.exceptions.ConnectorSecurityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration;
import com.evolveum.midpoint.common.result.OperationResult;
import com.evolveum.midpoint.provisioning.ucf.api.CommunicationException;
import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory;
import com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance;
import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException;
import com.evolveum.midpoint.provisioning.ucf.api.ObjectNotFoundException;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.schema.exception.SchemaException;
import com.evolveum.midpoint.schema.exception.SystemException;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ConnectorHostType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectReferenceType;
import static com.evolveum.midpoint.provisioning.ucf.impl.IcfUtil.processIcfException;
/**
* Currently the only implementation of the UCF Connector Manager API interface.
*
* It is hardcoded to ICF now.
*
* This class holds a list of all known ICF connectors in the system.
*
* @author Radovan Semancik
*/
@Component
public class ConnectorFactoryIcfImpl implements ConnectorFactory {
public static final String ICF_FRAMEWORK_URI = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1";
public static final String NS_ICF_CONFIGURATION = ICF_FRAMEWORK_URI + "/connector-schema-1.xsd";
// Note! This is also specified in SchemaConstants (MID-356)
public static final String NS_ICF_SCHEMA = ICF_FRAMEWORK_URI + "/resource-schema-1.xsd";
public static final String NS_ICF_SCHEMA_PREFIX = "icfs";
public static final String NS_ICF_RESOURCE_INSTANCE_PREFIX = "ri";
public static final QName ICFS_NAME = new QName(NS_ICF_SCHEMA, "name");
public static final QName ICFS_UID = new QName(NS_ICF_SCHEMA, "uid");
public static final QName ICFS_PASSWORD = new QName(NS_ICF_SCHEMA, "password");
public static final QName ICFS_ACCOUNT = new QName(NS_ICF_SCHEMA, "account");
public static final String CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_LOCAL_NAME = "configurationProperties";
public static final String CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_TYPE_LOCAL_NAME = "ConfigurationPropertiesType";
public static final String CONNECTOR_SCHEMA_CONFIGURATION_ELEMENT_LOCAL_NAME = "configuration";
public static final String CONNECTOR_SCHEMA_CONFIGURATION_TYPE_LOCAL_NAME = "ConfigurationType";
public static final QName CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_ELEMENT = new QName(NS_ICF_CONFIGURATION,
"connectorPoolConfiguration");
public static final QName CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_TYPE = new QName(NS_ICF_CONFIGURATION,
"ConnectorPoolConfigurationType");
public static final QName CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_ELEMENT = new QName(NS_ICF_CONFIGURATION,
"producerBufferSize");
public static final QName CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_TYPE = DOMUtil.XSD_INTEGER;
public static final QName CONNECTOR_SCHEMA_TIMEOUTS_ELEMENT = new QName(NS_ICF_CONFIGURATION, "timeouts");
public static final QName CONNECTOR_SCHEMA_TIMEOUTS_TYPE = new QName(NS_ICF_CONFIGURATION, "TimeoutsType");
private static final String ICF_CONFIGURATION_NAMESPACE_PREFIX = ICF_FRAMEWORK_URI + "/bundle/";
private static final String CONNECTOR_IDENTIFIER_SEPARATOR = "/";
private static final Trace LOGGER = TraceManager.getTrace(ConnectorFactoryIcfImpl.class);
private ConnectorInfoManagerFactory connectorInfoManagerFactory;
private ConnectorInfoManager localConnectorInfoManager;
private Set<URL> bundleURLs;
private Map<String, ConnectorInfo> connectors;
@Autowired(required=true)
MidpointConfiguration midpointConfiguration;
public ConnectorFactoryIcfImpl() {
}
/**
* Initialize the ICF implementation. Look for all connector bundles, get
* basic information about them and keep that in memory.
*/
@PostConstruct
public void initialize() {
// OLD
// bundleURLs = listBundleJars();
bundleURLs = new HashSet<URL>();
Configuration config = midpointConfiguration.getConfiguration("midpoint.icf");
// Is classpath scan enabled
if (config.getBoolean("scanClasspath")) {
// Scan class path
bundleURLs.addAll(scanClassPathForBundles());
}
//Scan all provided directories
@SuppressWarnings("unchecked")
List<String> dirs = config.getList("scanDirectory");
for (String dir: dirs) {
bundleURLs.addAll(scanDirectory(dir));
}
for (URL u : bundleURLs) {
LOGGER.debug("ICF bundle URL : {}", u);
}
connectorInfoManagerFactory = ConnectorInfoManagerFactory.getInstance();
connectors = new HashMap<String, ConnectorInfo>();
List<ConnectorInfo> connectorInfos = getLocalConnectorInfoManager().getConnectorInfos();
for (ConnectorInfo connectorInfo : connectorInfos) {
ConnectorKey key = connectorInfo.getConnectorKey();
String mapKey = keyToNamespaceSuffix(key);
connectors.put(mapKey, connectorInfo);
}
}
/**
* Creates new connector instance.
*
* It will initialize the connector by taking the XML Resource definition,
* transforming it to the ICF configuration and applying that to the new
* connector instance.
*
* @throws ObjectNotFoundException
*
*/
@Override
public ConnectorInstance createConnectorInstance(ConnectorType connectorType, String namespace)
throws ObjectNotFoundException {
ConnectorInfo cinfo = getConnectorInfo(connectorType);
if (cinfo == null) {
LOGGER.error("Failed to instantiate {}", ObjectTypeUtil.toShortString(connectorType));
LOGGER.debug("Connector key: {}, host: {}", getConnectorKey(connectorType),
ObjectTypeUtil.toShortString(connectorType));
LOGGER.trace("Connector object: {}", ObjectTypeUtil.dump(connectorType));
LOGGER.trace("Connector host object: {}", ObjectTypeUtil.dump(connectorType.getConnectorHost()));
throw new ObjectNotFoundException("The connector " + ObjectTypeUtil.toShortString(connectorType)
+ " was not found");
}
// Create new midPoint ConnectorInstance and pass it the ICF connector
// facade
ConnectorInstanceIcfImpl connectorImpl = new ConnectorInstanceIcfImpl(cinfo, connectorType, namespace);
return connectorImpl;
}
/**
* Returns a list XML representation of the ICF connectors.
* @throws CommunicationException
*/
@Override
public Set<ConnectorType> listConnectors(ConnectorHostType host, OperationResult parentRestul) throws CommunicationException {
OperationResult result = parentRestul.createSubresult(ConnectorFactory.OPERATION_LIST_CONNECTOR);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS,ConnectorFactoryIcfImpl.class);
result.addParam("host", host);
try {
if (host == null) {
Set<ConnectorType> connectors = listLocalConnectors();
result.recordSuccess();
return connectors;
} else {
Set<ConnectorType> connectors = listRemoteConnectors(host);
result.recordSuccess();
return connectors;
}
} catch (Exception icfException) {
Exception ex = processIcfException(icfException, result);
result.recordFatalError(ex.getMessage(), ex);
if (ex instanceof CommunicationException) {
throw (CommunicationException)ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException)ex;
} else {
throw new SystemException("Unexpected ICF exception: "+ex.getMessage(),ex);
}
}
}
private Set<ConnectorType> listLocalConnectors() {
Set<ConnectorType> connectorTypes = new HashSet<ConnectorType>();
for (Map.Entry<String, ConnectorInfo> e : connectors.entrySet()) {
ConnectorInfo cinfo = e.getValue();
ConnectorType connectorType = convertToConnectorType(cinfo, null);
connectorTypes.add(connectorType);
}
return connectorTypes;
}
private Set<ConnectorType> listRemoteConnectors(ConnectorHostType host) {
ConnectorInfoManager remoteConnectorInfoManager = getRemoteConnectorInfoManager(host);
Set<ConnectorType> connectorTypes = new HashSet<ConnectorType>();
List<ConnectorInfo> connectorInfos = remoteConnectorInfoManager.getConnectorInfos();
for (ConnectorInfo connectorInfo : connectorInfos) {
ConnectorType connectorType = convertToConnectorType(connectorInfo, host);
connectorTypes.add(connectorType);
}
return connectorTypes;
}
/**
* Converts ICF ConnectorInfo into a midPoint XML connector representation.
*
* TODO: schema transformation
*
* @param hostType
* host that this connector runs on or null for local connectors
*/
private ConnectorType convertToConnectorType(ConnectorInfo cinfo, ConnectorHostType hostType) {
ConnectorType connectorType = new ConnectorType();
ConnectorKey key = cinfo.getConnectorKey();
String stringID = keyToNamespaceSuffix(key);
StringBuilder connectorName = new StringBuilder("ICF ");
connectorName.append(key.getConnectorName());
if (hostType != null) {
connectorName.append(" @");
connectorName.append(hostType.getName());
}
connectorType.setName(connectorName.toString());
connectorType.setFramework(ICF_FRAMEWORK_URI);
connectorType.setConnectorType(key.getConnectorName());
connectorType.setNamespace(ICF_CONFIGURATION_NAMESPACE_PREFIX + stringID);
connectorType.setConnectorVersion(key.getBundleVersion());
connectorType.setConnectorBundle(key.getBundleName());
if (hostType != null) {
if (hostType.getOid() != null) {
// bind using connectorHostRef and OID
ObjectReferenceType ref = new ObjectReferenceType();
ref.setOid(hostType.getOid());
ref.setType(ObjectTypes.CONNECTOR_HOST.getTypeQName());
connectorType.setConnectorHostRef(ref);
} else {
// Embed the object
connectorType.setConnectorHost(hostType);
}
}
return connectorType;
}
/**
* Converts ICF connector key to a simple string.
*
* The string may be used as an OID.
*/
private String keyToNamespaceSuffix(ConnectorKey key) {
StringBuilder sb = new StringBuilder();
sb.append(key.getBundleName());
sb.append(CONNECTOR_IDENTIFIER_SEPARATOR);
// Don't include version. It is lesser evil.
// sb.append(key.getBundleVersion());
// sb.append(CONNECTOR_IDENTIFIER_SEPARATOR);
sb.append(key.getConnectorName());
return sb.toString();
}
/**
* Returns ICF connector info manager that manages local connectors. The
* manager will be created if it does not exist yet.
*
* @return ICF connector info manager that manages local connectors
*/
private ConnectorInfoManager getLocalConnectorInfoManager() {
if (null == localConnectorInfoManager) {
localConnectorInfoManager = connectorInfoManagerFactory.getLocalManager(bundleURLs.toArray(new URL[0]));
}
return localConnectorInfoManager;
}
/**
* Returns ICF connector info manager that manages local connectors. The
* manager will be created if it does not exist yet.
*
* @return ICF connector info manager that manages local connectors
*/
private ConnectorInfoManager getRemoteConnectorInfoManager(ConnectorHostType hostType) {
String hostname = hostType.getHostname();
int port = Integer.parseInt(hostType.getPort());
GuardedString key = new GuardedString(hostType.getSharedSecret().toCharArray());
// TODO: SSL
RemoteFrameworkConnectionInfo remoteFramewrorkInfo = new RemoteFrameworkConnectionInfo(hostname, port, key);
return connectorInfoManagerFactory.getRemoteManager(remoteFramewrorkInfo);
}
/**
* Scan class path for connector bundles
*
* @return Set of all bundle URL
*/
private Set<URL> scanClassPathForBundles() {
Set<URL> bundle = new HashSet<URL>();
// scan class path for bundles
Enumeration<URL> en = null;
try {
// Search all jars in classpath
en = this.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
} catch (IOException ex) {
LOGGER.debug("Error during reding content from class path");
}
// Find which one is ICF connector
while (en.hasMoreElements()) {
URL u = en.nextElement();
Properties prop = new Properties();
LOGGER.trace("Scan classloader resource: " + u.toString());
try {
// read content of META-INF/MANIFEST.MF
InputStream is = u.openStream();
// skip if unreadable
if (is == null) {
continue;
}
// Convert to properties
prop.load(is);
} catch (IOException ex) {
LOGGER.trace("Unable load: " + u + " [" + ex.getMessage() + "]");
}
if (null != prop.get("ConnectorBundle-Name")) {
LOGGER.info("Discovered icf bundle on CLASSPATH: " + prop.get("ConnectorBundle-Name") + " version: "
+ prop.get("ConnectorBundle-Version"));
//hack to split MANIFEST from name
try {
URL tmp = new URL(u.getPath().split("!")[0]);
bundle.add(tmp);
} catch (MalformedURLException e) {
LOGGER.error("This never happend we hope. URL:" + u.getPath(), e);
throw new SystemException(e);
}
}
}
return bundle;
}
/**
* Scan directory for bundles only on first lval we do the scan
*
* @param path
* @return
*/
private Set<URL> scanDirectory(String path) {
// Prepare return object
Set<URL> bundle = new HashSet<URL>();
// COnvert path to object File
File dir = new File(path);
// Test if this path is single jar or need to do deep examination
if (isThisJarFileBundle(dir)) {
try {
bundle.add(dir.toURI().toURL());
} catch (MalformedURLException e) {
LOGGER.error("This never happend we hope.", e);
throw new SystemException(e);
}
return bundle;
}
// Test if it is a directory
if (!dir.isDirectory()) {
LOGGER.error("Provided Icf connector path {} is not a directory.", dir.getAbsolutePath());
}
// List directory items
File[] dirEntries = dir.listFiles();
if (null == dirEntries) {
LOGGER.warn("No bundles found in directory {}", dir.getAbsolutePath());
return bundle;
}
// test all entires for bundle
for (int i = 0; i < dirEntries.length; i++) {
if (isThisJarFileBundle(dirEntries[i])) {
try {
bundle.add(dirEntries[i].toURI().toURL());
} catch (MalformedURLException e) {
LOGGER.error("This never happend we hope.", e);
throw new SystemException(e);
}
}
}
return bundle;
}
/**
* Test if provided file is connector bundle
*
* @param file
* tested file
* @return boolean
*/
private Boolean isThisJarFileBundle(File file) {
// Startup tests
if (null == file) {
throw new IllegalArgumentException("No file is providied for bundle test.");
}
// Skip all processing if it is not a file
if (!file.isFile()) {
LOGGER.debug("This {} is not a file", file.getAbsolutePath());
return false;
}
Properties prop = new Properties();
JarFile jar = null;
// Open jar file
try {
jar = new JarFile(file);
} catch (IOException ex) {
LOGGER.debug("Unable to read jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
return false;
}
// read jar file
InputStream is;
try {
JarEntry entry = new JarEntry("META-INF/MANIFEST.MF");
is = jar.getInputStream(entry);
} catch (IOException ex) {
LOGGER.debug("Unable to fine MANIFEST.MF in jar file: " + file.getAbsolutePath() + " [" + ex.getMessage()
+ "]");
return false;
}
// Parse jar file
try {
prop.load(is);
} catch (IOException ex) {
LOGGER.debug("Unable to parse jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
return false;
}
// Test if it is a connector
if (null != prop.get("ConnectorBundle-Name")) {
LOGGER.info("Discovered icf bundle in JAR: " + prop.get("ConnectorBundle-Name") + " version: "
+ prop.get("ConnectorBundle-Version"));
return true;
}
LOGGER.debug("Provided file {} is not iCF bundle jar", file.getAbsolutePath());
return false;
}
/**
* Get contect informations
*
* @param connectorType
* @return
* @throws ObjectNotFoundException
*/
private ConnectorInfo getConnectorInfo(ConnectorType connectorType) throws ObjectNotFoundException {
if (!ICF_FRAMEWORK_URI.equals(connectorType.getFramework())) {
throw new ObjectNotFoundException("Requested connector for framework " + connectorType.getFramework()
+ " cannot be found in framework " + ICF_FRAMEWORK_URI);
}
ConnectorKey key = getConnectorKey(connectorType);
if (connectorType.getConnectorHost() == null && connectorType.getConnectorHostRef() == null) {
// Local connector
return getLocalConnectorInfoManager().findConnectorInfo(key);
}
ConnectorHostType host = connectorType.getConnectorHost();
if (host == null) {
throw new ObjectNotFoundException(
"Attempt to use remote connector without ConnectorHostType resolved (there is only ConnectorHostRef");
}
return getRemoteConnectorInfoManager(host).findConnectorInfo(key);
}
private ConnectorKey getConnectorKey(ConnectorType connectorType) {
return new ConnectorKey(connectorType.getConnectorBundle(), connectorType.getConnectorVersion(),
connectorType.getConnectorType());
}
}
|
package edu.mit.ita.ch10;
public class LinkedStack<T> implements Stack<T> {
private final Node<T> head;
private int size;
public LinkedStack() {
head = Node.empty();
size = 0;
}
@Override
public void push(T element) {
Node<T> top = new Node<>(element);
top.next = head.next;
head.next = top;
size++;
}
@Override
public T pop() {
Node<T> top = peek0();
head.next = top.next;
size
return top.element;
}
@Override
public T peek() {
return peek0().element;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
private Node<T> peek0() {
if (isEmpty()) {
throw new IllegalStateException("Stack underflow");
}
return head.next;
}
private static class Node<T> {
final T element;
Node<T> next;
Node(T element) {
this.element = element;
}
static <T> Node<T> empty() {
return new Node<>(null);
}
}
}
|
package info.tregmine.commands;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.sql.Connection;
import java.sql.SQLException;
import static org.bukkit.ChatColor.*;
import org.bukkit.Server;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.*;
import org.bukkit.plugin.PluginManager;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.ConnectionPool;
import info.tregmine.database.DBWalletDAO;
import info.tregmine.database.DBTradeDAO;
import info.tregmine.api.math.Distance;
public class TradeCommand extends AbstractCommand implements Listener
{
String tradePre = YELLOW + "[Trade] ";
private enum TradeState {
ITEM_SELECT, BID, CONSIDER_BID;
};
private static class TradeContext
{
Inventory inventory;
TregminePlayer firstPlayer;
TregminePlayer secondPlayer;
TradeState state;
int bid;
}
private Map<TregminePlayer, TradeContext> activeTrades;
public TradeCommand(Tregmine tregmine)
{
super(tregmine, "trade");
activeTrades = new HashMap<TregminePlayer, TradeContext>();
PluginManager pluginMgm = tregmine.getServer().getPluginManager();
pluginMgm.registerEvents(this, tregmine);
}
@Override
public boolean handlePlayer(TregminePlayer player, String[] args)
{
if (args.length != 1) {
return false;
}
if (player.getChatState() != TregminePlayer.ChatState.CHAT) {
player.sendMessage(RED + "A trade is already in progress!");
return true;
}
Server server = tregmine.getServer();
String pattern = args[0];
List<TregminePlayer> candidates = tregmine.matchPlayer(pattern);
if (candidates.size() != 1) {
// TODO: error message
return true;
}
TregminePlayer target = candidates.get(0);
if (target.getChatState() != TregminePlayer.ChatState.CHAT) {
player.sendMessage(RED + target.getName() + "is in a trade!");
return true;
}
if (target.getId() == player.getId()) {
player.sendMessage(RED + "You cannot trade with yourself!");
return true;
}
double distance = Distance.calc2d(player.getLocation(), target.getLocation());
if (distance > 100) {
player.sendMessage(RED + "You can only trade with people less than " +
"100 blocks away.");
return true;
}
Inventory inv = server.createInventory(null, InventoryType.CHEST);
player.openInventory(inv);
TradeContext ctx = new TradeContext();
ctx.inventory = inv;
ctx.firstPlayer = player;
ctx.secondPlayer = target;
ctx.state = TradeState.ITEM_SELECT;
activeTrades.put(player, ctx);
activeTrades.put(target, ctx);
player.setChatState(TregminePlayer.ChatState.TRADE);
target.setChatState(TregminePlayer.ChatState.TRADE);
player.sendMessage(YELLOW + "[Trade] You are now trading with "
+ target.getChatName() + YELLOW + ". What do you want "
+ "to offer?");
target.sendMessage(YELLOW + "[Trade] You are now in a trade with "
+ player.getChatName() + YELLOW + ". To exit, type \"quit\".");
return true;
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event)
{
TregminePlayer player = tregmine.getPlayer((Player) event.getPlayer());
TradeContext ctx = activeTrades.get(player);
if (ctx == null) {
return;
}
TregminePlayer target = ctx.secondPlayer;
target.sendMessage(tradePre + player.getChatName() + " "
+ YELLOW + " is offering: ");
player.sendMessage("[Trade] You are offering: ");
ItemStack[] contents = ctx.inventory.getContents();
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
Material material = stack.getType();
int amount = stack.getAmount();
target.sendMessage(tradePre + amount + " "
+ material.toString());
player.sendMessage(tradePre + amount + " "
+ material.toString());
}
target.sendMessage(YELLOW
+ "[Trade] To make a bid, type \"bid <tregs>\". "
+ "For example: bid 1000");
player.sendMessage(YELLOW + "[Trade] Waiting for "
+ target.getChatName() + YELLOW
+ " to make a bid. Type \"change\" to modify " + "your offer.");
ctx.state = TradeState.BID;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event)
{
TregminePlayer player = tregmine.getPlayer(event.getPlayer());
if (player.getChatState() != TregminePlayer.ChatState.TRADE) {
return;
}
event.setCancelled(true);
TradeContext ctx = activeTrades.get(player);
if (ctx == null) {
return;
}
TregminePlayer first = ctx.firstPlayer;
TregminePlayer second = ctx.secondPlayer;
String text = event.getMessage();
String[] args = text.split(" ");
Tregmine.LOGGER.info("[TRADE " + first.getName() + ":" + second.getName() +
"] <" + player.getName() + "> " + text);
//Tregmine.LOGGER.info("state: " + ctx.state);
if ("quit".equals(args[0]) && args.length == 1) {
first.setChatState(TregminePlayer.ChatState.CHAT);
second.setChatState(TregminePlayer.ChatState.CHAT);
activeTrades.remove(first);
activeTrades.remove(second);
if (ctx.state == TradeState.ITEM_SELECT) {
first.closeInventory();
}
// Restore contents to player inventory
ItemStack[] contents = ctx.inventory.getContents();
Inventory firstInv = first.getInventory();
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
firstInv.addItem(stack);
}
first.sendMessage(YELLOW + "[Trade] Trade ended.");
second.sendMessage(YELLOW + "[Trade] Trade ended.");
}
else if ("bid".equalsIgnoreCase(args[0]) && args.length == 2) {
if (second != player) {
player.sendMessage(RED + "[Trade] You can't make a bid!");
return;
}
if (ctx.state != TradeState.BID) {
player.sendMessage(RED
+ "[Trade] You can't make a bid right now.");
return;
}
int amount = 0;
try {
amount = Integer.parseInt(args[1]);
if (amount < 0) {
player.sendMessage(RED
+ "[Trade] You have to bid an integer "
+ "number of tregs.");
return;
}
} catch (NumberFormatException e) {
player.sendMessage(RED + "[Trade] You have to bid an integer "
+ "number of tregs.");
return;
}
Connection conn = null;
try {
conn = ConnectionPool.getConnection();
DBWalletDAO walletDAO = new DBWalletDAO(conn);
long balance = walletDAO.balance(second);
if (amount > balance) {
player.sendMessage(RED + "[Trade] You only have " + balance
+ " tregs!");
return;
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
first.sendMessage(tradePre + second.getChatName() + YELLOW
+ " bid " + amount + " tregs. Type \"accept\" to "
+ "proceed with the trade. Type \"change\" to modify "
+ "your offer. Type \"quit\" to stop trading.");
second.sendMessage(YELLOW + "[Trade] You bid " + amount + " tregs.");
ctx.bid = amount;
ctx.state = TradeState.CONSIDER_BID;
}
else if ("change".equalsIgnoreCase(args[0]) && args.length == 1) {
if (first != player) {
player.sendMessage(RED + "[Trade] You can't change the offer!");
return;
}
player.openInventory(ctx.inventory);
ctx.state = TradeState.ITEM_SELECT;
}
else if ("accept".equals(args[0]) && args.length == 1) {
if (first != player) {
player.sendMessage(RED + "[Trade] You can't accept an offer!");
return;
}
ItemStack[] contents = ctx.inventory.getContents();
int t = 0;
for (ItemStack tis : contents) {
if (tis == null) {
continue;
}
t++;
}
int p = 0;
Inventory secondInv = second.getInventory();
for (ItemStack pis : secondInv.getContents()) {
if (pis != null) {
continue;
}
p++;
}
if (p < t) {
int diff = t - p;
first.sendMessage(tradePre + second.getChatName() + YELLOW +
" doesn't have enough inventory space, please wait a " +
"minute and try again :)");
second.sendMessage(tradePre + "You need to remove " + diff +
" item stack(s) from your inventory to be able to recieve " +
"the items!");
return;
}
// Withdraw ctx.bid tregs from second players wallet
// Add ctx.bid tregs from first players wallet
Connection conn = null;
try {
conn = ConnectionPool.getConnection();
DBWalletDAO walletDAO = new DBWalletDAO(conn);
DBTradeDAO tradeDAO = new DBTradeDAO(conn);
if (walletDAO.take(second, ctx.bid)) {
walletDAO.add(first, ctx.bid);
walletDAO.insertTransaction(second.getId(), first.getId(),
ctx.bid);
int tradeId =
tradeDAO.insertTrade(first.getId(), second.getId(),
ctx.bid);
tradeDAO.insertStacks(tradeId, contents);
first.sendMessage(tradePre + ctx.bid
+ " tregs was " + "added to your wallet!");
second.sendMessage(tradePre + ctx.bid
+ " tregs was " + "withdrawn to your wallet!");
}
else {
first.sendMessage(RED + "[Trade] Failed to withdraw "
+ ctx.bid + " from the wallet of "
+ second.getChatName() + "!");
return;
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
// Move items to second players inventory
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
secondInv.addItem(stack);
}
// Finalize
first.setChatState(TregminePlayer.ChatState.CHAT);
second.setChatState(TregminePlayer.ChatState.CHAT);
activeTrades.remove(first);
activeTrades.remove(second);
first.giveExp(5);
second.giveExp(5);
}
else {
first.sendMessage(tradePre + WHITE + "<"
+ player.getChatName() + WHITE + "> " + text);
second.sendMessage(tradePre + WHITE + "<"
+ player.getChatName() + WHITE + "> " + text);
}
}
}
|
package gov.adlnet.xapi.model;
import java.util.HashMap;
import java.util.Map.Entry;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class Result {
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
public Boolean isSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Boolean isCompletion() {
return completion;
}
public void setCompletion(Boolean completion) {
this.completion = completion;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public HashMap<String, String> getExtensions() {
return extensions;
}
public void setExtensions(HashMap<String, String> extensions) {
this.extensions = extensions;
}
public JsonElement serialize() {
JsonObject obj = new JsonObject();
if (this.success != null) {
obj.addProperty("success", this.success);
}
if (this.completion != null) {
obj.addProperty("completion", this.completion);
}
if (this.response != null) {
obj.addProperty("response", this.response);
}
if (this.duration != null) {
obj.addProperty("duration", this.duration);
}
if (this.extensions != null) {
JsonObject extensionsObj = new JsonObject();
obj.add("extensions", extensionsObj);
for (Entry<String, String> item : extensions.entrySet()) {
extensionsObj.addProperty(item.getKey(), item.getValue());
}
}
if (this.score != null) {
obj.add("score", this.score.serialize());
}
return obj;
}
private Score score;
private Boolean success;
private Boolean completion;
private String response;
private String duration;
private HashMap<String, String> extensions;
}
|
package it.shortener;
import redis.clients.jedis.Jedis;
public class RedisConnection {
public static void main(String[]args) throws Exception {
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.connect();
System.out.println("Connection to server sucessfully");
System.out.println("Server is running: "+jedis.ping());
jedis.set("tutorial-name", "Redis tutorial");
// Get the stored data and print it
System.out.println("Stored string in redis:: "+ jedis.get("tutorial-name"));
jedis.close();
}
}
|
package javax.time.calendar;
import java.io.Serializable;
import javax.time.calendar.field.DayOfMonth;
import javax.time.calendar.field.MonthOfYear;
import javax.time.calendar.field.Year;
import javax.time.calendar.format.FlexiDateTime;
import javax.time.period.Periods;
/**
* A month-day without a time zone in the ISO-8601 calendar system,
* such as '3rd December'.
* <p>
* MonthDay is an immutable calendrical that represents a month-day combination.
* This class does not store or represent a year, time or time zone.
* Thus, for example, the value "2nd October" can be stored in a MonthDay.
* <p>
* A MonthDay does not posses a year, thus the 29th of February is considered valid.
* <p>
* Static factory methods allow you to constuct instances.
* <p>
* MonthDay is thread-safe and immutable.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public final class MonthDay
implements Calendrical, Comparable<MonthDay>, Serializable, DateAdjustor, DateMatcher {
/**
* A serialization identifier for this class.
*/
private static final long serialVersionUID = -254395108L;
/**
* A sample year that can be used to seed calculations.
* This is a leap year to enable the 29th of February.
*/
private static final Year SAMPLE_YEAR = Year.isoYear(2000);
/**
* The month of year, not null.
*/
private final MonthOfYear month;
/**
* The day of month, not null.
*/
private final DayOfMonth day;
public static MonthDay monthDay(MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
if (monthOfYear == null) {
throw new NullPointerException("MonthOfYear must not be null");
}
if (dayOfMonth == null) {
throw new NullPointerException("DayOfMonth must not be null");
}
if (dayOfMonth.isValid(SAMPLE_YEAR, monthOfYear) == false) {
throw new IllegalCalendarFieldValueException("DayOfMonth", dayOfMonth.getValue(), 1, monthOfYear.lengthInDays(SAMPLE_YEAR));
}
return new MonthDay(monthOfYear, dayOfMonth);
}
public static MonthDay monthDay(MonthOfYear monthOfYear, int dayOfMonth) {
return monthDay(monthOfYear, DayOfMonth.dayOfMonth(dayOfMonth));
}
public static MonthDay monthDay(int monthOfYear, int dayOfMonth) {
return monthDay(MonthOfYear.monthOfYear(monthOfYear), DayOfMonth.dayOfMonth(dayOfMonth));
}
/**
* Constructor, previously validated.
*
* @param monthOfYear the month of year to represent, not null
* @param dayOfMonth the day of month to represent, valid for month, not null
*/
private MonthDay(MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
this.month = monthOfYear;
this.day = dayOfMonth;
}
/**
* Returns a copy of this month-day with the new month and day, checking
* to see if a new object is in fact required.
*
* @param newMonth the month of year to represent, from 1 (January) to 12 (December)
* @param newDay the day of month to represent, from 1 to 31
* @return the month-day, never null
*/
private MonthDay withMonthDay(MonthOfYear newMonth, DayOfMonth newDay) {
if (month == newMonth && day == newDay) {
return this;
}
return new MonthDay(newMonth, newDay);
}
/**
* Checks if the specified calendar field is supported.
* <p>
* This method queries whether this <code>MonthDay</code> can
* be queried using the specified calendar field.
*
* @param field the field to query, not null
* @return true if the field is supported
*/
public boolean isSupported(DateTimeFieldRule field) {
return field.isSupported(Periods.DAYS, Periods.YEARS);
}
/**
* Gets the value of the specified calendar field.
* <p>
* This method queries the value of the specified calendar field.
* If the calendar field is not supported then an exception is thrown.
*
* @param field the field to query, not null
* @return the value for the field
* @throws UnsupportedCalendarFieldException if the field is not supported
*/
public int get(DateTimeFieldRule field) {
return field.getValue(toFlexiDateTime());
}
/**
* Gets the month of year field.
* <p>
* This method provides access to an object representing the month field.
* This can be used to access the {@link MonthOfYear#getValue() int value}.
*
* @return the month of year, never null
*/
public MonthOfYear getMonthOfYear() {
return month;
}
/**
* Gets the day of month field.
* <p>
* This method provides access to an object representing the day of month field.
* This can be used to access the {@link DayOfMonth#getValue() int value}.
*
* @return the day of month, never null
*/
public DayOfMonth getDayOfMonth() {
return day;
}
/**
* Returns a copy of this MonthDay with the month of year altered.
* <p>
* If the day of month is invalid for the specified month, the day will
* be adjusted to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthOfYear the month of year to represent, not null
* @return a new updated MonthDay, never null
*/
public MonthDay with(MonthOfYear monthOfYear) {
if (day.isValid(SAMPLE_YEAR, monthOfYear) == false) {
return withMonthDay(monthOfYear, monthOfYear.getLastDayOfMonth(SAMPLE_YEAR));
}
return withMonthDay(monthOfYear, day);
}
public MonthDay with(DayOfMonth dayOfMonth) {
if (dayOfMonth.isValid(SAMPLE_YEAR, month) == false) {
throw new IllegalCalendarFieldValueException("Day of month cannot be changed to " +
dayOfMonth + " for the month " + month);
}
return withMonthDay(month, dayOfMonth);
}
public MonthDay withMonthOfYear(int monthOfYear) {
return with(MonthOfYear.monthOfYear(monthOfYear));
}
public MonthDay withDayOfMonth(int dayOfMonth) {
return with(DayOfMonth.dayOfMonth(dayOfMonth));
}
/**
* Returns a copy of this MonthDay rolling the month of year field by the
* specified number of months.
* <p>
* This method will add the specified number of months to the month-day,
* rolling from December back to January if necessary.
* <p>
* If the day of month is invalid for the specified month in the result,
* the day will be adjusted to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param months the months to roll by, positive or negative
* @return a new updated MonthDay, never null
*/
public MonthDay rollMonthOfYear(int months) {
if (months == 0) {
return this;
}
int newMonth0 = (months % 12) + (month.getValue() - 1);
newMonth0 = (newMonth0 + 12) % 12;
return withMonthOfYear(++newMonth0);
}
/**
* Returns a copy of this MonthDay rolling the day of month field by the
* specified number of days.
* <p>
* This method will add the specified number of days to the month-day,
* rolling from last day of month to the first if necessary.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param days the days to roll by, positive or negative
* @return a new updated MonthDay, never null
*/
public MonthDay rollDayOfMonth(int days) {
int monthLength = month.lengthInDays(SAMPLE_YEAR);
if (days == 0) {
return this;
}
int newDOM0 = (days % monthLength) + (day.getValue() - 1);
newDOM0 = (newDOM0 + monthLength) % monthLength;
return withMonthOfYear(++newDOM0);
}
/**
* Adjusts a date to have the value of this month-day, returning a new date.
* <p>
* If the day of month is invalid for the new year then an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param date the date to be adjusted, not null
* @return the adjusted date, never null
*/
public LocalDate adjustDate(LocalDate date) {
return adjustDate(date, DateResolvers.strict());
}
public LocalDate adjustDate(LocalDate date, DateResolver resolver) {
if (month == date.getMonthOfYear() && day == date.getDayOfMonth()) {
return date;
}
return resolver.resolveDate(date.getYear(), month, day);
}
/**
* Checks if the month-day represented by this object matches the input date.
*
* @param date the date to match, not null
* @return true if the date matches, false otherwise
*/
public boolean matchesDate(LocalDate date) {
return month == date.getMonthOfYear() && day == date.getDayOfMonth();
}
/**
* Converts this date to a <code>FlexiDateTime</code>.
*
* @return the flexible date-time representation for this instance, never null
*/
public FlexiDateTime toFlexiDateTime() {
return new FlexiDateTime(MonthOfYear.RULE, month.getValue(), DayOfMonth.RULE, day.getValue());
}
/**
* Compares this month-day to another month-day.
*
* @param other the other month-day to compare to, not null
* @return the comparator value, negative if less, postive if greater
* @throws NullPointerException if <code>other</code> is null
*/
public int compareTo(MonthDay other) {
int cmp = month.compareTo(other.month);
if (cmp == 0) {
cmp = day.compareTo(other.day);
}
return cmp;
}
/**
* Is this month-day after the specified month-day.
*
* @param other the other month-day to compare to, not null
* @return true if this is after the specified month-day
* @throws NullPointerException if <code>other</code> is null
*/
public boolean isAfter(MonthDay other) {
return compareTo(other) > 0;
}
/**
* Is this month-day before the specified month-day.
*
* @param other the other month-day to compare to, not null
* @return true if this point is before the specified month-day
* @throws NullPointerException if <code>other</code> is null
*/
public boolean isBefore(MonthDay other) {
return compareTo(other) < 0;
}
/**
* Is this month-day equal to the specified month-day.
*
* @param other the other month-day to compare to, null returns false
* @return true if this point is equal to the specified month-day
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof MonthDay) {
MonthDay otherMD = (MonthDay) other;
return month == otherMD.month && day.equals(otherMD.day);
}
return false;
}
/**
* A hashcode for this month-day.
*
* @return a suitable hashcode
*/
@Override
public int hashCode() {
return (month.getValue() << 6) + day.getValue();
}
/**
* Outputs the month-day as a <code>String</code>.
* <p>
* The output will be in the format '--MM-dd':
*
* @return the string form of the month-day
*/
@Override
public String toString() {
int monthValue = month.getValue();
int dayValue = day.getValue();
return new StringBuilder(10).append("
.append(monthValue < 10 ? "-0" : "-").append(monthValue)
.append(dayValue < 10 ? "-0" : "-").append(dayValue)
.toString();
}
}
|
package kodkod.engine;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import kodkod.ast.Formula;
import kodkod.ast.Relation;
import kodkod.engine.config.ExtendedOptions;
import kodkod.instance.ElectrodProblemPrinter;
import kodkod.instance.PardinusBounds;
import kodkod.instance.TemporalInstance;
/**
* A computational engine for solving unbounded temporal relational
* satisfiability problems. Such a problem is described by a
* {@link kodkod.ast.Formula formula} in first order temporal relational logic;
* finite unbounded temporal {@link PardinusBounds bounds} on the value of each
* {@link Relation relation} constrained by the respective formula; and a set of
* {@link ExtendedOptions options}, although there are currently no
* particular options for unbounded temporal solving.
*
* <p>
* An {@link ElectrodSolver} takes as input a relational problem and produces a
* satisfying model or a {@link TemporalInstance temporal instance} of it, if
* one exists.
* </p>
*
* @author Nuno Macedo // [HASLab] unbounded temporal model finding
*
*/
public class ElectrodSolver implements UnboundedSolver<ExtendedOptions>, TemporalSolver<ExtendedOptions>, IterableSolver<PardinusBounds, ExtendedOptions> {
private final ExtendedOptions options;
/**
* Constructs a new Solver with the default options.
*
* @ensures this.options' = new Options()
*/
public ElectrodSolver() {
this.options = new ExtendedOptions();
}
/**
* Constructs a new Solver with the given options.
*
* @ensures this.options' = options
* @throws NullPointerException
* options = null
*/
public ElectrodSolver(ExtendedOptions options) {
if (options == null)
throw new NullPointerException();
this.options = options;
}
/**
* {@inheritDoc}
*/
public ExtendedOptions options() {
return options;
}
/**
* {@inheritDoc}
*/
public Solution solve(Formula formula, PardinusBounds bounds) {
try {
String electrode = ElectrodProblemPrinter.print(formula, bounds);
PrintWriter writer;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-"+bounds.hashCode());
Date date = new Date();
String file = "electrod"+dateFormat.format(date);
writer = new PrintWriter(file+".elo", "UTF-8");
writer.println(electrode);
writer.close();
String s = "./electrod -v "+file+".elo";
String[] p = { System.getenv("PATH")+":/usr/local/bin" };
InputStream is = Runtime.getRuntime().exec(s,p).getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buff = new BufferedReader (isr);
String line;
while((line = buff.readLine()) != null)
System.err.println(line);
ElectrodProblemReader rd = new ElectrodProblemReader(bounds);
TemporalInstance res = rd.read(new File(file+".xml"));
return Solution.satisfiable(new Statistics(0, 0, 0, 0, 0), res);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Solution.unsatisfiable(null, null);
}
/**
* {@inheritDoc}
*/
public void free() {
// TODO Auto-generated method stub
}
@Override
public Iterator<Solution> solveAll(Formula formula, PardinusBounds bounds) {
Solution s = solve(formula,bounds);
Set<Solution> st = new HashSet<Solution>(Arrays.asList(s));
return st.iterator();
}
}
|
package dml.runtime.matrix.io;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.io.WritableComparable;
import dml.runtime.instructions.MRInstructions.RangeBasedReIndexInstruction.IndexRange;
import dml.runtime.matrix.mapred.IndexedMatrixValue;
import dml.runtime.matrix.operators.AggregateBinaryOperator;
import dml.runtime.matrix.operators.AggregateOperator;
import dml.runtime.matrix.operators.AggregateUnaryOperator;
import dml.runtime.matrix.operators.BinaryOperator;
import dml.runtime.matrix.operators.Operator;
import dml.runtime.matrix.operators.ReorgOperator;
import dml.runtime.matrix.operators.ScalarOperator;
import dml.runtime.matrix.operators.UnaryOperator;
import dml.runtime.util.UtilFunctions;
import dml.utils.DMLRuntimeException;
import dml.utils.DMLUnsupportedOperationException;
public abstract class MatrixValue implements WritableComparable {
static public class CellIndex {
public int row;
public int column;
public CellIndex(int r, int c) {
row = r;
column = c;
}
public boolean equals(CellIndex that) {
return (this.row == that.row && this.column == that.column);
}
public boolean equals(Object that) {
if (that instanceof CellIndex)
return equals((CellIndex) that);
else
return false;
}
public int hashCode() {
return UtilFunctions.longHashFunc((row << 16) + column);
}
public void set(int r, int c) {
row = r;
column = c;
}
public String toString()
{
return "("+row+","+column+")";
}
}
public MatrixValue() {
}
public MatrixValue(int rl, int cl, boolean sp) {
}
public MatrixValue(MatrixValue that) {
this.copy(that);
}
public MatrixValue(HashMap<CellIndex, Double> map) {
}
public abstract int getNumRows();
public abstract int getNumColumns();
public abstract int getMaxRow() throws DMLRuntimeException;;
public abstract int getMaxColumn() throws DMLRuntimeException;;
public abstract void setMaxRow(int _r) throws DMLRuntimeException;
public abstract void setMaxColumn(int _c) throws DMLRuntimeException;;
public abstract boolean isInSparseFormat();
public abstract void reset();
public abstract void reset(int rl, int cl);
public abstract void reset(int rl, int cl, boolean sp);
public abstract void resetDenseWithValue(int rl, int cl, double v);
public abstract void copy(MatrixValue that);
public abstract int getNonZeros();
public abstract void setValue(int r, int c, double v);
public abstract void setValue(CellIndex index, double v);
public abstract void addValue(int r, int c, double v);
public abstract double getValue(int r, int c);
public abstract void getCellValues(Collection<Double> ret);
public abstract void getCellValues(Map<Double, Integer> ret);
/* public abstract void sparseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void denseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void sparseUnaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException;
*/
public abstract MatrixValue scalarOperations(ScalarOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void scalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue binaryOperations(BinaryOperator op, MatrixValue thatValue, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void binaryOperationsInPlace(BinaryOperator op, MatrixValue thatValue)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue reorgOperations(ReorgOperator op, MatrixValue result,
int startRow, int startColumn, int length)
throws DMLUnsupportedOperationException, DMLRuntimeException;
// tertiary where all three inputs are matrices
public abstract void tertiaryOperations(Operator op, MatrixValue that, MatrixValue that2, HashMap<CellIndex, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException;
// tertiary where first two inputs are matrices, and third input is a scalar (double)
public abstract void tertiaryOperations(Operator op, MatrixValue that, double scalar_that2, HashMap<CellIndex, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException;
// tertiary where first input is a matrix, and second and third inputs are scalars (double)
public abstract void tertiaryOperations(Operator op, double scalar_that, double scalar_that2, HashMap<CellIndex, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException;
// tertiary where first and third inputs are matrices and second is a scalar
public abstract void tertiaryOperations(Operator op, double scalarThat, MatrixValue that2, HashMap<CellIndex, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int brlen, int bclen, MatrixIndexes indexesIn) throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn, boolean inCP)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue aggregateBinaryOperations(MatrixValue m1Value, MatrixValue m2Value,
MatrixValue result, AggregateBinaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue unaryOperations(UnaryOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void unaryOperationsInPlace(UnaryOperator op) throws DMLUnsupportedOperationException, DMLRuntimeException;
/*public abstract void combineOperations(MatrixValue thatValue, CollectMultipleConvertedOutputs multipleOutputs,
Reporter reporter, DoubleWritable keyBuff, IntWritable valueBuff, Vector<Integer> outputIndexes)
throws DMLUnsupportedOperationException, DMLRuntimeException, IOException;*/
public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction,
MatrixValue newWithCorrection) throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue newWithCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract MatrixValue maskOperations(MatrixValue valueOut, IndexRange range)
throws DMLUnsupportedOperationException, DMLRuntimeException;
public abstract void slideOperations(ArrayList<IndexedMatrixValue> outlist, IndexRange range, int rowCut, int colCut,
int blockRowFactor, int blockColFactor, int boundaryRlen, int boundaryClen)
throws DMLUnsupportedOperationException, DMLRuntimeException;
protected CellIndex tempCellIndex=new CellIndex(0, 0);
protected void updateCtable(double v1, double v2, double w, HashMap<CellIndex, Double> ctableResult) throws DMLRuntimeException {
int _row, _col;
// If any of the values are NaN (i.e., missing) then
// we skip this tuple, proceed to the next tuple
if ( Double.isNaN(v1) || Double.isNaN(v2) || Double.isNaN(w) ) {
return;
}
else {
_row = (int)v1;
_col = (int)v2;
if ( _row <= 0 || _col <= 0 ) {
throw new DMLRuntimeException("Erroneous input while computing the contingency table (one of the value <= zero).");
}
CellIndex temp=new CellIndex(_row, _col);
Double oldw=ctableResult.get(temp);
if(oldw==null)
oldw=0.0;
ctableResult.put(temp, oldw+w);
}
}
}
|
package lexek.fetcher;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.client.HttpClient;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Service
public class FetcherService {
private final Logger logger = LoggerFactory.getLogger(FetcherService.class);
private final HttpClient httpClient;
private final AsyncLoadingCache<String, Mono<Map<String, String>>> cache;
private long maxBodySize = 8388608;
private long maxSupportedRedirects = 1;
private boolean handleNonStandardPorts = false;
public FetcherService() {
this.httpClient = HttpClient.create(
options -> {
options.sslSupport();
options.afterChannelInit(channel ->
//need this to handle compressed responses
channel.pipeline().addBefore("reactor.right.reactiveBridge", "decompressor", new HttpContentDecompressor())
);
}
);
this.cache = Caffeine
.<String, Mono<Map<String, String>>>newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.maximumSize(1000)
.buildAsync(url -> validateUrlAndFetch(url, 0));
}
public Mono<Map<String, String>> fetch(String url) {
if (StringUtils.isEmpty(url)) {
return Mono.just(ImmutableMap.of("error", "Url is not present"));
}
return Mono
.fromFuture(cache.get(url))
.then(Function.identity());
}
private Mono<Map<String, String>> validateUrlAndFetch(String url, int redirect) {
try {
return doFetch(new URL(url), redirect);
} catch (MalformedURLException e) {
return Mono.just(ImmutableMap.of("error", "Incorrect url"));
}
}
private Mono<Map<String, String>> doFetch(URL url, int redirectNumber) {
if (redirectNumber > maxSupportedRedirects) {
return Mono.just(ImmutableMap.of(
"error", "Too many consequent redirects"
));
}
if (!handleNonStandardPorts) {
int port = url.getPort();
if (port != -1) {
if (url.getProtocol().equals("http") && port != 80 || url.getProtocol().equals("https") && port != 443) {
return Mono.just(ImmutableMap.of(
"error", "Handling of non-standard ports is disabled"
));
}
}
}
return httpClient
.get(
url.toExternalForm(),
request -> request.failOnServerError(false).failOnClientError(false) //disable exceptions on 4xx & 5xx statuses
)
.map(ReactorRequestWrapper::new)
.then(response -> handleResponse(url, response, redirectNumber))
.timeout(Duration.of(10, ChronoUnit.SECONDS))
.retry(3)
.doOnError(throwable -> logger.warn("caught exception", throwable))
.otherwise((e) -> Mono.just(ImmutableMap.of(
"error", e.getMessage() != null ? e.getMessage() : e.getClass().toString()
)))
.cache();
}
private Mono<Map<String, String>> handleResponse(URL url, ReactorRequestWrapper response, int redirectNumber) {
int status = response.status();
if (status == 301 || status == 302) {
String location = response.headers().get(HttpHeaderNames.LOCATION);
if (location == null) {
response.dispose();
return Mono.just(ImmutableMap.of("error", "Http redirect without location header"));
}
response.dispose();
return validateUrlAndFetch(location, redirectNumber + 1);
}
if (status != 200) {
response.dispose();
return Mono.just(ImmutableMap.of("error", "Invalid response status " + status));
}
CharSequence mimeType = HttpUtil.getMimeType(response);
if (mimeType == null) {
response.dispose();
return Mono.just(ImmutableMap.of("error", "No content-type"));
}
if (!Objects.equals(mimeType, "text/html")) {
response.dispose();
return Mono.just(ImmutableMap.of(
"error", "Unsupported content-type",
"mime", mimeType.toString()
));
}
long contentLength = HttpUtil.getContentLength(response, -1);
if (contentLength > maxBodySize) {
response.dispose();
return Mono.just(ImmutableMap.of(
"error", "Content is too big",
"mime", mimeType.toString()
));
}
return readyBody(response)
.cast(String.class)
.map(Jsoup::parse)
.map(FetcherService::parseBody)
.doOnNext(result -> {
if (!result.containsKey("error")) {
result.put("hostname", url.getHost());
result.put("mime", mimeType.toString());
}
});
}
private Mono<String> readyBody(ReactorRequestWrapper response) {
Charset charset = HttpUtil.getCharset(response, StandardCharsets.UTF_8);
return Mono.using(
PooledByteBufAllocator.DEFAULT::buffer,
buffer -> response
.originalResponse()
.receiveContent()
.map((content) -> buffer.writeBytes(content.content()))
.all((ignore) -> buffer.readableBytes() < maxBodySize)
.then()
.then(() -> Mono.just(buffer.toString(charset))),
ByteBuf::release
);
}
private static Map<String, String> parseBody(Document document) {
Map<String, String> result = new HashMap<>();
for (Element element : document.head().children()) {
String tag = element.tag().getName();
switch (tag) {
case "meta": {
String property = element.attr("PROPERTY");
String content = element.attr("CONTENT");
if (property != null && content != null) {
if (property.startsWith("og:")) {
result.put(property, content);
}
}
break;
}
case "title": {
result.put("title", element.ownText());
break;
}
}
}
return result;
}
@Value("${og.maxBodySize ?: 8388608}")
public void setMaxBodySize(long maxBodySize) {
this.maxBodySize = maxBodySize;
}
@Value("${og.maxSupportedRedirects ?: 1}")
public void setMaxSupportedRedirects(long maxSupportedRedirects) {
this.maxSupportedRedirects = maxSupportedRedirects;
}
@Value("${og.handleNonStandardPorts ?: false}")
public void setHandleNonStandardPorts(boolean handleNonStandardPorts) {
this.handleNonStandardPorts = handleNonStandardPorts;
}
}
|
package net.ohloh.ohcount4j;
import java.util.ArrayList;
import java.util.List;
import net.ohloh.ohcount4j.scan.ActionScriptScanner;
import net.ohloh.ohcount4j.scan.AdaScanner;
import net.ohloh.ohcount4j.scan.AssemblyScanner;
import net.ohloh.ohcount4j.scan.AugeasScanner;
import net.ohloh.ohcount4j.scan.AutoconfScanner;
import net.ohloh.ohcount4j.scan.AutomakeScanner;
import net.ohloh.ohcount4j.scan.AwkScanner;
import net.ohloh.ohcount4j.scan.BatScanner;
import net.ohloh.ohcount4j.scan.BinaryScanner;
import net.ohloh.ohcount4j.scan.BooScanner;
import net.ohloh.ohcount4j.scan.CStyleScanner;
import net.ohloh.ohcount4j.scan.CobolScanner;
import net.ohloh.ohcount4j.scan.ColdFusionScanner;
import net.ohloh.ohcount4j.scan.DScanner;
import net.ohloh.ohcount4j.scan.EiffelScanner;
import net.ohloh.ohcount4j.scan.ErlangScanner;
import net.ohloh.ohcount4j.scan.FSharpScanner;
import net.ohloh.ohcount4j.scan.FortranFixedScanner;
import net.ohloh.ohcount4j.scan.FortranFreeScanner;
import net.ohloh.ohcount4j.scan.GenericCodeScanner;
import net.ohloh.ohcount4j.scan.HTMLScanner;
import net.ohloh.ohcount4j.scan.HaskellScanner;
import net.ohloh.ohcount4j.scan.JspScanner;
import net.ohloh.ohcount4j.scan.LispScanner;
import net.ohloh.ohcount4j.scan.LuaScanner;
import net.ohloh.ohcount4j.scan.MakeScanner;
import net.ohloh.ohcount4j.scan.MathematicaScanner;
import net.ohloh.ohcount4j.scan.MatlabScanner;
import net.ohloh.ohcount4j.scan.ModulaScanner;
import net.ohloh.ohcount4j.scan.OCamlScanner;
import net.ohloh.ohcount4j.scan.PascalScanner;
import net.ohloh.ohcount4j.scan.PerlScanner;
import net.ohloh.ohcount4j.scan.PhpScanner;
import net.ohloh.ohcount4j.scan.PrologScanner;
import net.ohloh.ohcount4j.scan.PythonScanner;
import net.ohloh.ohcount4j.scan.RebolScanner;
import net.ohloh.ohcount4j.scan.RexxScanner;
import net.ohloh.ohcount4j.scan.RubyScanner;
import net.ohloh.ohcount4j.scan.Scanner;
import net.ohloh.ohcount4j.scan.SchemeScanner;
import net.ohloh.ohcount4j.scan.ShellScanner;
import net.ohloh.ohcount4j.scan.SmalltalkScanner;
import net.ohloh.ohcount4j.scan.SqlScanner;
import net.ohloh.ohcount4j.scan.TclScanner;
import net.ohloh.ohcount4j.scan.TexScanner;
import net.ohloh.ohcount4j.scan.VimScriptScanner;
import net.ohloh.ohcount4j.scan.VisualBasicScanner;
import net.ohloh.ohcount4j.scan.XmlScanner;
public enum Language implements LanguageCategory {
/*
* All languages must be defined here.
*
* Each language must declare three mandatory properties:
*
* - The language's official display name (niceName)
* - The category of the language, one of BUILD, LOGIC, MARKUP, UNKNOWN
* - A Scanner subclass capable of parsing this language
*/
ACTIONSCRIPT("ActionScript", LOGIC, ActionScriptScanner.class),
ADA("Ada", LOGIC, AdaScanner.class),
ASPX_CSHARP("ASP.NET (C#)", LOGIC, GenericCodeScanner.class), // TODO.
ASPX_VB("ASP.NET (VB)", LOGIC, GenericCodeScanner.class), // TODO.
ASSEMBLY("Assembly", LOGIC, AssemblyScanner.class),
AUGEAS("Augeas", LOGIC, AugeasScanner.class),
AUTOCONF("Autoconf", BUILD, AutoconfScanner.class),
AUTOMAKE("Automake", BUILD, AutomakeScanner.class),
AWK("Awk", LOGIC, AwkScanner.class),
BAT("Windows Batch", LOGIC, BatScanner.class),
BINARY("Binary", LOGIC, BinaryScanner.class),
BOO("Boo", LOGIC, BooScanner.class),
C("C", LOGIC, CStyleScanner.class),
CLASSIC_BASIC("Classic BASIC", LOGIC, GenericCodeScanner.class), // TODO.
COBOL("COBOL", LOGIC, CobolScanner.class),
COLDFUSION("ColdFusion", MARKUP, ColdFusionScanner.class),
CPP("C++", LOGIC, CStyleScanner.class),
CSHARP("C#", LOGIC, CStyleScanner.class),
CSS("CSS", MARKUP, CStyleScanner.class),
D("D", LOGIC, DScanner.class),
ECMASCRIPT("ECMAScript", LOGIC, CStyleScanner.class),
EIFFEL("Eiffel", LOGIC, EiffelScanner.class),
ERLANG("Erlang", LOGIC, ErlangScanner.class),
FORTRANFIXED("Fortran (Fixed-Format)", LOGIC, FortranFixedScanner.class),
FORTRANFREE("Fortran (Free-Format)", LOGIC, FortranFreeScanner.class),
FSHARP("F#", LOGIC, FSharpScanner.class),
GOLANG("Go", LOGIC, CStyleScanner.class),
GROOVY("Groovy", LOGIC, CStyleScanner.class),
HTML("HTML", MARKUP, HTMLScanner.class),
HASKELL("Haskell", LOGIC, HaskellScanner.class),
JAVA("Java", LOGIC, CStyleScanner.class),
JAVASCRIPT("JavaScript", LOGIC, CStyleScanner.class),
LIMBO("Limbo", LOGIC, CStyleScanner.class),
JSP("JSP", LOGIC, JspScanner.class),
LISP("Lisp", LOGIC, LispScanner.class),
LUA("Lua", LOGIC, LuaScanner.class),
MAKE("Make", BUILD, MakeScanner.class),
MATHEMATICA("Mathematica", LOGIC, MathematicaScanner.class),
MATLAB("Matlab", LOGIC, MatlabScanner.class),
MODULA2("Modula 2", LOGIC, ModulaScanner.class),
MODULA3("Modula 3", LOGIC, ModulaScanner.class),
OBJECTIVE_C("Objective-C", LOGIC, CStyleScanner.class),
OCAML("OCaml", LOGIC, OCamlScanner.class),
OCTAVE("Octave", LOGIC, MatlabScanner.class), // TODO. Octave also supports # comments
PASCAL("Pascal", LOGIC, PascalScanner.class),
PERL("Perl", LOGIC, PerlScanner.class),
PHP("Php", LOGIC, PhpScanner.class),
PUPPET("Puppet", LOGIC, GenericCodeScanner.class), // TODO.
PVWAVE("IDL/PV-WAVE/GDL", LOGIC, GenericCodeScanner.class), // TODO.
PROLOG("Prolog", LOGIC, PrologScanner.class),
PYTHON("Python", LOGIC, PythonScanner.class),
R("R", LOGIC, GenericCodeScanner.class), // TODO.
REBOL("REBOL", LOGIC, RebolScanner.class),
REXX("Rexx", LOGIC, RexxScanner.class),
RUBY("Ruby", LOGIC, RubyScanner.class),
SCHEME("Scheme", LOGIC, SchemeScanner.class),
SHELL("Shell", LOGIC, ShellScanner.class),
SMALLTALK("Smalltalk", LOGIC, SmalltalkScanner.class),
SQL("SQL", LOGIC, SqlScanner.class),
STRUCTURED_BASIC("Structured Basic", LOGIC, VisualBasicScanner.class),
TCL("Tcl", LOGIC, TclScanner.class),
TEX("TeX/LaTeX", MARKUP, TexScanner.class),
UNKNOWN("Unknown", CATEGORY_UNKNOWN, GenericCodeScanner.class),
VB("VisualBasic", LOGIC, VisualBasicScanner.class),
VBSCRIPT("VBScript", LOGIC, VisualBasicScanner.class),
VIMSCRIPT("Vimscript", LOGIC, VimScriptScanner.class),
XML("XML", MARKUP, XmlScanner.class),
XMLSCHEMA("XML Schema", MARKUP, XmlScanner.class),
XSLT("XSL Transformation", MARKUP, XmlScanner.class);
/*
* Optional properties of languages are declared here.
*
* At a minimum, a language should define one or more file
* extensions or filenames associated with the language.
*
* You may also declare additional names (beyond the uname
* and niceName) by which the language might be known.
* These aliases can be matched against things like Emacs
* mode headers or shebang directives.
*/
static {
ACTIONSCRIPT.extension("as");
ADA.extensions("ada", "adb");
ASPX_CSHARP.extension("aspx");
ASPX_VB.extension("aspx");
ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80");
AUGEAS.extensions("aug");
AUTOCONF.extensions("autoconf", "ac", "m4"); // m4 (unix macro processor)
AUTOMAKE.extensions("am");
AWK.extension("awk");
BAT.extension("bat");
BINARY.extensions("inc", "st");
BOO.extension("boo");
C.extensions("c", "h");
CLASSIC_BASIC.extensions("b", "bas");
COBOL.extension("cbl");
COLDFUSION.extensions("cfc", "cfm");
CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx");
CSHARP.aliases("C#", "cs").extension("cs");
CSS.extension("css");
D.extension("d");
ECMASCRIPT.extension("es");
EIFFEL.extension("e");
ERLANG.extension("erl");
FORTRANFIXED.extensions("i", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FORTRANFREE.extensions("i90", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FSHARP.extension("fs");
GOLANG.extensions("go");
GROOVY.extension("groovy");
HTML.extensions("htm", "html");
HASKELL.extensions("hs", "lhs");
JAVA.extension("java");
JAVASCRIPT.alias("js").extension("js");
JSP.extension("jsp");
LIMBO.extensions("b", "m");
LUA.extension("lua");
MAKE.filename("Makefile").extensions("mk", "pro");
MATHEMATICA.extensions("nb", "nbs");
MODULA2.extensions("mod", "m2");
MODULA3.extensions("m3", "i3");
OBJECTIVE_C.extensions("m", "h");
OCAML.extensions("ml", "mli");
OCTAVE.extensions("m", "octave");
PASCAL.extensions("pas", "pp");
PERL.extensions("pl", "pm");
PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps");
PVWAVE.extension("pro");
PROLOG.extension("pl");
PUPPET.extension("pp");
PYTHON.extension("py");
R.extension("r");
REBOL.extensions("r", "r3", "reb", "rebol");
REXX.extensions("cmd", "exec", "rexx");
RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile");
SCHEME.extensions("scm", "ss");
SHELL.extensions("bash", "sh");
SMALLTALK.extension("st");
SQL.extension("sql");
STRUCTURED_BASIC.extensions("b", "bas", "bi");
TCL.extension("tcl");
TEX.extension("tex");
VB.extensions("bas", "frm", "frx", "vb", "vba");
VBSCRIPT.extensions("vbs", "vbe");
VIMSCRIPT.extension("vim").aliases("Vim Script", "VimL");
XML.extensions("asx", "csproj", "xml", "mxml");
XMLSCHEMA.extension("xsd");
XSLT.extensions("xsl", "xslt");
}
private final String niceName;
private final String category;
private final Class<? extends Scanner> scannerClass;
private final List<String> extensions;
private final List<String> filenames;
private final List<String> aliases;
Language(String niceName, String category, Class<? extends Scanner> scannerClass) {
this.niceName = niceName;
this.category = category;
this.scannerClass = scannerClass;
extensions = new ArrayList<String>();
filenames = new ArrayList<String>();
aliases = new ArrayList<String>();
}
public String uname() {
return toString().toLowerCase();
}
public String niceName() {
return niceName;
}
public String category() {
return category;
}
public Class<? extends Scanner> scannerClass() {
return scannerClass;
}
public Scanner makeScanner() {
try {
Scanner scanner = scannerClass.newInstance();
scanner.setDefaultLanguage(this);
return scanner;
} catch (InstantiationException e) {
throw new OhcountException(e);
} catch (IllegalAccessException e) {
throw new OhcountException(e);
}
}
private Language extension(String ext) {
extensions.add(ext);
return this;
}
private Language extensions(String... exts) {
for (String ext : exts) {
extension(ext);
}
return this;
}
public List<String> getExtensions() {
return new ArrayList<String>(extensions);
}
private Language filename(String filename) {
filenames.add(filename);
return this;
}
private Language filenames(String... filenames) {
for (String filename : filenames) {
filename(filename);
}
return this;
}
public List<String> getFilenames() {
return new ArrayList<String>(filenames);
}
private Language alias(String alias) {
aliases.add(alias);
return this;
}
private Language aliases(String... aliases) {
for (String alias : aliases) {
alias(alias);
}
return this;
}
public List<String> getAliases() {
return new ArrayList<String>(aliases);
}
}
|
package openmods.liquids;
import java.util.*;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.*;
import openmods.Log;
import openmods.OpenMods;
import openmods.utils.BlockUtils;
import openmods.utils.Coord;
import openmods.utils.DirUtils;
import com.google.common.collect.Lists;
public class GenericTank extends FluidTank {
private List<ForgeDirection> surroundingTanks = Lists.newArrayList();
private long lastUpdate = 0;
private final IFluidFilter filter;
public interface IFluidFilter {
public boolean canAcceptFluid(FluidStack stack);
}
private static final IFluidFilter NO_RESTRICTIONS = new IFluidFilter() {
@Override
public boolean canAcceptFluid(FluidStack stack) {
return true;
}
};
private static IFluidFilter filter(final FluidStack... acceptableFluids) {
if (acceptableFluids.length == 0) return NO_RESTRICTIONS;
return new IFluidFilter() {
@Override
public boolean canAcceptFluid(FluidStack stack) {
for (FluidStack acceptableFluid : acceptableFluids)
if (acceptableFluid.isFluidEqual(stack)) return true;
return false;
}
};
}
public GenericTank(int capacity, FluidStack... acceptableFluids) {
super(capacity);
this.filter = filter(acceptableFluids);
}
private static boolean isNeighbourTank(World world, Coord coord, ForgeDirection dir) {
TileEntity tile = BlockUtils.getTileInDirection(world, coord, dir);
return tile instanceof IFluidHandler;
}
private static Set<ForgeDirection> getSurroundingTanks(World world, Coord coord, Set<ForgeDirection> sides) {
EnumSet<ForgeDirection> result = EnumSet.noneOf(ForgeDirection.class);
if (sides == null) sides = DirUtils.VALID_DIRECTIONS;
for (ForgeDirection dir : sides)
if (isNeighbourTank(world, coord, dir)) result.add(dir);
return result;
}
public FluidStack drain(FluidStack resource, boolean doDrain) {
if (resource == null ||
fluid == null ||
fluid.isFluidEqual(resource)) return null;
return drain(resource.amount, doDrain);
}
public int getSpace() {
return getCapacity() - getFluidAmount();
}
@Override
public int fill(FluidStack resource, boolean doFill) {
if (resource == null || !filter.canAcceptFluid(resource)) return 0;
return super.fill(resource, doFill);
}
private void periodicUpdateNeighbours(World world, Coord coord, Set<ForgeDirection> sides) {
long currentTime = OpenMods.proxy.getTicks(world);
if (currentTime - lastUpdate > 10) {
surroundingTanks = Lists.newArrayList(getSurroundingTanks(world, coord, sides));
lastUpdate = currentTime;
}
}
private static int tryFillNeighbour(FluidStack drainedFluid, ForgeDirection side, TileEntity otherTank) {
final FluidStack toFill = drainedFluid.copy();
final ForgeDirection fillSide = side.getOpposite();
if (otherTank instanceof IFluidHandler) return ((IFluidHandler)otherTank).fill(fillSide, toFill, true);
return 0;
}
public void distributeToSides(int amountPerTick, World world, Coord coord, Set<ForgeDirection> sides) {
if (world == null) return;
if (getFluidAmount() <= 0) return;
periodicUpdateNeighbours(world, coord, sides);
if (surroundingTanks.isEmpty()) return;
FluidStack drainedFluid = drain(amountPerTick, false);
if (drainedFluid != null && drainedFluid.amount > 0) {
int startingAmount = drainedFluid.amount;
Collections.shuffle(surroundingTanks);
for (ForgeDirection side : surroundingTanks) {
if (drainedFluid.amount <= 0) break;
TileEntity otherTank = BlockUtils.getTileInDirection(world, coord, side);
if (otherTank != null) drainedFluid.amount -= tryFillNeighbour(drainedFluid, side, otherTank);
}
// return any remainder
int distributed = startingAmount - drainedFluid.amount;
if (distributed > 0) drain(distributed, true);
}
}
public void fillFromSides(int maxAmount, World world, Coord coord) {
fillFromSides(maxAmount, world, coord, null);
}
public void fillFromSides(int maxAmount, World world, Coord coord, Set<ForgeDirection> sides) {
if (world == null) return;
int toDrain = Math.min(maxAmount, getSpace());
if (toDrain <= 0) return;
periodicUpdateNeighbours(world, coord, sides);
if (surroundingTanks.isEmpty()) return;
Collections.shuffle(surroundingTanks);
MAIN: for (ForgeDirection side : surroundingTanks) {
if (toDrain <= 0) break;
TileEntity otherTank = BlockUtils.getTileInDirection(world, coord, side);
if (otherTank instanceof IFluidHandler) {
final ForgeDirection drainSide = side.getOpposite();
final IFluidHandler handler = (IFluidHandler)otherTank;
final FluidTankInfo[] infos = handler.getTankInfo(drainSide);
if (infos == null) {
/* Log.debug("Tank %s @ (%d,%d,%d) returned null tank info. Nasty.",
otherTank.getClass(), otherTank.xCoord, otherTank.yCoord, otherTank.zCoord);
*/// For the moment, mute this output until MinecraftForge#2085 concludes.
continue;
}
for (FluidTankInfo info : infos) {
if (filter.canAcceptFluid(info.fluid)) {
FluidStack stack = info.fluid.copy();
stack.amount = toDrain;
FluidStack drained = handler.drain(drainSide, stack, true);
if (drained != null) {
fill(drained, true);
toDrain -= drained.amount;
}
if (toDrain <= 0) break MAIN;
}
}
}
}
}
}
|
package de.ptb.epics.eve.data.scandescription.updater.patches;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import de.ptb.epics.eve.data.scandescription.updater.AbstractModification;
import de.ptb.epics.eve.data.scandescription.updater.Modification;
import de.ptb.epics.eve.data.scandescription.updater.Patch;
import de.ptb.epics.eve.util.data.Version;
import static de.ptb.epics.eve.util.xml.XMLUtil.*;
/**
* Patches SCML v4.0 to v5.0 doing the following:
*
* <ul>
* <li>increment version to 5.0-</li>
* <li>introduces a standard tag (channel mode) and moves specific elements to it as follows:
* <ul>
* <li>schema definition changes from:
*
* <pre>
* <complexType name="smchannel">
* <sequence>
* <element name="channelid" type="tns:identifier"></element>
* <element name="averagecount" type="nonNegativeInteger" minOccurs="0"></element>
* <element name="maxdeviation" type="double" minOccurs="0"></element>
* <element name="minimum" type="double" minOccurs="0"></element>
* <element name="maxattempts" type="nonNegativeInteger" minOccurs="0"></element>
* <element name="normalize_id" type="tns:identifier" minOccurs="0"></element>
* <element name="sendreadyevent" type="boolean" minOccurs="0"></element>
* <element name="redoevent" type="tns:smevent" minOccurs="0" maxOccurs="unbounded"></element>
* <element name="deferredtrigger" type="boolean" minOccurs="0"></element>
* </sequence>
* </complexType>
* </pre>
*
* to:
*
* <pre>
* <complexType name="smchannel">
* <sequence>
* <element name="channelid" type="tns:identifier"></element>
* <element name="normalize_id" type="tns:identifier" minOccurs="0"></element>
* <choice>
* <element name="standard" type="tns:standardchannel"></element>
* <element name="interval" type="tns:intervalchannel"></element>
* </choice>
* </sequence>
* </complexType>
* <complexType name="standardchannel">
* <sequence>
* <element name="averagecount" type="nonNegativeInteger" minOccurs="0"></element>
* <element name="maxdeviation" type="double" minOccurs="0"></element>
* <element name="minimum" type="double" minOccurs="0"></element>
* <element name="maxattempts" type="nonNegativeInteger" minOccurs="0"></element>
* <element name="sendreadyevent" type="boolean" minOccurs="0"></element>
* <element name="redoevent" type="tns:smevent" minOccurs="0" maxOccurs="unbounded"></element>
* <element name="deferredtrigger" type="boolean" minOccurs="0"></element>
* </sequence>
* </complexType>
* <complexType name="intervalchannel">
* <sequence>
* <element name="triggerinterval" type="tns:positiveDouble"></element>
* <element name="stoppedby" type="tns:identifier"></element>
* </sequence>
* </complexType>
*
* <simpleType name="positiveDouble">
* <restriction base="double">
* <minInclusive value="0"></minInclusive>
* </restriction>
* </simpleType>
* </pre>
*
* </li>
* <li>
* A detector channel defined in SCML v4.0:
*
* <pre>
* <smchannel>
* <channelid>bIICurrent:Mnt1chan1</channelid>
* <averagecount>10</averagecount>
* <maxdeviation>2.0</maxdeviation>
* <minimum>3.0</minimum>
* <maxattempts>4</maxattempts>
* <normalize_id>bIICurrent:Mnt1lifeTimechan1</normalize_id>
* <redoevent>
* <monitorevent>
* <id>DiscPosPPSMC:gw23715000</id>
* <limit type="string" comparison="eq">Position1</limit>
* </monitorevent>
* </redoevent>
* </smchannel>
* </pre>
*
* is defined in SCML v5.0 as follows:
*
* <pre>
* <smchannel>
* <channelid>bIICurrent:Mnt1chan1</channelid>
* <normalize_id>bIICurrent:Mnt1lifeTimechan1</normalize_id>
* <standard>
* <averagecount>10</averagecount>
* <maxdeviation>2.0</maxdeviation>
* <minimum>3.0</minimum>
* <maxattempts>4</maxattempts>
* <redoevent>
* <monitorevent>
* <id>DiscPosPPSMC:gw23715000</id>
* <limit type="string" comparison="eq">Position1</limit>
* </monitorevent>
* </redoevent>
* </standard>
* </smchannel>
* </pre>
*
* </li>
* </ul>
* </li>
* </ul>
*
* @author Marcus Michalsky
* @since 1.27
*/
public class Patch4o0T5o0 extends Patch {
private static final Logger LOGGER = Logger.getLogger(Patch4o0T5o0.class.getName());
private static Patch4o0T5o0 INSTANCE;
private Patch4o0T5o0(Version source, Version target, List<Modification> modifications) {
super(source, target, modifications);
modifications.add(new Mod0(this));
modifications.add(new Mod1(this));
}
public static Patch4o0T5o0 getInstance() {
if (INSTANCE == null) {
List<Modification> modifications = new LinkedList<Modification>();
INSTANCE = new Patch4o0T5o0(new Version(4, 0), new Version(5, 0), modifications);
}
return INSTANCE;
}
private class Mod0 extends AbstractModification {
public Mod0(Patch patch) {
super(patch, "setting scml version to 5.0");
}
/**
* {@inheritDoc}
*/
@Override
public void modify(Document document) {
Node version = document.getElementsByTagName("version").item(0);
if (version.getNodeType() == Node.ELEMENT_NODE) {
((Text)version.getFirstChild()).setData("5.0");
}
}
}
private class Mod1 extends AbstractModification {
public Mod1(Patch patch) {
super(patch, "converted scan module channels to (newly introduced) standard mode channels");
}
/**
* {@inheritDoc}
*/
@Override
public void modify(Document document) {
NodeList smChannels = document.getElementsByTagName("smchannel");
for (Node smChannel : asList(smChannels)) {
LOGGER.debug("collecting child elements of smchannel");
Node channelid = null;
Node normalizeid = null;
List<Node> other = new ArrayList<>();
for (Node child : asList(smChannel.getChildNodes())) {
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (child.getNodeName().equals("channelid")) {
channelid = child;
LOGGER.debug("smchannel is " + channelid.getTextContent());
} else if (child.getNodeName().equals("normalize_id")) {
normalizeid = child;
LOGGER.debug("normalize id is " + normalizeid.getTextContent());
} else {
other.add(child);
LOGGER.debug("found element " + child.getNodeName());
}
}
LOGGER.debug("adding standard element to smchannel");
Element standardElement = document.createElement("standard");
smChannel.appendChild(standardElement);
LOGGER.debug("moving nodes to standard element");
// move "other" nodes (all childs but channelid and normalizeid) to standard element
for (Node node : other) {
try {
smChannel.removeChild(node);
standardElement.appendChild(node);
LOGGER.debug("moved " + node.getNodeName());
} catch (DOMException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
}
}
|
package org.amc.game.chess;
import java.util.ArrayList;
import java.util.List;
/**
* Contains the Rules of Chess
*
* @author Adrian Mclaughlin
*
*/
public class ChessGame{
private ChessBoard board;
private Player currentPlayer;
private Player playerOne;
private Player playerTwo;
List<ChessMoveRule> chessRules;
private PlayerKingInCheckCondition kingInCheck;
private GameState gameState;
public enum GameState{
RUNNING,
STALEMATE,
WHITE_IN_CHECK,
BLACK_IN_CHECK,
WHITE_CHECKMATE,
BLACK_CHECKMATE,
}
public ChessGame(ChessBoard board, Player playerOne, Player playerTwo) {
this.board = board;
this.playerOne = playerOne;
this.playerTwo = playerTwo;
this.currentPlayer = this.playerOne;
this.kingInCheck = new PlayerKingInCheckCondition();
chessRules = new ArrayList<>();
chessRules.add(new EnPassantRule());
chessRules.add(new CastlingRule());
chessRules.add(new PawnPromotionRule());
this.gameState=GameState.RUNNING;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
/**
* Returns the Player who is waiting for their turn
*
* @return Player
*/
Player getOpposingPlayer(Player player) {
return player == playerOne ? playerTwo : playerOne;
}
/**
* Changes the current player
*/
public void changePlayer() {
if (currentPlayer.equals(playerOne)) {
currentPlayer = playerTwo;
} else {
currentPlayer = playerOne;
}
}
/**
* Move a ChessPiece from one square to another as long as the move is valid
*
* @param player
* Player making the move
* @param move
* Move
* @throws InvalidMoveException
* if not a valid movement
*/
public void move(Player player, Move move) throws InvalidMoveException {
isPlayersTurn(player);
ChessPiece piece = board.getPieceFromBoardAt(move.getStart());
checkChessPieceExistsOnSquare(piece, move);
checkItsthePlayersPiece(player, piece);
moveThePlayersChessPiece(player, board, piece, move);
if(isOpponentsKingInCheck(player,board)){
isOpponentKingInCheckMate(player);
}else{
PlayerInStalement stalemate=new PlayerInStalement(getOpposingPlayer(player),player, board);
if(stalemate.isStalemate()){
gameState=GameState.STALEMATE;
}
}
}
private void isPlayersTurn(Player player) throws InvalidMoveException{
if(!getCurrentPlayer().equals(player)){
throw new InvalidMoveException("Not Player's turn");
}
}
private void checkChessPieceExistsOnSquare(ChessPiece piece, Move move)
throws InvalidMoveException {
if (piece == null) {
throw new InvalidMoveException("No piece at " + move.getStart());
}
}
private void checkItsthePlayersPiece(Player player, ChessPiece piece)
throws InvalidMoveException {
if (notPlayersChessPiece(player, piece)) {
throw new InvalidMoveException("Player can only move their own pieces");
}
}
private boolean notPlayersChessPiece(Player player, ChessPiece piece) {
return player.getColour() != piece.getColour();
}
private void moveThePlayersChessPiece(Player player, ChessBoard board, ChessPiece piece,
Move move) throws InvalidMoveException {
if (isPlayersKingInCheck(player, board)) {
doNormalMove(player, piece, move);
} else if (doesAGameRuleApply(board, move)) {
thenApplyGameRule(player, move);
} else {
doNormalMove(player, piece, move);
}
}
private void doNormalMove(Player player, ChessPiece piece, Move move)
throws InvalidMoveException {
if (piece.isValidMove(board, move)) {
thenMoveChessPiece(player, move);
} else {
throw new InvalidMoveException("Not a valid move");
}
}
private void thenMoveChessPiece(Player player, Move move) throws InvalidMoveException {
ChessBoard testBoard=new ChessBoard(board);
testBoard.move(move);
if (isPlayersKingInCheck(player,testBoard)) {
throw new InvalidMoveException("King is checked");
}else{
gameState=GameState.RUNNING;
board.move(move);
}
}
private void thenApplyGameRule(Player player, Move move) throws InvalidMoveException {
for (ChessMoveRule rule : chessRules) {
ChessBoard testBoard=new ChessBoard(board);
rule.applyRule(testBoard, move);
if (isPlayersKingInCheck(player, testBoard)) {
throw new InvalidMoveException("King is checked");
}else{
rule.applyRule(board, move);
}
}
}
/**
* Checks to see if the game has reached it's completion
*
* @param playerOne
* @param playerTwo
* @return Boolean
*/
public boolean isGameOver(Player playerOne, Player playerTwo) {
return gameState == GameState.STALEMATE || gameState == GameState.BLACK_CHECKMATE
|| gameState == GameState.WHITE_CHECKMATE;
}
boolean isCheckMate(Player player, ChessBoard board) {
PlayersKingCheckmateCondition checkmate=new PlayersKingCheckmateCondition(player, getOpposingPlayer(player), board);
return checkmate.isCheckMate();
}
boolean isPlayersKingInCheck(Player player, ChessBoard board) {
return kingInCheck.isPlayersKingInCheck(player, getOpposingPlayer(player), board);
}
boolean isOpponentsKingInCheck(Player player, ChessBoard board){
Player opponent=getOpposingPlayer(player);
boolean inCheck = kingInCheck.isPlayersKingInCheck(opponent,player,board);
if(inCheck)
{
gameState=(opponent.getColour().equals(Colour.WHITE))?GameState.WHITE_IN_CHECK:GameState.BLACK_IN_CHECK;
}
return inCheck;
}
boolean isOpponentKingInCheckMate(Player player){
Player opponent=getOpposingPlayer(player);
PlayersKingCheckmateCondition okcc=new PlayersKingCheckmateCondition(opponent, player, board);
if(okcc.isCheckMate()){
gameState=(opponent.getColour().equals(Colour.WHITE))?GameState.WHITE_CHECKMATE:GameState.BLACK_CHECKMATE;
return true;
}else{
return false;
}
}
/**
* Checks to see if a game rule applies to the Player's move Only applies
* one rule per move
*
* @param board
* @param move
* @return Boolean true if a Game rule applies to the Player's move
*/
boolean doesAGameRuleApply(ChessBoard board, Move move) {
for (ChessMoveRule rule : chessRules) {
if (rule.isRuleApplicable(board, move)) {
return true;
}
}
return false;
}
void setGameRules(List<ChessMoveRule> rules) {
this.chessRules = rules;
}
void setChessBoard(ChessBoard board) {
this.board = board;
}
/**
* Returns the ChessBoard
* @return ChessBoard
*/
public ChessBoard getChessBoard(){
return this.board;
}
public GameState getGameState(){
return this.gameState;
}
}
|
package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
public class RepositoryLinksService
{
private final BitbucketClient bitbucketClient;
public RepositoryLinksService(BitbucketClient bitbucketClient)
{
this.bitbucketClient = bitbucketClient;
}
/**
* @param owner
* @param slug
* @return
* @throws BitbucketClientException
*/
@SuppressWarnings("unchecked")
public List<RepositoryLink> getRepositoryLinks(String owner, String slug) throws BitbucketClientException
{
Type type = new TypeToken<List<RepositoryLink>>(){}.getType();
String resourceUrl = MessageFormat.format("/repositories/{0}/{1}/links", owner, slug);
return (List<RepositoryLink>) bitbucketClient.get(resourceUrl, type);
}
public RepositoryLink getRepositoryLink(String owner, String slug, int id) throws BitbucketClientException
{
Type type = new TypeToken<RepositoryLink>(){}.getType();
String resourceUrl = MessageFormat.format("/repositories/{0}/{1}/links/{2}", owner, slug, String.valueOf(id));
return (RepositoryLink) bitbucketClient.get(resourceUrl, type);
}
/**
* @param owner
* @param slug
* @param id
* @throws BitbucketClientException
*/
public void removeRepositoryLink(String owner, String slug, int id) throws BitbucketClientException
{
String resourceUrl = MessageFormat.format("/repositories/{0}/{1}/links/{2}", owner, slug, String.valueOf(id));
bitbucketClient.delete(resourceUrl);
}
/**
* Configures a new Repository Link to the bitbucket repository
*
* @param owner
* @param slug
* @param handler
* @param linkUrl
* @param linkKey
* @return
* @throws BitbucketClientException
*/
public RepositoryLink addRepositoryLink(String owner, String slug, String handler, String linkUrl, String linkKey) throws BitbucketClientException
{
Type type = new TypeToken<RepositoryLink>(){}.getType();
String resourceUrl = MessageFormat.format("/repositories/{0}/{1}/links", owner, slug);
List<String> params = Lists.newArrayList();
params.add("handler=" + handler);
params.add("link_url=" + linkUrl);
params.add("link_key=" + linkKey);
return (RepositoryLink) bitbucketClient.post(resourceUrl, params, type);
}
public static void main(String[] args) throws BitbucketClientException
{
BitbucketClient bitbucketClient = new BitbucketClient("https://bitbucket.org/!api/1.0");
bitbucketClient.setAuthorisation("dusanhornik", "macicka");
RepositoryLinksService repositoryLinksService = new RepositoryLinksService(bitbucketClient);
// list
List<RepositoryLink> repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
System.out.println(repositoryLinks);
//add
RepositoryLink link1 = repositoryLinksService.addRepositoryLink("dusanhornik", "jira-bitbucket-connector", "jira", "http://localhost:1234/jira", "BBC");
// System.out.println(link1);
//add
RepositoryLink link2 = repositoryLinksService.addRepositoryLink("dusanhornik", "jira-bitbucket-connector", "jira", "http://localhost:1234/jira", "ABC");
// System.out.println(link2);
//list
repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
System.out.println(repositoryLinks);
//remove
repositoryLinksService.removeRepositoryLink("dusanhornik", "jira-bitbucket-connector", link1.getId());
//list
repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
System.out.println(repositoryLinks);
//remove
repositoryLinksService.removeRepositoryLink("dusanhornik", "jira-bitbucket-connector", link2.getId());
//list
repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
System.out.println(repositoryLinks);
// long start = System.currentTimeMillis();
// List<RepositoryLink> links = Lists.newArrayList();
// for (int i = 0; i < 100; i++)
// links.add(link);
// System.out.println((System.currentTimeMillis()-start)/1000);
// //list
// repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
// System.out.println(repositoryLinks);
// start = System.currentTimeMillis();
// for (RepositoryLink repositoryLink : links)
// repositoryLinksService.removeRepositoryLink("dusanhornik", "jira-bitbucket-connector", repositoryLink.id);
// System.out.println((System.currentTimeMillis()-start)/1000);
// //list
// repositoryLinks = repositoryLinksService.getRepositoryLinks("dusanhornik", "jira-bitbucket-connector");
// System.out.println(repositoryLinks);
}
}
|
package gov.nih.nci.cagrid.bdt.extension;
import gov.nih.nci.cagrid.bdt.templates.BDTResourceCreatorTemplate;
import gov.nih.nci.cagrid.bdt.templates.JNDIConfigResourceTemplate;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.service.ServiceType;
import gov.nih.nci.cagrid.introduce.codegen.services.methods.SyncSource;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.extension.CodegenExtensionException;
import gov.nih.nci.cagrid.introduce.extension.CodegenExtensionPostProcessor;
import gov.nih.nci.cagrid.introduce.info.ServiceInformation;
import gov.nih.nci.cagrid.introduce.info.SpecificServiceInformation;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.projectmobius.common.MobiusException;
import org.projectmobius.common.XMLUtilities;
public class BDTCodegenExtensionPostProcessor implements CodegenExtensionPostProcessor {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void postCodegen(ServiceExtensionDescriptionType desc, ServiceInformation info)
throws CodegenExtensionException {
// 1. change the resource in the jndi file
File jndiConfigF = new File(info.getBaseDirectory().getAbsolutePath() + File.separator + "jndi-config.xml");
Document serverConfigJNDIDoc = null;
try {
serverConfigJNDIDoc = XMLUtilities.fileNameToDocument(jndiConfigF.getAbsolutePath());
} catch (MobiusException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ServiceType mainService = info.getServices().getService(0);
List serviceEls = serverConfigJNDIDoc.getRootElement().getChildren();
for (int i = 0; i < serviceEls.size(); i++) {
Element serviceEl = (Element) serviceEls.get(i);
if (serviceEl.getName().equals("service")
&& serviceEl.getAttributeValue("name").equals(
"SERVICE-INSTANCE-PREFIX/" + mainService.getName() + "BulkDataHandler")) {
List resourceEls = serviceEl.getChildren();
for (int j = 0; j < resourceEls.size(); j++) {
Element resourceEl = (Element) resourceEls.get(j);
if (resourceEl.getName().equals("resource") && resourceEl.getAttributeValue("name").equals("home")) {
serviceEl.removeContent(resourceEl);
break;
}
}
JNDIConfigResourceTemplate resourceT = new JNDIConfigResourceTemplate();
String resourceS = resourceT.generate(new SpecificServiceInformation(info, info.getServices()
.getService(0)));
Element newResourceEl;
try {
newResourceEl = XMLUtilities.stringToDocument(resourceS).getRootElement();
} catch (MobiusException e) {
throw new CodegenExtensionException(e.getMessage());
}
serviceEl.addContent(newResourceEl.detach());
FileWriter resourceFW;
try {
resourceFW = new FileWriter(jndiConfigF);
resourceFW.write(XMLUtilities.formatXML(XMLUtilities.documentToString(serverConfigJNDIDoc)));
resourceFW.close();
} catch (Exception e) {
throw new CodegenExtensionException(e.getMessage());
}
}
}
// 2. add any impls that need to be added if the method
// return a BDTHandle
if (mainService.getMethods() != null && mainService.getMethods().getMethod() != null) {
for (int i = 0; i < mainService.getMethods().getMethod().length; i++) {
MethodType method = mainService.getMethods().getMethod(i);
if (method.getOutput().getIsClientHandle().booleanValue()
&& method.getOutput().getClientHandleClass()
.equals(
mainService.getPackageName() + ".bdt.client." + mainService.getName()
+ "BulkDataHandlerClient")) {
// need to see if i have added the base impl to this method
boolean needToAdd = false;
File implSourceFile = new File(info.getBaseDirectory() + File.separator + "src" + File.separator
+ CommonTools.getPackageDir(mainService) + File.separator + "service" + File.separator
+ mainService.getName() + "Impl.java");
StringBuffer fileContent = null;
try {
fileContent = Utils.fileToStringBuffer(implSourceFile);
String clientMethod = SyncSource.createUnBoxedSignatureStringFromMethod(method, info);
int startOfMethod = SyncSource.startOfSignature(fileContent, clientMethod);
int endOfMethod = SyncSource.bracketMatch(fileContent, startOfMethod);
if (startOfMethod == -1 || endOfMethod == -1) {
System.err.println("WARNING: Unable to locate method in Impl : " + method.getName());
return;
}
String serviceMethod = fileContent.substring(startOfMethod, endOfMethod);
String oldclientMethod = "";
oldclientMethod += "//TODO: Implement this autogenerated method";
if (serviceMethod.indexOf(oldclientMethod) >= 0) {
needToAdd = true;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(implSourceFile);
if (needToAdd) {
// now that i know i will remove it and replace it
fileContent = null;
try {
fileContent = Utils.fileToStringBuffer(implSourceFile);
} catch (Exception e) {
e.printStackTrace();
}
// remove the method
String clientMethod = SyncSource.createUnBoxedSignatureStringFromMethod(method, info);
int startOfMethod = SyncSource.startOfSignature(fileContent, clientMethod);
int endOfMethod = SyncSource.bracketMatch(fileContent, startOfMethod);
if (startOfMethod == -1 || endOfMethod == -1) {
System.err.println("WARNING: Unable to locate method in Impl : " + method.getName());
return;
}
fileContent.delete(startOfMethod, endOfMethod);
try {
FileWriter fw = new FileWriter(implSourceFile);
fw.write(SyncSource.removeMultiNewLines(fileContent.toString()));
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
// now add the new method.....
fileContent = null;
try {
fileContent = Utils.fileToStringBuffer(implSourceFile);
} catch (Exception e) {
e.printStackTrace();
}
// insert the new client method
int endOfClass = fileContent.lastIndexOf("}");
clientMethod = "\n\t" + SyncSource.createUnBoxedSignatureStringFromMethod(method, info) + " "
+ SyncSource.createExceptions(method, info, mainService);
clientMethod += "{\n";
BDTResourceCreatorTemplate rt = new BDTResourceCreatorTemplate();
String methodTemplate = rt.generate(new SpecificServiceInformation(info, mainService));
clientMethod += methodTemplate + "\t}\n";
fileContent.insert(endOfClass - 1, clientMethod);
try {
String fileContentString = fileContent.toString();
FileWriter fw = new FileWriter(implSourceFile);
fw.write(fileContentString);
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
}
|
package org.cactoos.scalar;
import java.io.IOException;
import org.cactoos.Scalar;
/**
* Scalar that doesn't throw {@link Exception}, but throws
* {@link IOException} instead.
*
* <p>There is no thread-safety guarantee.
*
* <p>This class implements {@link Scalar}, which throws a checked
* {@link IOException}. This may not be convenient in many cases. To make
* it more convenient and get rid of the checked exception you can
* use the {@link Unchecked} decorator.</p>
*
* @param <T> Type of result
* @since 0.4
*/
public final class IoChecked<T> implements Scalar<T> {
/**
* Original scalar.
*/
private final Scalar<? extends T> origin;
/**
* Ctor.
* @param scalar Encapsulated scalar
*/
public IoChecked(final Scalar<? extends T> scalar) {
this.origin = scalar;
}
@Override
public T value() throws IOException {
return new Checked<>(
this.origin,
IOException::new
).value();
}
}
|
package com.sap.core.odata.processor.core.jpa;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.junit.Test;
import com.sap.core.odata.api.commons.InlineCount;
import com.sap.core.odata.api.edm.EdmEntityContainer;
import com.sap.core.odata.api.edm.EdmEntitySet;
import com.sap.core.odata.api.edm.EdmEntityType;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.edm.EdmLiteralKind;
import com.sap.core.odata.api.edm.EdmMapping;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmSimpleType;
import com.sap.core.odata.api.edm.EdmSimpleTypeException;
import com.sap.core.odata.api.edm.EdmType;
import com.sap.core.odata.api.edm.EdmTypeKind;
import com.sap.core.odata.api.edm.provider.EntityType;
import com.sap.core.odata.api.edm.provider.Facets;
import com.sap.core.odata.api.exception.ODataException;
import com.sap.core.odata.api.exception.ODataNotFoundException;
import com.sap.core.odata.api.processor.ODataContext;
import com.sap.core.odata.api.processor.ODataResponse;
import com.sap.core.odata.api.uri.NavigationPropertySegment;
import com.sap.core.odata.api.uri.PathInfo;
import com.sap.core.odata.api.uri.SelectItem;
import com.sap.core.odata.api.uri.info.GetEntitySetCountUriInfo;
import com.sap.core.odata.api.uri.info.GetEntitySetUriInfo;
import com.sap.core.odata.api.uri.info.GetEntityUriInfo;
import com.sap.core.odata.processor.api.jpa.ODataJPAContext;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.core.jpa.common.ODataJPATestConstants;
import com.sap.core.odata.processor.core.jpa.model.JPAEdmTestModelView;
public class ODataJPAResponseBuilderTest extends JPAEdmTestModelView{
@Test
public void testBuildListOfTGetEntitySetUriInfoStringODataJPAContext() {
try {
assertNotNull(ODataJPAResponseBuilder.build(getJPAEntities(), getResultsView(), "application/xml", getODataJPAContext()));
} catch (ODataJPARuntimeException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
}
@Test
public void testBuildNegatives() {// Bad content type
try {
EntityType entity = new EntityType();
entity.setName("SalesOrderHeader");
try {
assertNotNull(ODataJPAResponseBuilder.build(getEntity(), getLocalGetURIInfo(), "xml", getODataJPAContext()));
} catch (ODataNotFoundException e) {
assertTrue(true);
}
} catch (ODataJPARuntimeException e) {
assertTrue(true);//Nothing to do, Expected.
}
try {// Bad content type
assertNotNull(ODataJPAResponseBuilder.build(getJPAEntities(), getResultsView(), "xml", getODataJPAContext()));
} catch (ODataJPARuntimeException e) {
assertTrue(true);//Nothing to do, Expected.
}
}
private Object getEntity() {
SalesOrderHeader sHeader = new SalesOrderHeader(10, 34);
return sHeader;
}
@Test
public void testBuildObjectGetEntityUriInfoStringODataJPAContext() throws ODataNotFoundException {
try {
assertNotNull(ODataJPAResponseBuilder.build(new SalesOrderHeader(2, 10), getLocalGetURIInfo(), "application/xml", getODataJPAContext()));
}
catch (ODataJPARuntimeException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
}
@Test
public void testBuildNullSelects() {// Bad content type
try {
ODataJPAResponseBuilder.build(getJPAEntities(), getResultsViewWithNullSelects(), "xml", getODataJPAContext());
} catch (ODataJPARuntimeException e) {
assertTrue(true);//Nothing to do, Expected.
}
catch(Exception e)
{
assertTrue(true);
}
}
@Test
public void testBuildGetCount() {
ODataResponse objODataResponse = null;
try {
objODataResponse = ODataJPAResponseBuilder.build(1, getCountEntitySetUriInfo(), "application/xml", getODataJPAContext());
} catch (ODataJPARuntimeException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
assertNotNull(objODataResponse);
}
private GetEntitySetCountUriInfo getCountEntitySetUriInfo() {
GetEntitySetCountUriInfo objGetEntitySetCountUriInfo = EasyMock.createMock(GetEntitySetCountUriInfo.class);
EasyMock.replay(objGetEntitySetCountUriInfo);
return objGetEntitySetCountUriInfo;
}
private ODataJPAContext getODataJPAContext() {
ODataJPAContext objODataJPAContext = EasyMock.createMock(ODataJPAContext.class);
EasyMock.expect(objODataJPAContext.getODataContext()).andStubReturn(getLocalODataContext());
EasyMock.replay(objODataJPAContext);
return objODataJPAContext;
}
private ODataContext getLocalODataContext() {
ODataContext objODataContext = EasyMock.createMock(ODataContext.class);
try {
EasyMock.expect(objODataContext.getPathInfo()).andStubReturn(getLocalPathInfo());
} catch (ODataException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
EasyMock.replay(objODataContext);
return objODataContext;
}
private PathInfo getLocalPathInfo() {
PathInfo pathInfo = EasyMock.createMock(PathInfo.class);
EasyMock.expect(pathInfo.getServiceRoot()).andStubReturn(getLocalURI());
EasyMock.replay(pathInfo);
return pathInfo;
}
private URI getLocalURI() {
URI uri = null;
try {
uri = new URI("http://localhost:8080/com.sap.core.odata.processor.ref.web/");
} catch (URISyntaxException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
return uri;
}
private GetEntitySetUriInfo getResultsView() {
GetEntitySetUriInfo objGetEntitySetUriInfo = EasyMock.createMock(GetEntitySetUriInfo.class);
EasyMock.expect(objGetEntitySetUriInfo.getInlineCount()).andStubReturn(getLocalInlineCount());
EasyMock.expect(objGetEntitySetUriInfo.getTargetEntitySet()).andStubReturn(getLocalTargetEntitySet());
EasyMock.expect(objGetEntitySetUriInfo.getSelect()).andStubReturn(getSelectItemList());
EasyMock.expect(objGetEntitySetUriInfo.getExpand()).andStubReturn(getExpandList());
EasyMock.replay(objGetEntitySetUriInfo);
return objGetEntitySetUriInfo;
}
private List<ArrayList<NavigationPropertySegment>> getExpandList() {
List<ArrayList<NavigationPropertySegment>> expandList = new ArrayList<ArrayList<NavigationPropertySegment>>();
/*ArrayList<NavigationPropertySegment> navSegments = new ArrayList<NavigationPropertySegment>();
expandList.add(navSegments);
NavigationPropertySegment navProp = EasyMock.createMock(NavigationPropertySegment.class);
EasyMock.replay(navProp);*/
return expandList;
}
private GetEntitySetUriInfo getResultsViewWithNullSelects() {
GetEntitySetUriInfo objGetEntitySetUriInfo = EasyMock.createMock(GetEntitySetUriInfo.class);
EasyMock.expect(objGetEntitySetUriInfo.getInlineCount()).andStubReturn(getLocalInlineCount());
EasyMock.expect(objGetEntitySetUriInfo.getTargetEntitySet()).andStubReturn(getLocalTargetEntitySet());
EasyMock.expect(objGetEntitySetUriInfo.getSelect()).andStubReturn(null);
EasyMock.expect(objGetEntitySetUriInfo.getExpand()).andStubReturn(null);
EasyMock.replay(objGetEntitySetUriInfo);
return objGetEntitySetUriInfo;
}
private GetEntityUriInfo getLocalGetURIInfo() {
GetEntityUriInfo objGetEntityUriInfo = EasyMock.createMock(GetEntityUriInfo.class);
EasyMock.expect(objGetEntityUriInfo.getSelect()).andStubReturn(getSelectItemList());
EasyMock.expect(objGetEntityUriInfo.getTargetEntitySet()).andStubReturn(getLocalTargetEntitySet());
EasyMock.expect(objGetEntityUriInfo.getSelect()).andStubReturn(getSelectItemList());
EasyMock.expect(objGetEntityUriInfo.getExpand()).andReturn(getExpandList());
EasyMock.replay(objGetEntityUriInfo);
return objGetEntityUriInfo;
}
private List<SelectItem> getSelectItemList() {
List<SelectItem> selectItems = new ArrayList<SelectItem>();
selectItems.add(getSelectItem());
return selectItems;
}
private SelectItem getSelectItem() {
SelectItem selectItem = EasyMock.createMock(SelectItem.class);
EasyMock.expect(selectItem.getProperty()).andStubReturn(getEdmPropertyForSelect());
List<NavigationPropertySegment> navigationSegmentList = new ArrayList<NavigationPropertySegment>();
EasyMock.expect(selectItem.getNavigationPropertySegments()).andStubReturn(navigationSegmentList);
EasyMock.replay(selectItem);
return selectItem;
}
private EdmProperty getEdmPropertyForSelect() {
EdmSimpleType edmType = EasyMock.createMock(EdmSimpleType.class);
EasyMock.expect(edmType.getKind()).andStubReturn(EdmTypeKind.SIMPLE);
Facets facets = new Facets().setNullable(false);
try {
EasyMock.expect(edmType.valueToString(new Integer(2), EdmLiteralKind.URI, facets)).andStubReturn("2");
EasyMock.expect(edmType.valueToString(new Integer(2), EdmLiteralKind.DEFAULT, facets)).andStubReturn("2");
} catch (EdmSimpleTypeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
EasyMock.replay(edmType);
EdmProperty edmProperty = EasyMock.createMock(EdmProperty.class);
EdmMapping edmMapping = EasyMock.createMock(EdmMapping.class);
EasyMock.expect(edmMapping.getInternalName()).andStubReturn("soId");
EasyMock.expect(edmMapping.getMimeType()).andReturn(null);
EasyMock.replay(edmMapping);
try {
EasyMock.expect(edmProperty.getName()).andStubReturn("ID");
EasyMock.expect(edmProperty.getType()).andStubReturn(edmType);
EasyMock.expect(edmProperty.getMapping()).andStubReturn(edmMapping);
EasyMock.expect(edmProperty.getFacets()).andStubReturn(facets);
EasyMock.expect(edmProperty.getCustomizableFeedMappings()).andStubReturn(null);
EasyMock.expect(edmProperty.getMimeType()).andStubReturn(null);
EasyMock.replay(edmProperty);
} catch (EdmException e) {
fail("There is an exception is mocking some object "+e.getMessage());
}
return edmProperty;
}
private EdmProperty getEdmProperty() {
EdmProperty edmTyped = EasyMock.createMock(EdmProperty.class);
EdmMapping edmMapping = EasyMock.createMock(EdmMapping.class);
EasyMock.expect(edmMapping.getInternalName()).andStubReturn(
"Field1");
EasyMock.replay(edmMapping);
EdmType edmType = EasyMock.createMock(EdmType.class);
try {
EasyMock.expect(edmType.getKind()).andStubReturn(EdmTypeKind.SIMPLE);
EasyMock.expect(edmType.getName()).andStubReturn("identifier");
EasyMock.expect(edmTyped.getName()).andStubReturn("SalesOrderHeader");
EasyMock.expect(edmTyped.getMapping())
.andStubReturn(edmMapping);
EasyMock.expect(edmTyped.getType()).andStubReturn(edmType);
EasyMock.expect(edmTyped.getMapping()).andStubReturn(edmMapping);
} catch (EdmException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
EasyMock.replay(edmType);
EasyMock.replay(edmTyped);
return edmTyped;
}
private EdmEntitySet getLocalTargetEntitySet() {
EdmEntitySet objEdmEntitySet = EasyMock.createMock(EdmEntitySet.class);
try {
EasyMock.expect(objEdmEntitySet.getEntityType()).andStubReturn(getLocalEdmEntityType());
EasyMock.expect(objEdmEntitySet.getName()).andStubReturn("SalesOderHeaders");
EasyMock.expect(objEdmEntitySet.getEntityContainer()).andStubReturn(getLocalEdmEntityContainer());
} catch (EdmException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
EasyMock.replay(objEdmEntitySet);
return objEdmEntitySet;
}
private EdmEntityContainer getLocalEdmEntityContainer() {
EdmEntityContainer edmEntityContainer = EasyMock.createMock(EdmEntityContainer.class);
EasyMock.expect(edmEntityContainer.isDefaultEntityContainer()).andStubReturn(true);
try {
EasyMock.expect(edmEntityContainer.getName()).andStubReturn("salesorderprocessingContainer");
} catch (EdmException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
EasyMock.replay(edmEntityContainer);
return edmEntityContainer;
}
private EdmEntityType getLocalEdmEntityType() {
EdmEntityType objEdmEntityType = EasyMock.createMock(EdmEntityType.class);
try {
EasyMock.expect(objEdmEntityType.getName()).andStubReturn("SalesOderHeaders");
EasyMock.expect(objEdmEntityType.getNamespace()).andStubReturn("SalesOderHeaders");
EasyMock.expect(objEdmEntityType.hasStream()).andStubReturn(false);
EasyMock.expect(objEdmEntityType.hasStream()).andStubReturn(false);
ArrayList<String> propertyNames = new ArrayList<String>();
propertyNames.add("ID");
EasyMock.expect(objEdmEntityType.getProperty("ID")).andStubReturn(getEdmPropertyForSelect());
EasyMock.expect(objEdmEntityType.getPropertyNames()).andStubReturn(propertyNames);
EasyMock.expect(objEdmEntityType.getNavigationPropertyNames()).andStubReturn(new ArrayList<String>());
EasyMock.expect(objEdmEntityType.getKeyPropertyNames()).andStubReturn(propertyNames);
EasyMock.expect(objEdmEntityType.getKeyProperties()).andStubReturn(getKeyProperties());
} catch (EdmException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1+e.getMessage()
+ ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
EasyMock.replay(objEdmEntityType);
return objEdmEntityType;
}
private List<EdmProperty> getKeyProperties() {
List<EdmProperty> edmProperties = new ArrayList<EdmProperty>();
EdmType edmType = EasyMock.createMock(EdmType.class);
EasyMock.expect(edmType.getKind()).andStubReturn(EdmTypeKind.SIMPLE);
EasyMock.replay(edmType);
EdmProperty edmProperty = EasyMock.createMock(EdmProperty.class);
EdmMapping edmMapping = EasyMock.createMock(EdmMapping.class);
EasyMock.expect(edmMapping.getInternalName()).andStubReturn("soId");
EasyMock.replay(edmMapping);
try {
EasyMock.expect(edmProperty.getName()).andStubReturn("ID");
EasyMock.expect(edmProperty.getType()).andStubReturn(edmType);
EasyMock.expect(edmProperty.getMapping()).andStubReturn(edmMapping);
EasyMock.replay(edmProperty);
} catch (EdmException e) {
fail("There is an exception is mocking some object "+e.getMessage());
}
edmProperties.add(edmProperty);
return edmProperties;
}
private InlineCount getLocalInlineCount() {
return InlineCount.NONE;
}
class SalesOrderHeader
{
private int soId;
private int Field1;
public SalesOrderHeader(int soId,int field) {
this.soId = soId;
this.Field1 = field;
}
public int getField1() {
return Field1;
}
public void setField1(int field1) {
Field1 = field1;
}
public int getSoId() {
return soId;
}
public void setSoId(int soId) {
this.soId = soId;
}
}
private List<Object> getJPAEntities() {
List<Object> listJPAEntities = new ArrayList<Object>();
SalesOrderHeader entity;
entity = new SalesOrderHeader(2,10);
listJPAEntities.add(entity);
return listJPAEntities;
}
}
|
package org.fiteagle.api.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.hp.hpl.jena.util.FileManager;
public class Config {
private Path FILE_PATH;
private static Logger LOGGER = Logger.getLogger(Config.class.toString());
public Config() {
this.FILE_PATH = IConfig.PROPERTIES_DIRECTORY
.resolve(IConfig.FITEAGLE_FILE_NAME);
checkFolder();
setDefaultProperty();
}
public Config(String file_name) {
file_name = file_name.concat(IConfig.EXTENSION);
this.FILE_PATH = IConfig.PROPERTIES_DIRECTORY.resolve(file_name);
checkFolder();
}
public void createPropertiesFile() {
deletePropertiesFile();
setDefaultProperty();
}
private void checkFolder() {
if (Files.notExists(IConfig.PROPERTIES_DIRECTORY)) {
try {
Files.createDirectory(IConfig.PROPERTIES_DIRECTORY);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "The directory can't be created ", e);
}
}
}
public void setDefaultProperty() {
File file = FILE_PATH.toFile();
if (!file.exists()) {
Properties property = new Properties();
property.put(IConfig.KEY_HOSTNAME, IConfig.DEFAULT_HOSTNAME);
property.put(IConfig.LOCAL_NAMESPACE, IConfig.LOCAL_NAMESPACE_VALUE);
property.put(IConfig.RESOURCE_NAMESPACE,
IConfig.RESOURCE_NAMESPACE_VALUE);
writeProperties(property);
} else {
Properties property = readProperties();
if (!property.containsKey(IConfig.KEY_HOSTNAME)) {
property.put(IConfig.KEY_HOSTNAME, IConfig.DEFAULT_HOSTNAME);
}
if (!property.containsKey(IConfig.RESOURCE_NAMESPACE)) {
property.put(IConfig.RESOURCE_NAMESPACE,
IConfig.RESOURCE_NAMESPACE_VALUE);
}
if (!property.containsKey(IConfig.LOCAL_NAMESPACE)) {
property.put(IConfig.LOCAL_NAMESPACE,
IConfig.LOCAL_NAMESPACE_VALUE);
}
writeProperties(property);
}
}
public void setNewProperty(String propertyKey, String propertyValue) {
Properties property = readProperties();
property.put(propertyKey, propertyValue);
writeProperties(property);
}
public String getProperty(String propertyKey) {
String propertyValue = null;
propertyValue = readProperties().getProperty(propertyKey);
if (propertyValue == null) {
throw new IllegalArgumentException(
"there is no value for the property " + propertyKey);
}
return propertyValue;
}
public HashMap<String, String> getAllProperties() {
Properties property = readProperties();
Enumeration<Object> enuKeys = property.keys();
HashMap<String, String> allProperties = new HashMap<>();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = property.getProperty(key);
allProperties.put(key, value);
LOGGER.log(Level.INFO, key + ":" + value);
}
return allProperties;
}
public void deleteProperty(String propertyKey) {
Properties property = readProperties();
property.remove(propertyKey);
writeProperties(property);
}
public void updateProperty(String propertyKey, String propertyValue) {
Properties property = readProperties();
property.put(propertyKey, propertyValue);
writeProperties(property);
}
public void deletePropertiesFile() {
if (Files.exists(FILE_PATH)) {
try {
Files.delete(FILE_PATH);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "The file can't be deleted", e);
}
}
}
private Properties convertProperties() throws Exception{
Properties property = new Properties();
InputStream inputStream = FileManager.get().open(FILE_PATH.toString());
property.load(inputStream);
inputStream.close();
writeProperties(property);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String input = IOUtils.toString(new FileInputStream(FILE_PATH.toFile()), "UTF-8");
property = gson.fromJson(input, Properties.class);
return property;
}
public Properties readProperties() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Properties property = new Properties();
try {
String input = IOUtils.toString(new FileInputStream(FILE_PATH.toFile()), "UTF-8");
property = gson.fromJson(input, Properties.class);
}catch (IOException e) {
LOGGER.log(Level.SEVERE, "Properties file " + FILE_PATH.toString()
+ " can't be opened ", e);
} catch (JsonSyntaxException e) {
try{
property = convertProperties();
}catch(Exception e2){
LOGGER.log(Level.SEVERE, "JSONException - Could not read Properties file - Then tried to convert it into JSON but failed");
}
}
return property;
}
public void writeProperties(Properties property) {
FileWriter writer;
try {
File file = FILE_PATH.toFile();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(property);
writer = new FileWriter(file);
writer.write(jsonString);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
LOGGER.log(Level.SEVERE, "Properties file " + FILE_PATH.toString()
+ " is not found ", e);
e.printStackTrace();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "properties couldn't be stored in "
+ FILE_PATH.toString(), e);
}
}
}
|
package com.zsmartsystems.zigbee.console;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import com.zsmartsystems.zigbee.CommandResult;
import com.zsmartsystems.zigbee.ZigBeeEndpoint;
import com.zsmartsystems.zigbee.ZigBeeNetworkManager;
import com.zsmartsystems.zigbee.zcl.ZclAttribute;
import com.zsmartsystems.zigbee.zcl.ZclCluster;
import com.zsmartsystems.zigbee.zcl.ZclStatus;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesResponse;
import com.zsmartsystems.zigbee.zcl.field.ReadAttributeStatusRecord;
/**
*
* @author Chris Jackson
*
*/
public class ZigBeeConsoleAttributeReadCommand extends ZigBeeConsoleAbstractCommand {
@Override
public String getCommand() {
return "read";
}
@Override
public String getDescription() {
return "Read one or more attributes. If no attribute specified, all attributes will be read.";
}
@Override
public String getSyntax() {
return "ENDPOINT CLUSTER [ATTRIBUTE1 ATTRIBUTE2 ...] [PERIOD=x] [CYCLES=x]";
}
@Override
public String getHelp() {
return "";
}
@Override
public void process(ZigBeeNetworkManager networkManager, String[] args, PrintStream out)
throws IllegalArgumentException, InterruptedException, ExecutionException {
if (args.length < 3) {
throw new IllegalArgumentException("Invalid number of arguments");
}
final ZigBeeEndpoint endpoint = getEndpoint(networkManager, args[1]);
ZclCluster cluster = getCluster(endpoint, args[2]);
int repeatPeriod = 0;
int repeatCycles = 10;
final Map<Integer, String> attributes = new HashMap<>();
for (int i = 3; i < args.length; i++) {
String cmd[] = args[i].split("=");
if (cmd != null && cmd.length == 2) {
switch (cmd[0].toLowerCase()) {
case "period":
repeatPeriod = parseInteger(cmd[1]);
break;
case "cycles":
repeatCycles = parseInteger(cmd[1]);
break;
default:
break;
}
continue;
}
Integer attributeId = parseAttribute(args[i]);
ZclAttribute attribute = cluster.getAttribute(attributeId);
attributes.put(attributeId,
attribute != null ? attribute.getName() : String.format("Attribute %d", attributeId));
}
if(attributes.isEmpty()) {
if(!cluster.discoverAttributes(false, null).get()) {
out.println("Failed to discover attributes");
}
cluster.getAttributes().forEach(zclAttribute -> {
if(zclAttribute.isImplemented()) {
attributes.put(zclAttribute.getId(), zclAttribute.getName());
}
});
}
StringBuilder strAttributes = new StringBuilder();
for (String value : attributes.values()) {
if (strAttributes.length() != 0) {
strAttributes.append(", ");
}
strAttributes.append(value);
}
out.println("Reading endpoint " + endpoint.getEndpointAddress() + ", cluster " + printCluster(cluster)
+ ", attributes " + strAttributes.toString()
+ (repeatPeriod == 0 ? "" : (" @period = " + repeatPeriod + " sec")));
for (int cnt = 0; cnt < repeatCycles; cnt++) {
if (!readAttribute(out, cluster, attributes)) {
break;
}
if (repeatPeriod == 0) {
break;
}
Thread.sleep(repeatPeriod * 1000L);
}
}
private boolean readAttribute(PrintStream out, ZclCluster cluster, Map<Integer, String> attributes)
throws InterruptedException, ExecutionException {
CommandResult result = cluster.readAttributes(new ArrayList<>(attributes.keySet())).get();
if (result.isSuccess()) {
final ReadAttributesResponse response = result.getResponse();
out.println(String.format("Response for cluster 0x%04x", response.getClusterId()));
if (response.getRecords().size() == 0) {
out.println("No records returned");
return false;
}
for (ReadAttributeStatusRecord statusRecord : response.getRecords()) {
if (statusRecord.getStatus() == ZclStatus.SUCCESS) {
out.println("Attribute " + statusRecord.getAttributeIdentifier() + ", type "
+ statusRecord.getAttributeDataType() + ", value: " + statusRecord.getAttributeValue());
} else {
out.println("Attribute " + statusRecord.getAttributeIdentifier() + " error: "
+ statusRecord.getStatus());
}
}
return true;
} else {
out.println("Error executing command: " + result);
return false;
}
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.io.*;
import java.net.URL;
import java.security.AccessControlException;
import java.util.*;
import java.util.Map;
import com.samskivert.io.StreamUtil;
import static com.samskivert.Log.log;
/**
* The config util class provides routines for loading configuration information.
*/
public class ConfigUtil
{
/**
* Obtains the specified system property via {@link System#getProperty}, parses it into an
* integer and returns the value. If the property is not set, the default value will be
* returned. If the property is not a properly formatted integer, an error will be logged and
* the default value will be returned.
*/
public static int getSystemProperty (String key, int defval)
{
String valstr = System.getProperty(key);
int value = defval;
if (valstr != null) {
try {
value = Integer.parseInt(valstr);
} catch (NumberFormatException nfe) {
log.warning("'" + key + "' must be a numeric value", "value", valstr, "error", nfe);
}
}
return value;
}
/**
* Loads a properties file from the named file that exists somewhere in the classpath.
*
* <p> The classloader that loaded the <code>ConfigUtil</code> class is searched first,
* followed by the system classpath. If you wish to provide an additional classloader, use the
* version of this function that takes a classloader as an argument.
*
* @param path The path to the properties file, relative to the root of the classpath entry
* from which it will be loaded (e.g. <code>com/foo/config.properties</code>).
*
* @return A properties object loaded with the contents of the specified file if the file could
* be found, null otherwise.
*/
public static Properties loadProperties (String path)
throws IOException
{
return loadProperties(path, ConfigUtil.class.getClassLoader());
}
/**
* Like {@link #loadProperties(String)} but this method uses the supplied class loader rather
* than the class loader used to load the <code>ConfigUtil</code> class.
*/
public static Properties loadProperties (String path, ClassLoader loader)
throws IOException
{
Properties props = new Properties();
loadProperties(path, loader, props);
return props;
}
/**
* Like {@link #loadProperties(String,ClassLoader)} but the properties are loaded into the
* supplied {@link Properties} object.
*/
public static void loadProperties (
String path, ClassLoader loader, Properties target)
throws IOException
{
InputStream in = getStream(path, loader);
if (in == null) {
throw new FileNotFoundException(path);
}
target.load(in);
in.close();
}
/**
* Creates a properties instance by combining properties files loaded using the specified
* classpath-relative property file path.
*
* <p> The inheritance works in two ways:
*
* <ul><li><b>Overrides</b>
*
* <p> All properties files with the specified name are located in the classpath and merged
* into a single set of properties according to an explicit inheritance hierarchy defined by a
* couple of custom properties. This is best explained with an example:
*
* <p><code>com/samskivert/foolib/config.properties</code> contains:
*
* <pre>
* _package = foolib
*
* config1 = value1
* config2 = value2
* ...
* </pre>
*
* and this is packaged into <code>foolib.jar</code>. Happy Corp writes an application that
* uses foolib and wants to override some properties in foolib's configuration. They create a
* properties file in <code>happyapp.jar</code> with the path
* <code>com/samskivert/foolib/config.properties</code>. It contains:
*
* <pre>
* _package = happyapp
* _overrides = foolib
*
* config2 = happyvalue
* </pre>
*
* When foolib loads its <code>config.properties</code> the overrides from
* <code>happyapp.jar</code> will be applied to the properties defined in
* <code>foolib.jar</code> and foolib will see Happy Corp's overridden properties.
*
* <p> Note that conflicting overrides must be resolved "by hand" so to speak. For example, if
* Happy Corp used some other library that also overrode foolib's configuration, say barlib,
* whose <code>barlib.jar</code> contained:
*
* <pre>
* _package = barlib
* _overrides = foolib
*
* config1 = barvalue
* </pre>
*
* Happy Corp's <code>config.properties</code> would not be able to override foolib's
* configuration directly because the config system would not know which overrides to use. It
* instead must override barlib's configuration, like so:
*
* <pre>
* _package = happyapp
* _overrides = barlib
* ...
* </pre>
*
* Moreover, if there were yet a third library that also overrode foolib, Happy Corp would have
* to resolve the conflict between barlib and bazlib explicitly:
*
* <pre>
* _package = happyapp
* _overrides = barlib, bazlib
* ...
* </pre>
*
* This would force bazlib's overrides to take precedence over barlib's overrides, resolving
* the inheritance ambiguity created when both barlib and bazlib claimed to override foolib.
*
* <p> This all certainly seems a bit complicated, but in most cases there is only one user of
* a library and overriding is very straightforward. The additional functionality is provided
* to resolve cases where conflicts do arise.
*
* <li><b>Extends</b>
*
* <p> The second type of inheritance, extension, is more straightforward. In this case, a
* properties file explicitly extends another properties file. For example,
* <code>com/foocorp/puzzle/config.properties</code> contains:
*
* <pre>
* # Standard configuration options
* score = 25
* multiplier = 2
* </pre>
*
* <code>com/foocorp/puzzle/footris/config.properties</code> contains:
*
* <pre>
* _extends = com/foocorp/puzzle/config.properties
*
* # Footris configuration options
* score = 15 # override the default score
* bonus = 55
* </pre>
*
* The Footris configuration will inherit default values from the general puzzle configuration,
* overriding any that are specified explicitly.
*
* <p> When resolving a properties file that extends another properties file, first the
* extended properties are loaded and all <code>_overrides</code> are applied to that
* properties file. Then all <code>_overrides</code> are applied to the extending properties
* file and then the extending properties are merged with the extended properties. </ul>
*
* <em>A final note:</em> All of the inheritance directives must be grouped together in an
* uninterrupted sequence of lines. One the parsing code finds the first directive, it stops
* parsing when it sees a line that does not contain a directive.
*
* @param path The path to the properties file, relative to the root of the classpath entries
* from which it will be loaded (e.g. <code>com/foo/config.properties</code>).
*
* @return A properties object loaded with the contents of the specified file if the file could
* be found, null otherwise.
*/
public static Properties loadInheritedProperties (String path)
throws IOException
{
return loadInheritedProperties(path, ConfigUtil.class.getClassLoader());
}
/**
* Like {@link #loadInheritedProperties(String)} but loads the properties into the supplied
* target object.
*/
public static void loadInheritedProperties (String path, Properties target)
throws IOException
{
loadInheritedProperties(path, ConfigUtil.class.getClassLoader(), target);
}
/**
* Like {@link #loadInheritedProperties(String)} but this method uses the supplied class loader
* rather than the class loader used to load the <code>ConfigUtil</code> class.
*/
public static Properties loadInheritedProperties (String path, ClassLoader loader)
throws IOException
{
Properties props = new Properties();
loadInheritedProperties(path, loader, props);
return props;
}
/**
* Like {@link #loadInheritedProperties(String,ClassLoader)} but the properties are loaded into
* the supplied properties object. Properties that already exist in the supplied object will
* be overwritten by the loaded properties where they have the same key.
*
* @exception FileNotFoundException thrown if no properties files are found for the specified
* path.
*/
public static void loadInheritedProperties (String path, ClassLoader loader, Properties target)
throws IOException
{
// first look for the files in the supplied class loader
Enumeration<URL> enm = getResources(path, loader);
if (!enm.hasMoreElements()) {
// if we couldn't find anything there, try the system class loader (but only if that's
// not where we were already looking)
try {
ClassLoader sysloader = ClassLoader.getSystemClassLoader();
if (sysloader != loader) {
enm = getResources(path, sysloader);
}
} catch (AccessControlException ace) {
// can't get the system loader, no problem!
}
}
// stick the matches into an array list so that we can count them
ArrayList<URL> rsrcs = new ArrayList<URL>();
while (enm.hasMoreElements()) {
rsrcs.add(enm.nextElement());
}
// load up the metadata for the properties files
PropRecord root = null, crown = null;
HashMap<String,PropRecord> map = null;
if (rsrcs.size() == 0) {
// if we found no resources in our enumerations, complain
throw new FileNotFoundException(path);
} else if (rsrcs.size() == 1) {
// parse the metadata for our only properties file
root = parseMetaData(path, rsrcs.get(0));
} else {
map = new HashMap<String,PropRecord>();
for (int ii = 0; ii < rsrcs.size(); ii++) {
// parse the metadata for this properties file
PropRecord record = parseMetaData(path, rsrcs.get(ii));
// make sure the record we parseded is valid because we're going to be doing
// overrides
record.validate();
// then map it according to its package defintion
map.put(record._package, record);
// if this guy overrides nothing, he's the root property
if (record._overrides == null) {
// make sure there aren't two or more roots
if (root != null) {
String errmsg = record + " cannot have the same path as " + root +
" without one overriding the other.";
throw new IOException(errmsg);
}
root = record;
}
}
// now wire up all the records according to the hierarchy
for (PropRecord prec : map.values()) {
if (prec._overrides == null) {
// sanity check
if (prec != root) {
String errmsg = "Internal error: found multiple roots where we shouldn't " +
"have [root=" + root + ", prec=" + prec + "]";
throw new IOException(errmsg);
}
continue;
}
// wire this guy up to whomever he overrides
for (String ppkg : prec._overrides) {
PropRecord parent = map.get(ppkg);
if (parent == null) {
throw new IOException("Cannot find parent '" + ppkg + "' for " + prec);
}
parent.add(prec);
}
}
// verify that there is only one crown
ArrayList<PropRecord> crowns = new ArrayList<PropRecord>();
for (PropRecord prec : map.values()) {
if (prec.size() == 0) {
crowns.add(prec);
}
}
if (crowns.size() == 0) {
String errmsg = "No top-level property override could be found, perhaps there " +
"are circular references " + StringUtil.toString(map.values());
throw new IOException(errmsg);
} else if (crowns.size() > 1) {
StringBuilder errmsg = new StringBuilder();
errmsg.append("Multiple top-level properties were found, ");
errmsg.append("one definitive top-level file must provide ");
errmsg.append("an order for all others:\n");
for (int ii = 0; ii < crowns.size(); ii++) {
if (ii > 0) {
errmsg.append("\n");
}
errmsg.append(crowns.get(ii));
}
throw new IOException(errmsg.toString());
}
crown = crowns.get(0);
}
// if the root extends another file, resolve that first
if (!StringUtil.isBlank(root._extends)) {
try {
loadInheritedProperties(root._extends, loader, target);
} catch (FileNotFoundException fnfe) {
throw new IOException(
"Unable to locate parent '" + root._extends + "' for '" + root.path + "'");
}
}
// now apply all of the overrides, in the appropriate order
if (crown != null) {
HashMap<String,PropRecord> applied = new HashMap<String,PropRecord>();
loadPropertiesOverrides(crown, map, applied, loader, target);
} else {
// we have no overrides, so load our props up straight
InputStream in = root.sourceURL.openStream();
target.load(in);
in.close();
}
// finally remove the metadata properties
target.remove(PACKAGE_KEY);
target.remove(EXTENDS_KEY);
target.remove(OVERRIDES_KEY);
}
/** {@link #loadInheritedProperties(String,ClassLoader,Properties)} helper function. */
protected static void loadPropertiesOverrides (
PropRecord prec, Map<String,PropRecord> records, Map<String,PropRecord> applied,
ClassLoader loader, Properties target)
throws IOException
{
if (applied.containsKey(prec._package)) {
return;
}
// first load up properties from all of our parent nodes
if (prec._overrides != null) {
for (String override : prec._overrides) {
PropRecord parent = records.get(override);
loadPropertiesOverrides(parent, records, applied, loader, target);
}
}
// now apply our properties values
InputStream in = prec.sourceURL.openStream();
target.load(in);
in.close();
applied.put(prec._package, prec);
}
/**
* Performs simple processing of the supplied input stream to obtain inheritance metadata from
* the properties file.
*/
protected static PropRecord parseMetaData (String path, URL sourceURL)
throws IOException
{
InputStream input = sourceURL.openStream();
try {
BufferedReader bin = new BufferedReader(new InputStreamReader(input));
PropRecord record = new PropRecord(path, sourceURL);
boolean started = false;
String line;
while ((line = bin.readLine()) != null) {
if (line.startsWith(PACKAGE_KEY)) {
record._package = parseValue(line);
started = true;
} else if (line.startsWith(EXTENDS_KEY)) {
record._extends = parseValue(line);
started = true;
} else if (line.startsWith(OVERRIDES_KEY)) {
record._overrides = parseValues(line);
started = true;
} else if (started) {
break;
}
}
return record;
} finally {
StreamUtil.close(input);
}
}
/** {@link #parseMetaData} helper function. */
protected static String parseValue (String line)
{
int eidx = line.indexOf("=");
return (eidx == -1) ? "" : line.substring(eidx+1).trim();
}
/** {@link #parseMetaData} helper function. */
protected static String[] parseValues (String line)
{
String value = parseValue(line);
if (StringUtil.isBlank(value)) {
return null;
}
String[] values = StringUtil.split(value, ",");
for (int ii = 0; ii < values.length; ii++) {
values[ii] = values[ii].trim();
}
return values;
}
/**
* Returns an input stream referencing a file that exists somewhere in the classpath.
*
* <p> The classloader that loaded the <code>ConfigUtil</code> class is searched first,
* followed by the system classpath. If you wish to provide an additional classloader, use the
* version of this function that takes a classloader as an argument.
*
* @param path The path to the file, relative to the root of the classpath directory from which
* it will be loaded (e.g. <code>com/foo/bar/foo.gif</code>).
*/
public static InputStream getStream (String path)
{
return getStream(path, ConfigUtil.class.getClassLoader());
}
/**
* Returns an input stream referencing a file that exists somewhere in the classpath.
*
* <p> The supplied classloader is searched first, followed by the system classloader.
*
* @param path The path to the file, relative to the root of the classpath directory from which
* it will be loaded (e.g. <code>com/foo/bar/foo.gif</code>).
*/
public static InputStream getStream (String path, ClassLoader loader)
{
// first try the supplied class loader
InputStream in = getResourceAsStream(path, loader);
if (in != null) {
return in;
}
// if that didn't work, try the system class loader (but only if it's different from the
// class loader we just tried)
try {
ClassLoader sysloader = ClassLoader.getSystemClassLoader();
if (sysloader != loader) {
return getResourceAsStream(path, loader);
}
} catch (AccessControlException ace) {
// can't get the system loader, no problem!
}
return null;
}
protected static InputStream getResourceAsStream (String path, ClassLoader loader)
{
// make sure the class loader isn't null
if (loader == null) {
// log.debug("No loader for get resource request", "path", path);
return null;
}
// try the path as is
InputStream in = loader.getResourceAsStream(path);
if (in != null) {
return in;
}
// try toggling the leading slash
return loader.getResourceAsStream(togglePath(path));
}
protected static Enumeration<URL> getResources (String path, ClassLoader loader)
throws IOException
{
// make sure the class loader isn't null
if (loader == null) {
// log.debug("No loader for get resource request", "path", path);
return null;
}
// try the path as is
Enumeration<URL> enm = loader.getResources(path);
if (enm.hasMoreElements()) {
return enm;
}
// try toggling the leading slash
return loader.getResources(togglePath(path));
}
protected static String togglePath (String path)
{
if (path.startsWith("/")) {
return path.substring(1);
} else {
return "/" + path;
}
}
/** Used when parsing inherited properties. */
protected static final class PropRecord extends ArrayList<PropRecord>
{
public String _package;
public String[] _overrides;
public String _extends;
public String path;
public URL sourceURL;
public PropRecord (String path, URL sourceURL) {
this.path = path;
this.sourceURL = sourceURL;
}
public void validate () throws IOException {
if (StringUtil.isBlank(_package)) {
throw new IOException("Properties file missing '_package' identifier " + this);
}
if ((_overrides != null && _overrides.length > 0) &&
(!StringUtil.isBlank(_extends))) {
throw new IOException(
"Properties file cannot use both '_overrides' and '_extends' " + this);
}
}
@Override public boolean equals (Object other) {
return (other instanceof PropRecord) && _package.equals(((PropRecord)other)._package);
}
@Override public String toString () {
return "[package=" + _package + ", overrides=" + StringUtil.toString(_overrides) +
", extends=" + _extends + ", path=" + path + ", source=" + sourceURL + "]";
}
}
protected static final String PACKAGE_KEY = "_package";
protected static final String OVERRIDES_KEY = "_overrides";
protected static final String EXTENDS_KEY = "_extends";
}
|
package org.jdbdt;
import java.math.BigDecimal;
import java.sql.JDBCType;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.function.Function;
/**
* CSV input conversion helper class.
* @since 1.3
*
*/
enum CSVInputConversion {
/** Singleton instance */
INSTANCE;
/**
* Interface for data conversions.
* @param <T> Type of data.
*/
private class DataConversion<T> {
/** Target lass */
final Class<T> javaClass;
/** Conversion function. */
final Function<T, Object> func;
@SuppressWarnings("javadoc")
DataConversion(Class<T> javaClass, Function<T,Object> func) {
this.javaClass = javaClass;
this.func = func;
}
}
@SuppressWarnings("javadoc")
private final IdentityHashMap<JDBCType, LinkedList<DataConversion<?>>> dataConv
= new IdentityHashMap<>();
@SuppressWarnings("javadoc")
private void init(JDBCType type, Class<?> javaClass) {
init(type, javaClass, null);
}
@SuppressWarnings("javadoc")
private <T> void init(JDBCType type, Class<T> javaClass, Function<T,Object> func) {
LinkedList<DataConversion<?>> list = dataConv.get(type);
if (list == null) {
list = new LinkedList<>();
dataConv.put(type, list);
}
list.addLast(new DataConversion<T>(javaClass, func));
}
/**
* Convert object of given type.
* @param type JDBC type.
* @param o Input.
* @return Converted object or <code>o</code> if no conversion is either possible or required.
*/
@SuppressWarnings("unchecked")
public Object convert(JDBCType type, Object o) {
Class<?> javaClass = o.getClass();
LinkedList<DataConversion<?>> list = dataConv.get(type);
if (list != null) {
for (DataConversion<?> conv : list) {
if (conv.javaClass == javaClass) {
if (conv.func == null) {
break;
}
else {
try {
o = ((Function<Object,Object>) conv.func).apply(o);
break;
}
catch(RuntimeException e) {
}
}
}
}
}
return o;
}
/**
* Constructor.
*/
CSVInputConversion() {
// BOOLEAN
init(JDBCType.BOOLEAN, Boolean.class);
init(JDBCType.BOOLEAN, Number.class, n -> n.intValue() != 0);
init(JDBCType.BOOLEAN, String.class, Boolean::parseBoolean);
init(JDBCType.BOOLEAN, String.class, s -> Integer.parseInt(s) != 0);
// BIT
init(JDBCType.BIT, Boolean.class);
init(JDBCType.BIT, Number.class, n -> n.intValue() != 0);
init(JDBCType.BIT, String.class, Boolean::parseBoolean);
init(JDBCType.BIT, String.class, s -> Integer.parseInt(s) != 0);
// TINYINT
init(JDBCType.TINYINT, Byte.class);
init(JDBCType.TINYINT, Number.class, Number::byteValue);
init(JDBCType.TINYINT, String.class, Byte::parseByte);
// SMALLINT
init(JDBCType.SMALLINT, Short.class);
init(JDBCType.SMALLINT, Number.class, Number::shortValue);
init(JDBCType.SMALLINT, String.class, Short::parseShort);
// INTEGER
init(JDBCType.INTEGER, Integer.class);
init(JDBCType.INTEGER, Number.class, Number::intValue);
init(JDBCType.INTEGER, String.class, Integer::parseInt);
// BIGINT
init(JDBCType.BIGINT, Long.class);
init(JDBCType.BIGINT, Number.class, Number::longValue);
init(JDBCType.BIGINT, String.class, Long::parseLong);
// REAL
init(JDBCType.REAL, Float.class);
init(JDBCType.REAL, Number.class, Number::floatValue);
init(JDBCType.REAL, String.class, Float::parseFloat);
// FLOAT
init(JDBCType.FLOAT, Double.class);
init(JDBCType.FLOAT, Number.class, Number::doubleValue);
init(JDBCType.FLOAT, String.class, Double::parseDouble);
// DOUBLE
init(JDBCType.DOUBLE, Double.class);
init(JDBCType.DOUBLE, Number.class, Number::doubleValue);
init(JDBCType.DOUBLE, String.class, Double::parseDouble);
// DECIMAL
init(JDBCType.DECIMAL, BigDecimal.class);
init(JDBCType.DECIMAL, Double.class, BigDecimal::valueOf);
init(JDBCType.DECIMAL, Long.class, BigDecimal::valueOf);
init(JDBCType.DECIMAL, String.class, s -> BigDecimal.valueOf(Double.parseDouble(s)));
// NUMERIC
init(JDBCType.NUMERIC, BigDecimal.class);
init(JDBCType.NUMERIC, Double.class, BigDecimal::valueOf);
init(JDBCType.NUMERIC, Long.class, BigDecimal::valueOf);
init(JDBCType.NUMERIC, String.class, s -> BigDecimal.valueOf(Double.parseDouble(s)));
// DATE
init(JDBCType.DATE, java.sql.Date.class);
init(JDBCType.DATE, String.class, java.sql.Date::valueOf);
// TIME
init(JDBCType.TIME, java.sql.Time.class);
init(JDBCType.TIME, String.class, java.sql.Time::valueOf);
// TIMESTAMP
init(JDBCType.TIMESTAMP, java.sql.Timestamp.class);
init(JDBCType.TIMESTAMP, String.class, java.sql.Timestamp::valueOf);
// VARCHAR
init(JDBCType.LONGNVARCHAR, String.class);
init(JDBCType.VARCHAR, String.class);
init(JDBCType.CHAR, String.class);
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String related utility functions.
*/
public class StringUtil
{
/**
* Used to format objects in {@link #listToString(Object,StringUtil.Formatter)}.
*/
public static class Formatter
{
/** Formats the supplied object into a string. */
public String toString (Object object) {
return object == null ? "null" : object.toString();
}
/** Returns the string that will be prepended to a formatted list. */
public String getOpenBox () {
return "(";
}
/** Returns the string that will be appended to a formatted list. */
public String getCloseBox () {
return ")";
}
}
/**
* @return true if the string is null or empty, false otherwise.
*
* @deprecated use isBlank instead.
*/
@Deprecated
public static boolean blank (String value)
{
return isBlank(value);
}
/**
* @return true if the string is null or consists only of whitespace, false otherwise.
*/
public static boolean isBlank (String value)
{
for (int ii = 0, ll = (value == null) ? 0 : value.length(); ii < ll; ii++) {
if (!Character.isWhitespace(value.charAt(ii))) {
return false;
}
}
return true;
}
/**
* Calls {@link String#trim} on non-null values, returns null for null values.
*/
public static String trim (String value)
{
return (value == null) ? null : value.trim();
}
/**
* @return the supplied string if it is non-null, "" if it is null.
*/
public static String deNull (String value)
{
return (value == null) ? "" : value;
}
/**
* Truncate the specified String if it is longer than maxLength.
*/
public static String truncate (String s, int maxLength)
{
return truncate(s, maxLength, "");
}
/**
* Returns the string if it is non-blank (see {@link #isBlank}), the default value otherwise.
*/
public static String getOr (String value, String defval)
{
return isBlank(value) ? defval : value;
}
/**
* Truncate the specified String if it is longer than maxLength. The string will be truncated
* at a position such that it is maxLength chars long after the addition of the 'append'
* String.
*
* @param append a String to add to the truncated String only after truncation.
*/
public static String truncate (String s, int maxLength, String append)
{
if ((s == null) || (s.length() <= maxLength)) {
return s;
} else {
return s.substring(0, maxLength - append.length()) + append;
}
}
/**
* Returns a version of the supplied string with the first letter capitalized.
*/
public static String capitalize (String s)
{
if (isBlank(s)) {
return s;
}
char c = s.charAt(0);
if (Character.isUpperCase(c)) {
return s;
} else {
return String.valueOf(Character.toUpperCase(c)) + s.substring(1);
}
}
/**
* Returns a US locale lower case string. Useful when manipulating filenames and resource
* keys which would not have locale specific characters.
*/
public static String toUSLowerCase (String s)
{
return isBlank(s) ? s : s.toLowerCase(Locale.US);
}
/**
* Returns a US locale upper case string. Useful when manipulating filenames and resource
* keys which would not have locale specific characters.
*/
public static String toUSUpperCase (String s)
{
return isBlank(s) ? s : s.toUpperCase(Locale.US);
}
/**
* Validates a character.
*/
public static interface CharacterValidator
{
public boolean isValid (char c);
}
/**
* Sanitize the specified String so that only valid characters are in it.
*/
public static String sanitize (String source, CharacterValidator validator)
{
if (source == null) {
return null;
}
int nn = source.length();
StringBuilder buf = new StringBuilder(nn);
for (int ii=0; ii < nn; ii++) {
char c = source.charAt(ii);
if (validator.isValid(c)) {
buf.append(c);
}
}
return buf.toString();
}
/**
* Sanitize the specified String such that each character must match against the regex
* specified.
*/
public static String sanitize (String source, String charRegex)
{
final StringBuilder buf = new StringBuilder(" ");
final Matcher matcher = Pattern.compile(charRegex).matcher(buf);
return sanitize(source, new CharacterValidator() {
public boolean isValid (char c) {
buf.setCharAt(0, c);
return matcher.matches();
}
});
}
/**
* Returns a new string based on <code>source</code> with all instances of <code>before</code>
* replaced with <code>after</code>.
*/
public static String replace (String source, String before, String after)
{
int pos = source.indexOf(before);
if (pos == -1) {
return source;
}
StringBuilder sb = new StringBuilder(source.length() + 32);
int blength = before.length();
int start = 0;
while (pos != -1) {
sb.append(source.substring(start, pos));
sb.append(after);
start = pos + blength;
pos = source.indexOf(before, start);
}
sb.append(source.substring(start));
return sb.toString();
}
/**
* Pads the supplied string to the requested string width by appending spaces to the end of the
* returned string. If the original string is wider than the requested width, it is returned
* unmodified.
*/
public static String pad (String value, int width)
{
// sanity check
if (width <= 0) {
throw new IllegalArgumentException("Pad width must be greater than zero.");
} else if (value.length() >= width) {
return value;
} else {
return value + spaces(width-value.length());
}
}
/**
* Pads the supplied string to the requested string width by prepending spaces to the end of
* the returned string. If the original string is wider than the requested width, it is
* returned unmodified.
*/
public static String prepad (String value, int width)
{
// sanity check
if (width <= 0) {
throw new IllegalArgumentException("Pad width must be greater than zero.");
} else if (value.length() >= width) {
return value;
} else {
return spaces(width-value.length()) + value;
}
}
/**
* Returns a string containing the requested number of spaces.
*/
public static String spaces (int count)
{
return fill(' ', count);
}
/**
* Returns a string containing the specified character repeated the specified number of times.
*/
public static String fill (char c, int count)
{
char[] sameChars = new char[count];
Arrays.fill(sameChars, c);
return new String(sameChars);
}
/**
* Returns whether the supplied string represents an integer value by attempting to parse it
* with {@link Integer#parseInt}.
*/
public static boolean isInteger (String value)
{
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException nfe) {
// fall through
}
return false;
}
/**
* Formats a floating point value with useful default rules; ie. always display a digit to the
* left of the decimal and display only two digits to the right of the decimal (rounding as
* necessary).
*/
public static String format (float value)
{
return _ffmt.format(value);
}
/**
* Formats a floating point value with useful default rules; ie. always display a digit to the
* left of the decimal and display only two digits to the right of the decimal (rounding as
* necessary).
*/
public static String format (double value)
{
return _ffmt.format(value);
}
/**
* Converts the supplied object to a string. Normally this is accomplished via the object's
* built in <code>toString()</code> method, but in the case of arrays, <code>toString()</code>
* is called on each element and the contents are listed like so:
*
* <pre>
* (value, value, value)
* </pre>
*
* Arrays of ints, longs, floats and doubles are also handled for convenience.
*
* <p> Additionally, <code>Enumeration</code> or <code>Iterator</code> objects can be passed
* and they will be enumerated and output in a similar manner to arrays. Bear in mind that this
* uses up the enumeration or iterator in question.
*
* <p> Also note that passing null will result in the string "null" being returned.
*/
public static String toString (Object val)
{
StringBuilder buf = new StringBuilder();
toString(buf, val);
return buf.toString();
}
/**
* Like the single argument {@link #toString(Object)} with the additional function of
* specifying the characters that are used to box in list and array types. For example, if "["
* and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>.
*/
public static String toString (
Object val, String openBox, String closeBox)
{
StringBuilder buf = new StringBuilder();
toString(buf, val, openBox, closeBox);
return buf.toString();
}
/**
* Converts the supplied value to a string and appends it to the supplied string buffer. See
* the single argument version for more information.
*
* @param buf the string buffer to which we will append the string.
* @param val the value from which to generate the string.
*/
public static void toString (StringBuilder buf, Object val)
{
toString(buf, val, "(", ")");
}
/**
* Converts the supplied value to a string and appends it to the supplied string buffer. The
* specified boxing characters are used to enclose list and array types. For example, if "["
* and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>.
*
* @param buf the string buffer to which we will append the string.
* @param val the value from which to generate the string.
* @param openBox the opening box character.
* @param closeBox the closing box character.
*/
public static void toString (StringBuilder buf, Object val, String openBox, String closeBox)
{
toString(buf, val, openBox, closeBox, ", ");
}
/**
* Converts the supplied value to a string and appends it to the supplied string buffer. The
* specified boxing characters are used to enclose list and array types. For example, if "["
* and "]" were supplied, an int array might be formatted like so: <code>[1, 3, 5]</code>.
*
* @param buf the string buffer to which we will append the string.
* @param val the value from which to generate the string.
* @param openBox the opening box character.
* @param closeBox the closing box character.
* @param sep the separator string.
*/
public static void toString (
StringBuilder buf, Object val, String openBox, String closeBox, String sep)
{
if (val instanceof byte[]) {
buf.append(openBox);
byte[] v = (byte[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof short[]) {
buf.append(openBox);
short[] v = (short[])val;
for (short i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof int[]) {
buf.append(openBox);
int[] v = (int[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof long[]) {
buf.append(openBox);
long[] v = (long[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof float[]) {
buf.append(openBox);
float[] v = (float[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof double[]) {
buf.append(openBox);
double[] v = (double[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i]);
}
buf.append(closeBox);
} else if (val instanceof Object[]) {
buf.append(openBox);
Object[] v = (Object[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(toString(v[i]));
}
buf.append(closeBox);
} else if (val instanceof boolean[]) {
buf.append(openBox);
boolean[] v = (boolean[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(v[i] ? "t" : "f");
}
buf.append(closeBox);
} else if (val instanceof Iterable) {
toString(buf, ((Iterable<?>)val).iterator(), openBox, closeBox);
} else if (val instanceof Iterator) {
buf.append(openBox);
Iterator<?> iter = (Iterator<?>)val;
for (int i = 0; iter.hasNext(); i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(toString(iter.next()));
}
buf.append(closeBox);
} else if (val instanceof Enumeration) {
buf.append(openBox);
Enumeration<?> enm = (Enumeration<?>)val;
for (int i = 0; enm.hasMoreElements(); i++) {
if (i > 0) {
buf.append(sep);
}
buf.append(toString(enm.nextElement()));
}
buf.append(closeBox);
} else if (val instanceof Point2D) {
Point2D p = (Point2D)val;
buf.append(openBox);
coordsToString(buf, (int)p.getX(), (int)p.getY());
buf.append(closeBox);
} else if (val instanceof Dimension2D) {
Dimension2D d = (Dimension2D)val;
buf.append(openBox);
buf.append(d.getWidth()).append("x").append(d.getHeight());
buf.append(closeBox);
} else if (val instanceof Rectangle2D) {
Rectangle2D r = (Rectangle2D)val;
buf.append(openBox);
buf.append(r.getWidth()).append("x").append(r.getHeight());
coordsToString(buf, (int)r.getX(), (int)r.getY());
buf.append(closeBox);
} else {
buf.append(val);
}
}
/**
* Formats a collection of elements (either an array of objects, an {@link Iterator}, an {@link
* Enumeration} or a {@link Collection}) using the supplied formatter on each element. Note
* that if you simply wish to format a collection of elements by calling {@link
* Object#toString} on each element, you can just pass the list to the {@link
* #toString(Object)} method which will do just that.
*/
public static String listToString (Object val, Formatter formatter)
{
StringBuilder buf = new StringBuilder();
listToString(buf, val, formatter);
return buf.toString();
}
/**
* Formats the supplied collection into the supplied string buffer using the supplied
* formatter. See {@link #listToString(Object,StringUtil.Formatter)} for more details.
*/
public static void listToString (StringBuilder buf, Object val, Formatter formatter)
{
// get an iterator if this is a collection
if (val instanceof Iterable) {
val = ((Iterable<?>)val).iterator();
}
String openBox = formatter.getOpenBox();
String closeBox = formatter.getCloseBox();
if (val instanceof Object[]) {
buf.append(openBox);
Object[] v = (Object[])val;
for (int i = 0; i < v.length; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(formatter.toString(v[i]));
}
buf.append(closeBox);
} else if (val instanceof Iterator) {
buf.append(openBox);
Iterator<?> iter = (Iterator<?>)val;
for (int i = 0; iter.hasNext(); i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(formatter.toString(iter.next()));
}
buf.append(closeBox);
} else if (val instanceof Enumeration) {
buf.append(openBox);
Enumeration<?> enm = (Enumeration<?>)val;
for (int i = 0; enm.hasMoreElements(); i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(formatter.toString(enm.nextElement()));
}
buf.append(closeBox);
} else {
// fall back on the general purpose
toString(buf, val);
}
}
/**
* Generates a string representation of the supplied object by calling {@link #toString} on the
* contents of its public fields and prefixing that by the name of the fields. For example:
*
* <p><code>[itemId=25, itemName=Elvis, itemCoords=(14, 25)]</code>
*/
public static String fieldsToString (Object object)
{
return fieldsToString(object, ", ");
}
/**
* Like {@link #fieldsToString(Object)} except that the supplied separator string will be used
* between fields.
*/
public static String fieldsToString (Object object, String sep)
{
StringBuilder buf = new StringBuilder("[");
fieldsToString(buf, object, sep);
return buf.append("]").toString();
}
/**
* Appends to the supplied string buffer a representation of the supplied object by calling
* {@link #toString} on the contents of its public fields and prefixing that by the name of the
* fields. For example:
*
* <p><code>itemId=25, itemName=Elvis, itemCoords=(14, 25)</code>
*
* <p>Note: unlike the version of this method that returns a string, enclosing brackets are not
* included in the output of this method.
*/
public static void fieldsToString (StringBuilder buf, Object object)
{
fieldsToString(buf, object, ", ");
}
/**
* Like {@link #fieldsToString(StringBuilder,Object)} except that the supplied separator will
* be used between fields.
*/
public static void fieldsToString (
StringBuilder buf, Object object, String sep)
{
Class<?> clazz = object.getClass();
Field[] fields = clazz.getFields();
int written = 0;
// we only want non-static fields
for (int i = 0; i < fields.length; i++) {
int mods = fields[i].getModifiers();
if ((mods & Modifier.PUBLIC) == 0 || (mods & Modifier.STATIC) != 0) {
continue;
}
if (written > 0) {
buf.append(sep);
}
// look for a toString() method for this field
buf.append(fields[i].getName()).append("=");
try {
try {
Method meth = clazz.getMethod(fields[i].getName() + "ToString", new Class[0]);
buf.append(meth.invoke(object, (Object[]) null));
} catch (NoSuchMethodException nsme) {
toString(buf, fields[i].get(object));
}
} catch (Exception e) {
buf.append("<error: " + e + ">");
}
written++;
}
}
/**
* Formats a pair of coordinates such that positive values are rendered with a plus prefix and
* negative values with a minus prefix. Examples would look like: <code>+3+4</code>
* <code>-5+7</code>, etc.
*/
public static String coordsToString (int x, int y)
{
StringBuilder buf = new StringBuilder();
coordsToString(buf, x, y);
return buf.toString();
}
/**
* Formats a pair of coordinates such that positive values are rendered with a plus prefix and
* negative values with a minus prefix. Examples would look like: <code>+3+4</code>
* <code>-5+7</code>, etc.
*/
public static void coordsToString (StringBuilder buf, int x, int y)
{
if (x >= 0) {
buf.append("+");
}
buf.append(x);
if (y >= 0) {
buf.append("+");
}
buf.append(y);
}
/**
* Attempts to generate a string representation of the object using {@link Object#toString},
* but catches any exceptions that are thrown and reports them in the returned string
* instead. Useful for situations where you can't trust the rat bastards that implemented the
* object you're toString()ing.
*/
public static String safeToString (Object object)
{
try {
return toString(object);
} catch (Throwable t) {
// We catch any throwable, even Errors. Someone is just trying to debug something,
// probably inside another catch block.
return "<toString() failure: " + t + ">";
}
}
/**
* URL encodes the specified string using the UTF-8 character encoding.
*/
public static String encode (String s)
{
try {
return (s != null) ? URLEncoder.encode(s, "UTF-8") : null;
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("UTF-8 is unknown in this Java.");
}
}
/**
* URL decodes the specified string using the UTF-8 character encoding.
*/
public static String decode (String s)
{
try {
return (s != null) ? URLDecoder.decode(s, "UTF-8") : null;
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("UTF-8 is unknown in this Java.");
}
}
/**
* Generates a string from the supplied bytes that is the HEX encoded representation of those
* bytes. Returns the empty string for a <code>null</code> or empty byte array.
*
* @param bytes the bytes for which we want a string representation.
* @param count the number of bytes to stop at (which will be coerced into being <= the length
* of the array).
*/
public static String hexlate (byte[] bytes, int count)
{
if (bytes == null) {
return "";
}
count = Math.min(count, bytes.length);
char[] chars = new char[count*2];
for (int i = 0; i < count; i++) {
int val = bytes[i];
if (val < 0) {
val += 256;
}
chars[2*i] = XLATE.charAt(val/16);
chars[2*i+1] = XLATE.charAt(val%16);
}
return new String(chars);
}
/**
* Generates a string from the supplied bytes that is the HEX encoded representation of those
* bytes.
*/
public static String hexlate (byte[] bytes)
{
return (bytes == null) ? "" : hexlate(bytes, bytes.length);
}
/**
* Turn a hexlated String back into a byte array.
*/
public static byte[] unhexlate (String hex)
{
if (hex == null || (hex.length() % 2 != 0)) {
return null;
}
// if for some reason we are given a hex string that wasn't made by hexlate, convert to
// lowercase so things work.
hex = hex.toLowerCase();
byte[] data = new byte[hex.length()/2];
for (int ii = 0; ii < hex.length(); ii+=2) {
int value = (byte)(XLATE.indexOf(hex.charAt(ii)) << 4);
value += XLATE.indexOf(hex.charAt(ii+1));
// values over 127 are wrapped around, restoring negative bytes
data[ii/2] = (byte)value;
}
return data;
}
/**
* Encodes the supplied source text into an MD5 hash.
*/
public static byte[] md5 (String source)
{
return digest("MD5", source);
}
/**
* Returns a hex string representing the MD5 encoded source.
*
* @exception RuntimeException thrown if the MD5 codec was not available in this JVM.
*/
public static String md5hex (String source)
{
return hexlate(md5(source));
}
/**
* Returns a hex string representing the SHA-1 encoded source.
*
* @exception RuntimeException thrown if the SHA-1 codec was not available in this JVM.
*/
public static String sha1hex (String source)
{
return hexlate(digest("SHA-1", source));
}
/**
* Parses an array of signed byte-sized integers from their string representation. The array
* should be represented as a bare list of numbers separated by commas, for example:
*
* <pre>25, 17, 21, 99</pre>
*
* Any inability to parse the short array will result in the function returning null.
*/
public static byte[] parseByteArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
byte[] vals = new byte[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Byte.parseByte(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of short integers from their string representation. The array should be
* represented as a bare list of numbers separated by commas, for example:
*
* <pre>25, 17, 21, 99</pre>
*
* Any inability to parse the short array will result in the function returning null.
*/
public static short[] parseShortArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
short[] vals = new short[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Short.parseShort(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of integers from it's string representation. The array should be represented
* as a bare list of numbers separated by commas, for example:
*
* <pre>25, 17, 21, 99</pre>
*
* Any inability to parse the int array will result in the function returning null.
*/
public static int[] parseIntArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
int[] vals = new int[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Integer.parseInt(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of longs from it's string representation. The array should be represented as
* a bare list of numbers separated by commas, for example:
*
* <pre>25, 17125141422, 21, 99</pre>
*
* Any inability to parse the long array will result in the function returning null.
*/
public static long[] parseLongArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
long[] vals = new long[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Long.parseLong(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of floats from it's string representation. The array should be represented
* as a bare list of numbers separated by commas, for example:
*
* <pre>25.0, .5, 1, 0.99</pre>
*
* Any inability to parse the array will result in the function returning null.
*/
public static float[] parseFloatArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
float[] vals = new float[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Float.parseFloat(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of doubles from its string representation. The array should be represented
* as a bare list of numbers separated by commas, for example:
*
* <pre>25.0, .5, 1, 0.99</pre>
*
* Any inability to parse the array will result in the function returning null.
*/
public static double[] parseDoubleArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
double[] vals = new double[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
try {
// trim the whitespace from the token
vals[i] = Double.parseDouble(tok.nextToken().trim());
} catch (NumberFormatException nfe) {
return null;
}
}
return vals;
}
/**
* Parses an array of booleans from its string representation. The array should be represented
* as a bare list of numbers separated by commas, for example:
*
* <pre>false, false, true, false</pre>
*/
public static boolean[] parseBooleanArray (String source)
{
StringTokenizer tok = new StringTokenizer(source, ",");
boolean[] vals = new boolean[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
// accept a lone 't' for true for compatibility with toString(boolean[])
String token = tok.nextToken().trim();
vals[i] = Boolean.parseBoolean(token) || token.equalsIgnoreCase("t");
}
return vals;
}
/**
* Parses an array of strings from a single string. The array should be represented as a bare
* list of strings separated by commas, for example:
*
* <pre>mary, had, a, little, lamb, and, an, escaped, comma,,</pre>
*
* If a comma is desired in one of the strings, it should be escaped by putting two commas in a
* row. Any inability to parse the string array will result in the function returning null.
*/
public static String[] parseStringArray (String source)
{
return parseStringArray(source, false);
}
/**
* Like {@link #parseStringArray(String)} but can be instructed to invoke {@link String#intern}
* on the strings being parsed into the array.
*/
public static String[] parseStringArray (String source, boolean intern)
{
int tcount = 0, tpos = -1, tstart = 0;
// empty strings result in zero length arrays
if (source.length() == 0) {
return new String[0];
}
// sort out escaped commas
source = replace(source, ",,", "%COMMA%");
// count up the number of tokens
while ((tpos = source.indexOf(",", tpos+1)) != -1) {
tcount++;
}
String[] tokens = new String[tcount+1];
tpos = -1; tcount = 0;
// do the split
while ((tpos = source.indexOf(",", tpos+1)) != -1) {
tokens[tcount] = source.substring(tstart, tpos);
tokens[tcount] = replace(tokens[tcount].trim(), "%COMMA%", ",");
if (intern) {
tokens[tcount] = tokens[tcount].intern();
}
tstart = tpos+1;
tcount++;
}
// grab the last token
tokens[tcount] = source.substring(tstart);
tokens[tcount] = replace(tokens[tcount].trim(), "%COMMA%", ",");
return tokens;
}
/**
* Joins an array of strings (or objects which will be converted to strings) into a single
* string separated by commas.
*/
public static String join (Object[] values)
{
return join(values, false);
}
/**
* Joins an array of strings into a single string, separated by commas, and optionally escaping
* commas that occur in the individual string values such that a subsequent call to {@link
* #parseStringArray} would recreate the string array properly. Any elements in the values
* array that are null will be treated as an empty string.
*/
public static String join (Object[] values, boolean escape)
{
return join(values, ", ", escape);
}
/**
* Joins the supplied array of strings into a single string separated by the supplied
* separator.
*/
public static String join (Object[] values, String separator)
{
return join(values, separator, false);
}
/**
* Joins an array of strings into a single string, separated by commas, and escaping commas
* that occur in the individual string values such that a subsequent call to {@link
* #parseStringArray} would recreate the string array properly. Any elements in the values
* array that are null will be treated as an empty string.
*/
public static String joinEscaped (String[] values)
{
return join(values, true);
}
/**
* Splits the supplied string into components based on the specified separator string.
*/
public static String[] split (String source, String sep)
{
// handle the special case of a zero-component source
if (isBlank(source)) {
return new String[0];
}
int tcount = 0, tpos = -1, tstart = 0;
// count up the number of tokens
while ((tpos = source.indexOf(sep, tpos+1)) != -1) {
tcount++;
}
String[] tokens = new String[tcount+1];
tpos = -1; tcount = 0;
// do the split
while ((tpos = source.indexOf(sep, tpos+1)) != -1) {
tokens[tcount] = source.substring(tstart, tpos);
tstart = tpos+1;
tcount++;
}
// grab the last token
tokens[tcount] = source.substring(tstart);
return tokens;
}
/**
* Returns an array containing the values in the supplied array converted into a table of
* values wrapped at the specified column count and fit into the specified field width. For
* example, a call like <code>toWrappedString(values, 5, 3)</code> might result in output like
* so:
*
* <pre>
* 12 1 9 10 3
* 1 5 7 9 11
* 39 15 12 80 16
* </pre>
*/
public static String toMatrixString (int[] values, int colCount, int fieldWidth)
{
StringBuilder buf = new StringBuilder();
StringBuilder valbuf = new StringBuilder();
for (int i = 0; i < values.length; i++) {
// format the integer value
valbuf.setLength(0);
valbuf.append(values[i]);
// pad with the necessary spaces
int spaces = fieldWidth - valbuf.length();
for (int s = 0; s < spaces; s++) {
buf.append(" ");
}
// append the value itself
buf.append(valbuf);
// if we're at the end of a row but not the end of the whole integer list, append a
// newline
if (i % colCount == (colCount-1) &&
i != values.length-1) {
buf.append(LINE_SEPARATOR);
}
}
return buf.toString();
}
/**
* Used to convert a time interval to a more easily human readable string of the form: <code>1d
* 15h 4m 15s 987m</code>.
*/
public static String intervalToString (long millis)
{
StringBuilder buf = new StringBuilder();
boolean started = false;
long days = millis / (24 * 60 * 60 * 1000);
if (days != 0) {
buf.append(days).append("d ");
started = true;
}
long hours = (millis / (60 * 60 * 1000)) % 24;
if (started || hours != 0) {
buf.append(hours).append("h ");
}
long minutes = (millis / (60 * 1000)) % 60;
if (started || minutes != 0) {
buf.append(minutes).append("m ");
}
long seconds = (millis / (1000)) % 60;
if (started || seconds != 0) {
buf.append(seconds).append("s ");
}
buf.append(millis % 1000).append("m");
return buf.toString();
}
/**
* Returns the class name of the supplied object, truncated to one package prior to the actual
* class name. For example, <code>com.samskivert.util.StringUtil</code> would be reported as
* <code>util.StringUtil</code>. If a null object is passed in, <code>null</code> is returned.
*/
public static String shortClassName (Object object)
{
return (object == null) ? "null" : shortClassName(object.getClass());
}
/**
* Returns the supplied class's name, truncated to one package prior to the actual class
* name. For example, <code>com.samskivert.util.StringUtil</code> would be reported as
* <code>util.StringUtil</code>.
*/
public static String shortClassName (Class<?> clazz)
{
return shortClassName(clazz.getName());
}
/**
* Returns the supplied class name truncated to one package prior to the actual class name. For
* example, <code>com.samskivert.util.StringUtil</code> would be reported as
* <code>util.StringUtil</code>.
*/
public static String shortClassName (String name)
{
int didx = name.lastIndexOf(".");
if (didx == -1) {
return name;
}
didx = name.lastIndexOf(".", didx-1);
if (didx == -1) {
return name;
}
return name.substring(didx+1);
}
/**
* Converts a name of the form <code>weAreSoCool</code> to a name of the form
* <code>WE_ARE_SO_COOL</code>.
*/
public static String unStudlyName (String name)
{
boolean seenLower = false;
StringBuilder nname = new StringBuilder();
int nlen = name.length();
for (int i = 0; i < nlen; i++) {
char c = name.charAt(i);
// if we see an upper case character and we've seen a lower case character since the
// last time we did so, slip in an _
if (Character.isUpperCase(c)) {
if (seenLower) {
nname.append("_");
}
seenLower = false;
nname.append(c);
} else {
seenLower = true;
nname.append(Character.toUpperCase(c));
}
}
return nname.toString();
}
/**
* See {@link #stringCode(String,StringBuilder)}.
*/
public static int stringCode (String value)
{
return stringCode(value, null);
}
/**
* Encodes (case-insensitively) a short English language string into a semi-unique
* integer. This is done by selecting the first eight characters in the string that fall into
* the set of the 16 most frequently used characters in the English language and converting
* them to a 4 bit value and storing the result into the returned integer.
*
* <p> This method is useful for mapping a set of string constants to a set of unique integers
* (e.g. mapping an enumerated type to an integer and back without having to require that the
* declaration order of the enumerated type remain constant for all time). The caller must, of
* course, ensure that no collisions occur.
*
* @param value the string to be encoded.
* @param encoded if non-null, a string buffer into which the characters used for the encoding
* will be recorded.
*/
public static int stringCode (String value, StringBuilder encoded)
{
int code = 0;
for (int ii = 0, uu = 0; ii < value.length(); ii++) {
char c = Character.toLowerCase(value.charAt(ii));
Integer cc = _letterToBits.get(c);
if (cc == null) {
continue;
}
code += cc.intValue();
if (encoded != null) {
encoded.append(c);
}
if (++uu == 8) {
break;
}
code <<= 4;
}
return code;
}
/**
* Wordwraps a string. Treats any whitespace character as a single character.
*
* <p>If you want the text to wrap for a graphical display, use a wordwrapping component
* such as {@link com.samskivert.swing.Label} instead.
*
* @param str String to word-wrap.
* @param width Maximum line length.
*/
public static String wordWrap (String str, int width)
{
int size = str.length();
StringBuilder buf = new StringBuilder(size + size/width);
int lastidx = 0;
while (lastidx < size) {
if (lastidx + width >= size) {
buf.append(str.substring(lastidx));
break;
}
int lastws = lastidx;
for (int ii = lastidx, ll = lastidx + width; ii < ll; ii++) {
char c = str.charAt(ii);
if (c == '\n') {
buf.append(str.substring(lastidx, ii + 1));
lastidx = ii + 1;
break;
} else if (Character.isWhitespace(c)) {
lastws = ii;
}
}
if (lastws == lastidx) {
buf.append(str.substring(lastidx, lastidx + width)).append(LINE_SEPARATOR);
lastidx += width;
} else if (lastws > lastidx) {
buf.append(str.substring(lastidx, lastws)).append(LINE_SEPARATOR);
lastidx = lastws + 1;
}
}
return buf.toString();
}
/**
* Helper function for the various <code>join</code> methods.
*/
protected static String join (Object[] values, String separator, boolean escape)
{
StringBuilder buf = new StringBuilder();
int vlength = values.length;
for (int i = 0; i < vlength; i++) {
if (i > 0) {
buf.append(separator);
}
String value = (values[i] == null) ? "" : values[i].toString();
buf.append((escape) ? replace(value, ",", ",,") : value);
}
return buf.toString();
}
/**
* Helper function for {@link #md5hex} and {@link #sha1hex}.
*/
protected static byte[] digest (String codec, String source)
{
try {
MessageDigest digest = MessageDigest.getInstance(codec);
return digest.digest(source.getBytes());
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException(codec + " codec not available");
}
}
/** Used to easily format floats with sensible defaults. */
protected static final NumberFormat _ffmt = NumberFormat.getInstance();
static {
_ffmt.setMinimumIntegerDigits(1);
_ffmt.setMinimumFractionDigits(1);
_ffmt.setMaximumFractionDigits(2);
}
/** Used by {@link #hexlate} and {@link #unhexlate}. */
protected static final String XLATE = "0123456789abcdef";
/** Maps the 16 most frequent letters in the English language to a number between 0 and
* 15. Used by {@link #stringCode}. */
protected static final IntMap<Integer> _letterToBits = IntMaps.newHashIntMap();
static {
String mostCommon = "etaoinsrhldcumfp";
for (int ii = mostCommon.length() - 1; ii >= 0; ii
_letterToBits.put(mostCommon.charAt(ii), Integer.valueOf(ii));
}
// sorry g, w, y, b, v, k, x, j, q, z
}
/** The line separator for this platform. */
protected static String LINE_SEPARATOR = "\n";
static {
try {
LINE_SEPARATOR = System.getProperty("line.separator");
} catch (Exception e) {
}
}
}
|
package org.jtrfp.trcl.gpu;
import java.nio.IntBuffer;
import javax.media.opengl.GL3;
public class GLUniform {
private final GLProgram prg;
private final int uniformID;
private static GL3 gl;
GLUniform(GLProgram prg, int uniformID) {
this.prg = prg;
this.uniformID = uniformID;
gl = prg.getGl();
}
public void set(float value) {
gl.glUniform1f(uniformID, value);
}
public void set(int value) {
gl.glUniform1i(uniformID, value);
}
public void setui(int value) {
gl.glUniform1ui(uniformID, value);
}
public void set(float float1, float float2, float float3) {
gl.glUniform3f(uniformID, float1, float2, float3);
}
public void setArrayui(int[] vals) {
gl.glUniform1uiv(uniformID, vals.length, IntBuffer.wrap(vals));
}
}// end GLUniform
|
package edu.toronto.cs.phenotips.measurements;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.script.service.ScriptService;
import edu.toronto.cs.phenotips.measurements.internal.AbstractMeasurementHandler;
/**
* Bridge offering access to specific {@link MeasurementHandler measurement handlers} to scripts.
*
* @version $Id$
* @since 1.0M3
*/
@Component
@Named("measurements")
@Singleton
public class MeasurementsScriptService implements ScriptService
{
/** Fuzzy value representing a measurement value considered extremely below normal. */
private static final String VALUE_EXTREME_BELOW_NORMAL = "extreme-below-normal";
/** Fuzzy value representing a measurement value considered below normal, but not extremely. */
private static final String VALUE_BELOW_NORMAL = "below-normal";
/** Fuzzy value representing a measurement value considered normal. */
private static final String VALUE_NORMAL = "normal";
/** Fuzzy value representing a measurement value considered above normal, but not extremely. */
private static final String VALUE_ABOVE_NORMAL = "above-normal";
/** Fuzzy value representing a measurement value considered extremely above normal. */
private static final String VALUE_EXTREME_ABOVE_NORMAL = "extreme-above-normal";
/** Logging helper object. */
@Inject
private Logger logger;
/** Provides access to the different measurement handlers by name at runtime. */
@Inject
@Named("context")
private Provider<ComponentManager> componentManager;
/**
* Get the handler for a specific kind of measurements.
*
* @param measurementType the type of measurement to return
* @return the requested handler, {@code null} if not found
*/
public MeasurementHandler get(String measurementType)
{
try {
return this.componentManager.get().getInstance(MeasurementHandler.class, measurementType);
} catch (ComponentLookupException ex) {
this.logger.warn("Requested unknown measurement type [{}]", measurementType);
return null;
}
}
/**
* Get all the measurements handlers.
*
* @return a list of all the measurement handlers, or an empty list if there was a problem retrieving the actual
* list
*/
public List<MeasurementHandler> getAvailableMeasurementHandlers()
{
try {
List<MeasurementHandler> result = this.componentManager.get().getInstanceList(MeasurementHandler.class);
if (result == null) {
result = Collections.emptyList();
}
Collections.sort(result, MeasurementSorter.instance);
return result;
} catch (ComponentLookupException ex) {
this.logger.warn("Failed to list available measurements", ex);
return Collections.emptyList();
}
}
/**
* Get the names of all the measurements handlers.
*
* @return a set with the names of all the measurement handlers, or an empty set if there was a problem retrieving
* the actual values
*/
public Set<String> getAvailableMeasurementNames()
{
try {
Map<String, MeasurementHandler> handlers =
this.componentManager.get().getInstanceMap(MeasurementHandler.class);
if (handlers != null) {
Set<String> result = new TreeSet<String>(MeasurementNameSorter.instance);
result.addAll(handlers.keySet());
return result;
}
} catch (ComponentLookupException ex) {
this.logger.warn("Failed to list available measurement types", ex);
}
return Collections.emptySet();
}
/**
* Convert a percentile number into a string grossly describing the value.
*
* @param percentile a number between 0 and 100
* @return the percentile description
*/
public String getFuzzyValue(int percentile)
{
String returnValue = VALUE_NORMAL;
if (percentile <= 1) {
returnValue = VALUE_EXTREME_BELOW_NORMAL;
} else if (percentile <= 3) {
returnValue = VALUE_BELOW_NORMAL;
} else if (percentile >= 99) {
returnValue = VALUE_EXTREME_ABOVE_NORMAL;
} else if (percentile >= 97) {
returnValue = VALUE_ABOVE_NORMAL;
}
return returnValue;
}
/**
* Convert a standard deviation number into a string grossly describing the value.
*
* @param deviation standard deviation value
* @return the deviation description
*/
public String getFuzzyValue(double deviation)
{
String returnValue = VALUE_NORMAL;
if (deviation <= -3.0) {
returnValue = VALUE_EXTREME_BELOW_NORMAL;
} else if (deviation <= -2.0) {
returnValue = VALUE_BELOW_NORMAL;
} else if (deviation >= 3.0) {
returnValue = VALUE_EXTREME_ABOVE_NORMAL;
} else if (deviation >= 2.0) {
returnValue = VALUE_ABOVE_NORMAL;
}
return returnValue;
}
/**
* Temporary mechanism for sorting measurements, uses a hardcoded list of measurements in the desired order.
*
* @version $Id$
*/
private static final class MeasurementSorter implements Comparator<MeasurementHandler>
{
/** Hardcoded list of measurements and their order. */
private static final String[] TARGET_ORDER = new String[] {"weight", "height", "bmi", "armspan", "sitting",
"hc", "philtrum", "ear", "ocd", "icd", "pfl", "ipd", "hand", "palm", "foot"};
/** Singleton instance. */
private static MeasurementSorter instance = new MeasurementSorter();
@Override
public int compare(MeasurementHandler o1, MeasurementHandler o2)
{
String n1 = ((AbstractMeasurementHandler) o1).getName();
String n2 = ((AbstractMeasurementHandler) o2).getName();
int p1 = ArrayUtils.indexOf(TARGET_ORDER, n1);
int p2 = ArrayUtils.indexOf(TARGET_ORDER, n2);
if (p1 == -1 && p2 == -1) {
return n1.compareTo(n2);
} else if (p1 == -1) {
return 1;
} else if (p2 == -1) {
return -1;
}
return p1 - p2;
}
}
/**
* Temporary mechanism for sorting measurements, uses a hardcoded list of measurements in the desired order.
*
* @version $Id$
*/
private static final class MeasurementNameSorter implements Comparator<String>
{
/** Singleton instance. */
private static MeasurementNameSorter instance = new MeasurementNameSorter();
@Override
public int compare(String n1, String n2)
{
int p1 = ArrayUtils.indexOf(MeasurementSorter.TARGET_ORDER, n1);
int p2 = ArrayUtils.indexOf(MeasurementSorter.TARGET_ORDER, n2);
if (p1 == -1 && p2 == -1) {
return n1.compareTo(n2);
} else if (p1 == -1) {
return 1;
} else if (p2 == -1) {
return -1;
}
return p1 - p2;
}
}
}
|
package hep.lcio.util;
import hep.lcio.event.LCEvent;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
*
* @author jeremym
*
* Object comparison code refactored out of tonyj's old hep.lcio.test.RandomEvent .
*
*/
public class ObjectComparator {
// comparison result
public static final int NOT_EQUAL = 1;
public static final int EQUAL = 0;
public static final int NO_COMPARISON = -1;
// verbosity
public static final int SILENT = 0;
public static final int INFO = 1;
public static final int DEBUG = 2;
public static final int ALL = 3;
// current result
int m_result;
// current method
Method m_method ;
// dup map
Map m_alreadyChecked;
public ObjectComparator() {
m_result = EQUAL;
m_alreadyChecked = new HashMap();
}
private void setResultCode(int cr) throws IllegalArgumentException {
if ( cr < -1 || cr > 1 ) {
throw new IllegalArgumentException("Not a valid result: " + cr);
}
m_result = cr;
}
public String getResultString() {
String rs = "";
if ( m_result == NOT_EQUAL ) {
rs = "Not Equal";
} else if ( m_result == EQUAL ) {
rs = "Equal";
} else if ( m_result == NO_COMPARISON ) {
rs = "No Comparison";
}
return rs;
}
public void reset() {
//fg: should be same as c'tor
// m_result = NO_COMPARISON;
m_result = EQUAL ;
m_alreadyChecked.clear();
}
public int getResultCode() {
return m_result;
}
public void compare(Object o1, Object o2) throws IllegalArgumentException {
//System.out.println("class: " + o1.getClass().getCanonicalName() );
// did this object already?
if (m_alreadyChecked.get(o1) == o2) {
return;
}
// add to checked map
m_alreadyChecked.put(o1,o2);
try {
//System.out.println("comparisons...");
// basic object comparison
try {
if (o1 instanceof Comparable) {
//System.out.println("object");
compareObject(o1, o2);
}
} catch (Throwable t) {
System.out.println("error comparing object" );
}
// array
try {
if (o1.getClass().isArray()) {
//System.out.println("array");
compareArray(o1, o2);
}
} catch (Throwable t) {
System.out.println("error comparing array");
}
// collection
try {
if (o1 instanceof Collection) {
//System.out.println("collection");
compareCollection(o1, o2);
}
} catch (Throwable t) {
System.out.println("error comparing collection");
}
// bean
try {
compareBeanProperties(o1, o2);
} catch (Throwable t) {
System.out.println("error comparing bean properties");
}
// LCEvent
try {
if (o1 instanceof LCEvent) {
//System.out.println("LCEvent");
compareLCEvent(o1, o2);
}
} catch (Throwable t) {
System.out.println("error comparing LCEvent");
t.printStackTrace();
}
} catch (Throwable t) {
throw new IllegalArgumentException("FATAL ERROR: Could not compare " + o1 + " " + o2);
}
}
public void compareLCEvent(Object o1, Object o2) {
String[] names = ((LCEvent) o1).getCollectionNames();
for (int i=0; i<names.length; i++) {
System.out.println("object compare: " + names[i]);
Collection c1 = ((LCEvent) o1).getCollection(names[i]);
Collection c2 = ((LCEvent) o2).getCollection(names[i]);
// missing coll; don't bother comparing the rest of them
if (c1 == null || c2 == null) {
System.out.println("one of the events is missing coll: " + names[i]);
setResultCode(NOT_EQUAL);
return;
}
// different size colls treated like array with different # elements
if ( c1.size() != c2.size() ) {
System.out.println(names[i] + " size is different: " + c1.size() + " " + c2.size() );
setResultCode(NOT_EQUAL);
// same size coll
} else {
// iterate over coll, comparing the objects
Iterator i1 = c1.iterator();
Iterator i2 = c2.iterator();
while ( i1.hasNext() ) {
Object v1 = i1.next();
Object v2 = null;
if (i2.hasNext() ) {
v2 = i2.next();
// fewer elements in 2nd event
} else {
System.out.println("2nd event has fewer objects in coll: " + names[i]);
setResultCode(NOT_EQUAL);
break;
}
compare(v1,v2);
}
// more elements left in 2nd event
if (i2.hasNext() ) {
System.out.println("2nd event has more objects in coll: " + names[i]);
setResultCode(NOT_EQUAL);
}
}
}
}
public void compareObject(Object o1, Object o2) {
// both null
if (o1 == null && o2 == null) return;
// one null
if (o1 == null || o2 == null) {
System.out.println("one object is null");
setResultCode(NOT_EQUAL);
}
// comparison
if (o1 instanceof Comparable) {
int rc = ((Comparable) o1).compareTo(o2);
if (rc != 0) {
System.out.println( "objects not equal: " + o1.getClass().getName() + " ( last method: " + m_method + " )" );
System.out.println(o1 + " != " + o2);
setResultCode(NOT_EQUAL);
}
}
}
private void compareArray(Object o1, Object o2) {
if (Array.getLength(o1) != Array.getLength(o2)) {
System.out.println("arr len not equal");
setResultCode(NOT_EQUAL);
} else {
for (int i=0; i<Array.getLength(o1);i++) {
Object v1 = Array.get(o1, i);
Object v2 = Array.get(o2, i);
compare(v1, v2);
}
}
}
private void compareCollection(Object o1, Object o2) {
Collection c1 = (Collection) o1;
Collection c2 = (Collection) o2;
if (c1.size() != c2.size()) {
System.out.println("coll size !=");
setResultCode(NOT_EQUAL);
} else {
Iterator i1 = c1.iterator();
Iterator i2 = c2.iterator();
while ( i1.hasNext() ) {
Object v1 = i1.next();
Object v2 = i2.next();
compare(v1,v2);
}
}
}
private void compareBeanProperties(Object o1, Object o2) {
//System.out.println("bean");
try {
BeanInfo info = Introspector.getBeanInfo(o1.getClass(),Object.class);
PropertyDescriptor[] desc = info.getPropertyDescriptors();
//if ( desc.length == 0 ) {
// System.out.println("WARNING: no bean properties for " + o1.getClass().getCanonicalName() );
if ( desc.length != 0 ) {
for (int i=0; i<desc.length; i++) {
Method m = desc[i].getReadMethod();
m_method = m ;
if (m != null) {
try {
Object v1 = m.invoke(o1,null);
Object v2 = m.invoke(o2,null);
compare(v1,v2);
} catch (Throwable t) {
/* just eat it for now */
//System.out.println("skipping bean compare w/ error: " + desc[i].getDisplayName() );
//t.printStackTrace();
}
}
}
}
} catch (Throwable t) {
System.out.println("error comparing bean properties");
t.printStackTrace();
}
}
}
|
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.LayoutManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.plaf.TaskPaneAddon;
import org.jdesktop.swingx.plaf.TaskPaneUI;
/**
* <code>JXTaskPane</code> is a container for tasks and other
* arbitrary components.
*
* <p>
* Several <code>JXTaskPane</code>s are usually grouped together within a
* {@link org.jdesktop.swingx.JXTaskPaneContainer}. However it is not mandatory
* to use a JXTaskPaneContainer as the parent for JXTaskPane. The JXTaskPane can
* be added to any other container. See
* {@link org.jdesktop.swingx.JXTaskPaneContainer} to understand the benefits of
* using it as the parent container.
*
* <p>
* <code>JXTaskPane</code> provides control to expand and
* collapse the content area in order to show or hide the task list. It can have an
* <code>icon</code>, a <code>title</code> and can be marked as
* <code>special</code>. Marking a <code>JXTaskPane</code> as
* <code>special</code> ({@link #setSpecial(boolean)} is only a hint for
* the pluggable UI which will usually paint it differently (by example by
* using another color for the border of the pane).
*
* <p>
* When the JXTaskPane is expanded or collapsed, it will be
* animated with a fade effect. The animated can be disabled on a per
* component basis through {@link #setAnimated(boolean)}.
*
* To disable the animation for all newly created <code>JXTaskPane</code>,
* use the UIManager property:
* <code>UIManager.put("TaskPane.animate", Boolean.FALSE);</code>.
*
* <p>
* Example:
* <pre>
* <code>
* JXFrame frame = new JXFrame();
*
* // a container to put all JXTaskPane together
* JXTaskPaneContainer taskPaneContainer = new JXTaskPaneContainer();
*
* // create a first taskPane with common actions
* JXTaskPane actionPane = new JXTaskPane();
* actionPane.setTitle("Files and Folders");
* actionPane.setSpecial(true);
*
* // actions can be added, a hyperlink will be created
* Action renameSelectedFile = createRenameFileAction();
* actionPane.add(renameSelectedFile);
* actionPane.add(createDeleteFileAction());
*
* // add this taskPane to the taskPaneContainer
* taskPaneContainer.add(actionPane);
*
* // create another taskPane, it will show details of the selected file
* JXTaskPane details = new JXTaskPane();
* details.setTitle("Details");
*
* // add standard components to the details taskPane
* JLabel searchLabel = new JLabel("Search:");
* JTextField searchField = new JTextField("");
* details.add(searchLabel);
* details.add(searchField);
*
* taskPaneContainer.add(details);
*
* // put the action list on the left
* frame.add(taskPaneContainer, BorderLayout.EAST);
*
* // and a file browser in the middle
* frame.add(fileBrowser, BorderLayout.CENTER);
*
* frame.pack();
* frame.setVisible(true);
* </code>
* </pre>
*
* @see org.jdesktop.swingx.JXTaskPaneContainer
* @see org.jdesktop.swingx.JXCollapsiblePane
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
* @author Karl George Schaefer
*
* @javabean.attribute
* name="isContainer"
* value="Boolean.TRUE"
* rtexpr="true"
*
* @javabean.attribute
* name="containerDelegate"
* value="getContentPane"
*
* @javabean.class
* name="JXTaskPane"
* shortDescription="JXTaskPane is a container for tasks and other arbitrary components."
* stopClass="java.awt.Component"
*
* @javabean.icons
* mono16="JXTaskPane16-mono.gif"
* color16="JXTaskPane16.gif"
* mono32="JXTaskPane32-mono.gif"
* color32="JXTaskPane32.gif"
*/
public class JXTaskPane extends JPanel implements
JXCollapsiblePane.CollapsiblePaneContainer {
/**
* JXTaskPane pluggable UI key <i>swingx/TaskPaneUI</i>
*/
public final static String uiClassID = "swingx/TaskPaneUI";
// ensure at least the default ui is registered
static {
LookAndFeelAddons.contribute(new TaskPaneAddon());
}
/**
* Used when generating PropertyChangeEvents for the "scrollOnExpand" property
*/
public static final String SCROLL_ON_EXPAND_CHANGED_KEY = "scrollOnExpand";
/**
* Used when generating PropertyChangeEvents for the "title" property
*/
public static final String TITLE_CHANGED_KEY = "title";
/**
* Used when generating PropertyChangeEvents for the "icon" property
*/
public static final String ICON_CHANGED_KEY = "icon";
/**
* Used when generating PropertyChangeEvents for the "special" property
*/
public static final String SPECIAL_CHANGED_KEY = "special";
/**
* Used when generating PropertyChangeEvents for the "animated" property
*/
public static final String ANIMATED_CHANGED_KEY = "animated";
private String title;
private Icon icon;
private boolean special;
private boolean collapsed;
private boolean scrollOnExpand;
private int mnemonic;
private int mnemonicIndex = -1;
private JXCollapsiblePane collapsePane;
/**
* Creates a new empty <code>JXTaskPane</code>.
*/
public JXTaskPane() {
this((String) null);
}
/**
* Creates a new task pane with the specified title.
*
* @param title
* the title to use
*/
public JXTaskPane(String title) {
this(title, null);
}
/**
* Creates a new task pane with the specified icon.
*
* @param icon
* the icon to use
*/
public JXTaskPane(Icon icon) {
this(null, icon);
}
/**
* Creates a new task pane with the specified title and icon.
*
* @param title
* the title to use
* @param icon
* the icon to use
*/
public JXTaskPane(String title, Icon icon) {
collapsePane = new JXCollapsiblePane();
super.setLayout(new BorderLayout(0, 0));
super.addImpl(collapsePane, BorderLayout.CENTER, -1);
setTitle(title);
setIcon(icon);
updateUI();
setFocusable(true);
// disable animation if specified in UIManager
setAnimated(!Boolean.FALSE.equals(UIManager.get("TaskPane.animate")));
// listen for animation events and forward them to registered listeners
collapsePane.addPropertyChangeListener(
JXCollapsiblePane.ANIMATION_STATE_KEY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
JXTaskPane.this.firePropertyChange(evt.getPropertyName(), evt
.getOldValue(), evt.getNewValue());
}
});
}
/**
* Returns the contentPane object for this JXTaskPane.
* @return the contentPane property
*/
public Container getContentPane() {
return collapsePane.getContentPane();
}
/**
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the <code>UIManager</code>.
*
* @see javax.swing.JComponent#updateUI
*/
@Override
public void updateUI() {
// collapsePane is null when updateUI() is called by the "super()"
// constructor
if (collapsePane == null) {
return;
}
setUI((TaskPaneUI)LookAndFeelAddons.getUI(this, TaskPaneUI.class));
}
/**
* Sets the L&F object that renders this component.
*
* @param ui the <code>TaskPaneUI</code> L&F object
* @see javax.swing.UIDefaults#getUI
*
* @beaninfo bound: true hidden: true description: The UI object that
* implements the taskpane group's LookAndFeel.
*/
public void setUI(TaskPaneUI ui) {
super.setUI(ui);
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string {@link #uiClassID}
* @see javax.swing.JComponent#getUIClassID
* @see javax.swing.UIDefaults#getUI
*/
@Override
public String getUIClassID() {
return uiClassID;
}
/**
* Returns the title currently displayed in the border of this pane.
*
* @return the title currently displayed in the border of this pane
*/
public String getTitle() {
return title;
}
/**
* Sets the title to be displayed in the border of this pane.
*
* @param title the title to be displayed in the border of this pane
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setTitle(String title) {
String old = this.title;
this.title = title;
firePropertyChange(TITLE_CHANGED_KEY, old, title);
}
/**
* Returns the icon currently displayed in the border of this pane.
*
* @return the icon currently displayed in the border of this pane
*/
public Icon getIcon() {
return icon;
}
/**
* Sets the icon to be displayed in the border of this pane. Some pluggable
* UIs may impose size constraints for the icon. A size of 16x16 pixels is
* the recommended icon size.
*
* @param icon the icon to be displayed in the border of this pane
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setIcon(Icon icon) {
Icon old = this.icon;
this.icon = icon;
firePropertyChange(ICON_CHANGED_KEY, old, icon);
}
/**
* Returns true if this pane is "special".
*
* @return true if this pane is "special"
* @see #setSpecial(boolean)
*/
public boolean isSpecial() {
return special;
}
/**
* Sets this pane to be "special" or not. Marking a <code>JXTaskPane</code>
* as <code>special</code> is only a hint for the pluggable UI which will
* usually paint it differently (by example by using another color for the
* border of the pane).
*
* <p>
* Usually the first JXTaskPane in a JXTaskPaneContainer is marked as special
* because it contains the default set of actions which can be executed given
* the current context.
*
* @param special
* true if this pane is "special", false otherwise
* @javabean.property bound="true" preferred="true"
*/
public void setSpecial(boolean special) {
boolean oldValue = isSpecial();
this.special = special;
firePropertyChange(SPECIAL_CHANGED_KEY, oldValue, isSpecial());
}
/**
* Should this group be scrolled to be visible on expand.
*
* @param scrollOnExpand true to scroll this group to be
* visible if this group is expanded.
*
* @see #setCollapsed(boolean)
*
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setScrollOnExpand(boolean scrollOnExpand) {
boolean oldValue = isScrollOnExpand();
this.scrollOnExpand = scrollOnExpand;
firePropertyChange(SCROLL_ON_EXPAND_CHANGED_KEY,
oldValue, isScrollOnExpand());
}
/**
* Should this group scroll to be visible after
* this group was expanded.
*
* @return true if we should scroll false if nothing
* should be done.
*/
public boolean isScrollOnExpand() {
return scrollOnExpand;
}
/**
* Expands or collapses this group.
*
* @param collapsed
* true to collapse the group, false to expand it
* @javabean.property
* bound="true"
* preferred="false"
*/
public void setCollapsed(boolean collapsed) {
boolean oldValue = isCollapsed();
this.collapsed = collapsed;
collapsePane.setCollapsed(collapsed);
firePropertyChange("collapsed", oldValue, isCollapsed());
}
/**
* Returns the collapsed state of this task pane.
*
* @return {@code true} if the task pane is collapsed; {@code false}
* otherwise
*/
public boolean isCollapsed() {
return collapsed;
}
/**
* Enables or disables animation during expand/collapse transition.
*
* @param animated
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setAnimated(boolean animated) {
boolean oldValue = isAnimated();
collapsePane.setAnimated(animated);
firePropertyChange(ANIMATED_CHANGED_KEY, oldValue, isAnimated());
}
/**
* Returns true if this task pane is animated during expand/collapse
* transition.
*
* @return true if this task pane is animated during expand/collapse
* transition.
*/
public boolean isAnimated() {
return collapsePane.isAnimated();
}
/**
* Returns the keyboard mnemonic for the task pane.
*
* @return the keyboard mnemonic for the task pane
*/
public int getMnemonic() {
return mnemonic;
}
/**
* Sets the keyboard mnemonic on the task pane. The mnemonic is the key
* which when combined with the look and feel's mouseless modifier (usually
* Alt) will toggle this task pane.
* <p>
* A mnemonic must correspond to a single key on the keyboard and should be
* specified using one of the <code>VK_XXX</code> keycodes defined in
* <code>java.awt.event.KeyEvent</code>. Mnemonics are case-insensitive,
* therefore a key event with the corresponding keycode would cause the
* button to be activated whether or not the Shift modifier was pressed.
* <p>
* If the character defined by the mnemonic is found within the task pane's
* text string, the first occurrence of it will be underlined to indicate
* the mnemonic to the user.
*
* @param mnemonic
* the key code which represents the mnemonic
* @see java.awt.event.KeyEvent
* @see #setDisplayedMnemonicIndex
*
* @beaninfo bound: true attribute: visualUpdate true description: the
* keyboard character mnemonic
*/
public void setMnemonic(int mnemonic) {
int oldValue = getMnemonic();
this.mnemonic = mnemonic;
firePropertyChange("mnemonic", oldValue, getMnemonic());
updateDisplayedMnemonicIndex(getTitle(), mnemonic);
revalidate();
repaint();
}
/**
* Update the displayedMnemonicIndex property. This method
* is called when either text or mnemonic changes. The new
* value of the displayedMnemonicIndex property is the index
* of the first occurrence of mnemonic in text.
*/
private void updateDisplayedMnemonicIndex(String text, int mnemonic) {
if (text == null || mnemonic == '\0') {
mnemonicIndex = -1;
return;
}
char uc = Character.toUpperCase((char)mnemonic);
char lc = Character.toLowerCase((char)mnemonic);
int uci = text.indexOf(uc);
int lci = text.indexOf(lc);
if (uci == -1) {
mnemonicIndex = lci;
} else if(lci == -1) {
mnemonicIndex = uci;
} else {
mnemonicIndex = (lci < uci) ? lci : uci;
}
}
/**
* Returns the character, as an index, that the look and feel should
* provide decoration for as representing the mnemonic character.
*
* @since 1.4
* @return index representing mnemonic character
* @see #setDisplayedMnemonicIndex
*/
public int getDisplayedMnemonicIndex() {
return mnemonicIndex;
}
public void setDisplayedMnemonicIndex(int index)
throws IllegalArgumentException {
int oldValue = mnemonicIndex;
if (index == -1) {
mnemonicIndex = -1;
} else {
String text = getTitle();
int textLength = (text == null) ? 0 : text.length();
if (index < -1 || index >= textLength) { // index out of range
throw new IllegalArgumentException("index == " + index);
}
}
mnemonicIndex = index;
firePropertyChange("displayedMnemonicIndex", oldValue, index);
if (index != oldValue) {
revalidate();
repaint();
}
}
/**
* Adds an action to this <code>JXTaskPane</code>. Returns a
* component built from the action. The returned component has been
* added to the <code>JXTaskPane</code>.
*
* @param action
* @return a component built from the action
*/
public Component add(Action action) {
Component c = ((TaskPaneUI)ui).createAction(action);
add(c);
return c;
}
/**
* @see JXCollapsiblePane.CollapsiblePaneContainer
*/
public Container getValidatingContainer() {
return getParent();
}
/**
* Overridden to redirect call to the content pane.
*/
@Override
protected void addImpl(Component comp, Object constraints, int index) {
getContentPane().add(comp, constraints, index);
//Fixes SwingX #364; adding to internal component we need to revalidate ourself
revalidate();
}
/**
* Overridden to redirect call to the content pane.
*/
@Override
public void setLayout(LayoutManager mgr) {
if (collapsePane != null) {
getContentPane().setLayout(mgr);
}
}
/**
* Overridden to redirect call to the content pane
*/
@Override
public void remove(Component comp) {
getContentPane().remove(comp);
}
/**
* Overridden to redirect call to the content pane.
*/
@Override
public void remove(int index) {
getContentPane().remove(index);
}
/**
* Overridden to redirect call to the content pane.
*/
@Override
public void removeAll() {
getContentPane().removeAll();
}
/**
* @see JComponent#paramString()
*/
@Override
protected String paramString() {
return super.paramString()
+ ",title="
+ getTitle()
+ ",icon="
+ getIcon()
+ ",collapsed="
+ String.valueOf(isCollapsed())
+ ",special="
+ String.valueOf(isSpecial())
+ ",scrollOnExpand="
+ String.valueOf(isScrollOnExpand())
+ ",ui=" + getUI();
}
}
|
package org.lightmare.jpa;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.config.Configuration;
import org.lightmare.jndi.JndiManager;
import org.lightmare.jpa.jta.HibernateConfig;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.NamingUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Creates and caches {@link EntityManagerFactory} for each EJB bean
* {@link Class}'s appropriate field (annotated by @PersistenceContext)
*
* @author Levan
*
*/
public class JpaManager {
private List<String> classes;
private String path;
private URL url;
private Map<Object, Object> properties;
private boolean swapDataSource;
private boolean scanArchives;
private ClassLoader loader;
private static final String COULD_NOT_BIND_JNDI_ERROR = "could not bind connection";
private static final Logger LOG = Logger.getLogger(JpaManager.class);
private JpaManager() {
}
/**
* Checks if entity persistence.xml {@link URL} is provided
*
* @return boolean
*/
private boolean checkForURL() {
return ObjectUtils.notNull(url) && StringUtils.valid(url.toString());
}
/**
* Checks if entity classes or persistence.xml path are provided
*
* @param classes
* @return boolean
*/
private boolean checkForBuild() {
return CollectionUtils.valid(classes) || CollectionUtils.valid(path)
|| checkForURL() || swapDataSource || scanArchives;
}
/**
* Added transaction properties for JTA data sources
*/
private void addTransactionManager() {
if (properties == null) {
properties = new HashMap<Object, Object>();
}
HibernateConfig[] hibernateConfigs = HibernateConfig.values();
for (HibernateConfig hibernateConfig : hibernateConfigs) {
properties.put(hibernateConfig.key, hibernateConfig.value);
}
}
/**
* Creates {@link EntityManagerFactory} by hibernate or by extended builder
* {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file
* path are provided
*
* @see Ejb3ConfigurationImpl#configure(String, Map) and
* Ejb3ConfigurationImpl#createEntityManagerFactory()
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
@SuppressWarnings("deprecation")
private EntityManagerFactory buildEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
Ejb3ConfigurationImpl cfg;
boolean pathCheck = CollectionUtils.valid(path);
boolean urlCheck = checkForURL();
Ejb3ConfigurationImpl.Builder builder = new Ejb3ConfigurationImpl.Builder();
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
}
if (CollectionUtils.valid(classes)) {
builder.setClasses(classes);
// Loads entity classes to current ClassLoader instance
LibraryLoader.loadClasses(classes, loader);
}
if (pathCheck || urlCheck) {
Enumeration<URL> xmls;
ConfigLoader configLoader = new ConfigLoader();
if (pathCheck) {
xmls = configLoader.readFile(path);
} else {
xmls = configLoader.readURL(url);
}
builder.setXmls(xmls);
String shortPath = configLoader.getShortPath();
builder.setShortPath(shortPath);
}
builder.setSwapDataSource(swapDataSource);
builder.setScanArchives(scanArchives);
builder.setOverridenClassLoader(loader);
cfg = builder.build();
if (ObjectUtils.notTrue(swapDataSource)) {
addTransactionManager();
}
Ejb3ConfigurationImpl configured = cfg.configure(unitName, properties);
if (ObjectUtils.notNull(configured)) {
emf = configured.buildEntityManagerFactory();
} else {
emf = null;
}
return emf;
}
/**
* Checks if entity classes or persistence.xml file path are provided to
* create {@link EntityManagerFactory}
*
* @see #buildEntityManagerFactory(String, String, Map, List)
*
* @param unitName
* @param properties
* @param path
* @param classes
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private EntityManagerFactory createEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
if (checkForBuild()) {
emf = buildEntityManagerFactory(unitName);
} else if (properties == null) {
emf = Persistence.createEntityManagerFactory(unitName);
} else {
emf = Persistence.createEntityManagerFactory(unitName, properties);
}
return emf;
}
/**
* Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext}
*
* @param jndiName
* @param unitName
* @param emf
* @throws IOException
*/
private void bindJndiName(ConnectionSemaphore semaphore) throws IOException {
boolean bound = semaphore.isBound();
if (ObjectUtils.notTrue(bound)) {
String jndiName = semaphore.getJndiName();
if (CollectionUtils.valid(jndiName)) {
JndiManager jndiManager = new JndiManager();
try {
String fullJndiName = NamingUtils
.createJpaJndiName(jndiName);
if (jndiManager.lookup(fullJndiName) == null) {
jndiManager.rebind(fullJndiName, semaphore.getEmf());
}
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
String errorMessage = StringUtils.concat(
COULD_NOT_BIND_JNDI_ERROR, semaphore.getUnitName());
throw new IOException(errorMessage, ex);
}
}
}
semaphore.setBound(Boolean.TRUE);
}
/**
* Builds connection, wraps it in {@link ConnectionSemaphore} locks and
* caches appropriate instance
*
* @param unitName
* @throws IOException
*/
public void create(String unitName) throws IOException {
ConnectionSemaphore semaphore = ConnectionContainer
.getSemaphore(unitName);
if (semaphore.isInProgress()) {
EntityManagerFactory emf = createEntityManagerFactory(unitName);
semaphore.setEmf(emf);
semaphore.setInProgress(Boolean.FALSE);
bindJndiName(semaphore);
} else if (semaphore.getEmf() == null) {
String errorMessage = String.format(
"Connection %s was not in progress", unitName);
throw new IOException(errorMessage);
} else {
bindJndiName(semaphore);
}
}
/**
* Closes passed {@link EntityManagerFactory}
*
* @param emf
*/
public static void closeEntityManagerFactory(EntityManagerFactory emf) {
if (ObjectUtils.notNull(emf) && emf.isOpen()) {
emf.close();
}
}
public static void closeEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em) && em.isOpen()) {
em.close();
}
}
/**
* Builder class to create {@link JpaManager} class object
*
* @author Levan
*
*/
public static class Builder {
private JpaManager manager;
public Builder() {
manager = new JpaManager();
manager.scanArchives = Boolean.TRUE;
}
/**
* Sets {@link javax.persistence.Entity} class names to initialize
*
* @param classes
* @return {@link Builder}
*/
public Builder setClasses(List<String> classes) {
manager.classes = classes;
return this;
}
/**
* Sets {@link URL} for persistence.xml file
*
* @param url
* @return {@link Builder}
*/
public Builder setURL(URL url) {
manager.url = url;
return this;
}
/**
* Sets path for persistence.xml file
*
* @param path
* @return {@link Builder}
*/
public Builder setPath(String path) {
manager.path = path;
return this;
}
/**
* Sets additional persistence properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setProperties(Map<Object, Object> properties) {
manager.properties = properties;
return this;
}
/**
* Sets boolean check property to swap jta data source value with non
* jta data source value
*
* @param swapDataSource
* @return {@link Builder}
*/
public Builder setSwapDataSource(boolean swapDataSource) {
manager.swapDataSource = swapDataSource;
return this;
}
/**
* Sets boolean check to scan deployed archive files for
* {@link javax.persistence.Entity} annotated classes
*
* @param scanArchives
* @return {@link Builder}
*/
public Builder setScanArchives(boolean scanArchives) {
manager.scanArchives = scanArchives;
return this;
}
/**
* Sets {@link ClassLoader} for persistence classes
*
* @param loader
* @return {@link Builder}
*/
public Builder setClassLoader(ClassLoader loader) {
manager.loader = loader;
return this;
}
/**
* Sets all parameters from passed {@link Configuration} instance
*
* @param configuration
* @return {@link Builder}
*/
public Builder configure(Configuration configuration) {
setPath(configuration.getPersXmlPath())
.setProperties(configuration.getPersistenceProperties())
.setSwapDataSource(configuration.isSwapDataSource())
.setScanArchives(configuration.isScanArchives());
return this;
}
public JpaManager build() {
return manager;
}
}
}
|
package org.joda.time.base;
import java.io.Serializable;
import org.joda.time.Chronology;
import org.joda.time.DateTimeField;
import org.joda.time.DateTimeUtils;
import org.joda.time.ReadablePartial;
import org.joda.time.convert.ConverterManager;
import org.joda.time.convert.InstantConverter;
/**
* BasePartial is an abstract implementation of ReadablePartial that stores
* data in array and <code>Chronology</code> fields.
* <p>
* This class should generally not be used directly by API users.
* The {@link org.joda.time.ReadablePeriod} interface should be used when different
* kinds of partial objects are to be referenced.
* <p>
* BasePartial subclasses may be mutable and not thread-safe.
*
* @author Stephen Colebourne
* @since 1.0
*/
public abstract class BasePartial
extends AbstractPartial
implements ReadablePartial, Serializable {
/** Serialization version */
private static final long serialVersionUID = 2353678632973660L;
/** The chronology in use */
private Chronology iChronology;
/** The values of each field in this partial */
private int[] iValues;
/** A cached array of fields. */
private transient DateTimeField[] iFields;
/**
* Constructs a partial with the current time, using ISOChronology in
* the default zone to extract the fields.
* <p>
* The constructor uses the default time zone, resulting in the local time
* being initialised. Once the constructor is complete, all further calculations
* are performed without reference to a timezone (by switching to UTC).
*/
protected BasePartial() {
this(DateTimeUtils.currentTimeMillis(), null);
}
/**
* Constructs a partial with the current time, using the specified chronology
* and zone to extract the fields.
* <p>
* The constructor uses the time zone of the chronology specified.
* Once the constructor is complete, all further calculations are performed
* without reference to a timezone (by switching to UTC).
*
* @param chronology the chronology, null means ISOChronology in the default zone
*/
protected BasePartial(Chronology chronology) {
this(DateTimeUtils.currentTimeMillis(), chronology);
}
/**
* Constructs a partial extracting the partial fields from the specified
* milliseconds using the ISOChronology in the default zone.
* <p>
* The constructor uses the default time zone, resulting in the local time
* being initialised. Once the constructor is complete, all further calculations
* are performed without reference to a timezone (by switching to UTC).
*
* @param instant the milliseconds from 1970-01-01T00:00:00Z
*/
protected BasePartial(long instant) {
this(instant, null);
}
/**
* Constructs a partial extracting the partial fields from the specified
* milliseconds using the chronology provided.
* <p>
* The constructor uses the time zone of the chronology specified.
* Once the constructor is complete, all further calculations are performed
* without reference to a timezone (by switching to UTC).
*
* @param instant the milliseconds from 1970-01-01T00:00:00Z
* @param chronology the chronology, null means ISOChronology in the default zone
*/
protected BasePartial(long instant, Chronology chronology) {
super();
chronology = DateTimeUtils.getChronology(chronology);
iChronology = chronology.withUTC();
iValues = initValues(instant, chronology);
}
protected BasePartial(Object instant) {
super();
InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant);
long millis = converter.getInstantMillis(instant);
Chronology chronology = converter.getChronology(instant);
chronology = DateTimeUtils.getChronology(chronology);
iChronology = chronology.withUTC();
iValues = initValues(millis, chronology);
}
protected BasePartial(Object instant, Chronology chronology) {
super();
InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant);
long millis = converter.getInstantMillis(instant, chronology);
chronology = converter.getChronology(instant, chronology);
chronology = DateTimeUtils.getChronology(chronology);
iChronology = chronology.withUTC();
iValues = initValues(millis, chronology);
}
/**
* Constructs a partial with specified time field values and chronology.
* <p>
* The constructor uses the time zone of the chronology specified.
* Once the constructor is complete, all further calculations are performed
* without reference to a timezone (by switching to UTC).
* <p>
* The array of values is assigned (not cloned) to the new instance.
*
* @param values the new set of values
* @param chronology the chronology, null means ISOChronology in the default zone
*/
protected BasePartial(int[] values, Chronology chronology) {
super();
chronology = DateTimeUtils.getChronology(chronology);
iChronology = chronology.withUTC();
chronology.validate(this, values);
iValues = values;
}
/**
* Private constructor to be used by subclasses only which performs no validation.
* <p>
* Data is assigned (not cloned) to the new instance.
* Thus, two BasePartials will share the same field array.
*
* @param other the other partial to use to extract the fields and chronology
* @param values the new set of values, not cloned
*/
protected BasePartial(BasePartial other, int[] values) {
super();
iChronology = other.iChronology;
iValues = values;
iFields = other.iFields;
}
/**
* Initialize the array of values.
* The field and value arrays must match.
*
* @param instant the instant to use
* @param chrono the chronology to use
*/
protected int[] initValues(long instant, Chronology chrono) {
int[] values = new int[getFieldSize()];
for (int i = 0; i < values.length; i++) {
values[i] = getField(i, chrono).get(instant);
}
return values;
}
/**
* Gets the field at the specifed index.
*
* @param index the index
* @return the field
* @throws IndexOutOfBoundsException if the index is invalid
*/
public DateTimeField getField(int index) {
DateTimeField[] fields = iFields;
if (fields != null) {
return fields[index];
} else {
return getField(index, getChronology());
}
}
/**
* Gets an array of the fields that this partial supports.
* <p>
* The fields are returned largest to smallest, for example Hour, Minute, Second.
*
* @return the fields supported in an array that may be altered, largest to smallest
*/
public DateTimeField[] getFields() {
DateTimeField[] fields = iFields;
if (fields == null) {
fields = super.getFields();
iFields = fields;
}
return (DateTimeField[]) fields.clone();
}
/**
* Gets the value of the field at the specifed index.
*
* @param index the index
* @return the value
* @throws IndexOutOfBoundsException if the index is invalid
*/
public int getValue(int index) {
return iValues[index];
}
/**
* Gets an array of the value of each of the fields that this partial supports.
* <p>
* The fields are returned largest to smallest, for example Hour, Minute, Second.
* Each value corresponds to the same array index as <code>getFields()</code>
*
* @return the current values of each field (cloned), largest to smallest
*/
public int[] getValues() {
return (int[]) iValues.clone();
}
/**
* Gets the chronology of the partial which is never null.
* <p>
* The {@link Chronology} is the calculation engine behind the partial and
* provides conversion and validation of the fields in a particular calendar system.
*
* @return the chronology, never null
*/
public Chronology getChronology() {
return iChronology;
}
/**
* Sets the value of the field at the specifed index.
*
* @param index the index
* @param value the value to set
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void setValue(int index, int value) {
DateTimeField field = getField(index);
iValues = field.set(this, index, iValues, value);
}
/**
* Sets the values of all fields.
*
* @param values the array of values
*/
protected void setValues(int[] values) {
getChronology().validate(this, values);
iValues = values;
}
}
|
package org.opencloudb.util;
/**
*
*
* @author mycat
*/
public class TimeUtil {
private static volatile long CURRENT_TIME = System.currentTimeMillis();
public static final long currentTimeMillis() {
return CURRENT_TIME;
}
public static final void update() {
CURRENT_TIME = System.currentTimeMillis();
}
}
|
package com.vladmihalcea.book.hpjp.hibernate.query.dto.projection.hibernate;
import com.vladmihalcea.book.hpjp.hibernate.query.dto.projection.Post;
import com.vladmihalcea.book.hpjp.hibernate.query.dto.projection.PostComment;
import com.vladmihalcea.book.hpjp.util.AbstractTest;
import com.vladmihalcea.book.hpjp.util.providers.Database;
import org.hibernate.jpa.QueryHints;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.*;
import static org.junit.Assert.assertEquals;
/**
* @author Vlad Mihalcea
*/
@SuppressWarnings("unchecked")
public class HibernateDTOProjectionTest extends AbstractTest {
@Override
protected Class<?>[] entities() {
return new Class<?>[] {
Post.class,
PostComment.class
};
}
@Override
protected Database database() {
return Database.POSTGRESQL;
}
@Override
public void afterInit() {
doInJPA(entityManager -> {
entityManager.persist(
new Post()
.setId(1L)
.setTitle("High-Performance Java Persistence")
.setCreatedBy("Vlad Mihalcea")
.setCreatedOn(
LocalDateTime.of(2016, 11, 2, 12, 0, 0)
)
.setUpdatedBy("Vlad Mihalcea")
.setUpdatedOn(
LocalDateTime.now()
)
.addComment(
new PostComment()
.setId(1L)
.setReview("Best book on JPA and Hibernate!")
)
.addComment(
new PostComment()
.setId(2L)
.setReview("A must-read for every Java developer!")
)
);
entityManager.persist(
new Post()
.setId(2L)
.setTitle("Hypersistence Optimizer")
.setCreatedBy("Vlad Mihalcea")
.setCreatedOn(
LocalDateTime.of(2019, 3, 19, 12, 0, 0)
)
.setUpdatedBy("Vlad Mihalcea")
.setUpdatedOn(
LocalDateTime.now()
)
.addComment(
new PostComment()
.setId(3L)
.setReview("It's like pair programming with Vlad!")
)
);
});
}
@Test
public void testJPQLResultTransformer() {
doInJPA( entityManager -> {
List<PostDTO> postDTOs = entityManager.createQuery("""
select p.id as id,
p.title as title
from Post p
order by p.id
""")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(Transformers.aliasToBean(PostDTO.class))
.getResultList();
assertEquals(2, postDTOs.size());
PostDTO postDTO = postDTOs.get(0);
assertEquals(1L, postDTO.getId().longValue());
assertEquals("High-Performance Java Persistence", postDTO.getTitle());
} );
}
@Test
public void testNativeQueryResultTransformer() {
doInJPA( entityManager -> {
List<PostDTO> postDTOs = entityManager.createNativeQuery("""
SELECT p.id AS id,
p.title AS title
FROM post p
ORDER BY p.id
""")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(Transformers.aliasToBean(PostDTO.class))
.getResultList();
assertEquals(2, postDTOs.size());
PostDTO postDTO = postDTOs.get(0);
assertEquals(1L, postDTO.getId().longValue());
assertEquals("High-Performance Java Persistence", postDTO.getTitle());
} );
}
@Test
public void testParentChildDTOProjectionNativeQueryResultTransformer() {
doInJPA( entityManager -> {
List<PostDTO> postDTOs = entityManager.createNativeQuery("""
SELECT p.id AS p_id,
p.title AS p_title,
pc.id AS pc_id,
pc.review AS pc_review
FROM post p
JOIN post_comment pc ON p.id = pc.post_id
ORDER BY pc.id
""")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(new PostDTOResultTransformer())
.getResultList();
assertEquals(2, postDTOs.size());
assertEquals(2, postDTOs.get(0).getComments().size());
assertEquals(1, postDTOs.get(1).getComments().size());
PostDTO post1DTO = postDTOs.get(0);
assertEquals(1L, post1DTO.getId().longValue());
assertEquals(2, post1DTO.getComments().size());
assertEquals(1L, post1DTO.getComments().get(0).getId().longValue());
assertEquals(2L, post1DTO.getComments().get(1).getId().longValue());
PostDTO post2DTO = postDTOs.get(1);
assertEquals(2L, post2DTO.getId().longValue());
assertEquals(1, post2DTO.getComments().size());
assertEquals(3L, post2DTO.getComments().get(0).getId().longValue());
} );
}
@Test
public void testParentChildDTOProjectionJPQLResultTransformer() {
doInJPA( entityManager -> {
List<PostDTO> postDTOs = entityManager.createQuery("""
select p.id as p_id,
p.title as p_title,
pc.id as pc_id,
pc.review as pc_review
from PostComment pc
join pc.post p
order by pc.id
""")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(new PostDTOResultTransformer())
.getResultList();
assertEquals(2, postDTOs.size());
assertEquals(2, postDTOs.get(0).getComments().size());
assertEquals(1, postDTOs.get(1).getComments().size());
PostDTO post1DTO = postDTOs.get(0);
assertEquals(1L, post1DTO.getId().longValue());
assertEquals(2, post1DTO.getComments().size());
assertEquals(1L, post1DTO.getComments().get(0).getId().longValue());
assertEquals(2L, post1DTO.getComments().get(1).getId().longValue());
PostDTO post2DTO = postDTOs.get(1);
assertEquals(2L, post2DTO.getId().longValue());
assertEquals(1, post2DTO.getComments().size());
assertEquals(3L, post2DTO.getComments().get(0).getId().longValue());
} );
}
@Test
public void testParentChildEntityProjectionJPQLResultTransformer() {
doInJPA( entityManager -> {
List<Post> posts = entityManager.createQuery("""
select distinct p
from Post p
join fetch p.comments pc
order by pc.id
""")
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();
assertEquals(2, posts.size());
assertEquals(2, posts.get(0).getComments().size());
assertEquals(1, posts.get(1).getComments().size());
Post post1 = posts.get(0);
assertEquals(1L, post1.getId().longValue());
assertEquals(2, post1.getComments().size());
assertEquals(1L, post1.getComments().get(0).getId().longValue());
assertEquals(2L, post1.getComments().get(1).getId().longValue());
Post post2 = posts.get(1);
assertEquals(2L, post2.getId().longValue());
assertEquals(1, post2.getComments().size());
assertEquals(3L, post2.getComments().get(0).getId().longValue());
} );
}
public static class PostDTO {
public static final String ID_ALIAS = "p_id";
public static final String TITLE_ALIAS = "p_title";
private Long id;
private String title;
private List<PostCommentDTO> comments = new ArrayList<>();
public PostDTO() {
}
public PostDTO(Long id, String title) {
this.id = id;
this.title = title;
}
public PostDTO(Object[] tuples, Map<String, Integer> aliasToIndexMap) {
this.id = longValue(tuples[aliasToIndexMap.get(ID_ALIAS)]);
this.title = stringValue(tuples[aliasToIndexMap.get(TITLE_ALIAS)]);
}
public Long getId() {
return id;
}
public void setId(Number id) {
this.id = id.longValue();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<PostCommentDTO> getComments() {
return comments;
}
}
public static class PostCommentDTO {
public static final String ID_ALIAS = "pc_id";
public static final String REVIEW_ALIAS = "pc_review";
private Long id;
private String review;
public PostCommentDTO(Long id, String review) {
this.id = id;
this.review = review;
}
public PostCommentDTO(Object[] tuples, Map<String, Integer> aliasToIndexMap) {
this.id = longValue(tuples[aliasToIndexMap.get(ID_ALIAS)]);
this.review = stringValue(tuples[aliasToIndexMap.get(REVIEW_ALIAS)]);
}
public Long getId() {
return id;
}
public void setId(Number id) {
this.id = id.longValue();
}
public void setId(Long id) {
this.id = id;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}
public static class PostDTOResultTransformer implements ResultTransformer {
private Map<Long, PostDTO> postDTOMap = new LinkedHashMap<>();
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
Map<String, Integer> aliasToIndexMap = aliasToIndexMap(aliases);
Long postId = longValue(tuple[aliasToIndexMap.get(PostDTO.ID_ALIAS)]);
PostDTO postDTO = postDTOMap.computeIfAbsent(postId, id -> new PostDTO(tuple, aliasToIndexMap));
postDTO.getComments().add(new PostCommentDTO(tuple, aliasToIndexMap));
return postDTO;
}
@Override
public List transformList(List collection) {
return new ArrayList<>(postDTOMap.values());
}
}
public static Map<String, Integer> aliasToIndexMap(String[] aliases) {
Map<String, Integer> aliasToIndexMap = new LinkedHashMap<>();
for (int i = 0; i < aliases.length; i++) {
aliasToIndexMap.put(aliases[i], i);
}
return aliasToIndexMap;
}
}
|
package org.neo4j.api.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.transaction.TransactionManager;
import org.neo4j.api.core.NeoJvmInstance.Config;
import org.neo4j.impl.core.NodeManager;
import org.neo4j.impl.shell.NeoShellServer;
import org.neo4j.util.shell.AbstractServer;
/**
* An implementation of {@link NeoService} that is used to embed Neo in an
* application. You typically instantiate it by invoking the
* {@link #EmbeddedNeo(String) single argument constructor} that takes a path to
* a directory where Neo will store its data files, as such: <code>
* <pre>
* NeoService neo = new EmbeddedNeo( "var/neo" );
* // ... use neo
* neo.shutdown();
* </pre>
* </code> For more information, see {@link NeoService}.
*/
public final class EmbeddedNeo implements NeoService
{
public static final int DEFAULT_SHELL_PORT = AbstractServer.DEFAULT_PORT;
public static final String DEFAULT_SHELL_NAME = AbstractServer.DEFAULT_NAME;
private static Logger log = Logger.getLogger( EmbeddedNeo.class.getName() );
private NeoShellServer shellServer;
private Transaction placeboTransaction = null;
private final NeoJvmInstance neoJvmInstance;
private final NodeManager nodeManager;
/**
* Creates an embedded {@link NeoService} with a store located in
* <code>storeDir</code>, which will be created if it doesn't already
* exist.
* @param storeDir the store directory for the neo db files
*/
public EmbeddedNeo( String storeDir )
{
this.shellServer = null;
neoJvmInstance = new NeoJvmInstance( storeDir, true );
neoJvmInstance.start();
nodeManager = neoJvmInstance.getConfig().getNeoModule()
.getNodeManager();
}
/**
* A non-standard way of creating an embedded {@link NeoService}
* with a set of configuration parameters. Will most likely be removed in
* future releases.
* @param storeDir the store directory for the db files
* @param params configuration parameters
*/
public EmbeddedNeo( String storeDir, Map<String,String> params )
{
this.shellServer = null;
neoJvmInstance = new NeoJvmInstance( storeDir, true );
neoJvmInstance.start( params );
nodeManager = neoJvmInstance.getConfig().getNeoModule()
.getNodeManager();
}
/**
* A non-standard Convenience method that loads a standard property file and
* converts it into a generic <Code>Map<String,String></CODE>. Will most
* likely be removed in future releases.
* @param file the property file to load
* @return a map containing the properties from the file
*/
public static Map<String,String> loadConfigurations( String file )
{
Properties props = new Properties();
try
{
FileInputStream stream = new FileInputStream( new File( file ) );
try
{
props.load( stream );
}
finally
{
stream.close();
}
}
catch ( Exception e )
{
throw new RuntimeException( "Unable to load properties file["
+ file + "]", e );
}
Set<Entry<Object,Object>> entries = props.entrySet();
Map<String,String> stringProps = new HashMap<String,String>();
for ( Entry entry : entries )
{
String key = (String) entry.getKey();
String value = (String) entry.getValue();
stringProps.put( key, value );
}
return stringProps;
}
// private accessor for the remote shell (started with enableRemoteShell())
private NeoShellServer getShellServer()
{
return this.shellServer;
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#createNode()
*/
public Node createNode()
{
return nodeManager.createNode();
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#getNodeById(long)
*/
public Node getNodeById( long id )
{
return nodeManager.getNodeById( (int) id );
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#getRelationshipById(long)
*/
public Relationship getRelationshipById( long id )
{
return nodeManager.getRelationshipById( (int) id );
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#getReferenceNode()
*/
public Node getReferenceNode()
{
return nodeManager.getReferenceNode();
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#shutdown()
*/
public void shutdown()
{
if ( getShellServer() != null )
{
try
{
getShellServer().shutdown();
}
catch ( Throwable t )
{
log.warning( "Error shutting down shell server: " + t );
}
}
neoJvmInstance.shutdown();
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#enableRemoteShell()
*/
public boolean enableRemoteShell()
{
return this.enableRemoteShell( null );
}
/*
* (non-Javadoc)
* @see org.neo4j.api.core.NeoService#enableRemoteShell(java.util.Map)
*/
public boolean enableRemoteShell(
final Map<String,Serializable> initialProperties )
{
Map<String,Serializable> properties = initialProperties;
if ( properties == null )
{
properties = Collections.emptyMap();
}
try
{
if ( shellDependencyAvailable() )
{
this.shellServer = new NeoShellServer( this );
Object port = properties.get( "port" );
Object name = properties.get( "name" );
this.shellServer.makeRemotelyAvailable(
port != null ? (Integer) port : DEFAULT_SHELL_PORT,
name != null ? (String) name : DEFAULT_SHELL_NAME );
return true;
}
else
{
log.info( "Shell library not available. Neo shell not "
+ "started. Please add the Neo4j shell jar to the "
+ "classpath." );
return false;
}
}
catch ( RemoteException e )
{
throw new IllegalStateException( "Can't start remote neo shell: "
+ e );
}
}
private boolean shellDependencyAvailable()
{
try
{
Class.forName( "org.neo4j.util.shell.ShellServer" );
return true;
}
catch ( Throwable t )
{
return false;
}
}
/**
* Returns all relationship types in the underlying store. Relationship
* types are added to the underlying store the first time they are used in
* {@link Node#createRelationshipTo}.
* @return all relationship types in the underlying store
* @deprecated Might not be needed now that relationship types are {@link
* RelationshipType created dynamically}.
*/
public Iterable<RelationshipType> getRelationshipTypes()
{
return neoJvmInstance.getRelationshipTypes();
}
public Transaction beginTx()
{
if ( neoJvmInstance.transactionRunning() )
{
if ( placeboTransaction == null )
{
placeboTransaction = new PlaceboTransaction( neoJvmInstance
.getTransactionManager() );
}
return placeboTransaction;
}
TransactionManager txManager = neoJvmInstance.getTransactionManager();
try
{
txManager.begin();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
return new TransactionImpl( txManager );
}
private static class PlaceboTransaction implements Transaction
{
private final TransactionManager transactionManager;
PlaceboTransaction( TransactionManager transactionManager )
{
// we should override all so null is ok
this.transactionManager = transactionManager;
}
public void failure()
{
try
{
transactionManager.getTransaction().setRollbackOnly();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
public void success()
{
}
public void finish()
{
}
}
/**
* Returns a non-standard configuration object. Will most likely be removed
* in future releases.
*
* @return a configuration object
*/
public Config getConfig()
{
return neoJvmInstance.getConfig();
}
private static class TransactionImpl implements Transaction
{
private boolean success = false;
private final TransactionManager transactionManager;
TransactionImpl( TransactionManager transactionManager )
{
this.transactionManager = transactionManager;
}
public void failure()
{
this.success = false;
try
{
transactionManager.getTransaction().setRollbackOnly();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
public void success()
{
success = true;
}
public void finish()
{
try
{
if ( success )
{
if ( transactionManager.getTransaction() != null )
{
transactionManager.getTransaction().commit();
}
}
else
{
if ( transactionManager.getTransaction() != null )
{
transactionManager.getTransaction().rollback();
}
}
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
}
}
|
package org.orbeon.oxf.util;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;
import org.orbeon.datatypes.LocationData;
import org.orbeon.io.CharsetNames;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.externalcontext.ExternalContext;
import org.orbeon.oxf.externalcontext.WebAppListener;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.generator.RequestGenerator;
import org.orbeon.oxf.resources.ResourceManagerWrapper;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.xml.SAXUtils;
import org.orbeon.oxf.xml.XMLReceiverAdapter;
import org.orbeon.oxf.xml.dom.IOSupport;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetUtils {
private static final Pattern PATTERN_NO_AMP;
private static final int COPY_BUFFER_SIZE = 8192;
private static final String STANDARD_PARAMETER_ENCODING = CharsetNames.Utf8();
private static FileItemFactory fileItemFactory;
public static final int REQUEST_SCOPE = 0;
public static final int SESSION_SCOPE = 1;
public static final int APPLICATION_SCOPE = 2;
static {
final String token = "[^=&]";
PATTERN_NO_AMP = Pattern.compile( "(" + token + "+)=(" + token + "*)(?:&|(?<!&)\\z)" );
}
/**
* Return true if the document was modified since the given date, based on the If-Modified-Since
* header. If the request method was not "GET", or if no valid lastModified value was provided,
* consider the document modified.
*/
public static boolean checkIfModifiedSince(ExternalContext.Request request, long lastModified, Logger logger) {
// Do the check only for the GET method
if (!"GET".equals(request.getMethod().entryName().toUpperCase()) || lastModified <= 0)
return true;
// Check dates
final String ifModifiedHeader = StringConversions.getFirstValueFromStringArray(request.getHeaderValuesMap().get("if-modified-since"));
if (logger.isDebugEnabled())
logger.debug("Found If-Modified-Since header");
if (ifModifiedHeader != null) {
try {
long dateTime = DateUtils.parseRFC1123(ifModifiedHeader);
if (lastModified <= (dateTime + 1000)) {
if (logger.isDebugEnabled())
logger.debug("Sending SC_NOT_MODIFIED response");
return false;
}
} catch (Exception e) {// used to be ParseException, but NumberFormatException may be thrown as well
// Ignore
}
}
return true;
}
/**
* Return a request path info that looks like what one would expect. The path starts with a "/", relative to the
* servlet context. If the servlet was included or forwarded to, return the path by which the *current* servlet was
* invoked, NOT the path of the calling servlet.
*
* Request path = servlet path + path info.
*
* @param request servlet HTTP request
* @return path
*/
public static String getRequestPathInfo(HttpServletRequest request) {
// NOTE: Servlet 2.4 spec says: "These attributes [javax.servlet.include.*] are accessible from the included
// servlet via the getAttribute method on the request object and their values must be equal to the request URI,
// context path, servlet path, path info, and query string of the included servlet, respectively."
// NOTE: This is very different from the similarly-named forward attributes, which reflect the values of the
// first servlet in the chain!
// Get servlet path
String servletPath = (String) request.getAttribute("javax.servlet.include.servlet_path");
if (servletPath == null) {
servletPath = request.getServletPath();
if (servletPath == null)
servletPath = "";
}
// Get path info
String pathInfo = (String) request.getAttribute("javax.servlet.include.path_info");
if (pathInfo == null) {
pathInfo = request.getPathInfo();
if (pathInfo == null)
pathInfo = "";
}
// Concatenate servlet path and path info, avoiding a double slash
String requestPath = servletPath.endsWith("/") && pathInfo.startsWith("/")
? servletPath + pathInfo.substring(1)
: servletPath + pathInfo;
// Add starting slash if missing
if (!requestPath.startsWith("/"))
requestPath = "/" + requestPath;
return requestPath;
}
/**
* Return the last modification date of the given absolute URL if it is "fast" to do so, i.e. if it is an "oxf:" or
* a "file:" protocol.
*
* @param absoluteURL absolute URL to check
* @return last modification date if "fast" or 0 if not fast or if an error occurred
*/
public static long getLastModifiedIfFast(String absoluteURL) {
final long lastModified;
if (absoluteURL.startsWith("oxf:") || absoluteURL.startsWith("file:")) {
try {
lastModified = getLastModified(URLFactory.createURL(absoluteURL));
} catch (IOException e) {
throw new OXFException(e);
}
} else {
// Value of `0` for `lastModified` will cause `XFormsAssetServer` to set `Last-Modified` and `Expires` properly to "now".
lastModified = 0;
}
return lastModified;
}
/**
* Get the last modification date of a URL.
*
* @return last modified timestamp, null if le 0
*/
public static Long getLastModifiedAsLong(URL url) throws IOException {
final long connectionLastModified = getLastModified(url);
// Zero and negative values often have a special meaning, make sure to normalize here
return connectionLastModified <= 0 ? null : connectionLastModified;
}
/**
* Get the last modification date of a URL.
*
* @return last modified timestamp "as is"
*/
public static long getLastModified(URL url) throws IOException {
if ("file".equals(url.getProtocol())) {
// Optimize file: access. Also, this prevents throwing an exception if the file doesn't exist as we try to close the stream below.
return new File(URLDecoder.decode(url.getFile(), STANDARD_PARAMETER_ENCODING)).lastModified();
} else {
// Use URLConnection
final URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection)
((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
try {
return getLastModified(urlConnection);
} finally {
final InputStream is = urlConnection.getInputStream();
if (is != null)
is.close();
}
}
}
/**
* Get the last modification date of an open URLConnection.
*
* This handles the (broken at some point in the Java libraries) case of the file: protocol.
*
* @return last modified timestamp "as is"
*/
public static long getLastModified(URLConnection urlConnection) {
try {
long lastModified = urlConnection.getLastModified();
if (lastModified == 0 && "file".equals(urlConnection.getURL().getProtocol()))
lastModified = new File(URLDecoder.decode(urlConnection.getURL().getFile(), STANDARD_PARAMETER_ENCODING)).lastModified();
return lastModified;
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
}
/**
* Check if an URL is relative to another URL.
*/
public static boolean relativeURL(URL url1, URL url2) {
return ((url1.getProtocol() == null && url2.getProtocol() == null) || url1.getProtocol().equals(url2.getProtocol()))
&& ((url1.getAuthority() == null && url2.getAuthority() == null) || url1.getAuthority().equals(url2.getAuthority()))
&& ((url1.getPath() == null && url2.getPath() == null) || url2.getPath().startsWith(url1.getPath()));
}
// 10 Java callers
public static void copyStream(InputStream is, OutputStream os) throws IOException {
int count;
final byte[] buffer = new byte[COPY_BUFFER_SIZE];
while ((count = is.read(buffer)) > 0)
os.write(buffer, 0, count);
}
// 1 Java caller
public static void copyStream(Reader reader, Writer writer) throws IOException {
int count;
final char[] buffer = new char[COPY_BUFFER_SIZE / 2];
while ((count = reader.read(buffer)) > 0)
writer.write(buffer, 0, count);
}
/**
* @param queryString a query string of the form n1=v1&n2=v2&... to decode. May be null.
*
* @return a Map of String[] indexed by name, an empty Map if the query string was null
*/
// TODO: Move to PathUtils.
public static Map<String, String[]> decodeQueryString(final CharSequence queryString) {
final Map<String, String[]> result = new LinkedHashMap<String, String[]>();
if (queryString != null) {
final Matcher matcher = PATTERN_NO_AMP.matcher(queryString);
int matcherEnd = 0;
while (matcher.find()) {
matcherEnd = matcher.end();
try {
final String name = URLDecoder.decode(matcher.group(1), NetUtils.STANDARD_PARAMETER_ENCODING);
final String value = URLDecoder.decode(matcher.group(2), NetUtils.STANDARD_PARAMETER_ENCODING);
StringConversions.addValueToStringArrayMap(result, name, value);
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
}
if (queryString.length() != matcherEnd) {
// There was garbage at the end of the query.
throw new OXFException("Malformed URL: " + queryString);
}
}
return result;
}
private static final Pattern PATTERN_AMP;
static {
final String token = "[^=&]+";
PATTERN_AMP = Pattern.compile( "(" + token + ")=(" + token + ")?(?:&|&|(?<!&|&)\\z)" );
}
// This is a modified copy of decodeQueryString() above. Not sure why we need 2 versions! Try to avoid duplication!
// TODO: Move to PathUtils.
public static Map<String, String[]> decodeQueryStringPortlet(final CharSequence queryString) {
final Map<String, String[]> result = new LinkedHashMap<String, String[]>();
if (queryString != null) {
final Matcher matcher = PATTERN_AMP.matcher(queryString);
int matcherEnd = 0;
while (matcher.find()) {
matcherEnd = matcher.end();
try {
String name = URLDecoder.decode(matcher.group(1), STANDARD_PARAMETER_ENCODING);
String group2 = matcher.group(2);
final String value = group2 != null ? URLDecoder.decode(group2, STANDARD_PARAMETER_ENCODING) : "";
// Handle the case where the source contains &amp; because of double escaping which does occur in
// full Ajax updates!
if (name.startsWith("amp;"))
name = name.substring("amp;".length());
// NOTE: Replace spaces with '+'. This is an artifact of the fact that URLEncoder/URLDecoder
// are not fully reversible.
StringConversions.addValueToStringArrayMap(result, name, value.replace(' ', '+'));
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
}
if (queryString.length() != matcherEnd) {
// There was garbage at the end of the query.
throw new OXFException("Malformed URL: " + queryString);
}
}
return result;
}
/**
* Encode a query string. The input Map contains names indexing Object[].
*/
// TODO: Move to PathUtils.
public static String encodeQueryString(Map<String, Object[]> parameters) {
final StringBuilder sb = new StringBuilder(100);
boolean first = true;
try {
for (final Map.Entry<String, Object[]> entry : parameters.entrySet()) {
for (final Object currentValue : entry.getValue()) {
if (currentValue instanceof String) {
if (!first)
sb.append('&');
sb.append(URLEncoder.encode(entry.getKey(), NetUtils.STANDARD_PARAMETER_ENCODING));
sb.append('=');
sb.append(URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));
first = false;
}
}
}
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
return sb.toString();
}
// TODO: Move to PathUtils.
public static String encodeQueryString2(Map<String, String[]> parameters) {
final StringBuilder sb = new StringBuilder(100);
boolean first = true;
try {
for (final Map.Entry<String, String[]> entry : parameters.entrySet()) {
for (final Object currentValue : entry.getValue()) {
if (!first)
sb.append('&');
sb.append(URLEncoder.encode(entry.getKey(), NetUtils.STANDARD_PARAMETER_ENCODING));
sb.append('=');
sb.append(URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));
first = false;
}
}
} catch (UnsupportedEncodingException e) {
// Should not happen as we are using a required encoding
throw new OXFException(e);
}
return sb.toString();
}
/**
* Combine a path (possibly with parameters) and a parameters map to form a path info with a query string.
*/
// TODO: Move to PathUtils.
public static String pathInfoParametersToPathInfoQueryString(String path, Map<String, String[]> parameters) throws IOException {
final StringBuilder redirectURL = new StringBuilder(path);
if (parameters != null) {
boolean first = ! path.contains("?");
for (String name : parameters.keySet()) {
final String[] values = parameters.get(name);
for (final String currentValue : values) {
redirectURL.append(first ? "?" : "&");
redirectURL.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING));
redirectURL.append("=");
redirectURL.append(URLEncoder.encode(currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));
first = false;
}
}
}
return redirectURL.toString();
}
/**
* Check whether a URL starts with a protocol.
*
* We consider that a protocol consists only of ASCII letters and must be at least two
* characters long, to avoid confusion with Windows drive letters.
*/
// TODO: Move to PathUtils.
public static boolean urlHasProtocol(String urlString) {
return getProtocol(urlString) != null;
}
// TODO: Move to PathUtils.
public static String getProtocol(String urlString) {
int colonIndex = urlString.indexOf(":");
// Require at least two characters in a protocol
if (colonIndex < 2)
return null;
// Check that there is a protocol made only of letters
for (int i = 0; i < colonIndex; i++) {
final char c = urlString.charAt(i);
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) {
return null;
}
}
return urlString.substring(0, colonIndex);
}
/**
* Resolve a URI against a base URI. (Be sure to pay attention to the order or parameters.)
*
* @param href URI to resolve (accept human-readable URI)
* @param base URI base (accept human-readable URI)
* @return resolved URI
*/
public static String resolveURI(String href, String base) {
final String resolvedURIString;
if (base != null) {
final URI baseURI;
try {
baseURI = new URI(encodeHRRI(base, true));
} catch (URISyntaxException e) {
throw new OXFException(e);
}
resolvedURIString = baseURI.resolve(encodeHRRI(href, true)).normalize().toString();// normalize to remove "..", etc.
} else {
resolvedURIString = encodeHRRI(href, true);
}
return resolvedURIString;
}
public static byte[] base64StringToByteArray(String base64String) {
return Base64.decode(base64String);
}
/**
* Convert a String in xs:base64Binary to an xs:anyURI.
*
* NOTE: The implementation creates a temporary file. The Pipeline Context is required so
* that the file can be deleted when no longer used.
*/
public static String base64BinaryToAnyURI(String value, int scope, Logger logger) {
// Convert Base64 to binary first
final byte[] bytes = base64StringToByteArray(value);
return inputStreamToAnyURI(new ByteArrayInputStream(bytes), scope, logger);
}
/**
* Read an InputStream into a byte array.
*
* @param is InputStream
* @return byte array
*/
public static byte[] inputStreamToByteArray(InputStream is) {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
copyStream(new BufferedInputStream(is), os);
os.close();
return os.toByteArray();
} catch (Exception e) {
throw new OXFException(e);
}
}
public static InputStream uriToInputStream(String uri) throws Exception {
return new URI(uri).toURL().openStream();
}
// NOTE: Used by create-test-data.xpl
//@XPathFunction
public static String createTemporaryFile(int scope) {
return inputStreamToAnyURI(new InputStream() {
@Override
public int read() {
return -1;
}
}, scope, null);
}
/**
* Convert an InputStream to an xs:anyURI.
*
* The implementation creates a temporary file.
*/
public static String inputStreamToAnyURI(InputStream inputStream, int scope, Logger logger) {
// Get FileItem
final FileItem fileItem = prepareFileItemFromInputStream(inputStream, scope, logger);
// Return a file URL
final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
// Escape "+" because at least in one environment (JBoss 5.1.0 GA on OS X) not escaping the "+" in a file URL causes later incorrect conversion to space
return storeLocation.toURI().toString().replace("+", "%2B");
}
private static FileItem prepareFileItemFromInputStream(InputStream inputStream, int scope, Logger logger) {
// Get FileItem
final FileItem fileItem = prepareFileItem(scope, logger);
// Write to file
OutputStream os = null;
try {
os = fileItem.getOutputStream();
copyStream(inputStream, os);
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
// Create file if it doesn't exist (necessary when the file size is 0)
final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
try {
storeLocation.createNewFile();
} catch (IOException e) {
throw new OXFException(e);
}
return fileItem;
}
/**
* Return a FileItem which is going to be automatically destroyed upon destruction of the request, session or
* application.
*/
public static FileItem prepareFileItem(int scope, Logger logger) {
// We use the commons file upload utilities to save a file
if (fileItemFactory == null)
fileItemFactory = new DiskFileItemFactory(0, SystemUtils.getTemporaryDirectory());
final FileItem fileItem = fileItemFactory.createItem("dummy", "dummy", false, null);
// Make sure the file is deleted appropriately
if (scope == REQUEST_SCOPE) {
deleteFileOnRequestEnd(fileItem, logger);
} else if (scope == SESSION_SCOPE) {
deleteFileOnSessionTermination(fileItem, logger);
} else if (scope == APPLICATION_SCOPE) {
deleteFileOnApplicationDestroyed(fileItem, logger);
} else {
throw new OXFException("Invalid context requested: " + scope);
}
// Return FileItem object
return fileItem;
}
/**
* Add listener to fileItem which is going to be automatically destroyed at the end of request
*
* @param fileItem FileItem
*/
private static void deleteFileOnRequestEnd(final FileItem fileItem, final Logger logger) {
// Make sure the file is deleted at the end of request
PipelineContext.get().addContextListener(new PipelineContext.ContextListenerAdapter() {
public void contextDestroyed(boolean success) {
deleteFileItem(fileItem, REQUEST_SCOPE, logger);
}
});
}
/**
* Add listener to fileItem which is going to be automatically destroyed on session destruction
*
* @param fileItem FileItem
*/
private static void deleteFileOnSessionTermination(final FileItem fileItem, final Logger logger) {
// Try to delete the file on exit and on session termination
final ExternalContext externalContext = getExternalContext();
final ExternalContext.Session session = externalContext.getSession(false);
if (session != null) {
try {
session.addListener(new ExternalContext.SessionListener() {
public void sessionDestroyed(ExternalContext.Session session) {
deleteFileItem(fileItem, SESSION_SCOPE, logger);
}
});
} catch (IllegalStateException e) {
logger.info("Unable to add session listener: " + e.getMessage());
deleteFileItem(fileItem, SESSION_SCOPE, logger); // remove immediately
throw e;
}
} else if (logger != null) {
logger.debug("No existing session found so cannot register temporary file deletion upon session destruction: " + fileItem.getName());
}
}
/**
* Add listener to fileItem which is going to be automatically destroyed when the servlet is destroyed
*
* @param fileItem FileItem
*/
private static void deleteFileOnApplicationDestroyed(final FileItem fileItem, final Logger logger) {
// Try to delete the file on exit and on session termination
final ExternalContext externalContext = getExternalContext();
externalContext.getWebAppContext().addListener(new WebAppListener() {
public void webAppDestroyed() {
deleteFileItem(fileItem, APPLICATION_SCOPE, logger);
}
});
}
/**
* Convert a String in xs:anyURI to an xs:base64Binary.
*
* The URI has to be a URL. It is read entirely
*/
public static String anyURIToBase64Binary(String value) {
InputStream is = null;
try {
// Read from URL and convert to Base64
is = URLFactory.createURL(value).openStream();
final StringBuilder sb = new StringBuilder();
SAXUtils.inputStreamToBase64Characters(is, new XMLReceiverAdapter() {
public void characters(char ch[], int start, int length) {
sb.append(ch, start, length);
}
});
// Return Base64 String
return sb.toString();
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
}
public static void anyURIToOutputStream(String value, OutputStream outputStream) {
InputStream is = null;
try {
is = URLFactory.createURL(value).openStream();
copyStream(is, outputStream);
} catch (IOException e) {
throw new OXFException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new OXFException(e);
}
}
}
}
public static String encodeHRRI(String uriString, boolean processSpace) {
if (uriString == null)
return null;
// however, their use is highly discouraged (unless they are encoded by %20).".
// We assume that we never want leading or trailing spaces. You can use %20 if you really want this.
uriString = StringUtils.trimAllToEmpty(uriString);
// We try below to follow the "Human Readable Resource Identifiers" RFC, in draft as of 2007-06-06.
// * the control characters #x0 to #x1F and #x7F to #x9F
// * space #x20
|
package org.relique.jdbc.csv;
import java.net.URLDecoder;
import java.sql.*;
import java.util.Properties;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import org.relique.io.TableReader;
/**
* This class implements the java.sql.Driver JDBC interface for the CsvJdbc driver.
*/
public class CsvDriver implements Driver
{
public static final String DEFAULT_EXTENSION = ".csv";
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTECHAR = '"';
public static final String DEFAULT_HEADERLINE = null;
public static final boolean DEFAULT_SUPPRESS = false;
public static final boolean DEFAULT_TRIM_HEADERS = true;
public static final boolean DEFAULT_TRIM_VALUES = false;
public static final String DEFAULT_COLUMN_TYPES = "String";
public static final boolean DEFAULT_INDEXED_FILES = false;
public static final String DEFAULT_TIMESTAMP_FORMAT = "YYYY-MM-DD HH:mm:ss";
public static final String DEFAULT_DATE_FORMAT = "YYYY-MM-DD";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public static final String DEFAULT_COMMENT_CHAR = null;
public static final String DEFAULT_SKIP_LEADING_LINES = null;
public static final String DEFAULT_IGNORE_UNPARSEABLE_LINES = "False";
public static final String DEFAULT_FILE_TAIL_PREPEND = "False";
public static final String DEFAULT_DEFECTIVE_HEADERS = "False";
public static final String DEFAULT_SKIP_LEADING_DATA_LINES = "0";
public static final String FILE_EXTENSION = "fileExtension";
public static final String SEPARATOR = "separator";
public static final String QUOTECHAR = "quotechar";
public static final String HEADERLINE = "headerline";
public static final String SUPPRESS_HEADERS = "suppressHeaders";
public static final String TRIM_HEADERS = "trimHeaders";
public static final String TRIM_VALUES = "trimValues";
public static final String COLUMN_TYPES = "columnTypes";
public static final String INDEXED_FILES = "indexedFiles";
public static final String TIMESTAMP_FORMAT = "timestampFormat";
public static final String DATE_FORMAT = "dateFormat";
public static final String TIME_FORMAT = "timeFormat";
public static final String COMMENT_CHAR = "commentChar";
public static final String SKIP_LEADING_LINES = "skipLeadingLines";
public static final String IGNORE_UNPARSEABLE_LINES = "ignoreNonParseableLines";
public static final String FILE_TAIL_PREPEND = "fileTailPrepend";
public static final String DEFECTIVE_HEADERS = "defectiveHeaders";
public static final String SKIP_LEADING_DATA_LINES = "skipLeadingDataLines";
public static final String TRANSPOSED_LINES = "transposedLines";
public static final String TRANSPOSED_FIELDS_TO_SKIP = "transposedFieldsToSkip";
public static final String CHARSET = "charset";
public final static String URL_PREFIX = "jdbc:relique:csv:";
public static final String CRYPTO_FILTER_CLASS_NAME = "cryptoFilterClassName";
public static final String TIME_ZONE_NAME = "timeZoneName";
public static final String DEFAULT_TIME_ZONE_NAME = "UTC";
// choosing Rome makes sure we change chronology from Julian to Gregorian on
// 1582-10-04/15, as SQL does.
public static final String QUOTE_STYLE = "quoteStyle";
public static final String DEFAULT_QUOTE_STYLE = "SQL";
public static final String READER_CLASS_PREFIX = "class:";
public static final String ZIP_FILE_PREFIX = "zip:";
public static final String FIXED_WIDTHS = "fixedWidths";
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
throws SQLException
{
return new DriverPropertyInfo[0];
}
@Override
public int getMajorVersion()
{
return 1;
}
@Override
public int getMinorVersion()
{
return 0;
}
@Override
public Connection connect(String url, Properties info) throws SQLException
{
writeLog("CsvDriver:connect() - url=" + url);
// check for correct url
if (!url.startsWith(URL_PREFIX))
{
return null;
}
// strip any properties from end of URL and set them as additional
// properties
String urlProperties = "";
int questionIndex = url.indexOf('?');
if (questionIndex >= 0)
{
info = new Properties(info);
urlProperties = url.substring(questionIndex);
String[] split = urlProperties.substring(1).split("&");
for (int i = 0; i < split.length; i++)
{
String[] property = split[i].split("=");
try
{
if (property.length == 2)
{
String key = URLDecoder.decode(property[0], "UTF-8");
String value = URLDecoder.decode(property[1], "UTF-8");
info.setProperty(key, value);
}
else
{
throw new SQLException("Invalid property: " + split[i]);
}
}
catch (UnsupportedEncodingException e)
{
// we know UTF-8 is available
}
}
url = url.substring(0, questionIndex);
}
// get filepath from url
String filePath = url.substring(URL_PREFIX.length());
writeLog("CsvDriver:connect() - filePath="
+ filePath);
CsvConnection connection;
if (filePath.startsWith(READER_CLASS_PREFIX))
{
String className = filePath.substring(READER_CLASS_PREFIX.length());
try
{
Class<?> clazz = Class.forName(className);
/*
* Check that class implements our interface.
*/
Class<?>[] interfaces = clazz.getInterfaces();
boolean isInterfaceImplemented = false;
for (int i = 0; i < interfaces.length
&& (!isInterfaceImplemented); i++)
{
if (interfaces[i].equals(TableReader.class))
isInterfaceImplemented = true;
}
if (!isInterfaceImplemented)
{
throw new SQLException(
"Class does not implement interface "
+ TableReader.class.getName() + ": "
+ className);
}
Object tableReaderInstance = clazz.newInstance();
connection = new CsvConnection(
(TableReader) tableReaderInstance, info, urlProperties);
}
catch (ClassNotFoundException e)
{
throw new SQLException(e);
}
catch (IllegalAccessException e)
{
throw new SQLException(e);
}
catch (InstantiationException e)
{
throw new SQLException(e);
}
}
else if (filePath.startsWith(ZIP_FILE_PREFIX))
{
String zipFilename = filePath.substring(ZIP_FILE_PREFIX.length());
try
{
ZipFileTableReader zipFileTableReader = new ZipFileTableReader(
zipFilename, info.getProperty(CHARSET));
connection = new CsvConnection(zipFileTableReader, info,
urlProperties);
zipFileTableReader.setExtension(connection.getExtension());
}
catch (IOException e)
{
throw new SQLException("Failed opening ZIP file: "
+ zipFilename, e);
}
}
else
{
if (!filePath.endsWith(File.separator))
{
filePath += File.separator;
}
// check if filepath is a correct path.
File checkPath = new File(filePath);
if (!checkPath.exists())
{
throw new SQLException("Directory does not exist: " + filePath);
}
if (!checkPath.isDirectory())
{
throw new SQLException("Not a directory: " + filePath);
}
connection = new CsvConnection(filePath, info, urlProperties);
}
return connection;
}
@Override
public boolean acceptsURL(String url) throws SQLException
{
writeLog("CsvDriver:accept() - url=" + url);
return url.startsWith(URL_PREFIX);
}
@Override
public boolean jdbcCompliant()
{
return false;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException
{
throw new SQLFeatureNotSupportedException(
"Driver.getParentLogger() not supported");
}
public static void writeLog(String message)
{
PrintWriter logWriter = DriverManager.getLogWriter();
if (logWriter != null)
logWriter.println("CsvJdbc: " + message);
}
/**
* Convenience method to write a ResultSet to a CSV file.
* Output CSV file has the same format as the CSV file that is
* being queried, so that it can be used for later SQL queries.
* @param resultSet JDBC ResultSet to write.
* @param out open stream to write to.
* @param writeHeaderLine if true, the column names are written as first line.
* @throws SQLException
*/
public static void writeToCsv(ResultSet resultSet, PrintStream out, boolean writeHeaderLine)
throws SQLException
{
char separator = DEFAULT_SEPARATOR;
char quoteChar = DEFAULT_QUOTECHAR;
String quoteStyle = DEFAULT_QUOTE_STYLE;
if (resultSet instanceof CsvResultSet)
{
/*
* Use same formatting options as the CSV file this ResultSet was read from.
*/
CsvResultSet csvResultSet = (CsvResultSet)resultSet;
CsvConnection csvConnection = (CsvConnection)csvResultSet.getStatement().getConnection();
separator = csvConnection.getSeparator();
quoteChar = csvConnection.getQuotechar();
quoteStyle = csvConnection.getQuoteStyle();
}
ResultSetMetaData meta = resultSet.getMetaData();
int columnCount = meta.getColumnCount();
if (writeHeaderLine)
{
for (int i = 1; i <= columnCount; i++)
{
if (i > 1)
out.print(separator);
out.print(meta.getColumnName(i));
}
out.println();
}
/*
* Write each row of ResultSet.
*/
while (resultSet.next())
{
for (int i = 1; i <= columnCount; i++)
{
if (i > 1)
out.print(separator);
String value = resultSet.getString(i);
value = addQuotes(value, separator, quoteChar, quoteStyle);
out.print(value);
}
out.println();
}
out.flush();
}
private static String addQuotes(String value, char separator, char quoteChar, String quoteStyle)
{
/*
* Escape all quote chars embedded in the string.
*/
if (quoteStyle.equals("C"))
{
value = value.replace("\\", "\\\\");
value = value.replace("" + quoteChar, "\\" + quoteChar);
}
else
{
value = value.replace("" + quoteChar, "" + quoteChar + quoteChar);
}
/*
* Surround value with quotes if it contains any special characters.
*/
if (value.indexOf(separator) >= 0 || value.indexOf(quoteChar) >= 0 ||
value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0)
{
value = quoteChar + value + quoteChar;
}
return value;
}
// This static block inits the driver when the class is loaded by the JVM.
static
{
try
{
java.sql.DriverManager.registerDriver(new CsvDriver());
}
catch (SQLException e)
{
throw new RuntimeException(
"FATAL ERROR: Could not initialise CSV driver ! Message was: "
+ e.getMessage());
}
}
}
|
package saltr;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import saltr.response.SLTResponseTemplate;
public class SLTIdentityDialogBuilder extends AlertDialog.Builder {
private EditText name;
private EditText email;
private LinearLayout layout;
public SLTIdentityDialogBuilder(Context context) {
super(context);
name = new EditText(getContext());
email = new EditText(getContext());
layout = new LinearLayout(getContext());
name.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
email.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
name.setLines(1);
email.setLines(1);
name.setHint("Device Name");
email.setHint("myemail@example.com");
layout.addView(email);
layout.addView(name);
layout.setOrientation(1);
setTitle("Register Device with SALTR");
setView(layout);
setPositiveButton("Ok", null);
setNegativeButton("Cancel", null);
}
public void showDialog(final boolean devMode, final int timeout, final String clientKey, final String deviceId) {
final AlertDialog dialog = create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button ok = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Editable editableName = name.getText();
Editable editableEmail = email.getText();
SLTAddDeviceToSaltrApiCall apiCall = new SLTAddDeviceToSaltrApiCall(timeout, devMode, editableName.toString(), editableEmail.toString(), clientKey, deviceId);
apiCall.call(new SLTAddDeviceDelegate() {
@Override
public void onSuccess(SLTResponseTemplate response) {
if (response.getSuccess()) {
dialog.dismiss();
}
else {
Toast toast = Toast.makeText(getContext(), response.getError().getMessage(), Toast.LENGTH_LONG);
toast.show();
}
}
@Override
public void onFailure() {
Toast toast = Toast.makeText(getContext(), "Error", Toast.LENGTH_LONG);
toast.show();
}
});
}
});
Button cancel = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();
}
}
|
package org.se.lab.web;
import org.apache.log4j.Logger;
import org.se.lab.db.data.Community;
import org.se.lab.service.CommunityService;
import org.se.lab.service.ServiceException;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Named
@RequestScoped
public class AdminDataBean implements Serializable {
private static final long serialVersionUID = 1L;
private final static Logger LOG = Logger.getLogger(AdminDataBean.class);
private List<Community> requestedCommunityList;
private List<Community> approvedCommunityList;
private Flash flash;
private ExternalContext context;
private List<Community> selectedCommunities;
private Community selectedCommunity;
private String id = "";
private String userProfId;
private int userId = 0;
private String reactionOnPendingRequest = null;
@Inject
private CommunityService service;
@PostConstruct
public void init() {
context = FacesContext.getCurrentInstance().getExternalContext();
flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
//Get UserId of user, who owns session
Map<String, Object> session = context.getSessionMap();
id = context.getRequestParameterMap().get("userid");
flash.put("uid", id);
userProfId = String.valueOf(context.getFlash().get("uid"));
LOG.info("userProfId: " + userProfId);
if (session.size() != 0 && session.get("user") != null) {
userId = (int) session.get("user");
LOG.info("SESSIOn UID: " + userId);
} else {
try {
context.redirect("/pse/index.xhtml");
} catch (IOException e) {
LOG.error("Can't redirect to /pse/index.xhtml");
}
}
requestedCommunityList = new ArrayList<>();
approvedCommunityList = new ArrayList<>();
requestedCommunityList = service.getPending();
LOG.info("Size of Requested Comm: " + requestedCommunityList.size());
approvedCommunityList = service.getApproved();
LOG.info("Size of Requested Comm: " + approvedCommunityList.size());
}
public void declineRequestedCommunity(Community community) {
LOG.info("Community declined >" + community);
try {
service.refuse(community);
reactionOnPendingRequest = "Sucessfully declined";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(reactionOnPendingRequest));
refreshPage();
} catch (ServiceException e) {
reactionOnPendingRequest = "Decline failed";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, reactionOnPendingRequest, "Please retry"));
}
}
public void approveRequestedCommunity(Community community) {
LOG.info("Community approved > " + community);
try {
service.approve(community);
refreshPage();
} catch (ServiceException e) {
reactionOnPendingRequest = "Approval failed";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, reactionOnPendingRequest, "Please retry"));
}
}
private void refreshPage() {
try {
context.redirect("/pse/adminPortal.xhtml");
} catch (IOException e) {
LOG.error("Can't redirect to /pse/adminPortal.xhtml");
}
}
public void goToCommunity() {
LOG.info("In Method goToCommunity");
if (selectedCommunity != null) {
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getSessionMap().put("communityId", selectedCommunity.getId());
try {
context.getExternalContext().redirect("/pse/communityprofile.xhtml");
} catch (IOException e) {
LOG.error("Can't redirect to /pse/communityprofile.xhtml");
}
}
}
private void writeObject(ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
public String getReactionOnPendingRequest() {
return reactionOnPendingRequest;
}
public List<Community> getRequestedCommunityList() {
return requestedCommunityList;
}
public void setRequestedCommunityList(List<Community> requestedCommunityList) {
this.requestedCommunityList = requestedCommunityList;
}
public List<Community> getApprovedCommunityList() {
return approvedCommunityList;
}
public void setApprovedCommunityList(List<Community> approvedCommunityList) {
this.approvedCommunityList = approvedCommunityList;
}
public Community getSelectedCommunity() {
return selectedCommunity;
}
public void setSelectedCommunity(Community selectedCommunity) {
this.selectedCommunity = selectedCommunity;
}
public List<Community> getSelectedCommunities() {
return selectedCommunities;
}
public void setSelectedCommunities(List<Community> selectedCommunities) {
this.selectedCommunities = selectedCommunities;
}
}
|
package com.mikosik.jsolid.d3;
import static com.mikosik.jsolid.JSolid.align;
import static com.mikosik.jsolid.JSolid.cuboid;
import static com.mikosik.jsolid.JSolid.maxX;
import static com.mikosik.jsolid.JSolid.nothing;
import static com.mikosik.jsolid.JSolid.range;
import static com.mikosik.jsolid.JSolid.v;
import static com.mikosik.jsolid.util.ExceptionMatcher.exception;
import static com.mikosik.jsolid.util.SolidMatcher.matchesSolid;
import static org.testory.Testory.given;
import static org.testory.Testory.thenReturned;
import static org.testory.Testory.thenThrown;
import static org.testory.Testory.when;
import org.junit.Test;
public class AddTest {
private Cuboid solid;
@Test
public void add_two_cuboid_halves() throws Exception {
given(solid = cuboid(range(-1, 0), 2, 2));
when(() -> solid.add(cuboid(range(0, 1), 2, 2)));
thenReturned(matchesSolid(
v(-1, 1, 1),
v(-1, 1, -1),
v(-1, -1, 1),
v(-1, -1, -1),
v(0, 1, 1),
v(0, 1, -1),
v(0, -1, 1),
v(0, -1, -1),
v(1, 1, 1),
v(1, 1, -1),
v(1, -1, 1),
v(1, -1, -1)));
}
@Test
public void add_itself_returns_itself() throws Exception {
given(solid = cuboid(2, 2, 2));
when(() -> solid.add(cuboid(2, 2, 2)));
thenReturned(matchesSolid(
v(-1, 1, 1),
v(-1, 1, -1),
v(-1, -1, 1),
v(-1, -1, -1),
v(1, 1, 1),
v(1, 1, -1),
v(1, -1, 1),
v(1, -1, -1)));
}
@Test
public void adding_aligned_nothing_succeeds() throws Exception {
when(() -> cuboid(1, 2, 3).add(nothing(), align(maxX())).sides());
thenReturned();
}
@Test
public void adding_aligned_to_nothing_fails() throws Exception {
when(() -> nothing().add(cuboid(1, 2, 3), align(maxX())).sides());
thenThrown(exception(new IllegalArgumentException(
"It is not possible to align against empty Solid.")));
}
@Test
public void adding_anchored_nothing_succeeds() throws Exception {
when(() -> cuboid(1, 2, 3).add(nothing(), maxX()).sides());
thenReturned();
}
@Test
public void adding_anchored_to_nothing_fails() throws Exception {
when(() -> nothing().add(cuboid(1, 2, 3), maxX()).sides());
thenThrown(exception(new IllegalArgumentException(
"It is not possible to align against empty Solid.")));
}
}
|
package org.voovan.network;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Hashtable;
import java.util.Map;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.Status;
import org.voovan.tools.ByteBufferChannel;
import org.voovan.tools.log.Logger;
public abstract class IoSession {
private Map<Object, Object> attributes;
private SSLParser sslParser;
private ByteBufferChannel netDataBufferChannel;
private ByteBufferChannel appDataBufferChannel;
protected IoSession(){
attributes = new Hashtable<Object, Object>();
netDataBufferChannel = new ByteBufferChannel();
appDataBufferChannel = new ByteBufferChannel();
}
/**
*
* @return
*/
protected abstract ByteBufferChannel getByteBufferChannel();
/**
* SSLParser
* @return SSLParser
*/
protected SSLParser getSSLParser() {
return sslParser;
}
/**
* SSLParser
* @return SSLParser
*/
protected void setSSLParser(SSLParser sslParser) {
if(this.sslParser==null){
this.sslParser = sslParser;
}
}
/**
*
* @param key
* @return
*/
public Object getAttribute(Object key) {
return attributes.get(key);
}
/**
*
* @param key
* @param value
*/
public void setAttribute(Object key, Object value) {
this.attributes.put(key, value);
}
/**
*
* @param key
*/
public boolean containAttribute(Object key) {
return this.attributes.containsKey(key);
}
/**
* IP
* @return IP
*/
public abstract String loaclAddress();
/**
*
* @return -1
*/
public abstract int loaclPort();
/**
* IP
* @return ip
*/
public abstract String remoteAddress();
/**
*
* @return -1
*/
public abstract int remotePort();
/**
* socket
* @return socket , null
*/
public abstract SocketContext sockContext();
/**
*
* @param buffer
* @return
*/
protected abstract int read(ByteBuffer buffer) throws IOException;
/**
*
* onSent
* @param byteBuffer
* @throws IOException
*/
public abstract void send(ByteBuffer buffer) throws IOException;
/**
* SSL
* @param buffer
* @return
*/
protected int readSSLData(ByteBuffer buffer){
int readSize = 0;
ByteBuffer netBuffer = sslParser.buildAppDataBuffer();
ByteBuffer appBuffer = sslParser.buildAppDataBuffer();
try{
if(isConnect() && buffer!=null){
SSLEngineResult engineResult = null;
do{
netBuffer.clear();
appBuffer.clear();
if(read(netBuffer)!=0){
netDataBufferChannel.write(netBuffer);
engineResult = sslParser.unwarpData(netDataBufferChannel.getBuffer(), appBuffer);
appBuffer.flip();
appDataBufferChannel.write(appBuffer);
}
}while(engineResult==null?false:engineResult.getStatus() != Status.OK);
readSize = appDataBufferChannel.read(buffer);
}
}
catch(IOException e){
Logger.error(e);
}
return readSize;
}
/**
* SSL
* onSent
* @param byteBuffer
* @throws IOException
*/
public void sendSSLData(ByteBuffer buffer){
if(isConnect() && buffer!=null){
try {
sslParser.warpData(buffer);
} catch (IOException e) {
Logger.error(e);
}
}
}
/**
*
* @return
*/
protected abstract MessageLoader getMessageLoader();
/**
*
* @return
*/
protected abstract MessageSplitter getMessagePartition();
/**
*
* @return true: ,false:
*/
public abstract boolean isConnect();
public abstract boolean close();
@Override
public abstract String toString();
}
|
package ptrman.exp;
import processing.core.PApplet;
import processing.core.PImage;
import ptrman.bindingNars.NarsBinding;
import ptrman.bindingNars.OnaNarseseConsumer;
import ptrman.bpsolver.IImageDrawer;
import ptrman.bpsolver.Solver;
import ptrman.bpsolver.Solver2;
import ptrman.misc.ImageConverter;
import ptrman.visualizationTests.VisualizationDrawer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;
/**
* * connect to NAR
* * test in simple world (pong, etc)
*/
public class NarConSimpleWorld extends PApplet {
final static int RETINA_WIDTH = 128;
final static int RETINA_HEIGHT = 128;
public Solver2 solver2 = new Solver2();
private PImage pimg;
// scene to choose
// "pong" pong
public static String scene = "pong";
public static double ballX = 30.0;
public static double ballY = 50.0;
public static double ballVelX = 6.1;
public static double ballVelY = 1.6;
public static double batVel = 0.0;
public static double batY = 50.0;
public static int t = 0; // timer
public static Process pro = null;
public static OutputStream os;
public static InputStream is;
public static BufferedReader reader;
public static BufferedWriter writer;
public static String pathToOna = "C:\\Users\\R0B3\\dir\\github\\OpenNARS-for-Applications";
// helper to send string to ONA
public static void sendText(String str, boolean silent) {
if (!silent) {
System.out.println("=>"+str);
}
byte[] buf = (str+"\n").getBytes();
try {
os.write(buf);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String queuedOp = null; // string of op which is queued
// helper to let NAR perform inference steps
public void narInferenceSteps(int steps) {
sendText(""+steps, true);
try {
while(true) {
int len = is.available();
if(len > 0) {
byte[] buf = new byte[len];
is.read(buf);
String bufAsString = new String(buf);
for(String iLine : bufAsString.split("\\n")) {
if (iLine.contains("=/>") && iLine.contains("^")) { // is a seq with a op derived?
System.out.println("=/>^ "+iLine);
int here = 5;
}
if (iLine.substring(0, 9).equals("Derived: ") || iLine.substring(0, 9).equals("Revised: ")) {
continue; // ignore derivation messages
}
if (iLine.substring(0, 4).equals("done") || iLine.substring(0, 10).equals("performing")) {
// don't print
}
else {
System.out.println(iLine);
}
if(iLine.contains("executed with args")) {
int here = 5;
}
if (iLine.equals("^up executed with args ")) {
queuedOp = "^up";
}
else if (iLine.equals("^down executed with args ")) {
queuedOp = "^down";
}
if (iLine.substring(0, 4).equals("done")) {
return; // it is done with the steps
}
}
int here = 5;
}
try {
Thread.sleep(1); // give other processes time
} catch (InterruptedException e) {
//e.printStackTrace();
}
int here = 5;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public NarConSimpleWorld() {
/*
try {
socket = new DatagramSocket(50001);
socket.setSoTimeout(1);
} catch (SocketException e) {
e.printStackTrace();
}*/
// TODO < decide path based on OS >
String commandline = pathToOna+"\\NAR.exe";
try {
pro = Runtime.getRuntime().exec(new String[]{commandline, "shell"});
os = pro.getOutputStream();
is = pro.getInputStream();
sendText("*motorbabbling=false", false);
} catch (IOException e) {
e.printStackTrace();
}
solver2.narsBinding = new NarsBinding(new OnaNarseseConsumer());
}
public void setup() {
frameRate(8);
}
public static class InputDrawer implements IImageDrawer {
BufferedImage off_Image;
@Override
public BufferedImage apply(Solver bpSolver) {
if (off_Image == null || off_Image.getWidth() != RETINA_WIDTH || off_Image.getHeight() != RETINA_HEIGHT) {
off_Image = new BufferedImage(RETINA_WIDTH, RETINA_HEIGHT, BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = off_Image.createGraphics();
g2.setColor(Color.BLACK);
g2.drawRect(0, 0, off_Image.getWidth(), off_Image.getHeight());
g2.setColor(Color.WHITE);
g2.drawRect(6, (int)batY-15, 10, 30);
g2.fillOval((int)ballX, (int)ballY, 20, 20);
return off_Image;
}
}
static float animationTime = 0.0f;
public VisualizationDrawer drawer = new VisualizationDrawer(); // used for drawing
String oldState = "";
public void draw() {
t++;
if(VisualizationDrawer.rel2 != "") { // send current state
String n = "< {"+(VisualizationDrawer.rel2)+"} --> rel >. :|:";
sendText(n, false);
oldState = VisualizationDrawer.rel2;
}
{
Random rng = new Random();
if(rng.nextFloat() < 0.1) {
if (rng.nextFloat() < 0.5) {
batVel = -7.0;
String n = "^up. :|:";
sendText(n, false);
}
else {
batVel = 7.0;
String n = "^down. :|:";
sendText(n, false);
}
}
}
{ // simulate
if (ballX < 10) {
ballVelX = Math.abs(ballVelX);
}
if (ballX > 120) {
ballVelX = -Math.abs(ballVelX);
}
if (ballY < 0) {
ballVelY = Math.abs(ballVelY);
}
if (ballY > 100) {
ballVelY = -Math.abs(ballVelY);
}
if (ballX < 10) {
float distY = (float)Math.abs(ballY - batY);
if (distY < 15) {
// hit bat -> good NAR
sendText("good_nar. :|:", false);
}
else { // bat didn't hit ball, respawn ball
System.out.println("respawn ball");
Random rng = new Random();
ballX = 15+5 + rng.nextFloat()*80;
ballY = rng.nextFloat()*80;
ballVelY = (rng.nextFloat()*2.0 - 1.0)*2.0;
}
}
ballX += ballVelX;
ballY += ballVelY;
batY += batVel;
batY = Math.min(batY, 100-15/2);
batY = Math.max(batY, 15/2);
}
if (t%4 == 0) {
// feed with goal
String n = "good_nar! :|:\n\0";
sendText(n, false);
}
{ // give time to reason
narInferenceSteps(5);
// do actions
if (queuedOp != null && queuedOp.equals("^up")) {
batVel = -7.0;
}
if (queuedOp != null && queuedOp.equals("^down")) {
batVel = 7.0;
}
queuedOp = null;
}
background(0);
animationTime += 0.1f;
int steps = 50; // how many steps are done?
solver2.imageDrawer = new ptrman.exp.NarConSimpleWorld.InputDrawer();
solver2.preFrame(); // do all processing and setup before the actual processing of the frame
for (int iStep=0;iStep<steps;iStep++) {
solver2.frameStep(); // step of a frame
}
solver2.postFrame();
{ // draw processed image in the background
pimg = ImageConverter.convBufferedImageToPImage((new ptrman.exp.NarConSimpleWorld.InputDrawer()).apply(null), pimg);
tint(255.0f, 0.2f*255.0f);
image(pimg, 0, 0); // draw image
tint(255.0f, 255.0f); // reset tint
}
drawer.drawPrimitives(solver2, this);
// mouse cursor
//ellipse(mouseX, mouseY, 4, 4);
}
@Override
public void settings() {
size(200, 200);
}
public static void main(String[] passedArgs) {
PApplet.main(new String[] { "ptrman.exp.NarConSimpleWorld" });
}
}
|
package hu.bme.mit.trainbenchmark.benchmark.hawk.driver;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource.Factory.Registry;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.incquery.runtime.api.AdvancedIncQueryEngine;
import org.eclipse.incquery.runtime.api.IMatchUpdateListener;
import org.eclipse.incquery.runtime.api.IncQueryEngine;
import org.eclipse.incquery.runtime.api.IncQueryMatcher;
import org.eclipse.incquery.runtime.api.impl.BasePatternMatch;
import org.eclipse.incquery.runtime.emf.EMFScope;
import hu.bme.mit.trainbenchmark.benchmark.emfincquery.driver.EMFIncQueryBaseDriver;
import hu.bme.mit.trainbenchmark.benchmark.hawk.config.HawkBenchmarkConfig;
import hu.bme.mit.trainbenchmark.railway.RailwayPackage;
import uk.ac.york.mondo.integration.api.Credentials;
import uk.ac.york.mondo.integration.api.Hawk.Client;
import uk.ac.york.mondo.integration.api.HawkInstance;
import uk.ac.york.mondo.integration.api.HawkInstanceNotFound;
import uk.ac.york.mondo.integration.api.Repository;
import uk.ac.york.mondo.integration.api.utils.APIUtils;
import uk.ac.york.mondo.integration.api.utils.APIUtils.ThriftProtocol;
import uk.ac.york.mondo.integration.hawk.emf.HawkResourceFactoryImpl;
public class HawkDriver<M extends BasePatternMatch> extends EMFIncQueryBaseDriver<M> {
private static final String ECORE_METAMODEL = "/hu.bme.mit.trainbenchmark.emf.model/model/railway.ecore";
private static final String HAWK_REPOSITORY = "/models/hawkrepository/";
private static final String PASSWORD = "admin";
private static final String HAWK_INSTANCE = "trainbenchmark";
private static final String HAWK_ADDRESS = "localhost:8080/thrift/hawk/tuple";
private static final String HAWK_URL = "http://" + HAWK_ADDRESS;
protected HawkBenchmarkConfig hbc;
protected String hawkRepositoryPath;
public HawkDriver(final HawkBenchmarkConfig hbc) {
this.hbc = hbc;
}
@Override
public void initialize() throws Exception {
super.initialize();
final File workspaceRelativePath = new File(hbc.getWorkspacePath());
final String workspacePath = workspaceRelativePath.getAbsolutePath();
hawkRepositoryPath = workspacePath + HAWK_REPOSITORY;
cleanRepository(hawkRepositoryPath);
connectToHawk(workspacePath);
}
protected void cleanRepository(final String hawkRepositoryPath) throws IOException {
// remove the repository
final File hawkRepositoryFile = new File(hawkRepositoryPath);
FileUtils.deleteDirectory(hawkRepositoryFile);
}
protected void copyModelToHawk(final String hawkRepositoryPath, final String modelPath) throws IOException {
final File modelFile = new File(modelPath);
final File hawkRepositoryFile = new File(hawkRepositoryPath);
FileUtils.copyFileToDirectory(modelFile, hawkRepositoryFile);
}
protected void connectToHawk(final String workspacePath) throws Exception {
final Client client = APIUtils.connectToHawk(HAWK_URL, ThriftProtocol.TUPLE);
try {
client.startInstance(HAWK_INSTANCE, PASSWORD);
} catch (final HawkInstanceNotFound ex) {
client.createInstance(HAWK_INSTANCE, PASSWORD);
}
final String ecoreMetamodelPath = workspacePath + ECORE_METAMODEL;
final java.io.File file = new java.io.File(ecoreMetamodelPath);
final uk.ac.york.mondo.integration.api.File thriftFile = APIUtils.convertJavaFileToThriftFile(file);
outer: do {
final List<HawkInstance> listInstances = client.listInstances();
for (final HawkInstance hi : listInstances) {
if (HAWK_INSTANCE.equals(hi.getName()) && hi.isRunning()) {
break outer;
}
}
System.out.println("Waiting for Hawk to start.");
Thread.sleep(500);
} while (true);
final ResourceSetImpl resourceSet = new ResourceSetImpl();
final Registry resourceFactoryRegistry = resourceSet.getResourceFactoryRegistry();
resourceFactoryRegistry.getProtocolToFactoryMap().put("hawk+http", new HawkResourceFactoryImpl());
// set the Resource in the EMFDriver
resource = resourceSet.createResource(
URI.createURI("hawk+http://" + HAWK_ADDRESS + "?instance=" + HAWK_INSTANCE + "&subscribe=true&durability=temporary"));
resource.load(Collections.emptyMap());
client.registerMetamodels(HAWK_INSTANCE, Arrays.asList(thriftFile));
final Credentials credentials = new Credentials("dummy", "dummy");
final Repository repository = new Repository(HAWK_REPOSITORY, "org.hawk.localfolder.LocalFolder");
client.addRepository(HAWK_INSTANCE, repository, credentials);
}
@Override
public void read(final String modelPathWithoutExtension) throws Exception {
RailwayPackage.eINSTANCE.eClass();
final String modelPath = hbc.getModelPathWithoutExtension() + getPostfix();
// copy the model to the hawk repository to allow Hawk to load the model
copyModelToHawk(hawkRepositoryPath, modelPath);
// TODO: wait for finishing the operation
final EMFScope emfScope = new EMFScope(resource);
engine = AdvancedIncQueryEngine.from(IncQueryEngine.on(emfScope));
final IncQueryMatcher<M> matcher = checker.getMatcher();
final Collection<M> matches = matcher.getAllMatches();
checker.setMatches(matches);
engine.addMatchUpdateListener(matcher, new IMatchUpdateListener<M>() {
@Override
public void notifyAppearance(final M match) {
matches.add(match);
}
@Override
public void notifyDisappearance(final M match) {
matches.remove(match);
}
}, false);
}
public void persist() throws IOException {
resource.save(null);
}
}
|
package redis.clients.jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.ArrayList;
import java.util.List;
public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti;
private class MultiResponseBuilder extends Builder<List<Object>> {
private List<Response<?>> responses = new ArrayList<Response<?>>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<Object>();
if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
}
for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i);
response.set(list.get(i));
Object builtResponse;
try {
builtResponse = response.get();
} catch (JedisDataException e) {
builtResponse = e;
}
values.add(builtResponse);
}
return values;
}
public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) {
response.setDependency(dependency);
}
}
public void addResponse(Response<?> response) {
responses.add(response);
}
}
@Override
protected <T> Response<T> getResponse(Builder<T> builder) {
if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
return super.getResponse(builder);
}
}
public void setClient(Client client) {
this.client = client;
}
@Override
protected Client getClient(byte[] key) {
return client;
}
@Override
protected Client getClient(String key) {
return client;
}
public void clear() {
if (isInMulti()) {
discard();
}
sync();
}
public boolean isInMulti() {
return currentMulti != null;
}
/**
* Syncronize pipeline by reading all responses. This operation close the
* pipeline. In order to get return values from pipelined commands, capture
* the different Response<?> of the commands you execute.
*/
public void sync() {
List<Object> unformatted = client.getMany(getPipelinedResponseLength());
for (Object o : unformatted) {
generateResponse(o);
}
}
/**
* Syncronize pipeline by reading all responses. This operation close the
* pipeline. Whenever possible try to avoid using this version and use
* Pipeline.sync() as it won't go through all the responses and generate the
* right response type (usually it is a waste of time).
*
* @return A list of all the responses in the order you executed them.
*/
public List<Object> syncAndReturnAll() {
List<Object> unformatted = client.getMany(getPipelinedResponseLength());
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
} catch (JedisDataException e) {
formatted.add(e);
}
}
return formatted;
}
public Response<String> discard() {
if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI");
client.discard();
currentMulti = null;
return getResponse(BuilderFactory.STRING);
}
public Response<List<Object>> exec() {
if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI");
client.exec();
Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response);
currentMulti = null;
return response;
}
public Response<String> multi() {
if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested");
client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
currentMulti = new MultiResponseBuilder();
return response;
}
}
|
package org.innovateuk.ifs.competition.transactional;
import org.apache.commons.lang3.tuple.Pair;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.mapper.ApplicationMapper;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.application.resource.ApplicationPageResource;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.transactional.ApplicationService;
import org.innovateuk.ifs.category.domain.Category;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.domain.CompetitionType;
import org.innovateuk.ifs.competition.mapper.CompetitionMapper;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.competition.resource.*;
import org.innovateuk.ifs.invite.domain.competition.CompetitionAssessmentParticipant;
import org.innovateuk.ifs.invite.domain.competition.CompetitionParticipant;
import org.innovateuk.ifs.invite.domain.competition.CompetitionParticipantRole;
import org.innovateuk.ifs.invite.domain.ParticipantStatus;
import org.innovateuk.ifs.invite.repository.CompetitionParticipantRepository;
import org.innovateuk.ifs.project.repository.ProjectRepository;
import org.innovateuk.ifs.publiccontent.transactional.PublicContentService;
import org.innovateuk.ifs.transactional.BaseTransactionalService;
import org.innovateuk.ifs.user.domain.Organisation;
import org.innovateuk.ifs.user.domain.OrganisationType;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.mapper.OrganisationTypeMapper;
import org.innovateuk.ifs.user.mapper.UserMapper;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.OrganisationTypeResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.innovateuk.ifs.util.CollectionFunctions;
import org.innovateuk.ifs.workflow.resource.State;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.transaction.annotation.Transactional;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Optional.ofNullable;
import static org.innovateuk.ifs.application.resource.ApplicationState.*;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_CANNOT_RELEASE_FEEDBACK;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.security.SecurityRuleUtil.isInnovationLead;
import static org.innovateuk.ifs.security.SecurityRuleUtil.isSupport;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
import static org.springframework.data.domain.Sort.Direction.ASC;
/**
* Service for operations around the usage and processing of Competitions
*/
@Service
public class CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService {
@Autowired
private CompetitionRepository competitionRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private CompetitionParticipantRepository competitionParticipantRepository;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private CompetitionMapper competitionMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private OrganisationTypeMapper organisationTypeMapper;
@Autowired
private ApplicationMapper applicationMapper;
@Autowired
private ProjectRepository projectRepository;
@Autowired
private ApplicationService applicationService;
@Autowired
private PublicContentService publicContentService;
@Autowired
private CompetitionKeyStatisticsService competitionKeyStatisticsService;
@Autowired
private MilestoneService milestoneService;
private static final Map<String, Sort> APPLICATION_SORT_FIELD_MAP = new HashMap<String, Sort>() {{
put("id", new Sort(ASC, "id"));
put("name", new Sort(ASC, "name", "id"));
}};
private static final String EOI = "Expression of interest";
@Override
public ServiceResult<CompetitionResource> getCompetitionById(Long id) {
return find(competitionRepository.findById(id), notFoundError(Competition.class, id)).andOnSuccess(comp -> serviceSuccess(competitionMapper.mapToResource(comp)));
}
@Override
public ServiceResult<List<UserResource>> findInnovationLeads(Long competitionId) {
List<CompetitionAssessmentParticipant> competitionParticipants = competitionParticipantRepository.getByCompetitionIdAndRole(competitionId, CompetitionParticipantRole.INNOVATION_LEAD);
List<UserResource> innovationLeads = simpleMap(competitionParticipants, competitionParticipant -> userMapper.mapToResource(competitionParticipant.getUser()));
return serviceSuccess(innovationLeads);
}
@Override
@Transactional
public ServiceResult<Void> addInnovationLead(Long competitionId, Long innovationLeadUserId) {
return find(competitionRepository.findById(competitionId),
notFoundError(Competition.class, competitionId))
.andOnSuccessReturnVoid(competition -> {
find(userRepository.findOne(innovationLeadUserId),
notFoundError(User.class, innovationLeadUserId))
.andOnSuccess(innovationLead -> {
CompetitionAssessmentParticipant competitionParticipant = new CompetitionAssessmentParticipant();
competitionParticipant.setProcess(competition);
competitionParticipant.setUser(innovationLead);
competitionParticipant.setRole(CompetitionParticipantRole.INNOVATION_LEAD);
competitionParticipant.setStatus(ParticipantStatus.ACCEPTED);
competitionParticipantRepository.save(competitionParticipant);
return serviceSuccess();
});
});
}
@Override
@Transactional
public ServiceResult<Void> removeInnovationLead(Long competitionId, Long innovationLeadUserId) {
return find(competitionParticipantRepository.getByCompetitionIdAndUserIdAndRole(competitionId, innovationLeadUserId, CompetitionParticipantRole.INNOVATION_LEAD),
notFoundError(CompetitionParticipant.class, competitionId, innovationLeadUserId, CompetitionParticipantRole.INNOVATION_LEAD))
.andOnSuccessReturnVoid(competitionParticipant -> competitionParticipantRepository.delete(competitionParticipant));
}
@Override
public ServiceResult<List<CompetitionResource>> getCompetitionsByUserId(Long userId) {
List<ApplicationResource> userApplications = applicationService.findByUserId(userId).getSuccessObjectOrThrowException();
List<Long> competitionIdsForUser = userApplications.stream()
.map(ApplicationResource::getCompetition)
.distinct()
.collect(Collectors.toList());
return serviceSuccess((List) competitionMapper.mapToResource(
competitionRepository.findByIdIsIn(competitionIdsForUser))
);
}
@Override
public ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id) {
return find(competitionRepository.findById(id), notFoundError(OrganisationType.class, id)).andOnSuccess(comp -> serviceSuccess((List) organisationTypeMapper.mapToResource(comp.getLeadApplicantTypes())));
}
@Override
public ServiceResult<List<CompetitionResource>> findAll() {
return serviceSuccess((List) competitionMapper.mapToResource(
competitionRepository.findAll().stream().filter(comp -> !comp.isTemplate()).collect(Collectors.toList())
));
}
@Override
public ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions() {
List<Competition> competitions = competitionRepository.findLive();
return serviceSuccess(simpleMap(competitions, this::searchResultFromCompetition));
}
private ZonedDateTime findMostRecentFundingInformDate(Competition competition) {
return competition.getApplications()
.stream()
.filter(application -> application.getManageFundingEmailDate() != null)
.max(Comparator.comparing(Application::getManageFundingEmailDate))
.get().getManageFundingEmailDate();
}
@Override
public ServiceResult<List<CompetitionSearchResultItem>> findProjectSetupCompetitions() {
return getCurrentlyLoggedInUser().andOnSuccess(user -> {
List<Competition> competitions;
if (user.hasRole(UserRoleType.INNOVATION_LEAD)) {
competitions = competitionRepository.findProjectSetupForInnovationLead(user.getId());
} else {
competitions = competitionRepository.findProjectSetup();
}
// Only competitions with at least one funded and informed application can be considered as in project setup
return serviceSuccess(simpleMap(
CollectionFunctions.reverse(competitions.stream()
.filter(competition -> !competition.getCompetitionType().getName().equals(EOI))
.map(competition -> Pair.of(findMostRecentFundingInformDate(competition), competition))
.sorted(Comparator.comparing(Pair::getKey))
.map(Pair::getValue)
.collect(Collectors.toList())),
this::searchResultFromCompetition));
});
}
@Override
public ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions() {
List<Competition> competitions = competitionRepository.findUpcoming();
return serviceSuccess(simpleMap(competitions, this::searchResultFromCompetition));
}
@Override
public ServiceResult<List<CompetitionSearchResultItem>> findNonIfsCompetitions() {
List<Competition> competitions = competitionRepository.findNonIfs();
return serviceSuccess(simpleMap(competitions, this::searchResultFromCompetition));
}
@Override
public ServiceResult<List<CompetitionSearchResultItem>> findFeedbackReleasedCompetitions() {
List<Competition> competitions = competitionRepository.findFeedbackReleased();
return serviceSuccess(simpleMap(competitions, this::searchResultFromCompetition).stream().sorted((c1, c2) -> c2.getOpenDate().compareTo(c1.getOpenDate())).collect(Collectors.toList()));
}
@Override
public ServiceResult<ApplicationPageResource> findUnsuccessfulApplications(Long competitionId,
int pageIndex,
int pageSize,
String sortField) {
Set<State> unsuccessfulStates = simpleMapSet(asLinkedSet(
INELIGIBLE,
INELIGIBLE_INFORMED,
REJECTED), ApplicationState::getBackingState);
Sort sort = getApplicationSortField(sortField);
Pageable pageable = new PageRequest(pageIndex, pageSize, sort);
Page<Application> pagedResult = applicationRepository.findByCompetitionIdAndApplicationProcessActivityStateStateIn(competitionId, unsuccessfulStates, pageable);
List<ApplicationResource> unsuccessfulApplications = simpleMap(pagedResult.getContent(), this::convertToApplicationResource);
return serviceSuccess(new ApplicationPageResource(pagedResult.getTotalElements(), pagedResult.getTotalPages(), unsuccessfulApplications, pagedResult.getNumber(), pagedResult.getSize()));
}
private Sort getApplicationSortField(String sortBy) {
Sort result = APPLICATION_SORT_FIELD_MAP.get(sortBy);
return result != null ? result : APPLICATION_SORT_FIELD_MAP.get("id");
}
private ApplicationResource convertToApplicationResource(Application application) {
ApplicationResource applicationResource = applicationMapper.mapToResource(application);
Organisation leadOrganisation = organisationRepository.findOne(application.getLeadOrganisationId());
applicationResource.setLeadOrganisationName(leadOrganisation.getName());
return applicationResource;
}
@Override
public ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size) {
String searchQueryLike = String.format("%%%s%%", searchQuery);
PageRequest pageRequest = new PageRequest(page, size);
return getCurrentlyLoggedInUser().andOnSuccess(user -> {
if (user.hasRole(UserRoleType.INNOVATION_LEAD)) {
return handleCompetitionSearchResultPage(pageRequest, size, competitionRepository.searchForLeadTechnologist(searchQueryLike, user.getId(), pageRequest));
} else if (user.hasRole(UserRoleType.SUPPORT)) {
return handleCompetitionSearchResultPage(pageRequest, size, competitionRepository.searchForSupportUser(searchQueryLike, pageRequest));
} else {
return handleCompetitionSearchResultPage(pageRequest, size, competitionRepository.search(searchQueryLike, pageRequest));
}
});
}
private ServiceResult<CompetitionSearchResult> handleCompetitionSearchResultPage(PageRequest pageRequest, int size, Page<Competition> pageResult) {
CompetitionSearchResult result = new CompetitionSearchResult();
List<Competition> competitions = pageResult.getContent();
result.setContent(simpleMap(competitions, this::searchResultFromCompetition));
result.setNumber(pageRequest.getPageNumber());
result.setSize(size);
result.setTotalElements(pageResult.getTotalElements());
result.setTotalPages(pageResult.getTotalPages());
return serviceSuccess(result);
}
private CompetitionSearchResultItem searchResultFromCompetition(Competition c) {
ZonedDateTime openDate;
ServiceResult<MilestoneResource> openDateMilestone = milestoneService.getMilestoneByTypeAndCompetitionId(MilestoneType.OPEN_DATE, c.getId());
if (openDateMilestone.isSuccess()) {
openDate = openDateMilestone.getSuccessObject().getDate();
} else {
openDate = null;
}
return getCurrentlyLoggedInUser().andOnSuccess(currentUser -> serviceSuccess(new CompetitionSearchResultItem(c.getId(),
c.getName(),
ofNullable(c.getInnovationAreas()).orElseGet(Collections::emptySet)
.stream()
.map(Category::getName)
.collect(Collectors.toCollection(TreeSet::new)),
applicationRepository.countByCompetitionId(c.getId()),
c.startDateDisplay(),
c.getCompetitionStatus(),
ofNullable(c.getCompetitionType()).map(CompetitionType::getName).orElse(null),
projectRepository.findByApplicationCompetitionId(c.getId()).size(),
publicContentService.findByCompetitionId(c.getId()).getSuccessObjectOrThrowException().getPublishDate(),
isSupport(currentUser) ? "/competition/" + c.getId() + "/applications/all" : "/competition/" + c.getId(),
openDate
))).getSuccessObjectOrThrowException();
}
@Override
public ServiceResult<CompetitionCountResource> countCompetitions() {
//TODO INFUND-3833 populate complete count
return serviceSuccess(
new CompetitionCountResource(
getLiveCount(),
getPSCount(),
competitionRepository.countUpcoming(),
getFeedbackReleasedCount(),
competitionRepository.countNonIfs()));
}
private Long getLiveCount(){
return getCurrentlyLoggedInUser().andOnSuccessReturn(user ->
isInnovationLead(user) ?
competitionRepository.countLiveForInnovationLead(user.getId()) : competitionRepository.countLive()
).getSuccessObject();
}
private Long getPSCount(){
return getCurrentlyLoggedInUser().andOnSuccessReturn(user ->
isInnovationLead(user) ?
competitionRepository.countProjectSetupForInnovationLead(user.getId()) : competitionRepository.countProjectSetup()
).getSuccessObject();
}
private Long getFeedbackReleasedCount(){
return getCurrentlyLoggedInUser().andOnSuccessReturn(user ->
isInnovationLead(user) ?
competitionRepository.countFeedbackReleasedForInnovationLead(user.getId()) : competitionRepository.countFeedbackReleased()
).getSuccessObject();
}
@Override
@Transactional
public ServiceResult<Void> closeAssessment(long competitionId) {
Competition competition = competitionRepository.findById(competitionId);
competition.closeAssessment(ZonedDateTime.now());
return serviceSuccess();
}
@Override
@Transactional
public ServiceResult<Void> notifyAssessors(long competitionId) {
Competition competition = competitionRepository.findById(competitionId);
competition.notifyAssessors(ZonedDateTime.now());
return serviceSuccess();
}
@Override
@Transactional
public ServiceResult<Void> releaseFeedback(long competitionId) {
CompetitionFundedKeyStatisticsResource keyStatisticsResource =
competitionKeyStatisticsService.getFundedKeyStatisticsByCompetition(competitionId)
.getSuccessObjectOrThrowException();
if (keyStatisticsResource.isCanReleaseFeedback()) {
Competition competition = competitionRepository.findById(competitionId);
competition.releaseFeedback(ZonedDateTime.now());
return serviceSuccess();
} else {
return serviceFailure(new Error(COMPETITION_CANNOT_RELEASE_FEEDBACK));
}
}
@Override
@Transactional
public ServiceResult<Void> manageInformState(long competitionId) {
CompetitionFundedKeyStatisticsResource keyStatisticsResource =
competitionKeyStatisticsService.getFundedKeyStatisticsByCompetition(competitionId)
.getSuccessObjectOrThrowException();
if (keyStatisticsResource.isCanReleaseFeedback()) {
Competition competition = competitionRepository.findById(competitionId);
competition.setFundersPanelEndDate(ZonedDateTime.now());
}
return serviceSuccess();
}
@Override
public ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(Long competitionId) {
return serviceSuccess(competitionRepository.getOpenQueryByCompetition(competitionId));
}
@Override
public ServiceResult<Long> countAllOpenQueries(Long competitionId) {
return serviceSuccess(competitionRepository.countOpenQueries(competitionId));
}
@Override
public ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(Long competitionId) {
return serviceSuccess(competitionRepository.getPendingSpendProfiles(competitionId));
}
@Override
public ServiceResult<Long> countPendingSpendProfiles(Long competitionId) {
return serviceSuccess(competitionRepository.countPendingSpendProfiles(competitionId));
}
}
|
package seedu.tasklist.ui;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import seedu.tasklist.commons.core.LogsCenter;
import seedu.tasklist.commons.util.FxViewUtil;
/**
* Controller for a help page
*/
public class HelpWindow extends UiPart<Region> {
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String ICON = "/images/help_icon.png";
private static final String FXML = "HelpWindow.fxml";
private static final String TITLE = "Help";
private static final String USERGUIDE_URL =
"https://github.com/CS2103JAN2017-W14-B1/main/blob/master/docs/UserGuide.md#5-command-summary";
@FXML
private WebView browser;
private final Stage dialogStage;
public HelpWindow() {
super(FXML);
Scene scene = new Scene(getRoot());
//Null passed as the parent stage to make it non-modal.
dialogStage = createDialogStage(TITLE, null, scene);
dialogStage.setMaximized(true); //TODO: set a more appropriate initial size
FxViewUtil.setStageIcon(dialogStage, ICON);
browser.getEngine().load(USERGUIDE_URL);
FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0);
}
public void show() {
logger.fine("Showing help page about the application.");
dialogStage.showAndWait();
}
}
|
package ch.difty.scipamato.core.entity.filter;
/**
* The supported types of search terms.
*
* @author u.joss
*/
public enum SearchTermType {
BOOLEAN(0),
INTEGER(1),
STRING(2),
AUDIT(3),
// Dummy that helps testing business logic that throws an exception with
// undefined values (handled in the default case of a switch).
UNSUPPORTED(-1);
// cache the array
private static final SearchTermType[] SEARCH_TERM_TYPES = values();
private final int id;
SearchTermType(final int id) {
this.id = id;
}
public int getId() {
return id;
}
public static SearchTermType byId(final int id) {
for (final SearchTermType t : SEARCH_TERM_TYPES) {
if (id > UNSUPPORTED.id && t.getId() == id) {
return t;
}
}
throw new IllegalArgumentException("id " + id + " is not supported");
}
}
|
package org.ihtsdo.otf.mapping.jpa.handlers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.ihtsdo.otf.mapping.helpers.ConceptList;
import org.ihtsdo.otf.mapping.helpers.MapAdviceList;
import org.ihtsdo.otf.mapping.helpers.ValidationResult;
import org.ihtsdo.otf.mapping.helpers.ValidationResultJpa;
import org.ihtsdo.otf.mapping.jpa.MapEntryJpa;
import org.ihtsdo.otf.mapping.jpa.MapRecordJpa;
import org.ihtsdo.otf.mapping.jpa.helpers.TerminologyUtility;
import org.ihtsdo.otf.mapping.jpa.services.ContentServiceJpa;
import org.ihtsdo.otf.mapping.model.MapAdvice;
import org.ihtsdo.otf.mapping.model.MapEntry;
import org.ihtsdo.otf.mapping.model.MapRecord;
import org.ihtsdo.otf.mapping.model.MapRelation;
import org.ihtsdo.otf.mapping.rf2.Concept;
import org.ihtsdo.otf.mapping.services.ContentService;
import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility;
import org.ihtsdo.otf.mapping.services.helpers.FileSorter;
/**
* Implementation for sample allergy mapping project. Require valid codes to be
* allergies.
*/
public class MIMSAllergyToSnomedProjectSpecificAlgorithmHandler
extends DefaultProjectSpecificAlgorithmHandler {
/** The auto-generated map suggestions for preloading. */
private static Map<String, MapRecord> automaps = new HashMap<>();
/* see superclass */
@Override
public void initialize() throws Exception {
Logger.getLogger(getClass()).info("Running initialize for " + getClass().getSimpleName());
// Populate any project-specific caches.
cacheAutomaps();
}
/* see superclass */
@Override
public ValidationResult validateTargetCodes(MapRecord mapRecord)
throws Exception {
// No current validation restrictions
final ValidationResult validationResult = new ValidationResultJpa();
return validationResult;
}
/* see superclass */
@Override
public MapRecord computeInitialMapRecord(MapRecord mapRecord) throws Exception {
try {
if (automaps.isEmpty()) {
cacheAutomaps();
}
MapRecord existingMapRecord = automaps.get(mapRecord.getConceptId());
// // Run existing map record through standard map advice and relation
// // calculation
// if (existingMapRecord != null) {
// List<MapEntry> updatedMapEntries = new ArrayList<>();
// for (MapEntry mapEntry : existingMapRecord.getMapEntries()) {
// MapRelation mapRelation = computeMapRelation(existingMapRecord, mapEntry);
// MapAdviceList mapAdvices = computeMapAdvice(existingMapRecord, mapEntry);
// mapEntry.setMapRelation(mapRelation);
// mapEntry.getMapAdvices().addAll(mapAdvices.getMapAdvices());
// updatedMapEntries.add(mapEntry);
// existingMapRecord.setMapEntries(updatedMapEntries);
return existingMapRecord;
} catch (Exception e) {
throw e;
} finally {
}
}
/* see superclass */
@Override
public boolean isTargetCodeValid(String terminologyId) throws Exception {
//All SNOMED concepts are currently considered valid
return true;
}
/* see superclass */
@Override
public ValidationResult validateSemanticChecks(MapRecord mapRecord)
throws Exception {
final ValidationResult result = new ValidationResultJpa();
// Map record name must share at least one word with target name
final Set<String> recordWords = new HashSet<>(
Arrays.asList(mapRecord.getConceptName().toLowerCase().split(" ")));
final Set<String> entryWords = new HashSet<>();
for (final MapEntry entry : mapRecord.getMapEntries()) {
if (entry.getTargetName() != null) {
entryWords.addAll(
Arrays.asList(entry.getTargetName().toLowerCase().split(" ")));
}
}
final Set<String> recordMinusEntry = new HashSet<>(recordWords);
recordMinusEntry.removeAll(entryWords);
// If there are entry words and none match, warning
// if (entryWords.size() > 0 && recordWords.size() ==
// recordMinusEntry.size()) {
// result
// .addWarning("From concept and target code names must share at least one
// word.");
return result;
}
/**
* Cache existing maps.
*
* @throws Exception the exception
*/
private void cacheAutomaps() throws Exception {
// Lookup if this concept has an existing, auto-generated map record to pre-load
// Generated automap file must be saved here:
// {data.dir}/MIMS-Allergy/automap/results.txt
final ContentService contentService = new ContentServiceJpa();
Logger.getLogger(MIMSAllergyToSnomedProjectSpecificAlgorithmHandler.class)
.info("Caching the existing automaps");
final String dataDir = ConfigUtility.getConfigProperties().getProperty("data.dir");
if (dataDir == null) {
throw new Exception("Config file must specify a data.dir property");
}
// Check preconditions
String inputFile =
dataDir + "/MIMS-Allergy/automap/results.txt";
if (!new File(inputFile).exists()) {
throw new Exception("Specified input file missing: " + inputFile);
}
// Preload all concepts and create terminologyId->name maps, to avoid having
// to do individual lookups later
ConceptList sourceConcepts = contentService.getAllConcepts(mapProject.getSourceTerminology(),
mapProject.getSourceTerminologyVersion());
ConceptList destinationConcepts = contentService.getAllConcepts(
mapProject.getDestinationTerminology(), mapProject.getDestinationTerminologyVersion());
Map<String, String> sourceIdToName = new HashMap<>();
Map<String, String> destinationIdToName = new HashMap<>();
for (final Concept concept : sourceConcepts.getConcepts()) {
sourceIdToName.put(concept.getTerminologyId(), concept.getDefaultPreferredName());
}
for (final Concept concept : destinationConcepts.getConcepts()) {
destinationIdToName.put(concept.getTerminologyId(), concept.getDefaultPreferredName());
}
// Open reader and service
BufferedReader preloadMapReader = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = preloadMapReader.readLine()) != null) {
String fields[] = line.split("\t");
final String conceptId = fields[0];
// The first time a conceptId is encountered, set up the map (only need
// very limited information for the purpose of this function
if (automaps.get(conceptId) == null) {
MapRecord mimsAllergyAutomapRecord = new MapRecordJpa();
mimsAllergyAutomapRecord.setConceptId(conceptId);
String sourceConceptName = sourceIdToName.get(conceptId);
if (sourceConceptName != null) {
mimsAllergyAutomapRecord.setConceptName(sourceConceptName);
} else {
mimsAllergyAutomapRecord
.setConceptName("CONCEPT DOES NOT EXIST IN " + mapProject.getSourceTerminology());
}
automaps.put(conceptId, mimsAllergyAutomapRecord);
}
for (int i = 2; i < fields.length; i += 2) {
MapRecord mimsAllergyAutomapRecord = automaps.get(conceptId);
final String mapTarget = fields[i];
// For each suggested map target, create a map entry, and attach it to the record
MapEntry mapEntry = new MapEntryJpa();
mapEntry.setMapGroup(1);
mapEntry.setMapPriority(mimsAllergyAutomapRecord.getMapEntries().size() + 1);
mapEntry.setTargetId(mapTarget);
String targetConceptName = destinationIdToName.get(mapTarget);
if (targetConceptName != null) {
mapEntry.setTargetName(targetConceptName);
} else {
mapEntry
.setTargetName("CONCEPT DOES NOT EXIST IN " + mapProject.getDestinationTerminology());
}
// Add the entry to the record, and put the updated record in the map
mimsAllergyAutomapRecord.addMapEntry(mapEntry);
automaps.put(conceptId, mimsAllergyAutomapRecord);
}
}
Logger.getLogger(getClass()).info("Done caching maps");
preloadMapReader.close();
contentService.close();
}
/**
* Overriding defaultChecks, because there are some MIMS-specific settings that
* don't conform to the standard map requirements.
*
* @param mapRecord the map record
* @return the validation result
*/
@Override
public ValidationResult performDefaultChecks(MapRecord mapRecord) {
Map<Integer, List<MapEntry>> entryGroups = getEntryGroups(mapRecord);
final ValidationResult validationResult = new ValidationResultJpa();
// FATAL ERROR: map record has no entries
if (mapRecord.getMapEntries().size() == 0) {
validationResult.addError("Map record has no entries");
return validationResult;
}
// FATAL ERROR: multiple map groups present for a project without group
// structure
if (!mapProject.isGroupStructure() && entryGroups.keySet().size() > 1) {
validationResult
.addError("Project has no group structure but multiple map groups were found.");
return validationResult;
}
// For the MIMS project, we are allowing multiple entries without rules.
// This is acceptable because their desired final release format is not
// intended to follow strict RF2 guidelines.
// // FATAL ERROR: multiple entries in groups for non-rule based
// if (!mapProject.isRuleBased()) {
// for (Integer key : entryGroups.keySet()) {
// if (entryGroups.get(key).size() > 1) {
// validationResult.addError(
// "Project has no rule structure but multiple map entries found in group " + key);
// if (!validationResult.isValid()) {
// return validationResult;
// Verify that groups begin at index 1 and are sequential (i.e. no empty
// groups)
validationResult.merge(checkMapRecordGroupStructure(mapRecord, entryGroups));
// Validation Check: verify correct positioning of TRUE rules
validationResult.merge(checkMapRecordRules(mapRecord, entryGroups));
// Validation Check: very higher map groups do not have only NC nodes
validationResult.merge(checkMapRecordNcNodes(mapRecord, entryGroups));
// Validation Check: verify entries are not duplicated
validationResult.merge(checkMapRecordForDuplicateEntries(mapRecord));
// Validation Check: verify advice values are valid for the project (this
// can happen if "allowable map advice" changes without updating map
// entries)
validationResult.merge(checkMapRecordAdvices(mapRecord, entryGroups));
// Validation Check: all entries are non-null (empty entries are empty
// strings)
validationResult.merge(checkMapRecordForNullTargetIds(mapRecord));
return validationResult;
}
}
|
package ste.travian.gui;
import java.awt.Dimension;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
/**
* This is a JList that just defines the methods required to support DnD with
* the alliance groups tree.
*
* @author ste
*/
public class AllianceList
extends org.jdesktop.swingx.JXList
implements DragGestureListener, DragSourceListener {
DragSource ds;
/**
* Creates an AllianceList.
*/
public AllianceList() {
super(new DefaultListModel());
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setLayoutOrientation(JList.HORIZONTAL_WRAP);
setVisibleRowCount(-1);
setFixedCellWidth(90);
setTransferHandler(new TransferHandler("selectedAlliance"));
setDragEnabled(true);
ds = new DragSource();
ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
}
/**
* Returns the selected alliance or null if no alliance is selected.
* This is intended to be used also for DnD operations by the TransferHandler.
*
* @return the seleceted alliance or null
*/
public String getSelectedAlliance() {
return (String) getSelectedValue();
}
public void dragGestureRecognized(DragGestureEvent e) {
System.out.println("Drag Gesture Recognized!");
Transferable t = new StringSelection(getSelectedAlliance());
ds.startDrag(e, DragSource.DefaultMoveDrop, t, this);
}
public void dragEnter(DragSourceDragEvent e) {
System.out.println("Drag Enter");
}
public void dragExit(DragSourceEvent e) {
System.out.println("Drag Exit");
}
public void dragOver(DragSourceDragEvent e) {
System.out.println("Drag Over");
}
public void dragDropEnd(DragSourceDropEvent e) {
System.out.print("Drag Drop End: ");
if (e.getDropSuccess()) {
System.out.println("Succeeded");
} else {
System.out.println("Failed");
}
}
public void dropActionChanged(DragSourceDragEvent e) {
System.out.println("Drop Action Changed");
}
}
|
package uk.nhs.ciao.camel;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.camel.util.URISupport;
/**
* URI builder backed by Camel's URI utility methods
*/
public class URIBuilder {
private URI base;
private Map<String, Object> queryParameters;
public URIBuilder(final String uri) throws URISyntaxException {
reset(uri);
}
public URIBuilder(final URI uri) throws URISyntaxException {
reset(uri);
}
public final void reset(final String uri) throws URISyntaxException {
reset(new URI(uri));
}
public final void reset(final URI uri) throws URISyntaxException {
this.base = uri;
this.queryParameters = URISupport.parseQuery(this.base.getQuery());
}
@SuppressWarnings("unchecked")
public URIBuilder add(final String name, final String value) {
if (queryParameters.containsKey(name)) {
List<Object> list;
Object previousValue = queryParameters.get(name);
if (previousValue instanceof List<?>) {
list = (List<Object>)previousValue;
} else {
list = new ArrayList<Object>();
list.add(previousValue);
list.add(value);
queryParameters.put(name, list);
}
} else {
queryParameters.put(name, value);
}
return this;
}
public URIBuilder add(final String name, final boolean value) {
return add(name, String.valueOf(value));
}
public URIBuilder add(final String name, final int value) {
return add(name, String.valueOf(value));
}
public URIBuilder add(final String name, final long value) {
return add(name, String.valueOf(value));
}
public URIBuilder set(final String name, final String value) {
queryParameters.put(name, value);
return this;
}
public URIBuilder set(final String name, final boolean value) {
return set(name, String.valueOf(value));
}
public URIBuilder set(final String name, final int value) {
return set(name, String.valueOf(value));
}
public URIBuilder set(final String name, final long value) {
return set(name, String.valueOf(value));
}
public URIBuilder remove(final String name) {
queryParameters.remove(name);
return this;
}
public Set<String> getNames() {
return queryParameters.keySet();
}
public String getFirst(final String name) {
final Object value = queryParameters.get(name);
final Object first;
if (value instanceof List) {
final List<?> values = (List<?>)value;
first = values.isEmpty() ? null : values.get(0);
} else {
first = value;
}
return first == null ? null : first.toString();
}
@SuppressWarnings("unchecked")
public List<Object> getAll(final String name) {
final List<Object> values;
final Object value = queryParameters.get(name);
if (value instanceof List) {
values = (List<Object>)value;
} else if (value != null || queryParameters.containsKey(name)) {
values = Collections.singletonList(value);
} else {
values = Collections.emptyList();
}
return values;
}
public String getScheme() {
return base.getScheme();
}
public String getPath() {
return base.getPath();
}
public String getQuery() throws URISyntaxException {
final String query = URISupport.createQueryString(queryParameters);
return query.isEmpty() ? null : query;
}
public URI toURI() throws URISyntaxException {
return URISupport.createURIWithQuery(base, getQuery());
}
@Override
public String toString() {
try {
return toURI().toString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
|
package visnode.gui;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import org.paim.commons.Image;
import visnode.application.OutputImageFactory;
import visnode.application.ActionExportImage;
import visnode.commons.swing.WindowFactory;
/**
* Image viewer dialog
*/
public class ImageViewerPanel extends JPanel {
/** Image */
private final Image image;
/**
* Creates a new image viewer dialog
*
* @param image
*/
public ImageViewerPanel(Image image) {
super();
this.image = image;
initGui();
}
/**
* Shows the dialog
*
* @param image
*/
public static void showDialog(Image image) {
WindowFactory.frame().title("Image").create((container) -> {
container.add(new ImageViewerPanel(image));
}).setVisible(true);
}
/**
* Initializes the interface
*/
private void initGui() {
setLayout(new BorderLayout());
add(buildToolbar(), BorderLayout.NORTH);
add(buildInfo(), BorderLayout.SOUTH);
add(new JLabel(new ImageIcon(OutputImageFactory.getBuffered(image))));
}
/**
* Builds the tool bar
*
* @return
*/
private JComponent buildToolbar() {
JToolBar toolbar = new JToolBar();
toolbar.add(new ActionExportImage(image));
return toolbar;
}
/**
* Builds the info panel
*
* @return JComponent
*/
private JComponent buildInfo() {
JLabel info = new JLabel();
info.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
info.setText(String.format("%sx%s pixels range(%s/%s)",
image.getWidth(),
image.getHeight(),
image.getPixelValueRange().getLower(),
image.getPixelValueRange().getHigher()
));
return info;
}
}
|
package org.geotools.imageio.unidata;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.BandedSampleModel;
import java.awt.image.SampleModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import org.geotools.coverage.Category;
import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.grid.io.DefaultDimensionDescriptor;
import org.geotools.coverage.grid.io.DimensionDescriptor;
import org.geotools.coverage.io.CoverageSource.AdditionalDomain;
import org.geotools.coverage.io.CoverageSource.DomainType;
import org.geotools.coverage.io.CoverageSource.SpatialDomain;
import org.geotools.coverage.io.CoverageSource.TemporalDomain;
import org.geotools.coverage.io.CoverageSource.VerticalDomain;
import org.geotools.coverage.io.CoverageSourceDescriptor;
import org.geotools.coverage.io.RasterLayout;
import org.geotools.coverage.io.catalog.CoverageSlicesCatalog;
import org.geotools.coverage.io.range.FieldType;
import org.geotools.coverage.io.range.RangeType;
import org.geotools.coverage.io.range.impl.DefaultFieldType;
import org.geotools.coverage.io.range.impl.DefaultRangeType;
import org.geotools.coverage.io.util.DateRangeComparator;
import org.geotools.coverage.io.util.DateRangeTreeSet;
import org.geotools.coverage.io.util.DoubleRangeTreeSet;
import org.geotools.coverage.io.util.NumberRangeComparator;
import org.geotools.factory.GeoTools;
import org.geotools.feature.NameImpl;
import org.geotools.gce.imagemosaic.Utils;
import org.geotools.gce.imagemosaic.catalog.index.Indexer.Coverages.Coverage;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.imageio.unidata.cv.CoordinateVariable;
import org.geotools.imageio.unidata.utilities.UnidataCRSUtilities;
import org.geotools.imageio.unidata.utilities.UnidataUtilities;
import org.geotools.referencing.operation.transform.ProjectiveTransform;
import org.geotools.resources.coverage.CoverageUtilities;
import org.geotools.util.DateRange;
import org.geotools.util.NumberRange;
import org.geotools.util.Range;
import org.geotools.util.SimpleInternationalString;
import org.geotools.util.logging.Logging;
import org.opengis.coverage.SampleDimension;
import org.opengis.coverage.grid.GridEnvelope;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.Name;
import org.opengis.geometry.BoundingBox;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.metadata.spatial.PixelOrientation;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.TemporalCRS;
import org.opengis.referencing.datum.PixelInCell;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.MathTransform2D;
import org.opengis.util.InternationalString;
import org.opengis.util.ProgressListener;
import ucar.nc2.constants.AxisType;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.VariableDS;
/**
*
* @author Simone Giannecchini, GeoSolutions SAS
* @todo lazy initialization
* @todo management of data read with proper mangling
*/
public class UnidataVariableAdapter extends CoverageSourceDescriptor {
public class UnidataSpatialDomain extends SpatialDomain {
/** The spatial coordinate reference system */
private CoordinateReferenceSystem coordinateReferenceSystem;
/** The spatial referenced envelope */
private ReferencedEnvelope referencedEnvelope;
/** The gridGeometry of the spatial domain */
private GridGeometry2D gridGeometry;
public ReferencedEnvelope getReferencedEnvelope() {
return referencedEnvelope;
}
public void setReferencedEnvelope(ReferencedEnvelope referencedEnvelope) {
this.referencedEnvelope = referencedEnvelope;
}
public GridGeometry2D getGridGeometry() {
return gridGeometry;
}
public double[] getFullResolution() {
AffineTransform gridToCRS = (AffineTransform) gridGeometry.getGridToCRS();
return CoverageUtilities.getResolution(gridToCRS);
}
public void setGridGeometry(GridGeometry2D gridGeometry) {
this.gridGeometry = gridGeometry;
}
public void setCoordinateReferenceSystem(CoordinateReferenceSystem coordinateReferenceSystem) {
this.coordinateReferenceSystem = coordinateReferenceSystem;
}
@Override
public Set<? extends BoundingBox> getSpatialElements(boolean overall,
ProgressListener listener) throws IOException {
return Collections.singleton(referencedEnvelope);
}
@Override
public CoordinateReferenceSystem getCoordinateReferenceSystem2D() {
return coordinateReferenceSystem;
}
@Override
public MathTransform2D getGridToWorldTransform(ProgressListener listener)
throws IOException {
return gridGeometry.getGridToCRS2D(PixelOrientation.CENTER);
}
@Override
public Set<? extends RasterLayout> getRasterElements(boolean overall,
ProgressListener listener) throws IOException {
Rectangle bounds = gridGeometry.getGridRange2D().getBounds();
return Collections.singleton(new RasterLayout(bounds));
}
}
public class UnidataTemporalDomain extends TemporalDomain {
/**
* @param adaptee
*/
UnidataTemporalDomain(CoordinateVariable<?> adaptee) {
if(!Date.class.isAssignableFrom(adaptee.getType())){
throw new IllegalArgumentException("Unable to wrap non temporal CoordinateVariable:"+adaptee.toString());
}
this.adaptee = (CoordinateVariable<Date>)adaptee;
}
final CoordinateVariable<Date> adaptee;
public SortedSet<DateRange> getTemporalExtent() {
// Getting global Extent
Date startTime;
try {
startTime = adaptee.getMinimum();
Date endTime = adaptee.getMaximum();
final DateRange global = new DateRange(startTime, endTime);
final SortedSet<DateRange> globalTemporalExtent = new DateRangeTreeSet();
globalTemporalExtent.add(global);
return globalTemporalExtent;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public SortedSet<? extends DateRange> getTemporalElements(boolean overall,
ProgressListener listener) throws IOException {
if (overall) {
// Getting overall Extent
final SortedSet<DateRange> extent = new TreeSet<DateRange>(new DateRangeComparator());
for(Date dd:adaptee.read()){
extent.add(new DateRange(dd,dd));
}
return extent;
} else {
return getTemporalExtent();
}
}
@Override
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
return adaptee.getCoordinateReferenceSystem();
}
}
public class UnidataVerticalDomain extends VerticalDomain {
final CoordinateVariable<? extends Number> adaptee;
/**
* @param cv
*/
UnidataVerticalDomain(CoordinateVariable<?> cv) {
if(!Number.class.isAssignableFrom(cv.getType())){
throw new IllegalArgumentException("Unable to wrap a non Number CoordinateVariable:"+cv.toString());
}
this.adaptee = (CoordinateVariable<? extends Number>)cv;
}
public SortedSet<NumberRange<Double>> getVerticalExtent() {
// Getting global Extent
final CoordinateVariable<? extends Number> verticalDimension=this.adaptee;
NumberRange<Double> global;
try {
global = NumberRange.create(
verticalDimension.getMinimum().doubleValue(),
verticalDimension.getMaximum().doubleValue());
} catch (IOException e) {
throw new RuntimeException(e);
}
final SortedSet<NumberRange<Double>> globalVerticalExtent = new DoubleRangeTreeSet();
globalVerticalExtent.add(global);
return globalVerticalExtent;
}
@Override
public SortedSet<? extends NumberRange<Double>> getVerticalElements(boolean overall,
ProgressListener listener) throws IOException {
if (overall) {
// Getting overall Extent
final SortedSet<NumberRange<Double>> extent = new TreeSet<NumberRange<Double>>(new NumberRangeComparator());
for(Number vv:adaptee.read()){
final double doubleValue = vv.doubleValue();
extent.add(NumberRange.create(doubleValue,doubleValue));
}
return extent;
} else {
return getVerticalExtent();
}
}
@Override
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
return adaptee.getCoordinateReferenceSystem();
}
}
/**
*
* @author User
* TODO improve support for this
*/
public class UnidataAdditionalDomain extends AdditionalDomain {
/** The detailed domain extent */
private final Set<Object> domainExtent = new TreeSet<Object>();
/** The merged domain extent */
private final Set<Object> globalDomainExtent = new TreeSet<Object>(new Comparator<Object>() {
private NumberRangeComparator numberRangeComparator = new NumberRangeComparator();
private DateRangeComparator dateRangeComparator = new DateRangeComparator();
public int compare(Object o1, Object o2) {
// assume that o1 and o2 are both not null
boolean o1IsDateRange = true;
boolean o2IsDateRange = true;
if (o1 instanceof NumberRange) {
o1IsDateRange = false;
}
else if (!(o1 instanceof DateRange)) {
throw new ClassCastException(o1.getClass() + " is not an known range type");
}
if (o2 instanceof NumberRange) {
o2IsDateRange = false;
}
else if (!(o2 instanceof DateRange)) {
throw new ClassCastException(o2.getClass() + " is not an known range type");
}
if (o1IsDateRange && o2IsDateRange) {
return dateRangeComparator.compare((DateRange) o1, (DateRange) o2);
}
else if (!o1IsDateRange && !o2IsDateRange) {
return numberRangeComparator.compare((NumberRange<?>) o1, (NumberRange<?>) o2);
}
throw new ClassCastException("Incompatible range types: " + o1.getClass() + " is not the same as " + o2.getClass());
}
public boolean equals(Object o) {
return false;
}
});
/** The domain name */
private final String name;
private final DomainType type;
final CoordinateVariable<?> adaptee;
/**
* @param domainExtent
* @param globalDomainExtent
* @param name
* @param type
* @param adaptee
* TODO missing support for Range
* TODO missing support for String domains
* @throws IOException
*/
UnidataAdditionalDomain(CoordinateVariable<?> adaptee) throws IOException {
this.adaptee = adaptee;
name=adaptee.getName();
// type
Class<?> type=adaptee.getType();
if(Date.class.isAssignableFrom(type)){
this.type=DomainType.DATE;
// global domain
globalDomainExtent.add(new DateRange(
(Date)adaptee.getMinimum(),
(Date)adaptee.getMaximum()));
} else if(Number.class.isAssignableFrom(type)){
this.type=DomainType.NUMBER;
// global domain
globalDomainExtent.add(new NumberRange<Double>(
Double.class,
((Number)adaptee.getMinimum()).doubleValue(),
((Number)adaptee.getMaximum()).doubleValue()));
} else {
throw new UnsupportedOperationException("Unsupported CoordinateVariable:"+adaptee.toString());
}
// domain
domainExtent.addAll(adaptee.read());
}
@Override
public Set<Object> getElements(boolean overall, ProgressListener listener)
throws IOException {
if (overall) {
return globalDomainExtent;
} else {
return domainExtent;
}
}
@Override
public String getName() {
return name;
}
@Override
public DomainType getType() {
return type;
}
public Set<Object> getDomainExtent() {
return domainExtent;
}
}
final VariableDS variableDS;
private ucar.nc2.dataset.CoordinateSystem coordinateSystem;
private UnidataImageReader reader;
private int numBands;
private int rank;
private SampleModel sampleModel;
private int numberOfSlices;
private int width;
private int height;
private CoordinateReferenceSystem coordinateReferenceSystem;
private int[] shape;
private final static java.util.logging.Logger LOGGER = Logging.getLogger(UnidataVariableAdapter.class);
/** Usual schema are the_geom, imageIndex, so the first attribute (time or elevation) will have index = 2 */
private static final int FIRST_ATTRIBUTE_INDEX = 2;
/**
* Extracts the compound {@link CoordinateReferenceSystem} from the unidata variable.
*
* @return the compound {@link CoordinateReferenceSystem}.
* @throws Exception
*/
private void init() throws Exception {
// initialize the various domains
initSpatialElements();
// initialize rank and number of 2D slices
initRange();
initSlicesInfo();
}
/**
* @throws Exception
*
*/
private void initSlicesInfo() throws Exception {
// get the length of the coverageDescriptorsCache in each dimension
shape = variableDS.getShape();
switch (shape.length) {
case 2:
numberOfSlices = 1;
break;
case 3:
numberOfSlices = shape[0];
break;
case 4:
numberOfSlices = 0 + shape[0] * shape[1];
break;
default:
if (LOGGER.isLoggable(Level.WARNING))
LOGGER.warning("Ignoring variable: " + getName()
+ " with shape length: " + shape.length);
}
}
/**
* @throws IOException
*
*/
private void initSpatialElements() throws Exception {
final List<DimensionDescriptor> dimensions = new ArrayList<DimensionDescriptor>();
List<CoordinateVariable<?>> otherAxes = initCRS(dimensions);
initSpatialDomain();
// ADDITIONAL DOMAINS
addAdditionalDomain(otherAxes, dimensions);
setDimensionDescriptors(dimensions);
if (reader.ancillaryFileManager.isHasImposedSchema()) {
updateDimensions(dimensions);
}
}
/**
* Update the dimensions to attributes mapping for this variable if needed.
* Default behaviour is to get attributes from the name of the dimensions of the variable.
* In case the indexer.xml contains an explicit schema with different attributes for time and elevation
* we need to remap them and updates the dimensions mapping as well as the DimensionsDescriptors
* @param dimensionDescriptors
* @throws IOException
*/
private void updateDimensions(List<DimensionDescriptor> dimensionDescriptors) throws IOException {
final Map<Name, String> mapping = reader.ancillaryFileManager.variablesMap;
final Set<Name> keys = mapping.keySet();
final String varName = getName();
for (Name key: keys) {
// Go to the current variable
final String origName = mapping.get(key);
if (origName.equalsIgnoreCase(varName)){
// Get the mapped coverage name (as an instance, NO2 for a GOME2 with var = 'z')
final String coverageName = key.getLocalPart();
final Coverage coverage = reader.ancillaryFileManager.coveragesMapping.get(coverageName);
if (coverage.getSchema() != null) {
final CoverageSlicesCatalog catalog = reader.getCatalog();
if (catalog != null) {
// Current assumption is that we have a typeName for each coverage
final String[] typeNames = catalog.getTypeNames();
for (String typeName : typeNames) {
// Look for matching schema
if (typeName.equalsIgnoreCase(coverageName)) {
final SimpleFeatureType schemaType = catalog.getSchema(coverageName);
if (schemaType != null) {
// Schema found: proceed with remapping attributes
updateMapping(schemaType, dimensionDescriptors);
}
break;
}
}
}
}
break;
}
}
}
/**
* Update the dimensionDescriptor attributes mapping by checking the actual attribute names from the schema
* @param indexSchema
* @param descriptors
* @throws IOException
*/
public void updateMapping(SimpleFeatureType indexSchema, List<DimensionDescriptor> descriptors)
throws IOException {
Map<String, String> dimensionsMapping = reader.dimensionsMapping;
Set<String> keys = dimensionsMapping.keySet();
int indexAttribute = FIRST_ATTRIBUTE_INDEX;
// Remap time
String currentDimName = UnidataUtilities.TIME_DIM;
if (keys.contains(currentDimName)) {
if (remapAttribute(indexSchema, currentDimName, indexAttribute, descriptors,
dimensionsMapping)) {
indexAttribute++;
}
}
// Remap elevation
currentDimName = UnidataUtilities.ELEVATION_DIM;
if (keys.contains(currentDimName)) {
if (remapAttribute(indexSchema, currentDimName, indexAttribute, descriptors,
dimensionsMapping)) {
indexAttribute++;
}
}
}
/**
* Remap an attribute for a specified dimension. Get it from the schemaType and update
* both the related dimension Descriptor as well as the dimensions mapping.
*
* @param indexSchema
* @param currentDimName
* @param indexAttribute
* @param descriptors
* @param dimensionsMapping
* @return
*/
private boolean remapAttribute(final SimpleFeatureType indexSchema, final String currentDimName,
final int indexAttribute, final List<DimensionDescriptor> descriptors,
Map<String, String> dimensionsMapping) {
final int numAttributes = indexSchema.getAttributeCount();
if (numAttributes <= indexAttribute) {
// Stop looking for attributes in case there aren't anymore
return false;
}
// Get the attribute descriptor for that index
final AttributeDescriptor attributeDescriptor = indexSchema.getDescriptor(indexAttribute);
// Loop over dimensionDescriptors
for (DimensionDescriptor descriptor : descriptors) {
// Find the descriptor related to the current dimension
if (descriptor.getName().toUpperCase().equalsIgnoreCase(currentDimName)) {
final String updatedAttribute = attributeDescriptor.getLocalName();
if (!updatedAttribute.equals(((DefaultDimensionDescriptor) descriptor)
.getStartAttribute())) {
// Remap attributes in case the schema's attribute doesn't match the current attribute
((DefaultDimensionDescriptor) descriptor).setStartAttribute(updatedAttribute);
// Update the dimensions mapping too
dimensionsMapping.put(currentDimName, updatedAttribute);
}
// the attribute has been found, prepare for the next one
return true;
}
}
return false;
}
private List<CoordinateVariable<?>> initCRS(List<DimensionDescriptor> dimensions) throws IllegalArgumentException, RuntimeException,
IOException, IllegalStateException {
// from UnidataVariableAdapter
this.coordinateSystem = UnidataCRSUtilities.getCoordinateSystem(variableDS);
if (coordinateSystem == null){
throw new IllegalArgumentException("Provided CoordinateSystem is null");
}
// Creating the CoordinateReferenceSystem
coordinateReferenceSystem=UnidataCRSUtilities.WGS84;
/*
* Adds the axis in reverse order, because the NetCDF image reader put the last dimensions in the rendered image. Typical NetCDF convention is
* to put axis in the (time, depth, latitude, longitude) order, which typically maps to (longitude, latitude, depth, time) order in GeoTools
* referencing framework.
*/
final List<CoordinateVariable<?>> otherAxes = new ArrayList<CoordinateVariable<?>>();
for(CoordinateAxis axis :coordinateSystem.getCoordinateAxes()){
CoordinateVariable<?> cv=reader.coordinatesVariables.get(axis.getShortName());
switch(cv.getAxisType()){
case Time:case RunTime:
initTemporalDomain(cv, dimensions);
continue;
case GeoZ:case Height:case Pressure:
String axisName = cv.getName();
if (UnidataCRSUtilities.VERTICAL_AXIS_NAMES.contains(axisName)) {
initVerticalDomain(cv, dimensions);
}else{
otherAxes.add(cv);
}
continue;
case GeoX: case GeoY: case Lat: case Lon:
// do nothing
continue;
default:
otherAxes.add(cv);
}
}
return otherAxes;
}
/**
* @param cv
* @param dimensions
* @throws IOException
*/
private void initVerticalDomain(CoordinateVariable<?> cv, List<DimensionDescriptor> dimensions) throws IOException {
this.setHasVerticalDomain(true);
final UnidataVerticalDomain verticalDomain = new UnidataVerticalDomain(cv);
this.setVerticalDomain(verticalDomain);
//TODO: Map ZAxis unit to UCUM UNIT (depending on type... elevation, level, pressure, ...)
dimensions.add(new DefaultDimensionDescriptor(Utils.ELEVATION_DOMAIN,
cv.getUnit(), CoverageUtilities.UCUM.ELEVATION_UNITS.getSymbol(), cv.getName(), null));
}
/**
* @param cv
* @param dimensions
* @throws IOException
*/
private void initTemporalDomain(CoordinateVariable<?> cv, List<DimensionDescriptor> dimensions) throws IOException {
if(!cv.getType().equals(Date.class)){
throw new IllegalArgumentException("Unable to init temporal domani from CoordinateVariable that does not bind to Date");
}
if(!(cv.getCoordinateReferenceSystem() instanceof TemporalCRS)){
throw new IllegalArgumentException("Unable to init temporal domani from CoordinateVariable that does not have a TemporalCRS");
}
this.setHasTemporalDomain(true);
final UnidataTemporalDomain temporalDomain = new UnidataTemporalDomain(cv);
this.setTemporalDomain(temporalDomain);
//TODO: Fix that once schema attributes to dimension mapping is merged from Simone's code
dimensions.add(new DefaultDimensionDescriptor(Utils.TIME_DOMAIN,
CoverageUtilities.UCUM.TIME_UNITS.getName(), CoverageUtilities.UCUM.TIME_UNITS.getSymbol(), cv.getName(), null));
}
/**
* @param coordinateReferenceSystem
* @throws MismatchedDimensionException
* @throws IOException
*/
private void initSpatialDomain()
throws Exception {
// SPATIAL DOMAIN
final UnidataSpatialDomain spatialDomain = new UnidataSpatialDomain();
this.setSpatialDomain(spatialDomain);
spatialDomain.setCoordinateReferenceSystem(coordinateReferenceSystem);
spatialDomain.setReferencedEnvelope(reader.boundingBox);
spatialDomain.setGridGeometry(getGridGeometry());
}
private void initRange() {
// set the rank
rank = variableDS.getRank();
width = variableDS.getDimension(rank - UnidataUtilities.X_DIMENSION).getLength();
height = variableDS.getDimension(rank - UnidataUtilities.Y_DIMENSION).getLength();
numBands = rank > 2 ? variableDS.getDimension(2).getLength() : 1;
final int bufferType = UnidataUtilities.getRawDataType(variableDS);
sampleModel = new BandedSampleModel(bufferType, width, height, 1);
// range type
String description = variableDS.getDescription();
final StringBuilder sb = new StringBuilder();
final Set<SampleDimension> sampleDims = new HashSet<SampleDimension>();
sampleDims.add(new GridSampleDimension(description + ":sd", (Category[]) null, null));
InternationalString desc = null;
if (description != null && !description.isEmpty()) {
desc = new SimpleInternationalString(description);
}
final FieldType fieldType = new DefaultFieldType(new NameImpl(getName()), desc, sampleDims);
sb.append(description != null ? description.toString() + "," : "");
final RangeType range = new DefaultRangeType(getName(), description, fieldType);
this.setRangeType(range);
}
private void addAdditionalDomain(List<CoordinateVariable<?>> otherAxes, List<DimensionDescriptor> dimensions) {
if (otherAxes == null||otherAxes.isEmpty()) {
return;
}
final List<AdditionalDomain> additionalDomains = new ArrayList<AdditionalDomain>(otherAxes.size());
this.setAdditionalDomains(additionalDomains);
for(CoordinateVariable<?> cv :otherAxes){
// create domain
UnidataAdditionalDomain domain;
try {
domain = new UnidataAdditionalDomain(cv);
additionalDomains.add(domain);
// TODO: Parse Units from axis and map them to UCUM units
dimensions.add(new DefaultDimensionDescriptor(cv.getName(), "FIXME_UNIT", "FIXME_UNITSYMBOL", cv.getName(), null));
this.setHasAdditionalDomains(true);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
}
}
/**
* Extracts the {@link GridGeometry2D grid geometry} from the unidata variable.
*
* @return the {@link GridGeometry2D}.
* @throws IOException
*/
protected GridGeometry2D getGridGeometry() throws IOException {
int[] low = new int[2];
int[] high = new int[2];
// String[] axesNames = new String[rank];
double[] origin = new double[2];
double scaleX=Double.POSITIVE_INFINITY, scaleY=Double.POSITIVE_INFINITY;
for( CoordinateVariable<?> cv : reader.coordinatesVariables.values() ) {
if(!cv.isNumeric()){
continue;
}
final AxisType axisType = cv.getAxisType();
switch (axisType) {
case Lon: case GeoX:
// raster space
low[0] = 0;
high[0] = (int) cv.getSize();
// model space
if(cv.isRegular()){
// regular model space
origin[0]=cv.getStart();
scaleX=cv.getIncrement();
} else {
// model space is not declared to be regular, but we kind of assume it is!!!
final int valuesLength=(int) cv.getSize();
double min = ((Number)cv.getMinimum()).doubleValue();
double max = ((Number)cv.getMaximum()).doubleValue();
// make sure we skip nodata coords, bah...
if (!Double.isNaN(min) && !Double.isNaN(max)) {
origin[0] = min;
scaleX = (max-min) / valuesLength;
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Axis values contains NaN; finding first valid values");
}
for( int j = 0; j < valuesLength; j++ ) {
double v = ((Number)cv.read(j)).doubleValue();
if (!Double.isNaN(v)) {
for( int k = valuesLength; k > j; k
double vv = ((Number)cv.read(k)).doubleValue();
if (!Double.isNaN(vv)) {
origin[0] = v;
scaleX = (vv - v) / valuesLength;
}
}
}
}
}
}
break;
case Lat: case GeoY:
// raster space
low[1] = 0;
high[1] = (int) cv.getSize();
// model space
if(cv.isRegular()){
scaleY=-cv.getIncrement();
origin[1]=cv.getStart()-scaleY*high[1];
} else {
// model space is not declared to be regular, but we kind of assume it is!!!
final int valuesLength=(int) cv.getSize();
double min = ((Number)cv.getMinimum()).doubleValue();
double max = ((Number)cv.getMaximum()).doubleValue();
// make sure we skip nodata coords, bah...
if (!Double.isNaN(min) && !Double.isNaN(max)) {
scaleY = -(max-min) / valuesLength;
origin[1] = max;
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Axis values contains NaN; finding first valid values");
}
for( int j = 0; j < valuesLength; j++ ) {
double v = ((Number)cv.read(j)).doubleValue();
if (!Double.isNaN(v)) {
for( int k = valuesLength; k > j; k
double vv = ((Number)cv.read(k)).doubleValue();
if (!Double.isNaN(vv)) {
origin[1] = v;
scaleY = -(vv - v) / valuesLength;
}
}
}
}
}
}
break;
default:
break;
}
}
final AffineTransform at = new AffineTransform(scaleX, 0, 0, scaleY, origin[0], origin[1]);
final GridEnvelope gridRange = new GridEnvelope2D(
low[0],
low[1],
high[0]-low[0],
high[1]-low[1]);
final MathTransform raster2Model = ProjectiveTransform.create(at);
return new GridGeometry2D(gridRange,PixelInCell.CELL_CORNER ,raster2Model, coordinateReferenceSystem,GeoTools.getDefaultHints());
}
public int getNumBands() {
return numBands;
}
/**
* @return the number of dimensions in the variable.
*/
public int getRank() {
return rank;
}
public SampleModel getSampleModel() {
return sampleModel;
}
public UnidataVariableAdapter(UnidataImageReader reader, VariableDS variable) throws Exception {
this.variableDS = variable;
this.reader=reader;
setName(variable.getFullName());
init();
}
@Override
public UnidataSpatialDomain getSpatialDomain() {
return (UnidataSpatialDomain) super.getSpatialDomain();
}
@Override
public UnidataTemporalDomain getTemporalDomain() {
return (UnidataTemporalDomain) super.getTemporalDomain();
}
@Override
public UnidataVerticalDomain getVerticalDomain() {
return (UnidataVerticalDomain) super.getVerticalDomain();
}
/**
* @return
*/
int getWidth() {
return width;
}
/**
* @return
*/
int getHeight() {
return height;
}
/**
* Utility method to retrieve the z-index of a Variable coverageDescriptor stored on
* {@link NetCDFImageReader} NetCDF Flat Reader {@link HashMap} indexMap.
*
* @param imageIndex
* {@link int}
*
* @return z-index {@link int} -1 if variable rank < 3
*/
public int getZIndex(int index) {
if (rank > 2) {
if (rank == 3) {
return index;
} else if (rank == 4){
// return (int) Math.ceil((imageIndex - range.first()) /
// var.getDimension(rank - (Z_DIMENSION + 1)).getLength());
return index % UnidataUtilities.getZDimensionLength(variableDS);
} else {
throw new IllegalStateException("Unable to handle more than 4 dimensions");
}
}
return -1;
}
/**
* Utility method to retrieve the t-index of a Variable coverageDescriptor stored on
* {@link NetCDFImageReader} NetCDF Flat Reader {@link HashMap} indexMap.
*
* @param imageIndex
* {@link int}
*
* @return t-index {@link int} -1 if variable rank > 4
*/
public int getTIndex(int index) {
if (rank > 2) {
if (rank == 3) {
return index;
} else {
// return (imageIndex - range.first()) % var.getDimension(rank -
// (Z_DIMENSION + 1)).getLength();
return (int) Math.ceil(index
/ UnidataUtilities.getZDimensionLength(variableDS));
}
}
return -1;
}
/**
* @return the numberOfSlices
*/
public int getNumberOfSlices() {
return numberOfSlices;
}
/**
* @return the shape
*/
public int[] getShape() {
return shape;
}
}
|
package za.redbridge.experiment;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.encog.Encog;
import org.encog.ml.ea.train.EvolutionaryAlgorithm;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import za.redbridge.experiment.MMNEAT.MMNEATNetwork;
import za.redbridge.experiment.MMNEAT.MMNEATPopulation;
import za.redbridge.experiment.MMNEAT.MMNEATUtil;
import za.redbridge.simulator.config.SimConfig;
public class Main {
public static void main(String[] args) throws IOException {
Args options = new Args();
new JCommander(options, args);
SimConfig simConfig;
if (options.configFile != null && !options.configFile.isEmpty()) {
simConfig = new SimConfig(options.configFile);
} else {
simConfig = new SimConfig();
}
ScoreCalculator calculateScore = new ScoreCalculator(simConfig);
if (options.genomePath != null && !options.genomePath.isEmpty()) {
MMNEATNetwork network = loadNetwork(options.genomePath);
calculateScore.demo(network);
return;
}
MMNEATPopulation population = new MMNEATPopulation(2, options.populationSize);
population.reset();
System.out.println("Population initialized");
EvolutionaryAlgorithm train = MMNEATUtil.constructNEATTrainer(population, calculateScore);
String date = getDateFolderName();
for (int i = 0; i < options.numIterations; i++) {
calculateScore.resetEpochScore();
train.iteration();
double totalScore = calculateScore.getEpochTotalScore();
System.out.println("Epoch #" + train.getIteration() + " Average score: "
+ totalScore / options.populationSize);
// Save the network
MMNEATNetwork network = (MMNEATNetwork) train.getCODEC().decode(train.getBestGenome());
saveNetwork(network, "epoch " + train.getIteration(), date);
}
System.out.println("Training complete");
Encog.getInstance().shutdown();
}
private static String getDateFolderName() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
return df.format(new Date());
}
private static void saveNetwork(MMNEATNetwork network, String name, String folder)
throws IOException {
File dir = new File("networks/" + folder);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Failed to create directory structure for networks");
}
Path path = Paths.get(new File(dir, name).toURI());
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(path))) {
out.writeObject(network);
}
}
private static MMNEATNetwork loadNetwork(String filepath) {
MMNEATNetwork network = null;
Path path = Paths.get(filepath);
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path))) {
network = (MMNEATNetwork) in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("Class not found!");
e.printStackTrace();
}
return network;
}
private static class Args {
@Parameter(names = "-c", description = "Simulation config file to load")
private String configFile = "config/simulation.yml";
@Parameter(names = "-i", description = "Number of simulation iterations to train for")
private int numIterations = 150;
@Parameter(names = "-p", description = "Initial population size")
private int populationSize = 50;
@Parameter(names = "--demo", description = "Show a GUI demo of a given genome")
private String genomePath = null;
}
}
|
// jTDS JDBC Driver for Microsoft SQL Server and Sybase
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.sql.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import net.sourceforge.jtds.ssl.*;
import net.sourceforge.jtds.util.*;
/**
* This class implements the Sybase / Microsoft TDS protocol.
* <p>
* Implementation notes:
* <ol>
* <li>This class, together with TdsData, encapsulates all of the TDS specific logic
* required by the driver.
* <li>This is a ground up reimplementation of the TDS protocol and is rather
* simpler, and hopefully easier to understand, than the original.
* <li>The layout of the various Login packets is derived from the original code
* and freeTds work, and incorporates changes including the ability to login as a TDS 5.0 user.
* <li>All network I/O errors are trapped here, reported to the log (if active)
* and the parent Connection object is notified that the connection should be considered
* closed.
* <li>Rather than having a large number of classes one for each token, useful information
* about the current token is gathered together in the inner TdsToken class.
* <li>As the rest of the driver interfaces to this code via higher-level method calls there
* should be know need for knowledge of the TDS protocol to leak out of this class.
* It is for this reason that all the TDS Token constants are private.
* </ol>
*
* @author Mike Hutchinson
* @author Matt Brinkley
* @author Alin Sinpalean
* @author FreeTDS project
* @version $Id: TdsCore.java,v 1.112 2006-04-05 15:56:20 matt_brinkley Exp $
*/
public class TdsCore {
/**
* Inner static class used to hold information about TDS tokens read.
*/
private static class TdsToken {
/** The current TDS token byte. */
byte token;
/** The status field from a DONE packet. */
byte status;
/** The operation field from a DONE packet. */
byte operation;
/** The update count from a DONE packet. */
int updateCount;
/** The nonce from an NTLM challenge packet. */
byte[] nonce;
/** NTLM authentication message. */
byte[] ntlmMessage;
/** target info for NTLM message TODO: I don't need to store these!!! */
byte[] ntlmTarget;
/** The dynamic parameters from the last TDS_DYNAMIC token. */
ColInfo[] dynamParamInfo;
/** The dynamic parameter data from the last TDS_DYNAMIC token. */
Object[] dynamParamData;
/**
* Retrieve the update count status.
*
* @return <code>boolean</code> true if the update count is valid.
*/
boolean isUpdateCount() {
return (token == TDS_DONE_TOKEN || token == TDS_DONEINPROC_TOKEN)
&& (status & DONE_ROW_COUNT) != 0;
}
/**
* Retrieve the DONE token status.
*
* @return <code>boolean</code> true if the current token is a DONE packet.
*/
boolean isEndToken() {
return token == TDS_DONE_TOKEN
|| token == TDS_DONEINPROC_TOKEN
|| token == TDS_DONEPROC_TOKEN;
}
/**
* Retrieve the NTLM challenge status.
*
* @return <code>boolean</code> true if the current token is an NTLM challenge.
*/
boolean isAuthToken() {
return token == TDS_AUTH_TOKEN;
}
/**
* Retrieve the results pending status.
*
* @return <code>boolean</code> true if more results in input.
*/
boolean resultsPending() {
return !isEndToken() || ((status & DONE_MORE_RESULTS) != 0);
}
/**
* Retrieve the result set status.
*
* @return <code>boolean</code> true if the current token is a result set.
*/
boolean isResultSet() {
return token == TDS_COLFMT_TOKEN
|| token == TDS7_RESULT_TOKEN
|| token == TDS_RESULT_TOKEN
|| token == TDS5_WIDE_RESULT
|| token == TDS_COLINFO_TOKEN
|| token == TDS_ROW_TOKEN;
}
/**
* Retrieve the row data status.
*
* @return <code>boolean</code> true if the current token is a result row.
*/
public boolean isRowData() {
return token == TDS_ROW_TOKEN;
}
}
/**
* Inner static class used to hold table meta data.
*/
private static class TableMetaData {
/** Table catalog (database) name. */
String catalog;
/** Table schema (user) name. */
String schema;
/** Table name. */
String name;
}
// Package private constants
/** Minimum network packet size. */
public static final int MIN_PKT_SIZE = 512;
/** Default minimum network packet size for TDS 7.0 and newer. */
public static final int DEFAULT_MIN_PKT_SIZE_TDS70 = 4096;
/** Maximum network packet size. */
public static final int MAX_PKT_SIZE = 32768;
/** The size of the packet header. */
public static final int PKT_HDR_LEN = 8;
/** TDS 4.2 or 7.0 Query packet. */
public static final byte QUERY_PKT = 1;
/** TDS 4.2 or 5.0 Login packet. */
public static final byte LOGIN_PKT = 2;
/** TDS Remote Procedure Call. */
public static final byte RPC_PKT = 3;
/** TDS Reply packet. */
public static final byte REPLY_PKT = 4;
/** TDS Cancel packet. */
public static final byte CANCEL_PKT = 6;
/** TDS MSDTC packet. */
public static final byte MSDTC_PKT = 14;
/** TDS 5.0 Query packet. */
public static final byte SYBQUERY_PKT = 15;
/** TDS 7.0 Login packet. */
public static final byte MSLOGIN_PKT = 16;
/** TDS 7.0 NTLM Authentication packet. */
public static final byte NTLMAUTH_PKT = 17;
/** SQL 2000 prelogin negotiation packet. */
public static final byte PRELOGIN_PKT = 18;
/** SSL Mode - Login packet must be encrypted. */
public static final int SSL_ENCRYPT_LOGIN = 0;
/** SSL Mode - Client requested force encryption. */
public static final int SSL_CLIENT_FORCE_ENCRYPT = 1;
/** SSL Mode - No server certificate installed. */
public static final int SSL_NO_ENCRYPT = 2;
/** SSL Mode - Server requested force encryption. */
public static final int SSL_SERVER_FORCE_ENCRYPT = 3;
// Sub packet types
/** TDS 5.0 Parameter format token. */
private static final byte TDS5_PARAMFMT2_TOKEN = (byte) 32; // 0x20
/** TDS 5.0 Language token. */
private static final byte TDS_LANG_TOKEN = (byte) 33; // 0x21
/** TSD 5.0 Wide result set token. */
private static final byte TDS5_WIDE_RESULT = (byte) 97; // 0x61
/** TDS 5.0 Close token. */
private static final byte TDS_CLOSE_TOKEN = (byte) 113; // 0x71
/** TDS DBLIB Offsets token. */
private static final byte TDS_OFFSETS_TOKEN = (byte) 120; // 0x78
/** TDS Procedure call return status token. */
private static final byte TDS_RETURNSTATUS_TOKEN= (byte) 121; // 0x79
/** TDS Procedure ID token. */
private static final byte TDS_PROCID = (byte) 124; // 0x7C
/** TDS 7.0 Result set column meta data token. */
private static final byte TDS7_RESULT_TOKEN = (byte) 129; // 0x81
/** TDS 7.0 Computed Result set column meta data token. */
private static final byte TDS7_COMP_RESULT_TOKEN= (byte) 136; // 0x88
/** TDS 4.2 Column names token. */
private static final byte TDS_COLNAME_TOKEN = (byte) 160; // 0xA0
/** TDS 4.2 Column meta data token. */
private static final byte TDS_COLFMT_TOKEN = (byte) 161; // 0xA1
/** TDS Table name token. */
private static final byte TDS_TABNAME_TOKEN = (byte) 164; // 0xA4
/** TDS Cursor results column infomation token. */
private static final byte TDS_COLINFO_TOKEN = (byte) 165; // 0xA5
/** TDS Optional command token. */
private static final byte TDS_OPTIONCMD_TOKEN = (byte) 166; // 0xA6
/** TDS Computed result set names token. */
private static final byte TDS_COMP_NAMES_TOKEN = (byte) 167; // 0xA7
/** TDS Computed result set token. */
private static final byte TDS_COMP_RESULT_TOKEN = (byte) 168; // 0xA8
/** TDS Order by columns token. */
private static final byte TDS_ORDER_TOKEN = (byte) 169; // 0xA9
/** TDS error result token. */
private static final byte TDS_ERROR_TOKEN = (byte) 170; // 0xAA
/** TDS Information message token. */
private static final byte TDS_INFO_TOKEN = (byte) 171; // 0xAB
/** TDS Output parameter value token. */
private static final byte TDS_PARAM_TOKEN = (byte) 172; // 0xAC
/** TDS Login acknowledgement token. */
private static final byte TDS_LOGINACK_TOKEN = (byte) 173; // 0xAD
/** TDS control token. */
private static final byte TDS_CONTROL_TOKEN = (byte) 174; // 0xAE
/** TDS Result set data row token. */
private static final byte TDS_ROW_TOKEN = (byte) 209; // 0xD1
/** TDS Computed result set data row token. */
private static final byte TDS_ALTROW = (byte) 211; // 0xD3
/** TDS 5.0 parameter value token. */
private static final byte TDS5_PARAMS_TOKEN = (byte) 215; // 0xD7
/** TDS 5.0 capabilities token. */
private static final byte TDS_CAP_TOKEN = (byte) 226; // 0xE2
/** TDS environment change token. */
private static final byte TDS_ENVCHANGE_TOKEN = (byte) 227; // 0xE3
/** TDS 5.0 message token. */
private static final byte TDS_MSG50_TOKEN = (byte) 229; // 0xE5
/** TDS 5.0 RPC token. */
private static final byte TDS_DBRPC_TOKEN = (byte) 230; // 0xE6
/** TDS 5.0 Dynamic SQL token. */
private static final byte TDS5_DYNAMIC_TOKEN = (byte) 231; // 0xE7
/** TDS 5.0 parameter descriptor token. */
private static final byte TDS5_PARAMFMT_TOKEN = (byte) 236; // 0xEC
/** TDS 7.0 NTLM authentication challenge token. */
private static final byte TDS_AUTH_TOKEN = (byte) 237; // 0xED
/** TDS 5.0 Result set column meta data token. */
private static final byte TDS_RESULT_TOKEN = (byte) 238; // 0xEE
/** TDS done token. */
private static final byte TDS_DONE_TOKEN = (byte) 253; // 0xFD DONE
/** TDS done procedure token. */
private static final byte TDS_DONEPROC_TOKEN = (byte) 254; // 0xFE DONEPROC
/** TDS done in procedure token. */
private static final byte TDS_DONEINPROC_TOKEN = (byte) 255; // 0xFF DONEINPROC
// Environment change payload codes
/** Environment change: database changed. */
private static final byte TDS_ENV_DATABASE = (byte) 1;
/** Environment change: language changed. */
private static final byte TDS_ENV_LANG = (byte) 2;
/** Environment change: charset changed. */
private static final byte TDS_ENV_CHARSET = (byte) 3;
/** Environment change: network packet size changed. */
private static final byte TDS_ENV_PACKSIZE = (byte) 4;
/** Environment change: locale changed. */
private static final byte TDS_ENV_LCID = (byte) 5;
/** Environment change: TDS 8 collation changed. */
private static final byte TDS_ENV_SQLCOLLATION = (byte) 7; // TDS8 Collation
// Static variables used only for performance
/** Used to optimize the {@link #getParameters()} call */
private static final ParamInfo[] EMPTY_PARAMETER_INFO = new ParamInfo[0];
// End token status bytes
/** Done: more results are expected. */
private static final byte DONE_MORE_RESULTS = (byte) 0x01;
/** Done: command caused an error. */
private static final byte DONE_ERROR = (byte) 0x02;
/** Done: There is a valid row count. */
private static final byte DONE_ROW_COUNT = (byte) 0x10;
/** Done: Cancel acknowledgement. */
static final byte DONE_CANCEL = (byte) 0x20;
/**
* Done: Response terminator (if more than one request packet is sent, each
* response is terminated by a DONE packet with this flag set).
*/
private static final byte DONE_END_OF_RESPONSE = (byte) 0x80;
// Prepared SQL types
/** Do not prepare SQL */
public static final int UNPREPARED = 0;
/** Prepare SQL using temporary stored procedures */
public static final int TEMPORARY_STORED_PROCEDURES = 1;
/** Prepare SQL using sp_executesql */
public static final int EXECUTE_SQL = 2;
/** Prepare SQL using sp_prepare and sp_execute */
public static final int PREPARE = 3;
// Sybase capability flags
/** Sybase char and binary > 255.*/
static final int SYB_LONGDATA = 1;
/** Sybase date and time data types.*/
static final int SYB_DATETIME = 2;
/** Sybase nullable bit type.*/
static final int SYB_BITNULL = 4;
/** Sybase extended column meta data.*/
static final int SYB_EXTCOLINFO = 8;
/** Sybase univarchar etc. */
static final int SYB_UNICODE = 16;
/** Sybase 15+ unitext. */
static final int SYB_UNITEXT = 32;
/** Sybase 15+ bigint. */
static final int SYB_BIGINT = 64;
/** Cancel has been generated by <code>Statement.cancel()</code>. */
private final static int ASYNC_CANCEL = 0;
/** Cancel has been generated by a query timeout. */
private final static int TIMEOUT_CANCEL = 1;
/** Map of system stored procedures that have shortcuts in TDS8. */
private static HashMap tds8SpNames = new HashMap();
static {
tds8SpNames.put("sp_cursor", new Integer(1));
tds8SpNames.put("sp_cursoropen", new Integer(2));
tds8SpNames.put("sp_cursorprepare", new Integer(3));
tds8SpNames.put("sp_cursorexecute", new Integer(4));
tds8SpNames.put("sp_cursorprepexec", new Integer(5));
tds8SpNames.put("sp_cursorunprepare", new Integer(6));
tds8SpNames.put("sp_cursorfetch", new Integer(7));
tds8SpNames.put("sp_cursoroption", new Integer(8));
tds8SpNames.put("sp_cursorclose", new Integer(9));
tds8SpNames.put("sp_executesql", new Integer(10));
tds8SpNames.put("sp_prepare", new Integer(11));
tds8SpNames.put("sp_execute", new Integer(12));
tds8SpNames.put("sp_prepexec", new Integer(13));
tds8SpNames.put("sp_prepexecrpc", new Integer(14));
tds8SpNames.put("sp_unprepare", new Integer(15));
}
// Class variables
/** Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly). */
private static String hostName;
/** A reference to ntlm.SSPIJNIClient. */
private static SSPIJNIClient sspiJNIClient;
// Instance variables
/** The Connection object that created this object. */
private final ConnectionJDBC2 connection;
/** The TDS version being supported by this connection. */
private int tdsVersion;
/** The make of SQL Server (Sybase/Microsoft). */
private final int serverType;
/** The Shared network socket object. */
private final SharedSocket socket;
/** The output server request stream. */
private final RequestStream out;
/** The input server response stream. */
private final ResponseStream in;
/** True if the server response is fully read. */
private boolean endOfResponse = true;
/** True if the current result set is at end of file. */
private boolean endOfResults = true;
/** The array of column meta data objects for this result set. */
private ColInfo[] columns;
/** The array of column data objects in the current row. */
private Object[] rowData;
/** The array of table names associated with this result. */
private TableMetaData[] tables;
/** The descriptor object for the current TDS token. */
private TdsToken currentToken = new TdsToken();
/** The stored procedure return status. */
private Integer returnStatus;
/** The return parameter meta data object for the current procedure call. */
private ParamInfo returnParam;
/** The array of parameter meta data objects for the current procedure call. */
private ParamInfo[] parameters;
/** The index of the next output parameter to populate. */
private int nextParam = -1;
/** The head of the diagnostic messages chain. */
private final SQLDiagnostic messages;
/** Indicates that this object is closed. */
private boolean isClosed;
/** Flag that indicates if logon() should try to use Windows Single Sign On using SSPI. */
private boolean ntlmAuthSSO;
/** Indicates that a fatal error has occured and the connection will close. */
private boolean fatalError;
/** Mutual exclusion lock on connection. */
private Semaphore connectionLock;
/** Indicates processing a batch. */
private boolean inBatch;
/** Indicates type of SSL connection. */
private int sslMode = SSL_NO_ENCRYPT;
/** Indicates pending cancel that needs to be cleared. */
private boolean cancelPending;
/** Synchronization monitor for {@link #cancelPending}. */
private final int[] cancelMonitor = new int[1];
/**
* Construct a TdsCore object.
*
* @param connection The connection which owns this object.
* @param messages The SQLDiagnostic messages chain.
*/
TdsCore(ConnectionJDBC2 connection, SQLDiagnostic messages) {
this.connection = connection;
this.socket = connection.getSocket();
this.messages = messages;
serverType = connection.getServerType();
tdsVersion = socket.getTdsVersion();
out = socket.getRequestStream(connection.getNetPacketSize(), connection.getMaxPrecision());
in = socket.getResponseStream(out, connection.getNetPacketSize());
}
/**
* Check that the connection is still open.
*
* @throws SQLException
*/
private void checkOpen() throws SQLException {
if (connection.isClosed()) {
throw new SQLException(
Messages.get("error.generic.closed", "Connection"),
"HY010");
}
}
/**
* Retrieve the TDS protocol version.
*
* @return The protocol version as an <code>int</code>.
*/
int getTdsVersion() {
return tdsVersion;
}
/**
* Retrieve the current result set column descriptors.
*
* @return The column descriptors as a <code>ColInfo[]</code>.
*/
ColInfo[] getColumns() {
return columns;
}
/**
* Sets the column meta data.
*
* @param columns the column descriptor array
*/
void setColumns(ColInfo[] columns) {
this.columns = columns;
this.rowData = new Object[columns.length];
this.tables = null;
}
/**
* Retrieve the parameter meta data from a Sybase prepare.
*
* @return The parameter descriptors as a <code>ParamInfo[]</code>.
*/
ParamInfo[] getParameters() {
if (currentToken.dynamParamInfo != null) {
ParamInfo[] params = new ParamInfo[currentToken.dynamParamInfo.length];
for (int i = 0; i < params.length; i++) {
ColInfo ci = currentToken.dynamParamInfo[i];
params[i] = new ParamInfo(ci, ci.realName, null, 0);
}
return params;
}
return EMPTY_PARAMETER_INFO;
}
/**
* Retrieve the current result set data items.
*
* @return the row data as an <code>Object</code> array
*/
Object[] getRowData() {
return rowData;
}
/**
* Negotiate SSL settings with SQL 2000+ server.
* <p/>
* Server returns the following values for SSL mode:
* <ol>
* <ll>0 = Certificate installed encrypt login packet only.
* <li>1 = Certificate installed client requests force encryption.
* <li>2 = No certificate no encryption possible.
* <li>3 = Server requests force encryption.
* </ol>
* @param instance The server instance name.
* @param ssl The SSL URL property value.
* @throws IOException
*/
void negotiateSSL(String instance, String ssl)
throws IOException, SQLException {
if (!ssl.equalsIgnoreCase(Ssl.SSL_OFF)) {
if (ssl.equalsIgnoreCase(Ssl.SSL_REQUIRE) ||
ssl.equalsIgnoreCase(Ssl.SSL_AUTHENTICATE)) {
sendPreLoginPacket(instance, true);
sslMode = readPreLoginPacket();
if (sslMode != SSL_CLIENT_FORCE_ENCRYPT &&
sslMode != SSL_SERVER_FORCE_ENCRYPT) {
throw new SQLException(
Messages.get("error.ssl.encryptionoff"),
"08S01");
}
} else {
sendPreLoginPacket(instance, false);
sslMode = readPreLoginPacket();
}
if (sslMode != SSL_NO_ENCRYPT) {
socket.enableEncryption(ssl);
}
}
}
/**
* Login to the SQL Server.
*
* @param serverName server host name
* @param database required database
* @param user user name
* @param password user password
* @param domain Windows NT domain (or null)
* @param charset required server character set
* @param appName application name
* @param progName library name
* @param wsid workstation ID
* @param language language to use for server messages
* @param macAddress client network MAC address
* @param packetSize required network packet size
* @throws SQLException if an error occurs
*/
void login(final String serverName,
final String database,
final String user,
final String password,
final String domain,
final String charset,
final String appName,
final String progName,
String wsid,
final String language,
final String macAddress,
final int packetSize)
throws SQLException {
try {
if (wsid.length() == 0) {
wsid = getHostName();
}
if (tdsVersion >= Driver.TDS70) {
sendMSLoginPkt(serverName, database, user, password,
domain, appName, progName, wsid, language,
macAddress, packetSize);
} else if (tdsVersion == Driver.TDS50) {
send50LoginPkt(serverName, user, password,
charset, appName, progName, wsid,
language, packetSize);
} else {
send42LoginPkt(serverName, user, password,
charset, appName, progName, wsid,
language, packetSize);
}
if (sslMode == SSL_ENCRYPT_LOGIN) {
socket.disableEncryption();
}
nextToken();
while (!endOfResponse) {
if (currentToken.isAuthToken()) {
sendNtlmChallengeResponse(currentToken.nonce, user, password, domain);
}
nextToken();
}
messages.checkErrors();
} catch (IOException ioe) {
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
}
}
/**
* Get the next result set or update count from the TDS stream.
*
* @return <code>boolean</code> if the next item is a result set.
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
boolean getMoreResults() throws SQLException {
checkOpen();
nextToken();
while (!endOfResponse
&& !currentToken.isUpdateCount()
&& !currentToken.isResultSet()) {
nextToken();
}
// Cursor opens are followed by TDS_TAB_INFO and TDS_COL_INFO
// Process these now so that the column descriptors are updated.
// Sybase wide result set headers are followed by a TDS_CONTROL_TOKEN
// skip that as well.
if (currentToken.isResultSet()) {
byte saveToken = currentToken.token;
try {
byte x = (byte) in.peek();
while ( x == TDS_TABNAME_TOKEN
|| x == TDS_COLINFO_TOKEN
|| x == TDS_CONTROL_TOKEN) {
nextToken();
x = (byte)in.peek();
}
} catch (IOException e) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", e.getMessage()),
"08S01"), e);
}
currentToken.token = saveToken;
}
return currentToken.isResultSet();
}
/**
* Retrieve the status of the next result item.
*
* @return <code>boolean</code> true if the next item is a result set.
*/
boolean isResultSet() {
return currentToken.isResultSet();
}
/**
* Retrieve the status of the next result item.
*
* @return <code>boolean</code> true if the next item is row data.
*/
boolean isRowData() {
return currentToken.isRowData();
}
/**
* Retrieve the status of the next result item.
*
* @return <code>boolean</code> true if the next item is an update count.
*/
boolean isUpdateCount() {
return currentToken.isUpdateCount();
}
/**
* Retrieve the update count from the current TDS token.
*
* @return The update count as an <code>int</code>.
*/
int getUpdateCount() {
if (currentToken.isEndToken()) {
return currentToken.updateCount;
}
return -1;
}
/**
* Retrieve the status of the response stream.
*
* @return <code>boolean</code> true if the response has been entirely consumed
*/
boolean isEndOfResponse() {
return endOfResponse;
}
/**
* Empty the server response queue.
*
* @throws SQLException if an error occurs
*/
void clearResponseQueue() throws SQLException {
checkOpen();
while (!endOfResponse) {
nextToken();
}
}
/**
* Consume packets from the server response queue up to (and including) the
* first response terminator.
*
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
void consumeOneResponse() throws SQLException {
checkOpen();
while (!endOfResponse) {
nextToken();
// If it's a response terminator, return
if (currentToken.isEndToken()
&& (currentToken.status & DONE_END_OF_RESPONSE) != 0) {
return;
}
}
}
/**
* Retrieve the next data row from the result set.
*
* @return <code>false</code> if at the end of results, <code>true</code>
* otherwise
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
boolean getNextRow() throws SQLException {
if (endOfResponse || endOfResults) {
return false;
}
checkOpen();
nextToken();
// Will either be first or next data row or end.
while (!currentToken.isRowData() && !currentToken.isEndToken()) {
nextToken(); // Could be messages
}
return currentToken.isRowData();
}
/**
* Retrieve the status of result set.
* <p>
* This does a quick read ahead and is needed to support the isLast()
* method in the ResultSet.
*
* @return <code>boolean</code> - <code>true</code> if there is more data
* in the result set.
*/
boolean isDataInResultSet() throws SQLException {
byte x;
checkOpen();
try {
x = (endOfResponse) ? TDS_DONE_TOKEN : (byte) in.peek();
while (x != TDS_ROW_TOKEN
&& x != TDS_DONE_TOKEN
&& x != TDS_DONEINPROC_TOKEN
&& x != TDS_DONEPROC_TOKEN) {
nextToken();
x = (byte) in.peek();
}
messages.checkErrors();
} catch (IOException e) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", e.getMessage()),
"08S01"), e);
}
return x == TDS_ROW_TOKEN;
}
/**
* Retrieve the return status for the current stored procedure.
*
* @return The return status as an <code>Integer</code>.
*/
Integer getReturnStatus() {
return this.returnStatus;
}
/**
* Inform the server that this connection is closing.
* <p>
* Used by Sybase a no-op for Microsoft.
*/
synchronized void closeConnection() {
try {
if (tdsVersion == Driver.TDS50) {
socket.setTimeout(1000);
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS_CLOSE_TOKEN);
out.write((byte)0);
out.flush();
endOfResponse = false;
clearResponseQueue();
}
} catch (Exception e) {
// Ignore any exceptions as this connection
// is closing anyway.
}
}
/**
* Close the <code>TdsCore</code> connection object and associated streams.
*/
void close() throws SQLException {
if (!isClosed) {
try {
clearResponseQueue();
out.close();
in.close();
} finally {
isClosed = true;
}
}
}
/**
* Send (only) one cancel packet to the server.
*
* @param timeout true if this is a query timeout cancel
*/
void cancel(boolean timeout) {
Semaphore mutex = null;
try {
mutex = connection.getMutex();
synchronized (cancelMonitor) {
if (!cancelPending && !endOfResponse) {
cancelPending = socket.cancel(out.getStreamId());
}
// If a cancel request was sent, reset the end of response flag
if (cancelPending) {
cancelMonitor[0] = timeout ? TIMEOUT_CANCEL : ASYNC_CANCEL;
endOfResponse = false;
}
}
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Submit a simple SQL statement to the server and process all output.
*
* @param sql the statement to execute
* @throws SQLException if an error is returned by the server
*/
void submitSQL(String sql) throws SQLException {
checkOpen();
messages.clearWarnings();
if (sql.length() == 0) {
throw new IllegalArgumentException("submitSQL() called with empty SQL String");
}
executeSQL(sql, null, null, false, 0, -1, -1, true);
clearResponseQueue();
messages.checkErrors();
}
/**
* Notifies the <code>TdsCore</code> that a batch is starting. This is so
* that it knows to use <code>sp_executesql</code> for parameterized
* queries (because there's no way to prepare a statement in the middle of
* a batch).
* <p>
* Sets the {@link #inBatch} flag.
*/
void startBatch() {
inBatch = true;
}
/**
* Send an SQL statement with optional parameters to the server.
*
* @param sql SQL statement to execute
* @param procName stored procedure to execute or <code>null</code>
* @param parameters parameters for call or null
* @param noMetaData suppress meta data for cursor calls
* @param timeOut optional query timeout or 0
* @param maxRows the maximum number of data rows to return (-1 to
* leave unaltered)
* @param maxFieldSize the maximum number of bytes in a column to return
* (-1 to leave unaltered)
* @param sendNow whether to send the request now or not
* @throws SQLException if an error occurs
*/
synchronized void executeSQL(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
int timeOut,
int maxRows,
int maxFieldSize,
boolean sendNow)
throws SQLException {
boolean sendFailed = true; // Used to ensure mutex is released.
try {
// Obtain a lock on the connection giving exclusive access
// to the network connection for this thread
if (connectionLock == null) {
connectionLock = connection.getMutex();
}
// Also checks if connection is open
clearResponseQueue();
messages.exceptions = null;
// Set the connection row count and text size if required.
// Once set these will not be changed within a
// batch so execution of the set rows query will
// only occur once a the start of a batch.
// No other thread can send until this one has finished.
setRowCountAndTextSize(maxRows, maxFieldSize);
messages.clearWarnings();
this.returnStatus = null;
// Normalize the parameters argument to simplify later checks
if (parameters != null && parameters.length == 0) {
parameters = null;
}
this.parameters = parameters;
// Normalise the procName argument as well
if (procName != null && procName.length() == 0) {
procName = null;
}
if (parameters != null && parameters[0].isRetVal) {
returnParam = parameters[0];
nextParam = 0;
} else {
returnParam = null;
nextParam = -1;
}
if (parameters != null) {
if (procName == null && sql.startsWith("EXECUTE ")) {
// If this is a callable statement that could not be fully parsed
// into an RPC call convert to straight SQL now.
// An example of non RPC capable SQL is {?=call sp_example('literal', ?)}
for (int i = 0; i < parameters.length; i++){
// Output parameters not allowed.
if (!parameters[i].isRetVal && parameters[i].isOutput){
throw new SQLException(Messages.get("error.prepare.nooutparam",
Integer.toString(i + 1)), "07000");
}
}
sql = Support.substituteParameters(sql, parameters, connection);
parameters = null;
} else {
// Check all parameters are either output or have values set
for (int i = 0; i < parameters.length; i++){
if (!parameters[i].isSet && !parameters[i].isOutput){
throw new SQLException(Messages.get("error.prepare.paramnotset",
Integer.toString(i + 1)), "07000");
}
parameters[i].clearOutValue();
// FIXME Should only set TDS type if not already set
// but we might need to take a lot of care not to
// exceed size limitations (e.g. write 11 chars in a
// VARCHAR(10) )
TdsData.getNativeType(connection, parameters[i]);
}
}
}
try {
switch (tdsVersion) {
case Driver.TDS42:
executeSQL42(sql, procName, parameters, noMetaData, sendNow);
break;
case Driver.TDS50:
executeSQL50(sql, procName, parameters);
break;
case Driver.TDS70:
case Driver.TDS80:
case Driver.TDS81:
executeSQL70(sql, procName, parameters, noMetaData, sendNow);
break;
default:
throw new IllegalStateException("Unknown TDS version " + tdsVersion);
}
if (sendNow) {
out.flush();
connectionLock.release();
connectionLock = null;
sendFailed = false;
endOfResponse = false;
endOfResults = true;
wait(timeOut);
} else {
sendFailed = false;
}
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
}
} finally {
if ((sendNow || sendFailed) && connectionLock != null) {
connectionLock.release();
connectionLock = null;
}
// Clear the in batch flag
if (sendNow) {
inBatch = false;
}
}
}
/**
* Prepares the SQL for use with Microsoft server.
*
* @param sql the SQL statement to prepare.
* @param params the actual parameter list
* @param needCursor true if a cursorprepare is required
* @param resultSetType value of the resultSetType parameter when
* the Statement was created
* @param resultSetConcurrency value of the resultSetConcurrency parameter
* whenthe Statement was created
* @return name of the procedure or prepared statement handle.
* @exception SQLException
*/
String microsoftPrepare(String sql,
ParamInfo[] params,
boolean needCursor,
int resultSetType,
int resultSetConcurrency)
throws SQLException {
checkOpen();
messages.clearWarnings();
int prepareSql = connection.getPrepareSql();
if (prepareSql == TEMPORARY_STORED_PROCEDURES) {
StringBuffer spSql = new StringBuffer(sql.length() + 32 + params.length * 15);
String procName = connection.getProcName();
spSql.append("create proc ");
spSql.append(procName);
spSql.append(' ');
for (int i = 0; i < params.length; i++) {
spSql.append("@P");
spSql.append(i);
spSql.append(' ');
spSql.append(params[i].sqlType);
if (i + 1 < params.length) {
spSql.append(',');
}
}
// continue building proc
spSql.append(" as ");
spSql.append(Support.substituteParamMarkers(sql, params));
try {
submitSQL(spSql.toString());
return procName;
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious (I/O) error, rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Add a warning
messages.addWarning(Support.linkException(
new SQLWarning(
Messages.get("error.prepare.prepfailed",
e.getMessage()),
e.getSQLState(), e.getErrorCode()),
e));
}
} else if (prepareSql == PREPARE) {
int scrollOpt, ccOpt;
ParamInfo prepParam[] = new ParamInfo[needCursor ? 6 : 4];
// Setup prepare handle param
prepParam[0] = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT);
// Setup parameter descriptor param
prepParam[1] = new ParamInfo(Types.LONGVARCHAR,
Support.getParameterDefinitions(params),
ParamInfo.UNICODE);
// Setup sql statemement param
prepParam[2] = new ParamInfo(Types.LONGVARCHAR,
Support.substituteParamMarkers(sql, params),
ParamInfo.UNICODE);
// Setup options param
prepParam[3] = new ParamInfo(Types.INTEGER, new Integer(1), ParamInfo.INPUT);
if (needCursor) {
// Select the correct type of Server side cursor to
// match the scroll and concurrency options.
scrollOpt = MSCursorResultSet.getCursorScrollOpt(resultSetType,
resultSetConcurrency, true);
ccOpt = MSCursorResultSet.getCursorConcurrencyOpt(resultSetConcurrency);
// Setup scroll options parameter
prepParam[4] = new ParamInfo(Types.INTEGER,
new Integer(scrollOpt),
ParamInfo.OUTPUT);
// Setup concurrency options parameter
prepParam[5] = new ParamInfo(Types.INTEGER,
new Integer(ccOpt),
ParamInfo.OUTPUT);
}
columns = null; // Will be populated if preparing a select
try {
executeSQL(null, needCursor ? "sp_cursorprepare" : "sp_prepare",
prepParam, false, 0, -1, -1, true);
int resultCount = 0;
while (!endOfResponse) {
nextToken();
if (isResultSet()) {
resultCount++;
}
}
// columns will now hold meta data for any select statements
if (resultCount != 1) {
// More than one result set was returned or none
// therefore metadata not available or unsafe.
columns = null;
}
Integer prepareHandle = (Integer) prepParam[0].getOutValue();
if (prepareHandle != null) {
return prepareHandle.toString();
}
// Probably an exception occured, check for it
messages.checkErrors();
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious (I/O) error, rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Add a warning
messages.addWarning(Support.linkException(
new SQLWarning(
Messages.get("error.prepare.prepfailed",
e.getMessage()),
e.getSQLState(), e.getErrorCode()),
e));
}
}
return null;
}
/**
* Creates a light weight stored procedure on a Sybase server.
*
* @param sql SQL statement to prepare
* @param params the actual parameter list
* @return name of the procedure
* @throws SQLException if an error occurs
*/
synchronized String sybasePrepare(String sql, ParamInfo[] params)
throws SQLException {
checkOpen();
messages.clearWarnings();
if (sql == null || sql.length() == 0) {
throw new IllegalArgumentException(
"sql parameter must be at least 1 character long.");
}
String procName = connection.getProcName();
if (procName == null || procName.length() != 11) {
throw new IllegalArgumentException(
"procName parameter must be 11 characters long.");
}
// TODO Check if output parameters are handled ok
// Check no text/image parameters
for (int i = 0; i < params.length; i++) {
if (params[i].sqlType.equals("text")
|| params[i].sqlType.equals("unitext")
|| params[i].sqlType.equals("image")) {
return null; // Sadly no way
}
}
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS5_DYNAMIC_TOKEN);
byte buf[] = Support.encodeString(connection.getCharset(), sql);
out.write((short) (buf.length + 41));
out.write((byte) 1);
out.write((byte) 0);
out.write((byte) 10);
out.writeAscii(procName.substring(1));
out.write((short) (buf.length + 26));
out.writeAscii("create proc ");
out.writeAscii(procName.substring(1));
out.writeAscii(" as ");
out.write(buf);
out.flush();
endOfResponse = false;
clearResponseQueue();
messages.checkErrors();
return procName;
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious error rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Return null;
return null;
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Drops a Sybase temporary stored procedure.
*
* @param procName the temporary procedure name
* @throws SQLException if an error occurs
*/
synchronized void sybaseUnPrepare(String procName)
throws SQLException {
checkOpen();
messages.clearWarnings();
if (procName == null || procName.length() != 11) {
throw new IllegalArgumentException(
"procName parameter must be 11 characters long.");
}
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS5_DYNAMIC_TOKEN);
out.write((short) (15));
out.write((byte) 4);
out.write((byte) 0);
out.write((byte) 10);
out.writeAscii(procName.substring(1));
out.write((short)0);
out.flush();
endOfResponse = false;
clearResponseQueue();
messages.checkErrors();
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious error rethrow
throw e;
}
// This exception probably caused by failure to unprepare
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Enlist the current connection in a distributed transaction or request the location of the
* MSDTC instance controlling the server we are connected to.
*
* @param type set to 0 to request TM address or 1 to enlist connection
* @param oleTranID the 40 OLE transaction ID
* @return a <code>byte[]</code> array containing the TM address data
* @throws SQLException
*/
synchronized byte[] enlistConnection(int type, byte[] oleTranID) throws SQLException {
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(MSDTC_PKT);
out.write((short)type);
switch (type) {
case 0: // Get result set with location of MSTDC
out.write((short)0);
break;
case 1: // Set OLE transaction ID
if (oleTranID != null) {
out.write((short)oleTranID.length);
out.write(oleTranID);
} else {
// Delist the connection from all transactions.
out.write((short)0);
}
break;
}
out.flush();
endOfResponse = false;
endOfResults = true;
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"),
ioe);
} finally {
if (mutex != null) {
mutex.release();
}
}
byte[] tmAddress = null;
if (getMoreResults() && getNextRow()) {
if (rowData.length == 1) {
Object x = rowData[0];
if (x instanceof byte[]) {
tmAddress = (byte[])x;
}
}
}
clearResponseQueue();
messages.checkErrors();
return tmAddress;
}
/**
* Obtain the counts from a batch of SQL updates.
* <p/>
* If an error occurs Sybase will continue processing a batch consisting of
* TDS_LANGUAGE records whilst SQL Server will usually stop after the first
* error except when the error is caused by a duplicate key.
* Sybase will also stop after the first error when executing RPC calls.
* Care is taken to ensure that <code>SQLException</code>s are chained
* because there could be several errors reported in a batch.
*
* @param counts the <code>ArrayList</code> containing the update counts
* @param sqlEx any previous <code>SQLException</code>(s) encountered
* @return updated <code>SQLException</code> or <code>null</code> if no
* error has yet occured
*/
SQLException getBatchCounts(ArrayList counts, SQLException sqlEx) {
Integer lastCount = JtdsStatement.SUCCESS_NO_INFO;
try {
checkOpen();
while (!endOfResponse) {
nextToken();
if (currentToken.isResultSet()) {
// Serious error, statement must not return a result set
throw new SQLException(
Messages.get("error.statement.batchnocount"),
"07000");
}
// Analyse type of end token and try to extract correct
// update count when calling stored procs.
switch (currentToken.token) {
case TDS_DONE_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0
|| lastCount == JtdsStatement.EXECUTE_FAILED) {
counts.add(JtdsStatement.EXECUTE_FAILED);
} else {
if (currentToken.isUpdateCount()) {
counts.add(new Integer(currentToken.updateCount));
} else {
counts.add(lastCount);
}
}
lastCount = JtdsStatement.SUCCESS_NO_INFO;
break;
case TDS_DONEINPROC_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0) {
lastCount = JtdsStatement.EXECUTE_FAILED;
} else if (currentToken.isUpdateCount()) {
lastCount = new Integer(currentToken.updateCount);
}
break;
case TDS_DONEPROC_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0
|| lastCount == JtdsStatement.EXECUTE_FAILED) {
counts.add(JtdsStatement.EXECUTE_FAILED);
} else {
counts.add(lastCount);
}
lastCount = JtdsStatement.SUCCESS_NO_INFO;
break;
}
}
// Check for any exceptions
messages.checkErrors();
} catch (SQLException e) {
// Chain all exceptions
if (sqlEx != null) {
sqlEx.setNextException(e);
} else {
sqlEx = e;
}
} finally {
while (!endOfResponse) {
// Flush rest of response
try {
nextToken();
} catch (SQLException ex) {
// Chain any exceptions to the BatchUpdateException
if (sqlEx != null) {
sqlEx.setNextException(ex);
} else {
sqlEx = ex;
}
}
}
}
return sqlEx;
}
/**
* Write a TDS login packet string. Text followed by padding followed
* by a byte sized length.
*/
private void putLoginString(String txt, int len)
throws IOException {
byte[] tmp = Support.encodeString(connection.getCharset(), txt);
out.write(tmp, 0, len);
out.write((byte) (tmp.length < len ? tmp.length : len));
}
/**
* Send the SQL Server 2000 pre login packet.
* <p>Packet contains; netlib version, ssl mode, instance
* and process ID.
* @param instance
* @param forceEncryption
* @throws IOException
*/
private void sendPreLoginPacket(String instance, boolean forceEncryption)
throws IOException {
out.setPacketType(PRELOGIN_PKT);
// Write Netlib pointer
out.write((short)0);
out.write((short)21);
out.write((byte)6);
// Write Encrypt flag pointer
out.write((short)1);
out.write((short)27);
out.write((byte)1);
// Write Instance name pointer
out.write((short)2);
out.write((short)28);
out.write((byte)(instance.length()+1));
// Write process ID pointer
out.write((short)3);
out.write((short)(28+instance.length()+1));
out.write((byte)4);
// Write terminator
out.write((byte)0xFF);
// Write fake net lib ID 8.341.0
out.write(new byte[]{0x08, 0x00, 0x01, 0x55, 0x00, 0x00});
// Write force encryption flag
out.write((byte)(forceEncryption? 1: 0));
// Write instance name
out.writeAscii(instance);
out.write((byte)0);
// Write dummy process ID
out.write(new byte[]{0x01, 0x02, 0x00, 0x00});
out.flush();
}
/**
* Process the pre login acknowledgement from the server.
* <p>Packet contains; server version no, SSL mode, instance name
* and process id.
* <p>Server returns the following values for SSL mode:
* <ol>
* <ll>0 = Certificate installed encrypt login packet only.
* <li>1 = Certificate installed client requests force encryption.
* <li>2 = No certificate no encryption possible.
* <li>3 = Server requests force encryption.
* </ol>
* @return The server side SSL mode.
* @throws IOException
*/
private int readPreLoginPacket() throws IOException {
byte list[][] = new byte[8][];
byte data[][] = new byte[8][];
int recordCount = 0;
byte record[] = new byte[5];
// Read entry pointers
record[0] = (byte)in.read();
while ((record[0] & 0xFF) != 0xFF) {
if (recordCount == list.length) {
throw new IOException("Pre Login packet has more than 8 entries");
}
// Read record
in.read(record, 1, 4);
list[recordCount++] = record;
record = new byte[5];
record[0] = (byte)in.read();
}
// Read entry data
for (int i = 0; i < recordCount; i++) {
byte value[] = new byte[(byte)list[i][4]];
in.read(value);
data[i] = value;
}
if (Logger.isActive()) {
// Diagnostic dump
Logger.println("PreLogin server response");
for (int i = 0; i < recordCount; i++) {
Logger.println("Record " + i+ " = " +
Support.toHex(data[i]));
}
}
if (recordCount > 1) {
return data[1][0]; // This is the server side SSL mode
} else {
// Response too short to include SSL mode!
return SSL_NO_ENCRYPT;
}
}
/**
* TDS 4.2 Login Packet.
*
* @param serverName server host name
* @param user user name
* @param password user password
* @param charset required server character set
* @param appName application name
* @param progName program name
* @param wsid workstation ID
* @param language server language for messages
* @param packetSize required network packet size
* @throws IOException if an I/O error occurs
*/
private void send42LoginPkt(final String serverName,
final String user,
final String password,
final String charset,
final String appName,
final String progName,
final String wsid,
final String language,
final int packetSize)
throws IOException {
final byte[] empty = new byte[0];
out.setPacketType(LOGIN_PKT);
putLoginString(wsid, 30); // Host name
putLoginString(user, 30); // user name
putLoginString(password, 30); // password
putLoginString("00000123", 30); // hostproc (offset 93 0x5d)
out.write((byte) 3); // type of int2
out.write((byte) 1); // type of int4
out.write((byte) 6); // type of char
out.write((byte) 10);// type of flt
out.write((byte) 9); // type of date
out.write((byte) 1); // notify of use db
out.write((byte) 1); // disallow dump/load and bulk insert
out.write((byte) 0); // sql interface type
out.write((byte) 0); // type of network connection
out.write(empty, 0, 7);
putLoginString(appName, 30); // appname
putLoginString(serverName, 30); // server name
out.write((byte)0); // remote passwords
out.write((byte)password.length());
byte[] tmp = Support.encodeString(connection.getCharset(), password);
out.write(tmp, 0, 253);
out.write((byte) (tmp.length + 2));
out.write((byte) 4); // tds version
out.write((byte) 2);
out.write((byte) 0);
out.write((byte) 0);
putLoginString(progName, 10); // prog name
out.write((byte) 6); // prog version
out.write((byte) 0);
out.write((byte) 0);
out.write((byte) 0);
out.write((byte) 0); // auto convert short
out.write((byte) 0x0D); // type of flt4
out.write((byte) 0x11); // type of date4
putLoginString(language, 30); // language
out.write((byte) 1); // notify on lang change
out.write((short) 0); // security label hierachy
out.write((byte) 0); // security encrypted
out.write(empty, 0, 8); // security components
out.write((short) 0); // security spare
putLoginString(charset, 30); // Character set
out.write((byte) 1); // notify on charset change
putLoginString(String.valueOf(packetSize), 6); // length of tds packets
out.write(empty, 0, 8); // pad out to a longword
out.flush(); // Send the packet
endOfResponse = false;
}
/**
* TDS 5.0 Login Packet.
* <P>
* @param serverName server host name
* @param user user name
* @param password user password
* @param charset required server character set
* @param appName application name
* @param progName library name
* @param wsid workstation ID
* @param language server language for messages
* @param packetSize required network packet size
* @throws IOException if an I/O error occurs
*/
private void send50LoginPkt(final String serverName,
final String user,
final String password,
final String charset,
final String appName,
final String progName,
final String wsid,
final String language,
final int packetSize)
throws IOException {
final byte[] empty = new byte[0];
out.setPacketType(LOGIN_PKT);
putLoginString(wsid, 30); // Host name
putLoginString(user, 30); // user name
putLoginString(password, 30); // password
putLoginString("00000123", 30); // hostproc (offset 93 0x5d)
out.write((byte) 3); // type of int2
out.write((byte) 1); // type of int4
out.write((byte) 6); // type of char
out.write((byte) 10);// type of flt
out.write((byte) 9); // type of date
out.write((byte) 1); // notify of use db
out.write((byte) 1); // disallow dump/load and bulk insert
out.write((byte) 0); // sql interface type
out.write((byte) 0); // type of network connection
out.write(empty, 0, 7);
putLoginString(appName, 30); // appname
putLoginString(serverName, 30); // server name
out.write((byte)0); // remote passwords
out.write((byte)password.length());
byte[] tmp = Support.encodeString(connection.getCharset(), password);
out.write(tmp, 0, 253);
out.write((byte) (tmp.length + 2));
out.write((byte) 5); // tds version
out.write((byte) 0);
out.write((byte) 0);
out.write((byte) 0);
putLoginString(progName, 10); // prog name
out.write((byte) 5); // prog version
out.write((byte) 0);
out.write((byte) 0);
out.write((byte) 0);
out.write((byte) 0); // auto convert short
out.write((byte) 0x0D); // type of flt4
out.write((byte) 0x11); // type of date4
putLoginString(language, 30); // language
out.write((byte) 1); // notify on lang change
out.write((short) 0); // security label hierachy
out.write((byte) 0); // security encrypted
out.write(empty, 0, 8); // security components
out.write((short) 0); // security spare
putLoginString(charset, 30); // Character set
out.write((byte) 1); // notify on charset change
if (packetSize > 0) {
putLoginString(String.valueOf(packetSize), 6); // specified length of tds packets
} else {
putLoginString(String.valueOf(MIN_PKT_SIZE), 6); // Default length of tds packets
}
out.write(empty, 0, 4);
// Request capabilities
// jTDS sends 01 0B 4F FF 85 EE EF 65 7F FF FF FF D6
// Sybase 11.92 01 0A 00 00 00 23 61 41 CF FF FF C6
// Sybase 12.52 01 0A 03 84 0A E3 61 41 FF FF FF C6
// Sybase 15.00 01 0B 4F F7 85 EA EB 61 7F FF FF FF C6
// Response capabilities
// jTDS sends 02 0A 00 00 04 06 80 06 48 00 00 00
// Sybase 11.92 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 12.52 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 15.00 02 0A 00 00 04 00 00 06 00 00 00 00
byte capString[] = {
// Request capabilities
(byte)0x01,(byte)0x0B,(byte)0x4F,(byte)0xFF,(byte)0x85,(byte)0xEE,(byte)0xEF,
(byte)0x65,(byte)0x7F,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xD6,
// Response capabilities
(byte)0x02,(byte)0x0A,(byte)0x00,(byte)0x02,(byte)0x04,(byte)0x06,
(byte)0x80,(byte)0x06,(byte)0x48,(byte)0x00,(byte)0x00,(byte)0x0C
};
if (packetSize == 0) {
// Tell the server we will use its packet size
capString[17] = 0;
}
out.write(TDS_CAP_TOKEN);
out.write((short)capString.length);
out.write(capString);
out.flush(); // Send the packet
endOfResponse = false;
}
/**
* Send a TDS 7 login packet.
* <p>
* This method incorporates the Windows single sign on code contributed by
* Magendran Sathaiah. To invoke single sign on just leave the user name
* blank or null. NB. This can only work if the driver is being executed on
* a Windows PC and <code>ntlmauth.dll</code> is on the path.
*
* @param serverName server host name
* @param database required database
* @param user user name
* @param password user password
* @param domain Windows NT domain (or <code>null</code>)
* @param appName application name
* @param progName program name
* @param wsid workstation ID
* @param language server language for messages
* @param macAddress client network MAC address
* @param netPacketSize TDS packet size to use
* @throws IOException if an I/O error occurs
*/
private void sendMSLoginPkt(final String serverName,
final String database,
final String user,
final String password,
final String domain,
final String appName,
final String progName,
final String wsid,
final String language,
final String macAddress,
final int netPacketSize)
throws IOException, SQLException {
final byte[] empty = new byte[0];
boolean ntlmAuth = false;
byte[] ntlmMessage = null;
if (user == null || user.length() == 0) {
// See if executing on a Windows platform and if so try and
// use the single sign on native library.
if (Support.isWindowsOS()) {
ntlmAuthSSO = true;
ntlmAuth = true;
} else {
throw new SQLException(Messages.get("error.connection.sso"),
"08001");
}
} else if (domain != null && domain.length() > 0) {
// Assume we want to use Windows authentication with
// supplied user and password.
ntlmAuth = true;
}
if (ntlmAuthSSO) {
try {
// Create the NTLM request block using the native library
sspiJNIClient = SSPIJNIClient.getInstance();
ntlmMessage = sspiJNIClient.invokePrepareSSORequest();
} catch (Exception e) {
throw new IOException("SSO Failed: " + e.getMessage());
}
}
//mdb:begin-change
short packSize = (short) (86 + 2 *
(wsid.length() +
appName.length() +
serverName.length() +
progName.length() +
database.length() +
language.length()));
final short authLen;
//NOTE(mdb): ntlm includes auth block; sql auth includes uname and pwd.
if (ntlmAuth) {
if (ntlmAuthSSO && ntlmMessage != null) {
authLen = (short) ntlmMessage.length;
} else {
authLen = (short) (32 + domain.length());
}
packSize += authLen;
} else {
authLen = 0;
packSize += (2 * (user.length() + password.length()));
}
//mdb:end-change
out.setPacketType(MSLOGIN_PKT);
out.write((int)packSize);
// TDS version
if (tdsVersion == Driver.TDS70) {
out.write((int)0x70000000);
} else {
out.write((int)0x71000001);
}
// Network Packet size requested by client
out.write((int)netPacketSize);
// Program version?
out.write((int)7);
// Process ID
out.write((int)123);
// Connection ID
out.write((int)0);
// 0x20: enable warning messages if USE <database> issued
// 0x40: change to initial database must succeed
// 0x80: enable warning messages if SET LANGUAGE issued
byte flags = (byte) (0x20 | 0x40 | 0x80);
out.write(flags);
//mdb: this byte controls what kind of auth we do.
flags = 0x03; // ODBC (JDBC) driver
if (ntlmAuth)
flags |= 0x80; // Use NT authentication
out.write(flags);
out.write((byte)0); // SQL type flag
out.write((byte)0); // Reserved flag
// TODO Set Timezone and collation?
out.write(empty, 0, 4); // Time Zone
out.write(empty, 0, 4); // Collation
// Pack up value lengths, positions.
short curPos = 86;
// Hostname
out.write((short)curPos);
out.write((short) wsid.length());
curPos += wsid.length() * 2;
//mdb: NTLM doesn't send username and password...
if (!ntlmAuth) {
// Username
out.write((short)curPos);
out.write((short) user.length());
curPos += user.length() * 2;
// Password
out.write((short)curPos);
out.write((short) password.length());
curPos += password.length() * 2;
} else {
out.write((short)curPos);
out.write((short) 0);
out.write((short)curPos);
out.write((short) 0);
}
// App name
out.write((short)curPos);
out.write((short) appName.length());
curPos += appName.length() * 2;
// Server name
out.write((short)curPos);
out.write((short) serverName.length());
curPos += serverName.length() * 2;
// Unknown
out.write((short) 0);
out.write((short) 0);
// Program name
out.write((short)curPos);
out.write((short) progName.length());
curPos += progName.length() * 2;
// Server language
out.write((short)curPos);
out.write((short) language.length());
curPos += language.length() * 2;
// Database
out.write((short)curPos);
out.write((short) database.length());
curPos += database.length() * 2;
// MAC address
out.write(getMACAddress(macAddress));
//mdb: location of ntlm auth block. note that for sql auth, authLen==0.
out.write((short)curPos);
out.write((short)authLen);
//"next position" (same as total packet size)
out.write((int)packSize);
out.write(wsid);
// Pack up the login values.
//mdb: for ntlm auth, uname and pwd aren't sent up...
if (!ntlmAuth) {
final String scrambledPw = tds7CryptPass(password);
out.write(user);
out.write(scrambledPw);
}
out.write(appName);
out.write(serverName);
out.write(progName);
out.write(language);
out.write(database);
//mdb: add the ntlm auth info...
if (ntlmAuth) {
if (ntlmAuthSSO) {
// Use the NTLM message generated by the native library
out.write(ntlmMessage);
} else {
// host and domain name are _narrow_ strings.
final byte[] domainBytes = domain.getBytes("UTF8");
//byte[] hostBytes = localhostname.getBytes("UTF8");
final byte[] header = {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00};
out.write(header); //header is ascii "NTLMSSP\0"
out.write((int)1); //sequence number = 1
if(connection.getUseNTLMv2())
out.write((int)0xb205); //flags (same as below, only with Request Target set)
else
out.write((int)0xb201); //flags (see below)
// NOTE: flag reference:
// 0x8000 = negotiate always sign
// 0x2000 = client is sending workstation name
// 0x1000 = client is sending domain name
// 0x0200 = negotiate NTLM
// 0x0004 - Request Target, which requests that server send target
// 0x0001 = negotiate Unicode
//domain info
out.write((short) domainBytes.length);
out.write((short) domainBytes.length);
out.write((int)32); //offset, relative to start of auth block.
//host info
//NOTE(mdb): not sending host info; hope this is ok!
out.write((short) 0);
out.write((short) 0);
out.write((int)32); //offset, relative to start of auth block.
// add the variable length data at the end...
out.write(domainBytes);
}
}
out.flush(); // Send the packet
endOfResponse = false;
}
/**
* Send the response to the NTLM authentication challenge.
* @param nonce The secret to hash with password.
* @param user The user name.
* @param password The user password.
* @param domain The Windows NT Dommain.
* @throws java.io.IOException
*/
private void sendNtlmChallengeResponse(final byte[] nonce,
String user,
final String password,
String domain)
throws java.io.IOException {
out.setPacketType(NTLMAUTH_PKT);
// Prepare and Set NTLM Type 2 message appropriately
if (ntlmAuthSSO) {
byte[] ntlmMessage = currentToken.ntlmMessage;
try {
// Create the challenge response using the native library
ntlmMessage = sspiJNIClient.invokePrepareSSOSubmit(ntlmMessage);
} catch (Exception e) {
throw new IOException("SSO Failed: " + e.getMessage());
}
out.write(ntlmMessage);
} else {
// host and domain name are _narrow_ strings.
//byte[] domainBytes = domain.getBytes("UTF8");
//byte[] user = user.getBytes("UTF8");
byte[] lmAnswer, ntAnswer;
//the response to the challenge...
if(connection.getUseNTLMv2())
{
//TODO: does this need to be random?
//byte[] clientNonce = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
byte[] clientNonce = new byte[8];
(new Random()).nextBytes(clientNonce);
lmAnswer = NtlmAuth.answerLmv2Challenge(domain, user, password, nonce, clientNonce);
ntAnswer = NtlmAuth.answerNtlmv2Challenge(
domain, user, password, nonce, currentToken.ntlmTarget, clientNonce);
}
else
{
//LM/NTLM (v1)
lmAnswer = NtlmAuth.answerLmChallenge(password, nonce);
ntAnswer = NtlmAuth.answerNtChallenge(password, nonce);
}
final byte[] header = {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00};
out.write(header); //header is ascii "NTLMSSP\0"
out.write((int)3); //sequence number = 3
final int domainLenInBytes = domain.length() * 2;
final int userLenInBytes = user.length() * 2;
//mdb: not sending hostname; I hope this is ok!
final int hostLenInBytes = 0; //localhostname.length()*2;
int pos = 64 + domainLenInBytes + userLenInBytes + hostLenInBytes;
// lan man response: length and offset
out.write((short)lmAnswer.length);
out.write((short)lmAnswer.length);
out.write((int)pos);
pos += lmAnswer.length;
// nt response: length and offset
out.write((short)ntAnswer.length);
out.write((short)ntAnswer.length);
out.write((int)pos);
pos = 64;
//domain
out.write((short) domainLenInBytes);
out.write((short) domainLenInBytes);
out.write((int)pos);
pos += domainLenInBytes;
//user
out.write((short) userLenInBytes);
out.write((short) userLenInBytes);
out.write((int)pos);
pos += userLenInBytes;
//local hostname
out.write((short) hostLenInBytes);
out.write((short) hostLenInBytes);
out.write((int)pos);
pos += hostLenInBytes;
//unknown
out.write((short) 0);
out.write((short) 0);
out.write((int)pos);
//flags
out.write((int)0x8201); //flags (???)
//variable length stuff...
out.write(domain);
out.write(user);
//Not sending hostname...I hope this is OK!
//comm.appendChars(localhostname);
//the response to the challenge...
out.write(lmAnswer);
out.write(ntAnswer);
}
out.flush();
}
/**
* Read the next TDS token from the response stream.
*
* @throws SQLException if an I/O or protocol error occurs
*/
private void nextToken()
throws SQLException
{
checkOpen();
if (endOfResponse) {
currentToken.token = TDS_DONE_TOKEN;
currentToken.status = 0;
return;
}
try {
currentToken.token = (byte)in.read();
switch (currentToken.token) {
case TDS5_PARAMFMT2_TOKEN:
tds5ParamFmt2Token();
break;
case TDS_LANG_TOKEN:
tdsInvalidToken();
break;
case TDS5_WIDE_RESULT:
tds5WideResultToken();
break;
case TDS_CLOSE_TOKEN:
tdsInvalidToken();
break;
case TDS_RETURNSTATUS_TOKEN:
tdsReturnStatusToken();
break;
case TDS_PROCID:
tdsProcIdToken();
break;
case TDS_OFFSETS_TOKEN:
tdsOffsetsToken();
break;
case TDS7_RESULT_TOKEN:
tds7ResultToken();
break;
case TDS7_COMP_RESULT_TOKEN:
tdsInvalidToken();
break;
case TDS_COLNAME_TOKEN:
tds4ColNamesToken();
break;
case TDS_COLFMT_TOKEN:
tds4ColFormatToken();
break;
case TDS_TABNAME_TOKEN:
tdsTableNameToken();
break;
case TDS_COLINFO_TOKEN:
tdsColumnInfoToken();
break;
case TDS_COMP_NAMES_TOKEN:
tdsInvalidToken();
break;
case TDS_COMP_RESULT_TOKEN:
tdsInvalidToken();
break;
case TDS_ORDER_TOKEN:
tdsOrderByToken();
break;
case TDS_ERROR_TOKEN:
case TDS_INFO_TOKEN:
tdsErrorToken();
break;
case TDS_PARAM_TOKEN:
tdsOutputParamToken();
break;
case TDS_LOGINACK_TOKEN:
tdsLoginAckToken();
break;
case TDS_CONTROL_TOKEN:
tdsControlToken();
break;
case TDS_ROW_TOKEN:
tdsRowToken();
break;
case TDS_ALTROW:
tdsInvalidToken();
break;
case TDS5_PARAMS_TOKEN:
tds5ParamsToken();
break;
case TDS_CAP_TOKEN:
tdsCapabilityToken();
break;
case TDS_ENVCHANGE_TOKEN:
tdsEnvChangeToken();
break;
case TDS_MSG50_TOKEN:
tds5ErrorToken();
break;
case TDS5_DYNAMIC_TOKEN:
tds5DynamicToken();
break;
case TDS5_PARAMFMT_TOKEN:
tds5ParamFmtToken();
break;
case TDS_AUTH_TOKEN:
tdsNtlmAuthToken();
break;
case TDS_RESULT_TOKEN:
tds5ResultToken();
break;
case TDS_DONE_TOKEN:
case TDS_DONEPROC_TOKEN:
case TDS_DONEINPROC_TOKEN:
tdsDoneToken();
break;
default:
throw new ProtocolException(
"Invalid packet type 0x" +
Integer.toHexString((int) currentToken.token & 0xFF));
}
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
} catch (ProtocolException pe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.tdserror", pe.getMessage()),
"08S01"), pe);
} catch (OutOfMemoryError err) {
// Consume the rest of the response
in.skipToEnd();
endOfResponse = true;
endOfResults = true;
cancelPending = false;
throw err;
}
}
/**
* Report unsupported TDS token in input stream.
*
* @throws IOException
*/
private void tdsInvalidToken()
throws IOException, ProtocolException
{
in.skip(in.readShort());
throw new ProtocolException("Unsupported TDS token: 0x" +
Integer.toHexString((int) currentToken.token & 0xFF));
}
/**
* Process TDS 5 Sybase 12+ Dynamic results parameter descriptor.
* <p>When returning output parameters this token will be followed
* by a TDS5_PARAMS_TOKEN with the actual data.
* @throws IOException
* @throws ProtocolException
*/
private void tds5ParamFmt2Token() throws IOException, ProtocolException {
in.readInt(); // Packet length
int paramCnt = in.readShort();
ColInfo[] params = new ColInfo[paramCnt];
for (int i = 0; i < paramCnt; i++) {
// Get the parameter details using the
// ColInfo class as the server format is the same.
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
int column_flags = in.readInt(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
params[i] = col;
}
currentToken.dynamParamInfo = params;
currentToken.dynamParamData = new Object[paramCnt];
}
/**
* Process Sybase 12+ wide result token which provides enhanced
* column meta data.
*
* @throws IOException
*/
private void tds5WideResultToken()
throws IOException, ProtocolException
{
in.readInt(); // Packet length
int colCnt = in.readShort();
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int colNum = 0; colNum < colCnt; ++colNum) {
ColInfo col = new ColInfo();
// Get the alias name
int nameLen = in.read();
col.name = in.readNonUnicodeString(nameLen);
// Get the catalog name
nameLen = in.read();
col.catalog = in.readNonUnicodeString(nameLen);
// Get the schema name
nameLen = in.read();
col.schema = in.readNonUnicodeString(nameLen);
// Get the table name
nameLen = in.read();
col.tableName = in.readNonUnicodeString(nameLen);
// Get the column name
nameLen = in.read();
col.realName = in.readNonUnicodeString(nameLen);
if (col.name == null || col.name.length() == 0) {
col.name = col.realName;
}
int column_flags = in.readInt(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
columns[colNum] = col;
}
endOfResults = false;
}
/**
* Process stored procedure return status token.
*
* @throws IOException
*/
private void tdsReturnStatusToken() throws IOException, SQLException {
returnStatus = new Integer(in.readInt());
if (this.returnParam != null) {
returnParam.setOutValue(Support.convert(this.connection,
returnStatus,
returnParam.jdbcType,
connection.getCharset()));
}
}
/**
* Process procedure ID token.
* <p>
* Used by DBLIB to obtain the object id of a stored procedure.
*/
private void tdsProcIdToken() throws IOException {
in.skip(8);
}
/**
* Process offsets token.
* <p>
* Used by DBLIB to return the offset of various keywords in a statement.
* This saves the client from having to parse a SQL statement. Enabled with
* <code>"set offsets from on"</code>.
*/
private void tdsOffsetsToken() throws IOException {
/*int keyword =*/ in.read();
/*int unknown =*/ in.read();
/*int offset =*/ in.readShort();
}
/**
* Process a TDS 7.0 result set token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds7ResultToken()
throws IOException, ProtocolException, SQLException {
endOfResults = false;
int colCnt = in.readShort();
if (colCnt < 0) {
// Short packet returned by TDS8 when the column meta data is
// supressed on cursor fetch etc.
// NB. With TDS7 no result set packet is returned at all.
return;
}
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int i = 0; i < colCnt; i++) {
ColInfo col = new ColInfo();
col.userType = in.readShort();
int flags = in.readShort();
col.nullable = ((flags & 0x01) != 0) ?
ResultSetMetaData.columnNullable :
ResultSetMetaData.columnNoNulls;
col.isCaseSensitive = (flags & 0X02) != 0;
col.isIdentity = (flags & 0x10) != 0;
col.isWriteable = (flags & 0x0C) != 0;
TdsData.readType(in, col);
// Set the charsetInfo field of col
if (tdsVersion >= Driver.TDS80 && col.collation != null) {
TdsData.setColumnCharset(col, connection);
}
int clen = in.read();
col.realName = in.readUnicodeString(clen);
col.name = col.realName;
this.columns[i] = col;
}
}
/**
* Process a TDS 4.2 column names token.
* <p>
* Note: Will be followed by a COL_FMT token.
*
* @throws IOException
*/
private void tds4ColNamesToken() throws IOException {
ArrayList colList = new ArrayList();
final int pktLen = in.readShort();
this.tables = null;
int bytesRead = 0;
while (bytesRead < pktLen) {
ColInfo col = new ColInfo();
int nameLen = in.read();
String name = in.readNonUnicodeString(nameLen);
bytesRead = bytesRead + 1 + nameLen;
col.realName = name;
col.name = name;
colList.add(col);
}
int colCnt = colList.size();
this.columns = (ColInfo[]) colList.toArray(new ColInfo[colCnt]);
this.rowData = new Object[colCnt];
}
/**
* Process a TDS 4.2 column format token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds4ColFormatToken()
throws IOException, ProtocolException {
final int pktLen = in.readShort();
int bytesRead = 0;
int numColumns = 0;
while (bytesRead < pktLen) {
if (numColumns > columns.length) {
throw new ProtocolException("Too many columns in TDS_COL_FMT packet");
}
ColInfo col = columns[numColumns];
if (serverType == Driver.SQLSERVER) {
col.userType = in.readShort();
int flags = in.readShort();
col.nullable = ((flags & 0x01) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isCaseSensitive = (flags & 0x02) != 0;
col.isWriteable = (flags & 0x0C) != 0;
col.isIdentity = (flags & 0x10) != 0;
} else {
// Sybase does not send column flags
col.isCaseSensitive = false;
col.isWriteable = true;
if (col.nullable == ResultSetMetaData.columnNoNulls) {
col.nullable = ResultSetMetaData.columnNullableUnknown;
}
col.userType = in.readInt();
}
bytesRead += 4;
bytesRead += TdsData.readType(in, col);
numColumns++;
}
if (numColumns != columns.length) {
throw new ProtocolException("Too few columns in TDS_COL_FMT packet");
}
endOfResults = false;
}
/**
* Process a table name token.
* <p> Sent by select for browse or cursor functions.
*
* @throws IOException
*/
private void tdsTableNameToken() throws IOException, ProtocolException {
final int pktLen = in.readShort();
int bytesRead = 0;
ArrayList tableList = new ArrayList();
while (bytesRead < pktLen) {
int nameLen;
String tabName;
TableMetaData table;
if (tdsVersion >= Driver.TDS81) {
// TDS8.1 supplies the server.database.owner.table as up to
// four separate components which allows us to have names
// with embedded periods.
table = new TableMetaData();
bytesRead++;
int tableNameToken = in.read();
switch (tableNameToken) {
case 4: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
// Read and discard server name; see Bug 1403067
in.readUnicodeString(nameLen);
case 3: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.catalog = in.readUnicodeString(nameLen);
case 2: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.schema = in.readUnicodeString(nameLen);
case 1: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.name = in.readUnicodeString(nameLen);
case 0: break;
default:
throw new ProtocolException("Invalid table TAB_NAME_TOKEN: "
+ tableNameToken);
}
} else {
if (tdsVersion >= Driver.TDS70) {
nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
tabName = in.readUnicodeString(nameLen);
} else {
// TDS 4.2 or TDS 5.0
nameLen = in.read();
bytesRead++;
if (nameLen == 0) {
continue; // Sybase/SQL 6.5 use a zero length name to terminate list
}
tabName = in.readNonUnicodeString(nameLen);
bytesRead += nameLen;
}
table = new TableMetaData();
// tabName can be a fully qualified name
int dotPos = tabName.lastIndexOf('.');
if (dotPos > 0) {
table.name = tabName.substring(dotPos + 1);
int nextPos = tabName.lastIndexOf('.', dotPos-1);
if (nextPos + 1 < dotPos) {
table.schema = tabName.substring(nextPos + 1, dotPos);
}
dotPos = nextPos;
nextPos = tabName.lastIndexOf('.', dotPos-1);
if (nextPos + 1 < dotPos) {
table.catalog = tabName.substring(nextPos + 1, dotPos);
}
} else {
table.name = tabName;
}
}
tableList.add(table);
}
if (tableList.size() > 0) {
this.tables = (TableMetaData[]) tableList.toArray(new TableMetaData[tableList.size()]);
}
}
/**
* Process a column infomation token.
* <p>Sent by select for browse or cursor functions.
* @throws IOException
* @throws ProtocolException
*/
private void tdsColumnInfoToken()
throws IOException, ProtocolException
{
final int pktLen = in.readShort();
int bytesRead = 0;
int columnIndex = 0;
while (bytesRead < pktLen) {
// Seems like all columns are always returned in the COL_INFO
// packet and there might be more than 255 columns, so we'll
// just increment a counter instead.
// Ignore the column index.
in.read();
if (columnIndex >= columns.length) {
throw new ProtocolException("Column index " + (columnIndex + 1) +
" invalid in TDS_COLINFO packet");
}
ColInfo col = columns[columnIndex++];
int tableIndex = in.read();
// In some cases (e.g. if the user calls 'CREATE CURSOR'), the
// TDS_TABNAME packet seems to be missing although the table index
// in this packet is > 0. Weird.
// If tables are available check for valid table index.
if (tables != null && tableIndex > tables.length) {
throw new ProtocolException("Table index " + tableIndex +
" invalid in TDS_COLINFO packet");
}
byte flags = (byte)in.read(); // flags
bytesRead += 3;
if (tableIndex != 0 && tables != null) {
TableMetaData table = tables[tableIndex-1];
col.catalog = table.catalog;
col.schema = table.schema;
col.tableName = table.name;
}
col.isKey = (flags & 0x08) != 0;
col.isHidden = (flags & 0x10) != 0;
// If bit 5 is set, we have a column name
if ((flags & 0x20) != 0) {
final int nameLen = in.read();
bytesRead += 1;
final String colName = in.readString(nameLen);
bytesRead += (tdsVersion >= Driver.TDS70) ? nameLen * 2 : nameLen;
col.realName = colName;
}
}
}
/**
* Process an order by token.
* <p>Sent to describe columns in an order by clause.
* @throws IOException
*/
private void tdsOrderByToken()
throws IOException
{
// Skip this packet type
int pktLen = in.readShort();
in.skip(pktLen);
}
/**
* Process a TD4/TDS7 error or informational message.
*
* @throws IOException
*/
private void tdsErrorToken()
throws IOException
{
int pktLen = in.readShort(); // Packet length
int sizeSoFar = 6;
int number = in.readInt();
int state = in.read();
int severity = in.read();
int msgLen = in.readShort();
String message = in.readString(msgLen);
sizeSoFar += 2 + ((tdsVersion >= Driver.TDS70) ? msgLen * 2 : msgLen);
final int srvNameLen = in.read();
String server = in.readString(srvNameLen);
sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70) ? srvNameLen * 2 : srvNameLen);
final int procNameLen = in.read();
String procName = in.readString(procNameLen);
sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70) ? procNameLen * 2 : procNameLen);
int line = in.readShort();
sizeSoFar += 2;
// Skip any EED information to read rest of packet
if (pktLen - sizeSoFar > 0)
in.skip(pktLen - sizeSoFar);
if (currentToken.token == TDS_ERROR_TOKEN)
{
if (severity < 10) {
severity = 11; // Ensure treated as error
}
if (severity >= 20) {
// A fatal error has occured, the connection will be closed by
// the server immediately after the last TDS_DONE packet
fatalError = true;
}
} else {
if (severity > 9) {
severity = 9; // Ensure treated as warning
}
}
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
}
/**
* Process output parameters.
* </p>
* Normally the output parameters are preceded by a TDS type 79
* (procedure return value) record; however there are at least two
* situations with TDS version 8 where this is not the case:
* <ol>
* <li>For the return value of a SQL 2000+ user defined function.</li>
* <li>For a remote procedure call (server.database.user.procname) where
* the 79 record is only sent if a result set is also returned by the remote
* procedure. In this case the 79 record just acts as marker for the start of
* the output parameters. The actual return value is in an output param token.</li>
* </ol>
* Output parameters are distinguished from procedure return values by the value of
* a byte that immediately follows the parameter name. A value of 1 seems to indicate
* a normal output parameter while a value of 2 indicates a procedure return value.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsOutputParamToken()
throws IOException, ProtocolException, SQLException {
in.readShort(); // Packet length
String name = in.readString(in.read()); // Column Name
// Next byte indicates if output parameter or return value
// 1 = normal output param, 2 = function or stored proc return
boolean funcReturnVal = (in.read() == 2);
// Next byte is the parameter type that we supplied which
// may not be the same as the parameter definition
/* int inputTdsType = */ in.read();
// Not sure what these bytes are (they always seem to be zero).
in.skip(3);
ColInfo col = new ColInfo();
TdsData.readType(in, col);
// Set the charsetInfo field of col
if (tdsVersion >= Driver.TDS80 && col.collation != null) {
TdsData.setColumnCharset(col, connection);
}
Object value = TdsData.readData(connection, in, col);
// Real output parameters will either be unnamed or will have a valid
// parameter name beginning with '@'. Ignore any other spurious parameters
// such as those returned from calls to writetext in the proc.
if (parameters != null
&& (name.length() == 0 || name.startsWith("@"))) {
if (tdsVersion >= Driver.TDS80 && funcReturnVal) {
// TDS 8 Allows function return values of types other than int
// Also used to for return value of remote procedure calls.
if (returnParam != null) {
if (value != null) {
returnParam.setOutValue(
Support.convert(connection, value,
returnParam.jdbcType,
connection.getCharset()));
returnParam.collation = col.collation;
returnParam.charsetInfo = col.charsetInfo;
} else {
returnParam.setOutValue(null);
}
}
} else {
// Look for next output parameter in list
while (++nextParam < parameters.length) {
if (parameters[nextParam].isOutput) {
if (value != null) {
parameters[nextParam].setOutValue(
Support.convert(connection, value,
parameters[nextParam].jdbcType,
connection.getCharset()));
parameters[nextParam].collation = col.collation;
parameters[nextParam].charsetInfo = col.charsetInfo;
} else {
parameters[nextParam].setOutValue(null);
}
break;
}
}
}
}
}
/**
* Process a login acknowledgement packet.
*
* @throws IOException
*/
private void tdsLoginAckToken() throws IOException {
String product;
int major, minor, build = 0;
in.readShort(); // Packet length
int ack = in.read(); // Ack TDS 5 = 5 for OK 6 for fail, 1/0 for the others
// Update the TDS protocol version in this TdsCore and in the Socket.
// The Connection will update itself immediately after this call.
// As for other objects containing a TDS version value, there are none
// at this point (we're just constructing the Connection).
tdsVersion = TdsData.getTdsVersion(((int) in.read() << 24) | ((int) in.read() << 16)
| ((int) in.read() << 8) | (int) in.read());
socket.setTdsVersion(tdsVersion);
product = in.readString(in.read());
if (tdsVersion >= Driver.TDS70) {
major = in.read();
minor = in.read();
build = in.read() << 8;
build += in.read();
} else {
if (product.toLowerCase().startsWith("microsoft")) {
in.skip(1);
major = in.read();
minor = in.read();
} else {
major = in.read();
minor = in.read() * 10;
minor += in.read();
}
in.skip(1);
}
if (product.length() > 1 && -1 != product.indexOf('\0')) {
product = product.substring(0, product.indexOf('\0'));
}
connection.setDBServerInfo(product, major, minor, build);
if (tdsVersion == Driver.TDS50 && ack != 5) {
// Login rejected by server create SQLException
messages.addDiagnostic(4002, 0, 14,
"Login failed", "", "", 0);
currentToken.token = TDS_ERROR_TOKEN;
} else {
// MJH 2005-11-02
// If we get this far we are logged in OK so convert
// any exceptions into warnings. Any exceptions are
// likely to be caused by problems in accessing the
// default database for this login id for SQL 6.5 and
// Sybase ASE. SQL 7.0+ will fail to login if there is
// no access to the default or specified database.
// I am not convinced that this is a good idea but it
// appears that other drivers e.g. jConnect do this and
// return the exceptions on the connection warning chain.
SQLException ex = messages.exceptions;
// Avoid returning useless warnings about language
// character set etc.
messages.clearWarnings();
// Convert exceptions to warnings
while (ex != null) {
messages.addWarning(new SQLWarning(ex.getMessage(),
ex.getSQLState(),
ex.getErrorCode()));
ex = ex.getNextException();
}
messages.exceptions = null;
}
}
/**
* Process a control token (function unknown).
*
* @throws IOException
*/
private void tdsControlToken() throws IOException {
int pktLen = in.readShort();
in.skip(pktLen);
}
/**
* Process a row data token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsRowToken() throws IOException, ProtocolException {
for (int i = 0; i < columns.length; i++) {
rowData[i] = TdsData.readData(connection, in, columns[i]);
}
endOfResults = false;
}
/**
* Process TDS 5.0 Params Token.
* Stored procedure output parameters or data returned in parameter format
* after a TDS Dynamic packet or as extended error information.
* <p>The type of the preceding token is inspected to determine if this packet
* contains output parameter result data. A TDS5_PARAMFMT2_TOKEN is sent before
* this one in Sybase 12 to introduce output parameter results.
* A TDS5_PARAMFMT_TOKEN is sent before this one to introduce extended error
* information.
*
* @throws IOException
*/
private void tds5ParamsToken() throws IOException, ProtocolException, SQLException {
if (currentToken.dynamParamInfo == null) {
throw new ProtocolException(
"TDS 5 Param results token (0xD7) not preceded by param format (0xEC or 0X20).");
}
for (int i = 0; i < currentToken.dynamParamData.length; i++) {
currentToken.dynamParamData[i] =
TdsData.readData(connection, in, currentToken.dynamParamInfo[i]);
String name = currentToken.dynamParamInfo[i].realName;
// Real output parameters will either be unnamed or will have a valid
// parameter name beginning with '@'. Ignore any other Spurious parameters
// such as those returned from calls to writetext in the proc.
if (parameters != null
&& (name.length() == 0 || name.startsWith("@"))) {
// Sybase 12+ this token used to set output parameter results
while (++nextParam < parameters.length) {
if (parameters[nextParam].isOutput) {
Object value = currentToken.dynamParamData[i];
if (value != null) {
parameters[nextParam].setOutValue(
Support.convert(connection, value,
parameters[nextParam].jdbcType,
connection.getCharset()));
} else {
parameters[nextParam].setOutValue(null);
}
break;
}
}
}
}
}
/**
* Processes a TDS 5.0 capability token.
* <p>
* Sent after login to describe the server's capabilities.
*
* @throws IOException if an I/O error occurs
*/
private void tdsCapabilityToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
if (in.read() != 1) {
throw new ProtocolException("TDS_CAPABILITY: expected request string");
}
int capLen = in.read();
if (capLen != 11 && capLen != 0) {
throw new ProtocolException("TDS_CAPABILITY: byte count not 11");
}
byte capRequest[] = new byte[11];
if (capLen == 0) {
Logger.println("TDS_CAPABILITY: Invalid request length");
} else {
in.read(capRequest);
}
if (in.read() != 2) {
throw new ProtocolException("TDS_CAPABILITY: expected response string");
}
capLen = in.read();
if (capLen != 10 && capLen != 0) {
throw new ProtocolException("TDS_CAPABILITY: byte count not 10");
}
byte capResponse[] = new byte[10];
if (capLen == 0) {
Logger.println("TDS_CAPABILITY: Invalid response length");
} else {
in.read(capResponse);
}
// Request capabilities
// jTDS sends 01 0B 4F FF 85 EE EF 65 7F FF FF FF D6
// Sybase 11.92 01 0A 00 00 00 23 61 41 CF FF FF C6
// Sybase 12.52 01 0A 03 84 0A E3 61 41 FF FF FF C6
// Sybase 15.00 01 0B 4F F7 85 EA EB 61 7F FF FF FF C6
// Response capabilities
// jTDS sends 02 0A 00 00 04 06 80 06 48 00 00 00
// Sybase 11.92 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 12.52 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 15.00 02 0A 00 00 04 00 00 06 00 00 00 00
// Now set the correct attributes for this connection.
// See the CT_LIB documentation for details on the bit
// positions.
int capMask = 0;
if ((capRequest[0] & 0x02) == 0x02) {
capMask |= SYB_UNITEXT;
}
if ((capRequest[1] & 0x03) == 0x03) {
capMask |= SYB_DATETIME;
}
if ((capRequest[2] & 0x80) == 0x80) {
capMask |= SYB_UNICODE;
}
if ((capRequest[3] & 0x02) == 0x02) {
capMask |= SYB_EXTCOLINFO;
}
if ((capRequest[2] & 0x01) == 0x01) {
capMask |= SYB_BIGINT;
}
if ((capRequest[4] & 0x04) == 0x04) {
capMask |= SYB_BITNULL;
}
if ((capRequest[7] & 0x30) == 0x30) {
capMask |= SYB_LONGDATA;
}
connection.setSybaseInfo(capMask);
}
/**
* Process an environment change packet.
*
* @throws IOException
* @throws SQLException
*/
private void tdsEnvChangeToken()
throws IOException, SQLException
{
int len = in.readShort();
int type = in.read();
switch (type) {
case TDS_ENV_DATABASE:
{
int clen = in.read();
final String newDb = in.readString(clen);
clen = in.read();
final String oldDb = in.readString(clen);
connection.setDatabase(newDb, oldDb);
break;
}
case TDS_ENV_LANG:
{
int clen = in.read();
String language = in.readString(clen);
clen = in.read();
String oldLang = in.readString(clen);
if (Logger.isActive()) {
Logger.println("Language changed from " + oldLang + " to " + language);
}
break;
}
case TDS_ENV_CHARSET:
{
final int clen = in.read();
final String charset = in.readString(clen);
if (tdsVersion >= Driver.TDS70) {
in.skip(len - 2 - clen * 2);
} else {
in.skip(len - 2 - clen);
}
connection.setServerCharset(charset);
break;
}
case TDS_ENV_PACKSIZE:
{
final int blocksize;
final int clen = in.read();
blocksize = Integer.parseInt(in.readString(clen));
if (tdsVersion >= Driver.TDS70) {
in.skip(len - 2 - clen * 2);
} else {
in.skip(len - 2 - clen);
}
this.connection.setNetPacketSize(blocksize);
out.setBufferSize(blocksize);
if (Logger.isActive()) {
Logger.println("Changed blocksize to " + blocksize);
}
}
break;
case TDS_ENV_LCID:
// Only sent by TDS 7
// In TDS 8 replaced by column specific collation info.
// TODO Make use of this for character set conversions?
in.skip(len - 1);
break;
case TDS_ENV_SQLCOLLATION:
{
int clen = in.read();
byte collation[] = new byte[5];
if (clen == 5) {
in.read(collation);
connection.setCollation(collation);
} else {
in.skip(clen);
}
clen = in.read();
in.skip(clen);
break;
}
default:
{
if (Logger.isActive()) {
Logger.println("Unknown environment change type 0x" +
Integer.toHexString(type));
}
in.skip(len - 1);
break;
}
}
}
/**
* Process a TDS 5 error or informational message.
*
* @throws IOException
*/
private void tds5ErrorToken() throws IOException {
int pktLen = in.readShort(); // Packet length
int sizeSoFar = 6;
int number = in.readInt();
int state = in.read();
int severity = in.read();
// Discard text state
int stateLen = in.read();
in.readNonUnicodeString(stateLen);
in.read(); // == 1 if extended error data follows
// Discard status and transaction state
in.readShort();
sizeSoFar += 4 + stateLen;
int msgLen = in.readShort();
String message = in.readNonUnicodeString(msgLen);
sizeSoFar += 2 + msgLen;
final int srvNameLen = in.read();
String server = in.readNonUnicodeString(srvNameLen);
sizeSoFar += 1 + srvNameLen;
final int procNameLen = in.read();
String procName = in.readNonUnicodeString(procNameLen);
sizeSoFar += 1 + procNameLen;
int line = in.readShort();
sizeSoFar += 2;
// Skip any EED information to read rest of packet
if (pktLen - sizeSoFar > 0)
in.skip(pktLen - sizeSoFar);
if (severity > 10)
{
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
} else {
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
}
}
/**
* Process TDS5 dynamic SQL aknowledgements.
*
* @throws IOException
*/
private void tds5DynamicToken()
throws IOException
{
int pktLen = in.readShort();
byte type = (byte)in.read();
/*byte status = (byte)*/in.read();
pktLen -= 2;
if (type == (byte)0x20) {
// Only handle aknowledgements for now
int len = in.read();
in.skip(len);
pktLen -= len+1;
}
in.skip(pktLen);
}
/**
* Process TDS 5 Dynamic results parameter descriptors.
* <p>
* With Sybase 12+ this has been superseded by the TDS5_PARAMFMT2_TOKEN
* except when used to return extended error information.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds5ParamFmtToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
int paramCnt = in.readShort();
ColInfo[] params = new ColInfo[paramCnt];
for (int i = 0; i < paramCnt; i++) {
// Get the parameter details using the
// ColInfo class as the server format is the same.
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
int column_flags = in.read(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
if ((byte)in.peek() == TDS_DONE_TOKEN) {
// Sybase 11.92 bug data type missing!
currentToken.dynamParamInfo = null;
currentToken.dynamParamData = null;
// error trapped in sybasePrepare();
messages.addDiagnostic(9999, 0, 16,
"Prepare failed", "", "", 0);
return; // Give up
}
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
params[i] = col;
}
currentToken.dynamParamInfo = params;
currentToken.dynamParamData = new Object[paramCnt];
}
/**
* Process a NTLM Authentication challenge.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsNtlmAuthToken()
throws IOException, ProtocolException
{
int pktLen = in.readShort(); // Packet length
int hdrLen = 40;
if (pktLen < hdrLen)
throw new ProtocolException("NTLM challenge: packet is too small:" + pktLen);
byte[] ntlmMessage = new byte[pktLen];
in.read(ntlmMessage);
final int seq = getIntFromBuffer(ntlmMessage, 8);
if (seq != 2)
throw new ProtocolException("NTLM challenge: got unexpected sequence number:" + seq);
final int flags = getIntFromBuffer( ntlmMessage, 20 );
//NOTE: the context is always included; if not local, then it is just
// set to all zeros.
//boolean hasContext = ((flags & 0x4000) != 0);
//final boolean hasContext = true;
//NOTE: even if target is omitted, the length will be zero.
//final boolean hasTarget = ((flags & 0x800000) != 0);
//extract the target, if present. This will be used for ntlmv2 auth.
final int headerOffset = 40; // The assumes the context is always there, which appears to be the case.
//header has: 2 byte lenght, 2 byte allocated space, and four-byte offset.
int size = getShortFromBuffer( ntlmMessage, headerOffset);
int offset = getIntFromBuffer( ntlmMessage, headerOffset + 4);
currentToken.ntlmTarget = new byte[size];
System.arraycopy(ntlmMessage, offset, currentToken.ntlmTarget, 0, size);
currentToken.nonce = new byte[8];
currentToken.ntlmMessage = ntlmMessage;
System.arraycopy(ntlmMessage, 24, currentToken.nonce, 0, 8);
}
private static int getIntFromBuffer(byte[] buf, int offset)
{
int b1 = ((int) buf[offset] & 0xff);
int b2 = ((int) buf[offset+1] & 0xff) << 8;
int b3 = ((int) buf[offset+2] & 0xff) << 16;
int b4 = ((int) buf[offset+3] & 0xff) << 24;
return b4 | b3 | b2 | b1;
}
private static int getShortFromBuffer(byte[] buf, int offset)
{
int b1 = ((int) buf[offset] & 0xff);
int b2 = ((int) buf[offset+1] & 0xff) << 8;
return b2 | b1;
}
/**
* Process a TDS 5.0 result set packet.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds5ResultToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
int colCnt = in.readShort();
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int colNum = 0; colNum < colCnt; ++colNum) {
// Get the column name
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
col.name = col.realName;
int column_flags = in.read(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
columns[colNum] = col;
}
endOfResults = false;
}
/**
* Process a DONE, DONEINPROC or DONEPROC token.
*
* @throws IOException
*/
private void tdsDoneToken() throws IOException {
currentToken.status = (byte)in.read();
in.skip(1);
currentToken.operation = (byte)in.read();
in.skip(1);
currentToken.updateCount = in.readInt();
if (!endOfResults) {
// This will eliminate the select row count for sybase
currentToken.status &= ~DONE_ROW_COUNT;
endOfResults = true;
}
// Check for cancel ack
if ((currentToken.status & DONE_CANCEL) != 0) {
// Synchronize resetting of the cancelPending flag to ensure it
// doesn't happen during the sending of a cancel request
synchronized (cancelMonitor) {
cancelPending = false;
// Only throw an exception if this was a cancel() call
if (cancelMonitor[0] == ASYNC_CANCEL) {
messages.addException(
new SQLException(Messages.get("error.generic.cancelled",
"Statement"),
"HY008"));
}
}
}
if ((currentToken.status & DONE_MORE_RESULTS) == 0) {
// There are no more results or pending cancel packets
// to process.
endOfResponse = !cancelPending;
if (fatalError) {
// A fatal error has occured, the server has closed the
// connection
connection.setClosed();
}
}
if (serverType == Driver.SQLSERVER) {
// MS SQL Server provides additional information we
// can use to return special row counts for DDL etc.
if (currentToken.operation == (byte) 0xC1) {
currentToken.status &= ~DONE_ROW_COUNT;
}
}
}
/**
* Execute SQL using TDS 4.2 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or null.
* @param parameters Parameters for call or null.
* @param noMetaData Suppress meta data for cursor calls.
* @throws SQLException
*/
private void executeSQL42(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws IOException, SQLException {
if (procName != null) {
// RPC call
out.setPacketType(RPC_PKT);
byte[] buf = Support.encodeString(connection.getCharset(), procName);
out.write((byte) buf.length);
out.write(buf);
out.write((short) (noMetaData ? 2 : 0));
if (parameters != null) {
for (int i = nextParam + 1; i < parameters.length; i++) {
if (parameters[i].name != null) {
buf = Support.encodeString(connection.getCharset(),
parameters[i].name);
out.write((byte) buf.length);
out.write(buf);
} else {
out.write((byte) 0);
}
out.write((byte) (parameters[i].isOutput ? 1 : 0));
TdsData.writeParam(out,
connection.getCharsetInfo(),
null,
parameters[i]);
}
}
if (!sendNow) {
// Send end of packet byte to batch RPC
out.write((byte) DONE_END_OF_RESPONSE);
}
} else if (sql.length() > 0) {
if (parameters != null) {
sql = Support.substituteParameters(sql, parameters, connection);
}
out.setPacketType(QUERY_PKT);
out.write(sql);
if (!sendNow) {
// Batch SQL statements
out.write(" ");
}
}
}
/**
* Execute SQL using TDS 5.0 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or null.
* @param parameters Parameters for call or null.
* @throws SQLException
*/
private void executeSQL50(String sql,
String procName,
ParamInfo[] parameters)
throws IOException, SQLException {
boolean haveParams = parameters != null;
boolean useParamNames = false;
currentToken.dynamParamInfo = null;
currentToken.dynamParamData = null;
// Sybase does not allow text or image parameters as parameters
// to statements or stored procedures. With Sybase 12.5 it is
// possible to use a new TDS data type to send long data as
// parameters to statements (but not procedures). This usage
// replaces the writetext command that had to be used in the past.
// As we do not support writetext, with older versions of Sybase
// we just give up and embed all text/image data in the SQL statement.
for (int i = 0; haveParams && i < parameters.length; i++) {
if (parameters[i].sqlType.equals("text")
|| parameters[i].sqlType.equals("image")
|| parameters[i].sqlType.equals("unitext")) {
if (procName != null && procName.length() > 0) {
// Call to store proc nothing we can do
if (parameters[i].sqlType.equals("text")
|| parameters[i].sqlType.equals("unitext")) {
throw new SQLException(
Messages.get("error.chartoolong"), "HY000");
}
throw new SQLException(
Messages.get("error.bintoolong"), "HY000");
}
if (parameters[i].tdsType != TdsData.SYBLONGDATA) {
// prepared statement substitute parameters into SQL
sql = Support.substituteParameters(sql, parameters, connection);
haveParams = false;
procName = null;
break;
}
}
}
out.setPacketType(SYBQUERY_PKT);
if (procName == null) {
// Use TDS_LANGUAGE TOKEN with optional parameters
out.write((byte)TDS_LANG_TOKEN);
if (haveParams) {
sql = Support.substituteParamMarkers(sql, parameters);
}
if (connection.isWideChar()) {
// Need to preconvert string to get correct length
byte[] buf = Support.encodeString(connection.getCharset(), sql);
out.write((int) buf.length + 1);
out.write((byte)(haveParams ? 1 : 0));
out.write(buf);
} else {
out.write((int) sql.length() + 1);
out.write((byte) (haveParams ? 1 : 0));
out.write(sql);
}
} else if (procName.startsWith("#jtds")) {
// Dynamic light weight procedure call
out.write((byte) TDS5_DYNAMIC_TOKEN);
out.write((short) (procName.length() + 4));
out.write((byte) 2);
out.write((byte) (haveParams ? 1 : 0));
out.write((byte) (procName.length() - 1));
out.write(procName.substring(1));
out.write((short) 0);
} else {
byte buf[] = Support.encodeString(connection.getCharset(), procName);
// RPC call
out.write((byte) TDS_DBRPC_TOKEN);
out.write((short) (buf.length + 3));
out.write((byte) buf.length);
out.write(buf);
out.write((short) (haveParams ? 2 : 0));
useParamNames = true;
}
// Output any parameters
if (haveParams) {
// First write parameter descriptors
out.write((byte) TDS5_PARAMFMT_TOKEN);
int len = 2;
for (int i = nextParam + 1; i < parameters.length; i++) {
len += TdsData.getTds5ParamSize(connection.getCharset(),
connection.isWideChar(),
parameters[i],
useParamNames);
}
out.write((short) len);
out.write((short) ((nextParam < 0) ? parameters.length : parameters.length - 1));
for (int i = nextParam + 1; i < parameters.length; i++) {
TdsData.writeTds5ParamFmt(out,
connection.getCharset(),
connection.isWideChar(),
parameters[i],
useParamNames);
}
// Now write the actual data
out.write((byte) TDS5_PARAMS_TOKEN);
for (int i = nextParam + 1; i < parameters.length; i++) {
TdsData.writeTds5Param(out,
connection.getCharsetInfo(),
parameters[i]);
}
}
}
/**
* Returns <code>true</code> if the specified <code>procName</code>
* is a sp_prepare or sp_prepexec handle; returns <code>false</code>
* otherwise.
*
* @param procName Stored procedure to execute or <code>null</code>.
* @return <code>true</code> if the specified <code>procName</code>
* is a sp_prepare or sp_prepexec handle; <code>false</code>
* otherwise.
*/
public static boolean isPreparedProcedureName(final String procName) {
return procName != null && procName.length() > 0
&& Character.isDigit(procName.charAt(0));
}
/**
* Execute SQL using TDS 7.0 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or <code>null</code>.
* @param parameters Parameters for call or <code>null</code>.
* @param noMetaData Suppress meta data for cursor calls.
* @throws SQLException
*/
private void executeSQL70(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws IOException, SQLException {
int prepareSql = connection.getPrepareSql();
if (parameters == null && prepareSql == EXECUTE_SQL) {
// Downgrade EXECUTE_SQL to UNPREPARED
// if there are no parameters.
// Should we downgrade TEMPORARY_STORED_PROCEDURES and PREPARE as well?
// No it may be a complex select with no parameters but costly to
// evaluate for each execution.
prepareSql = UNPREPARED;
}
if (inBatch) {
// For batch execution with parameters
// we need to be consistant and use
// execute SQL
prepareSql = EXECUTE_SQL;
}
if (procName == null) {
// No procedure name so not a callable statement and also
// not a temporary stored procedure call.
if (parameters != null) {
if (prepareSql == TdsCore.UNPREPARED) {
// Low tech approach just substitute parameter data into the
// SQL statement.
sql = Support.substituteParameters(sql, parameters, connection);
} else {
// If we have parameters then we need to use sp_executesql to
// parameterise the statement unless the user has specified
ParamInfo[] params;
params = new ParamInfo[2 + parameters.length];
System.arraycopy(parameters, 0, params, 2, parameters.length);
params[0] = new ParamInfo(Types.LONGVARCHAR,
Support.substituteParamMarkers(sql, parameters),
ParamInfo.UNICODE);
TdsData.getNativeType(connection, params[0]);
params[1] = new ParamInfo(Types.LONGVARCHAR,
Support.getParameterDefinitions(parameters),
ParamInfo.UNICODE);
TdsData.getNativeType(connection, params[1]);
parameters = params;
// Use sp_executesql approach
procName = "sp_executesql";
}
}
} else {
// Either a stored procedure name has been supplied or this
// statement should executed using a prepared statement handle
if (isPreparedProcedureName(procName)) {
// If the procedure is a prepared handle then redefine the
// procedure name as sp_execute with the handle as a parameter.
ParamInfo params[];
if (parameters != null) {
params = new ParamInfo[1 + parameters.length];
System.arraycopy(parameters, 0, params, 1, parameters.length);
} else {
params = new ParamInfo[1];
}
params[0] = new ParamInfo(Types.INTEGER, new Integer(procName),
ParamInfo.INPUT);
TdsData.getNativeType(connection, params[0]);
parameters = params;
// Use sp_execute approach
procName = "sp_execute";
}
}
if (procName != null) {
// RPC call
out.setPacketType(RPC_PKT);
Integer shortcut;
if (tdsVersion >= Driver.TDS80
&& (shortcut = (Integer) tds8SpNames.get(procName)) != null) {
// Use the shortcut form of procedure name for TDS8
out.write((short) -1);
out.write((short) shortcut.shortValue());
} else {
out.write((short) procName.length());
out.write(procName);
}
// If noMetaData is true then column meta data will be supressed.
// This option is used by sp_cursorfetch or optionally by sp_execute
// provided that the required meta data has been cached.
out.write((short) (noMetaData ? 2 : 0));
if (parameters != null) {
// Send the required parameter data
for (int i = nextParam + 1; i < parameters.length; i++) {
if (parameters[i].name != null) {
out.write((byte) parameters[i].name.length());
out.write(parameters[i].name);
} else {
out.write((byte) 0);
}
out.write((byte) (parameters[i].isOutput ? 1 : 0));
TdsData.writeParam(out,
connection.getCharsetInfo(),
connection.getCollation(),
parameters[i]);
}
}
if (!sendNow) {
// Append RPC packets
out.write((byte) DONE_END_OF_RESPONSE);
}
} else if (sql.length() > 0) {
// Simple SQL query with no parameters
out.setPacketType(QUERY_PKT);
out.write(sql);
if (!sendNow) {
// Append SQL packets
out.write(" ");
}
}
}
/**
* Sets the server row count (to limit the number of rows in a result set)
* and text size (to limit the size of returned TEXT/NTEXT fields).
*
* @param rowCount the number of rows to return or 0 for no limit or -1 to
* leave as is
* @param textSize the maximum number of bytes in a TEXT column to return
* or -1 to leave as is
* @throws SQLException if an error is returned by the server
*/
private void setRowCountAndTextSize(int rowCount, int textSize)
throws SQLException {
boolean newRowCount =
rowCount >= 0 && rowCount != connection.getRowCount();
boolean newTextSize =
textSize >= 0 && textSize != connection.getTextSize();
if (newRowCount || newTextSize) {
try {
StringBuffer query = new StringBuffer(64);
if (newRowCount) {
query.append("SET ROWCOUNT ").append(rowCount);
}
if (newTextSize) {
query.append(" SET TEXTSIZE ")
.append(textSize == 0 ? 2147483647 : textSize);
}
out.setPacketType(QUERY_PKT);
out.write(query.toString());
out.flush();
endOfResponse = false;
endOfResults = true;
wait(0);
clearResponseQueue();
messages.checkErrors();
// Update the values stored in the Connection
connection.setRowCount(rowCount);
connection.setTextSize(textSize);
} catch (IOException ioe) {
throw new SQLException(
Messages.get("error.generic.ioerror",
ioe.getMessage()), "08S01");
}
}
}
/**
* Waits for the first byte of the server response.
*
* @param timeOut the timeout period in seconds or 0
*/
private void wait(int timeOut) throws IOException, SQLException {
Object timer = null;
try {
if (timeOut > 0) {
// Start a query timeout timer
timer = TimerThread.getInstance().setTimer(timeOut * 1000,
new TimerThread.TimerListener() {
public void timerExpired() {
TdsCore.this.cancel(true);
}
});
}
in.peek();
} finally {
if (timer != null) {
if (!TimerThread.getInstance().cancelTimer(timer)) {
throw new SQLException(
Messages.get("error.generic.timeout"), "HYT00");
}
}
}
}
/**
* Releases parameter and result set data and metadata to free up memory.
* <p/>
* This is useful before the <code>TdsCore</code> is cached for reuse.
*/
public void cleanUp() {
if (endOfResponse) {
// Clean up parameters
returnParam = null;
parameters = null;
// Clean up result data and meta data
columns = null;
rowData = null;
tables = null;
// Clean up warnings; any exceptions will be cleared when thrown
messages.clearWarnings();
}
}
/**
* Returns the diagnostic chain for this instance.
*/
public SQLDiagnostic getMessages() {
return messages;
}
/**
* Converts a user supplied MAC address into a byte array.
*
* @param macString the MAC address as a hex string
* @return the MAC address as a <code>byte[]</code>
*/
private static byte[] getMACAddress(String macString) {
byte[] mac = new byte[6];
boolean ok = false;
if (macString != null && macString.length() == 12) {
try {
for (int i = 0, j = 0; i < 6; i++, j += 2) {
mac[i] = (byte) Integer.parseInt(
macString.substring(j, j + 2), 16);
}
ok = true;
} catch (Exception ex) {
// Ignore it. ok will be false.
}
}
if (!ok) {
Arrays.fill(mac, (byte) 0);
}
return mac;
}
/**
* Tries to figure out what client name we should identify ourselves as.
* Gets the hostname of this machine,
*
* @return name to use as the client
*/
private static String getHostName() {
if (hostName != null) {
return hostName;
}
String name;
try {
name = java.net.InetAddress.getLocalHost().getHostName().toUpperCase();
} catch (java.net.UnknownHostException e) {
hostName = "UNKNOWN";
return hostName;
}
int pos = name.indexOf('.');
if (pos >= 0) {
name = name.substring(0, pos);
}
if (name.length() == 0) {
hostName = "UNKNOWN";
return hostName;
}
try {
Integer.parseInt(name);
// All numbers probably an IP address
hostName = "UNKNOWN";
return hostName;
} catch (NumberFormatException e) {
// Bit tacky but simple check for all numbers
}
hostName = name;
return name;
}
/**
* A <B>very</B> poor man's "encryption".
*
* @param pw password to encrypt
* @return encrypted password
*/
private static String tds7CryptPass(final String pw) {
final int xormask = 0x5A5A;
final int len = pw.length();
final char[] chars = new char[len];
for (int i = 0; i < len; ++i) {
final int c = (int) (pw.charAt(i)) ^ xormask;
final int m1 = (c >> 4) & 0x0F0F;
final int m2 = (c << 4) & 0xF0F0;
chars[i] = (char) (m1 | m2);
}
return new String(chars);
}
}
|
package de.golfgl.gdxgamesvcs;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Timer;
import de.golfgl.gdxgamesvcs.achievement.IAchievement;
import de.golfgl.gdxgamesvcs.achievement.IFetchAchievementsResponseListener;
import de.golfgl.gdxgamesvcs.gamestate.IFetchGameStatesListResponseListener;
import de.golfgl.gdxgamesvcs.gamestate.ILoadGameStateResponseListener;
import de.golfgl.gdxgamesvcs.gamestate.ISaveGameStateResponseListener;
import de.golfgl.gdxgamesvcs.leaderboard.IFetchLeaderBoardEntriesResponseListener;
import de.golfgl.gdxgamesvcs.leaderboard.ILeaderBoardEntry;
/**
* This is a mock implementation of {@link IGameServiceClient}. Useful during
* development phase when you don't want to connect to an existing service but just
* test your application behavior against service responses.
*
* It emulate network latencies with a fixed sleep time, helpful to test your wait
* screen and your GUI behaviors.
*
* By default mock supports all feature, you may override {@link #isFeatureSupported(de.golfgl.gdxgamesvcs.IGameServiceClient.GameServiceFeature)}
* in order to configure your mock.
*
* Subclass implements abstract methods in order to provide mock data (game state, achievements and leaderboard entries)
*
* @author mgsx
*
*/
abstract public class MockGameServiceClient implements IGameServiceClient
{
private float latency;
private IGameServiceListener gsListener;
private volatile boolean connected, connecting;
private void sleep(final Runnable runnable) {
if (runnable != null)
Timer.schedule(new Timer.Task() {
@Override
public void run() {
runnable.run();
}
}, latency);
}
/**
* Create mock service
* @param latency time of latency in seconds for each emulated remote call.
*/
public MockGameServiceClient(float latency) {
this.latency = latency;
}
/**
* @return some fake leaderboard entries data
*/
abstract protected Array<ILeaderBoardEntry> getLeaderboardEntries();
/**
* @return some fake game states fileNames
*/
abstract protected Array<String> getGameStates();
/**
* @return fake saved game state data
*/
abstract protected byte[] getGameState();
/**
* @return fake achievements list
*/
abstract protected Array<IAchievement> getAchievements();
@Override
public String getGameServiceId() {
return "Mock";
}
@Override
public void showAchievements() throws GameServiceException {
}
@Override
public void showLeaderboards(String leaderBoardId) throws GameServiceException {
}
@Override
public boolean isFeatureSupported(GameServiceFeature feature) {
return true;
}
@Override
public void setListener(IGameServiceListener gsListener) {
this.gsListener = gsListener;
}
@Override
public boolean connect(boolean silent) {
if(!connected && !connecting){
connecting = true;
sleep(new Runnable() {
@Override
public void run() {
connecting = false;
connected = true;
if(gsListener != null) gsListener.gsConnected();
}
});
}
return connected || connecting;
}
@Override
public void disconnect() {
sleep(new Runnable() {
@Override
public void run() {
if(gsListener != null) gsListener.gsDisconnected();
}
});
}
@Override
public void logOff() {
connected = connecting = false;
disconnect();
}
@Override
public String getPlayerDisplayName() {
return connected ? getPlayerName() : null;
}
abstract protected String getPlayerName();
@Override
public boolean isConnected() {
return connected;
}
@Override
public boolean isConnectionPending() {
return connecting;
}
@Override
public boolean fetchAchievements(final IFetchAchievementsResponseListener callback) {
sleep(new Runnable() {
@Override
public void run() {
callback.onFetchAchievementsResponse(getAchievements());
}
});
return true;
}
@Override
public boolean submitToLeaderboard(String leaderboardId, long score, String tag) {
sleep(null);
return true;
}
@Override
public boolean fetchLeaderboardEntries(String leaderBoardId, int limit, boolean relatedToPlayer,
final IFetchLeaderBoardEntriesResponseListener callback) {
sleep(new Runnable() {
@Override
public void run() {
callback.onLeaderBoardResponse(getLeaderboardEntries());
}
});
return true;
}
@Override
public boolean submitEvent(String eventId, int increment) {
sleep(null);
return true;
}
@Override
public boolean unlockAchievement(String achievementId) {
sleep(null);
return true;
}
@Override
public boolean incrementAchievement(String achievementId, int incNum, float completionPercentage) {
sleep(null);
return true;
}
@Override
public void saveGameState(String fileId, byte[] gameState, long progressValue,
final ISaveGameStateResponseListener listener) {
sleep(new Runnable() {
@Override
public void run() {
if(listener != null) listener.onGameStateSaved(true, null);
}
});
}
@Override
public void loadGameState(String fileId, final ILoadGameStateResponseListener responseListener) {
sleep(new Runnable() {
@Override
public void run() {
responseListener.gsGameStateLoaded(getGameState());
}
});
}
@Override
public boolean deleteGameState(String fileId, final ISaveGameStateResponseListener success) {
sleep(new Runnable() {
@Override
public void run() {
if (success != null)
success.onGameStateSaved(true, null);
}
});
return true;
}
@Override
public boolean fetchGameStates(final IFetchGameStatesListResponseListener callback) {
sleep(new Runnable() {
@Override
public void run() {
callback.onFetchGameStatesListResponse(getGameStates());
}
});
return true;
}
}
|
package com.example;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class CustomTimePicker extends View implements AlarmTimePicker {
Context context;
int minsize;
final float grabPointOffset = 0.2f;
final float grabPointSize = 0.1f;
final float handWidth = 5f;
final double minuteIncrement = Math.PI / 30.0;
final double hourIncrement = Math.PI / 6.0;
final float hourHandLength = 0.55f;
final int maxInterval = 30;
int currentInterval = 0;
final float clockNumberSize = 50f;
float radius = 0;
float hourGrabX;
float minGrabX;
float hourGrabY;
float minGrabY;
float sliderGrabX;
float sliderGrabY;
RectF intervalBarRect;
RectF clockRect;
float midX;
float midY;
int minutes = 0;
int hours = 0;
int interval = 0;
public CustomTimePicker(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
for (int i = 0; i < attrs.getAttributeCount(); i++)
Log.i("attribute", attrs.getAttributeName(i));
this.minsize = Integer.parseInt(attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example", "minsize"));
this.minutes = Integer.parseInt(attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example", "minutes"));
this.hours = Integer.parseInt(attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example", "hours"));
updateSize();
}
protected void onDraw(Canvas c) {
drawClockface(c);
drawClockHands(c);
drawClockTime(c);
drawIntervalBar(c);
}
private void drawIntervalBar(Canvas c) {
Paint intervalBarPaint = new Paint();
intervalBarPaint.setColor(Color.BLACK);
intervalBarPaint.setStyle(Paint.Style.STROKE);
intervalBarPaint.setStrokeWidth(handWidth);
intervalBarPaint.setAntiAlias(true);
c.drawLine(intervalBarRect.left,
intervalBarRect.centerY(),
intervalBarRect.right,
intervalBarRect.centerY(),
intervalBarPaint);
sliderGrabX = intervalBarRect.left + currentInterval * intervalBarRect.width();
sliderGrabY = intervalBarRect.centerY();
c.drawCircle(sliderGrabX, sliderGrabY, radius*grabPointSize, intervalBarPaint);
}
private void drawClockTime(Canvas c) {
Paint textPaint = new Paint();
textPaint.setTextSize(intervalBarRect.height());
textPaint.setAntiAlias(true);
textPaint.setColor(Color.BLACK);
String time = timeToString(hours, minutes);
float textLength = textPaint.measureText(time);
c.drawText(time, midX - textLength / 2, midY - radius, textPaint);
}
private void drawClockHands(Canvas c) {
Paint clockHand = new Paint();
clockHand.setColor(Color.BLACK);
clockHand.setAntiAlias(true);
clockHand.setStrokeWidth(handWidth);
clockHand.setStyle(Paint.Style.STROKE);
double hxDir = Math.cos(getHourHandAngle() - Math.PI / 2);
double hyDir = Math.sin(getHourHandAngle() - Math.PI / 2);
double mxDir = Math.cos(getMinuteHandAngle() - Math.PI / 2);
double myDir = Math.sin(getMinuteHandAngle() - Math.PI / 2);
float hx = (float) hxDir * radius * hourHandLength;
float hy = (float) hyDir * radius * hourHandLength;
float mx = (float) mxDir * radius;
float my = (float) myDir * radius;
minGrabX = midX + mx - (float)(mxDir * radius * grabPointOffset);
minGrabY = midY + my - (float)(myDir * radius * grabPointOffset);
hourGrabX = midX + hx - (float)(hxDir * radius * grabPointOffset);
hourGrabY = midY + hy - (float)(hyDir * radius * grabPointOffset);
c.drawLine(midX, midY, midX + hx, midY + hy, clockHand);
c.drawLine(midX, midY, midX + mx, midY + my, clockHand);
c.drawCircle(minGrabX, minGrabY, radius * grabPointSize, clockHand);
c.drawCircle(hourGrabX, hourGrabY, radius * grabPointSize, clockHand);
clockHand.setStyle(Paint.Style.FILL);
c.drawCircle(midX,midY,handWidth/2,clockHand);
}
private void drawClockface(Canvas c) {
Paint clockHourBackground = new Paint();
Paint clockMinBackground = new Paint();
Paint intervalArcPaint = new Paint();
intervalArcPaint.setColor(Color.RED);
clockHourBackground.setColor(Color.LTGRAY);
clockHourBackground.setStyle(Paint.Style.STROKE);
clockMinBackground.setColor(Color.WHITE);
intervalArcPaint.setAntiAlias(true);
clockHourBackground.setAntiAlias(true);
clockMinBackground.setAntiAlias(true);
c.drawArc(clockRect,
(float) Math.toDegrees(getMinuteHandAngle() - Math.PI / 2),
(float) Math.toDegrees(-minuteIncrement * (maxInterval * currentInterval)),
true,
intervalArcPaint);
c.drawCircle(midX, midY, radius * 0.95f, clockMinBackground);
c.drawCircle(midX, midY, radius * hourHandLength, clockHourBackground);
Paint linePaint = new Paint();
linePaint.setColor(Color.DKGRAY);
linePaint.setAntiAlias(true);
linePaint.setStrokeWidth(2);
for (double m = 0; m < 60; m++) {
double angle = Math.PI * 2 * m / 60;
float xDir = (float) Math.cos(angle);
float yDir = (float) Math.sin(angle);
float len = m % 5 == 0 ? 0.9f : 0.95f;
c.drawLine(midX + xDir * radius * len * 0.95f,
midY + yDir * radius * len * 0.95f,
midX + xDir * radius * 0.95f,
midY + yDir * radius * 0.95f, linePaint);
}
linePaint.setTextSize(clockNumberSize);
for (double h = 1; h < 13; h++) {
double angle = Math.PI * 2 * h / 12 - Math.PI / 2;
float xDir = (float) Math.cos(angle);
float yDir = (float) Math.sin(angle);
String text = Integer.toString((int) h);
Rect textSize = new Rect(0,0,0,0);
linePaint.getTextBounds(text, 0, text.length(), textSize);
c.drawText(text,
midX + xDir * radius * 0.7f - textSize.width() / 2,
midY + yDir * radius * 0.7f + textSize.height() / 2,
linePaint);
}
}
public String timeToString(int h, int m) {
String hours = h < 10 ? "0" + h : Integer.toString(h);
String minutes = m < 10 ? "0" + m : Integer.toString(m);
return hours + ":" + minutes;
}
private double getHourHandAngle() {
return ((hours % 12) * hourIncrement) + (minutes / 60.0 * hourIncrement);
}
private double getMinuteHandAngle() {
return (minutes * minuteIncrement);
}
boolean hourGrabbed = false;
boolean minGrabbed = false;
boolean sliderGrabbed = false;
public boolean onTouchEvent(MotionEvent me) {
switch (me.getAction()) {
case (MotionEvent.ACTION_UP):
hourGrabbed = false;
minGrabbed = false;
sliderGrabbed = false;
break;
case (MotionEvent.ACTION_DOWN):
if (Math.abs(me.getX() - minGrabX) < radius * grabPointSize &&
Math.abs(me.getY() - minGrabY) < radius * grabPointSize) {
minGrabbed = true;
} else if (Math.abs(me.getX() - hourGrabX) < radius * grabPointSize &&
Math.abs(me.getY() - hourGrabY) < radius * grabPointSize) {
hourGrabbed = true;
} else if (Math.abs(me.getX() - sliderGrabX) < intervalBarRect.height() / 2 &&
Math.abs(me.getY() - sliderGrabY) < intervalBarRect.height() / 2) {
sliderGrabbed = true;
}
break;
case (MotionEvent.ACTION_MOVE):
double newAngle = Math.atan((me.getY() - midY) / (me.getX() - midX)) + Math.PI / 2;
if (me.getX() - midX < 0)
newAngle += Math.PI;
if (minGrabbed) updateMinuteHand(newAngle);
else if (hourGrabbed) updateHourHand(newAngle);
else if (sliderGrabbed) updateSlider(me.getX());
break;
}
invalidate();
return true;
}
private void updateSlider(float x) {
if (x < intervalBarRect.left) currentInterval = 0;
else if (x > intervalBarRect.right) currentInterval = maxInterval;
else {
currentInterval = (int)(((x - intervalBarRect.left)/intervalBarRect.width())*(float)maxInterval);
}
}
private double angleDiff(double a1, double a2) {
double diff = a2 - a1;
if (diff < -Math.PI) diff += Math.PI*2;
else if (diff > Math.PI) diff -= Math.PI*2;
return diff;
}
private void updateMinuteHand(double newAngle) {
double diff = angleDiff(getMinuteHandAngle(), newAngle);
if (Math.abs(diff) > minuteIncrement) {
double increments = (diff / minuteIncrement);
increments = Math.round(increments);
Log.v("clock","incrementing mins by "+increments);
incrementMinutes((int)increments);
}
}
private void updateHourHand(double newAngle) {
double diff = angleDiff(getHourHandAngle(), newAngle);
if (Math.abs(diff) > hourIncrement) {
double increments = (diff / hourIncrement);
increments = Math.round(increments);
Log.v("clock","incrementing hours by "+increments);
incrementHours((int) increments);
}
}
public void incrementMinutes(int increment) {
minutes += increment;
if (minutes >= 60) {
minutes %= 60;
incrementHours(1);
} else if (minutes < 0) {
minutes += 60;
incrementHours(-1);
}
}
private void incrementHours(int increment) {
hours = (hours + increment) % 24;
if (hours < 0) hours += 24;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
updateSize();
}
private void updateSize() {
int minDimension = Math.min(getWidth(), getHeight());
float barHeight = minDimension / 8;
if (getHeight() >= 1.25f * getWidth())
radius = getWidth() / 2f;
else
radius = Math.min(getWidth(), getHeight()) / 2f - barHeight;
midX = getWidth() / 2f;
midY = getHeight() / 2f;
intervalBarRect = new RectF(midX - radius*0.9f, midY + radius, midX + radius*0.9f, midY + radius + barHeight);
clockRect = new RectF(midX - radius, midY - radius, midX + radius, midY + radius);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = minsize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = minsize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
@Override
public int getHours() { return hours; }
@Override
public int getMinutes() { return minutes; }
@Override
public int getInterval() { return currentInterval; }
public void setHours(int hours) { this.hours = hours; }
public void setMinutes(int minutes) { this.minutes = minutes; }
public void setInterval(int interval){ currentInterval = interval; }
}
|
package bisq.core.support.dispute;
import bisq.core.locale.Res;
import bisq.core.proto.CoreProtoResolver;
import bisq.core.support.SupportType;
import bisq.core.support.dispute.mediation.FileTransferReceiver;
import bisq.core.support.dispute.mediation.FileTransferSender;
import bisq.core.support.dispute.mediation.FileTransferSession;
import bisq.core.support.messages.ChatMessage;
import bisq.core.trade.model.bisq_v1.Contract;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.network.NetworkNode;
import bisq.common.crypto.PubKeyRing;
import bisq.common.proto.ProtoUtil;
import bisq.common.proto.network.NetworkPayload;
import bisq.common.proto.persistable.PersistablePayload;
import bisq.common.util.CollectionUtils;
import bisq.common.util.ExtraDataMapValidator;
import bisq.common.util.Utilities;
import com.google.protobuf.ByteString;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@Slf4j
@EqualsAndHashCode
@Getter
public final class Dispute implements NetworkPayload, PersistablePayload {
public enum State {
NEEDS_UPGRADE,
NEW,
OPEN,
REOPENED,
CLOSED;
public static Dispute.State fromProto(protobuf.Dispute.State state) {
return ProtoUtil.enumFromProto(Dispute.State.class, state.name());
}
public static protobuf.Dispute.State toProtoMessage(Dispute.State state) {
return protobuf.Dispute.State.valueOf(state.name());
}
}
private final String tradeId;
private final String id;
private final int traderId;
private final boolean disputeOpenerIsBuyer;
private final boolean disputeOpenerIsMaker;
// PubKeyRing of trader who opened the dispute
private final PubKeyRing traderPubKeyRing;
private final long tradeDate;
private final long tradePeriodEnd;
private Contract contract;
@Nullable
private final byte[] contractHash;
@Nullable
private final byte[] depositTxSerialized;
@Nullable
private final byte[] payoutTxSerialized;
@Nullable
private final String depositTxId;
@Nullable
private final String payoutTxId;
private String contractAsJson;
@Nullable
private final String makerContractSignature;
@Nullable
private final String takerContractSignature;
private final PubKeyRing agentPubKeyRing; // dispute agent
private final boolean isSupportTicket;
private final ObservableList<ChatMessage> chatMessages = FXCollections.observableArrayList();
// disputeResultProperty.get is Nullable!
private final ObjectProperty<DisputeResult> disputeResultProperty = new SimpleObjectProperty<>();
private final long openingDate;
@Nullable
@Setter
private String disputePayoutTxId;
@Setter
// Added v1.2.0
private SupportType supportType;
// Only used at refundAgent so that he knows how the mediator resolved the case
@Setter
@Nullable
private String mediatorsDisputeResult;
@Setter
@Nullable
private String delayedPayoutTxId;
// Added at v1.4.0
@Setter
@Nullable
private String donationAddressOfDelayedPayoutTx;
// Added at v1.6.0
private Dispute.State disputeState = State.NEW;
// Should be only used in emergency case if we need to add data but do not want to break backward compatibility
// at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new
// field in a class would break that hash and therefore break the storage mechanism.
@Nullable
@Setter
private Map<String, String> extraDataMap;
// We do not persist uid, it is only used by dispute agents to guarantee an uid.
@Setter
@Nullable
private transient String uid;
@Setter
private transient long payoutTxConfirms = -1;
@Setter
private transient boolean payoutDone = false;
private transient final BooleanProperty isClosedProperty = new SimpleBooleanProperty();
private transient final IntegerProperty badgeCountProperty = new SimpleIntegerProperty();
private transient FileTransferReceiver fileTransferSession = null;
public FileTransferReceiver createOrGetFileTransferReceiver(NetworkNode networkNode, NodeAddress peerNodeAddress, FileTransferSession.FtpCallback callback) throws IOException {
// the receiver stores its state temporarily here in the dispute
// this method gets called to retrieve the session each time a part of the log files is received
if (fileTransferSession == null) {
fileTransferSession = new FileTransferReceiver(networkNode, peerNodeAddress, this.tradeId, this.traderId, this.getRoleStringForLogFile(), callback);
}
return fileTransferSession;
}
public FileTransferSender createFileTransferSender(NetworkNode networkNode, NodeAddress peerNodeAddress, FileTransferSession.FtpCallback callback) {
return new FileTransferSender(networkNode, peerNodeAddress, this.tradeId, this.traderId, this.getRoleStringForLogFile(), callback);
}
// Constructor
public Dispute(long openingDate,
String tradeId,
int traderId,
boolean disputeOpenerIsBuyer,
boolean disputeOpenerIsMaker,
PubKeyRing traderPubKeyRing,
long tradeDate,
long tradePeriodEnd,
Contract contract,
@Nullable byte[] contractHash,
@Nullable byte[] depositTxSerialized,
@Nullable byte[] payoutTxSerialized,
@Nullable String depositTxId,
@Nullable String payoutTxId,
String contractAsJson,
@Nullable String makerContractSignature,
@Nullable String takerContractSignature,
PubKeyRing agentPubKeyRing,
boolean isSupportTicket,
SupportType supportType) {
this.openingDate = openingDate;
this.tradeId = tradeId;
this.traderId = traderId;
this.disputeOpenerIsBuyer = disputeOpenerIsBuyer;
this.disputeOpenerIsMaker = disputeOpenerIsMaker;
this.traderPubKeyRing = traderPubKeyRing;
this.tradeDate = tradeDate;
this.tradePeriodEnd = tradePeriodEnd;
this.contract = contract;
this.contractHash = contractHash;
this.depositTxSerialized = depositTxSerialized;
this.payoutTxSerialized = payoutTxSerialized;
this.depositTxId = depositTxId;
this.payoutTxId = payoutTxId;
this.contractAsJson = contractAsJson;
this.makerContractSignature = makerContractSignature;
this.takerContractSignature = takerContractSignature;
this.agentPubKeyRing = agentPubKeyRing;
this.isSupportTicket = isSupportTicket;
this.supportType = supportType;
id = tradeId + "_" + traderId;
uid = UUID.randomUUID().toString();
refreshAlertLevel(true);
}
// PROTO BUFFER
@Override
public protobuf.Dispute toProtoMessage() {
// Needed to avoid ConcurrentModificationException
List<ChatMessage> clonedChatMessages = new ArrayList<>(chatMessages);
protobuf.Dispute.Builder builder = protobuf.Dispute.newBuilder()
.setTradeId(tradeId)
.setTraderId(traderId)
.setDisputeOpenerIsBuyer(disputeOpenerIsBuyer)
.setDisputeOpenerIsMaker(disputeOpenerIsMaker)
.setTraderPubKeyRing(traderPubKeyRing.toProtoMessage())
.setTradeDate(tradeDate)
.setTradePeriodEnd(tradePeriodEnd)
.setContract(contract.toProtoMessage())
.setContractAsJson(contractAsJson)
.setAgentPubKeyRing(agentPubKeyRing.toProtoMessage())
.setIsSupportTicket(isSupportTicket)
.addAllChatMessage(clonedChatMessages.stream()
.map(msg -> msg.toProtoNetworkEnvelope().getChatMessage())
.collect(Collectors.toList()))
.setIsClosed(this.isClosed())
.setOpeningDate(openingDate)
.setState(Dispute.State.toProtoMessage(disputeState))
.setId(id);
Optional.ofNullable(contractHash).ifPresent(e -> builder.setContractHash(ByteString.copyFrom(e)));
Optional.ofNullable(depositTxSerialized).ifPresent(e -> builder.setDepositTxSerialized(ByteString.copyFrom(e)));
Optional.ofNullable(payoutTxSerialized).ifPresent(e -> builder.setPayoutTxSerialized(ByteString.copyFrom(e)));
Optional.ofNullable(depositTxId).ifPresent(builder::setDepositTxId);
Optional.ofNullable(payoutTxId).ifPresent(builder::setPayoutTxId);
Optional.ofNullable(disputePayoutTxId).ifPresent(builder::setDisputePayoutTxId);
Optional.ofNullable(makerContractSignature).ifPresent(builder::setMakerContractSignature);
Optional.ofNullable(takerContractSignature).ifPresent(builder::setTakerContractSignature);
Optional.ofNullable(disputeResultProperty.get()).ifPresent(result -> builder.setDisputeResult(disputeResultProperty.get().toProtoMessage()));
Optional.ofNullable(supportType).ifPresent(result -> builder.setSupportType(SupportType.toProtoMessage(supportType)));
Optional.ofNullable(mediatorsDisputeResult).ifPresent(result -> builder.setMediatorsDisputeResult(mediatorsDisputeResult));
Optional.ofNullable(delayedPayoutTxId).ifPresent(result -> builder.setDelayedPayoutTxId(delayedPayoutTxId));
Optional.ofNullable(donationAddressOfDelayedPayoutTx).ifPresent(result -> builder.setDonationAddressOfDelayedPayoutTx(donationAddressOfDelayedPayoutTx));
Optional.ofNullable(getExtraDataMap()).ifPresent(builder::putAllExtraData);
return builder.build();
}
public static Dispute fromProto(protobuf.Dispute proto, CoreProtoResolver coreProtoResolver) {
Dispute dispute = new Dispute(proto.getOpeningDate(),
proto.getTradeId(),
proto.getTraderId(),
proto.getDisputeOpenerIsBuyer(),
proto.getDisputeOpenerIsMaker(),
PubKeyRing.fromProto(proto.getTraderPubKeyRing()),
proto.getTradeDate(),
proto.getTradePeriodEnd(),
Contract.fromProto(proto.getContract(), coreProtoResolver),
ProtoUtil.byteArrayOrNullFromProto(proto.getContractHash()),
ProtoUtil.byteArrayOrNullFromProto(proto.getDepositTxSerialized()),
ProtoUtil.byteArrayOrNullFromProto(proto.getPayoutTxSerialized()),
ProtoUtil.stringOrNullFromProto(proto.getDepositTxId()),
ProtoUtil.stringOrNullFromProto(proto.getPayoutTxId()),
proto.getContractAsJson(),
ProtoUtil.stringOrNullFromProto(proto.getMakerContractSignature()),
ProtoUtil.stringOrNullFromProto(proto.getTakerContractSignature()),
PubKeyRing.fromProto(proto.getAgentPubKeyRing()),
proto.getIsSupportTicket(),
SupportType.fromProto(proto.getSupportType()));
dispute.setExtraDataMap(CollectionUtils.isEmpty(proto.getExtraDataMap()) ?
null : ExtraDataMapValidator.getValidatedExtraDataMap(proto.getExtraDataMap()));
dispute.chatMessages.addAll(proto.getChatMessageList().stream()
.map(ChatMessage::fromPayloadProto)
.collect(Collectors.toList()));
if (proto.hasDisputeResult())
dispute.disputeResultProperty.set(DisputeResult.fromProto(proto.getDisputeResult()));
dispute.disputePayoutTxId = ProtoUtil.stringOrNullFromProto(proto.getDisputePayoutTxId());
String mediatorsDisputeResult = proto.getMediatorsDisputeResult();
if (!mediatorsDisputeResult.isEmpty()) {
dispute.setMediatorsDisputeResult(mediatorsDisputeResult);
}
String delayedPayoutTxId = proto.getDelayedPayoutTxId();
if (!delayedPayoutTxId.isEmpty()) {
dispute.setDelayedPayoutTxId(delayedPayoutTxId);
}
String donationAddressOfDelayedPayoutTx = proto.getDonationAddressOfDelayedPayoutTx();
if (!donationAddressOfDelayedPayoutTx.isEmpty()) {
dispute.setDonationAddressOfDelayedPayoutTx(donationAddressOfDelayedPayoutTx);
}
if (Dispute.State.fromProto(proto.getState()) == State.NEEDS_UPGRADE) {
// old disputes did not have a state field, so choose an appropriate state:
dispute.setState(proto.getIsClosed() ? State.CLOSED : State.OPEN);
if (dispute.getDisputeState() == State.CLOSED) {
// mark chat messages as read for pre-existing CLOSED disputes
// otherwise at upgrade, all old disputes would have 1 unread chat message
// because currently when a dispute is closed, the last chat message is not marked read
dispute.getChatMessages().forEach(m -> m.setWasDisplayed(true));
}
} else {
dispute.setState(Dispute.State.fromProto(proto.getState()));
}
dispute.refreshAlertLevel(true);
return dispute;
}
// API
public void addAndPersistChatMessage(ChatMessage chatMessage) {
if (!chatMessages.contains(chatMessage)) {
chatMessages.add(chatMessage);
} else {
log.error("disputeDirectMessage already exists");
}
}
public boolean removeAllChatMessages() {
if (chatMessages.size() > 1) {
// removes all chat except the initial guidelines message.
String firstMessageUid = chatMessages.get(0).getUid();
chatMessages.removeIf((msg) -> !msg.getUid().equals(firstMessageUid));
return true;
}
return false;
}
public void maybeClearSensitiveData() {
String change = "";
if (contract.maybeClearSensitiveData()) {
change += "contract;";
}
String edited = contract.sanitizeContractAsJson(contractAsJson);
if (!edited.equals(contractAsJson)) {
contractAsJson = edited;
change += "contractAsJson;";
}
if (removeAllChatMessages()) {
change += "chat messages;";
}
if (change.length() > 0) {
log.info("cleared sensitive data from {} of dispute for trade {}", change, Utilities.getShortId(getTradeId()));
}
}
// Setters
public void setIsClosed() {
setState(State.CLOSED);
}
public void reOpen() {
setState(State.REOPENED);
}
public void setState(Dispute.State disputeState) {
this.disputeState = disputeState;
this.isClosedProperty.set(disputeState == State.CLOSED);
}
public void setDisputeResult(DisputeResult disputeResult) {
disputeResultProperty.set(disputeResult);
}
public void setExtraData(String key, String value) {
if (key == null || value == null) {
return;
}
if (extraDataMap == null) {
extraDataMap = new HashMap<>();
}
extraDataMap.put(key, value);
}
// Getters
public String getShortTradeId() {
return Utilities.getShortId(tradeId);
}
public ReadOnlyBooleanProperty isClosedProperty() {
return isClosedProperty;
}
public ReadOnlyIntegerProperty getBadgeCountProperty() {
return badgeCountProperty;
}
public ReadOnlyObjectProperty<DisputeResult> disputeResultProperty() {
return disputeResultProperty;
}
public Date getTradeDate() {
return new Date(tradeDate);
}
public Date getTradePeriodEnd() {
return new Date(tradePeriodEnd);
}
public Date getOpeningDate() {
return new Date(openingDate);
}
public boolean isNew() {
return this.disputeState == State.NEW;
}
public boolean isClosed() {
return this.disputeState == State.CLOSED;
}
public void refreshAlertLevel(boolean senderFlag) {
// if the dispute is "new" that is 1 alert that has to be propagated upstream
// or if there are unread messages that is 1 alert that has to be propagated upstream
if (isNew() || unreadMessageCount(senderFlag) > 0) {
badgeCountProperty.setValue(1);
} else {
badgeCountProperty.setValue(0);
}
}
public long unreadMessageCount(boolean senderFlag) {
return chatMessages.stream()
.filter(m -> m.isSenderIsTrader() == senderFlag || m.isSystemMessage())
.filter(m -> !m.isWasDisplayed())
.count();
}
public void setDisputeSeen(boolean senderFlag) {
if (this.disputeState == State.NEW)
setState(State.OPEN);
refreshAlertLevel(senderFlag);
}
public void setChatMessagesSeen(boolean senderFlag) {
getChatMessages().forEach(m -> m.setWasDisplayed(true));
refreshAlertLevel(senderFlag);
}
public String getRoleString() {
if (disputeOpenerIsMaker) {
if (disputeOpenerIsBuyer)
return Res.get("support.buyerOfferer");
else
return Res.get("support.sellerOfferer");
} else {
if (disputeOpenerIsBuyer)
return Res.get("support.buyerTaker");
else
return Res.get("support.sellerTaker");
}
}
public String getRoleStringForLogFile() {
return (disputeOpenerIsBuyer ? "BUYER" : "SELLER") + "_"
+ (disputeOpenerIsMaker ? "MAKER" : "TAKER");
}
@Override
public String toString() {
return "Dispute{" +
"\n tradeId='" + tradeId + '\'' +
",\n id='" + id + '\'' +
",\n uid='" + uid + '\'' +
",\n state=" + disputeState +
",\n traderId=" + traderId +
",\n disputeOpenerIsBuyer=" + disputeOpenerIsBuyer +
",\n disputeOpenerIsMaker=" + disputeOpenerIsMaker +
",\n traderPubKeyRing=" + traderPubKeyRing +
",\n tradeDate=" + tradeDate +
",\n tradePeriodEnd=" + tradePeriodEnd +
",\n contract=" + contract +
",\n contractHash=" + Utilities.bytesAsHexString(contractHash) +
",\n depositTxSerialized=" + Utilities.bytesAsHexString(depositTxSerialized) +
",\n payoutTxSerialized=" + Utilities.bytesAsHexString(payoutTxSerialized) +
",\n depositTxId='" + depositTxId + '\'' +
",\n payoutTxId='" + payoutTxId + '\'' +
",\n contractAsJson='" + contractAsJson + '\'' +
",\n makerContractSignature='" + makerContractSignature + '\'' +
",\n takerContractSignature='" + takerContractSignature + '\'' +
",\n agentPubKeyRing=" + agentPubKeyRing +
",\n isSupportTicket=" + isSupportTicket +
",\n chatMessages=" + chatMessages +
",\n isClosedProperty=" + isClosedProperty +
",\n disputeResultProperty=" + disputeResultProperty +
",\n disputePayoutTxId='" + disputePayoutTxId + '\'' +
",\n openingDate=" + openingDate +
",\n supportType=" + supportType +
",\n mediatorsDisputeResult='" + mediatorsDisputeResult + '\'' +
",\n delayedPayoutTxId='" + delayedPayoutTxId + '\'' +
",\n donationAddressOfDelayedPayoutTx='" + donationAddressOfDelayedPayoutTx + '\'' +
"\n}";
}
}
|
// Nexus Core - a framework for developing distributed applications
package com.threerings.nexus.distrib;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import com.threerings.nexus.io.Streamable;
import static com.threerings.nexus.util.Log.log;
/**
* A set attribute for a Nexus object. Contains an unordered set of distinct values.
*/
public class DSet<T> extends DAttribute
implements Set<T>
{
/** An interface for publishing set events to listeners. */
public static interface Listener<T> extends DListener
{
/** Notifies listener of an added element. */
void elementAdded (T element);
/** Notifies listener of a removed element. */
void elementRemoved (T element);
}
/** An adaptor for listening to just added notifications. */
public static abstract class AddedListener<T> implements Listener<T>
{
public final void elementRemoved (T element) { /*NOOP*/ }
}
/** An adaptor for listening to just removed notifications. */
public static abstract class RemovedListener<T> implements Listener<T>
{
public final void elementAdded (T element) { /*NOOP*/ }
}
/**
* Creates a distributed set with the supplied underlying set implementation.
*/
public static <T> DSet<T> create (Set<T> impl)
{
return new DSet<T>(impl);
}
/**
* Creates a distributed set with the supplied underlying set implementation.
*/
public DSet (Set<T> impl)
{
_impl = impl;
}
/**
* Adds a listener for set changes.
*/
public void addListener (Listener<T> listener)
{
_listeners = addListener(_listeners, listener);
}
/**
* Removes a listener for set changes.
*/
public void removeListener (Listener<T> listener)
{
removeListener(_listeners, listener);
}
// from interface Set<T>
public int size ()
{
return _impl.size();
}
// from interface Set<T>
public boolean isEmpty ()
{
return _impl.isEmpty();
}
// from interface Set<T>
public boolean contains (Object key)
{
return _impl.contains(key);
}
// from interface Set<T>
public boolean add (T elem)
{
checkMutate();
if (!_impl.add(elem)) return false;
postAdded(elem);
return true;
}
// from interface Set<T>
public boolean remove (Object rawElem)
{
checkMutate();
@SuppressWarnings("unchecked") T elem = (T)rawElem;
if (!_impl.remove(elem)) return false;
postRemoved(elem);
return true;
}
// from interface Set<T>
public boolean containsAll (Collection<?> coll)
{
return _impl.containsAll(coll);
}
// from interface Set<T>
public boolean addAll (Collection<? extends T> coll)
{
boolean modified = false;
for (T elem : coll) {
if (add(elem)) {
modified = true;
}
}
return modified;
}
// from interface Set<T>
public boolean retainAll (Collection<?> coll)
{
boolean modified = false;
for (Iterator<T> iter = iterator(); iter.hasNext(); ) {
if (!coll.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
// from interface Set<T>
public boolean removeAll (Collection<?> coll)
{
boolean modified = false;
for (Iterator<T> iter = iterator(); iter.hasNext(); ) {
if (remove(iter.next())) {
modified = true;
}
}
return modified;
}
// from interface Set<T>
public void clear ()
{
checkMutate();
// generate removed events for our elements (do so on a copy of our set so that we don't
// trigger CME if the removed events are processed as they are generated)
for (T elem : new ArrayList<T>(_impl)) {
postRemoved(elem);
}
_impl.clear();
}
// from interface Set<T>
public Iterator<T> iterator ()
{
final Iterator<T> iiter = _impl.iterator();
return new Iterator<T>() {
public boolean hasNext () {
return iiter.hasNext();
}
public T next () {
return (_current = iiter.next());
}
public void remove () {
if (_current == null) {
throw new IllegalStateException();
}
checkMutate();
iiter.remove();
postRemoved(_current);
}
protected T _current;
};
}
// from interface Set<T>
public Object[] toArray ()
{
return _impl.toArray();
}
// from interface Set<T>
public <T> T[] toArray (T[] array)
{
return _impl.toArray(array);
}
@Override // from DAttribute
public void readContents (Streamable.Input in)
{
_impl = in.<Set<T>>readValue();
}
@Override // from DAttribute
public void writeContents (Streamable.Output out)
{
out.writeValue(_impl);
}
protected void postAdded (T elem)
{
_owner.postEvent(new AddedEvent<T>(_owner.getId(), _index, elem));
}
protected void applyAdded (T elem)
{
_impl.add(elem);
for (int ii = 0, ll = _listeners.length; ii < ll; ii++) {
@SuppressWarnings("unchecked") Listener<T> listener = (Listener<T>)_listeners[ii];
if (listener != null) {
try {
listener.elementAdded(elem);
} catch (Throwable t) {
log.warning("Listener choked in elementAdded", "elem", elem,
"listener", listener, t);
}
}
}
}
protected void postRemoved (T elem)
{
_owner.postEvent(new RemovedEvent<T>(_owner.getId(), _index, elem));
}
protected void applyRemoved (T elem)
{
_impl.remove(elem);
for (int ii = 0, ll = _listeners.length; ii < ll; ii++) {
@SuppressWarnings("unchecked") Listener<T> listener = (Listener<T>)_listeners[ii];
if (listener != null) {
try {
listener.elementRemoved(elem);
} catch (Throwable t) {
log.warning("Listener choked in elementRemoved", "elem", elem,
"listener", listener, t);
}
}
}
}
/** An event emitted when an element is added. */
protected static class AddedEvent<T> extends DAttribute.Event
{
public AddedEvent (int targetId, short index, T elem) {
super(targetId, index);
_elem = elem;
}
@Override public void applyTo (NexusObject target) {
@SuppressWarnings("unchecked") DSet<T> attr = (DSet<T>)target.getAttribute(this.index);
attr.applyAdded(_elem);
}
@Override protected void toString (StringBuilder buf) {
super.toString(buf);
buf.append(", elem=").append(_elem);
}
protected final T _elem;
}
/** An event emitted when an element is removed. */
protected static class RemovedEvent<T> extends DAttribute.Event
{
public RemovedEvent (int targetId, short index, T elem) {
super(targetId, index);
_elem = elem;
}
@Override public void applyTo (NexusObject target) {
@SuppressWarnings("unchecked") DSet<T> attr = (DSet<T>)target.getAttribute(this.index);
attr.applyRemoved(_elem);
}
@Override protected void toString (StringBuilder buf) {
super.toString(buf);
buf.append(", elem=").append(_elem);
}
protected final T _elem;
}
/** Contains our underlying elements. */
protected Set<T> _impl;
/** Our registered listeners. */
protected transient DListener[] _listeners = NO_LISTENERS;
}
|
package org.metaborg.spoofax.core.analysis.constraint;
import static org.metaborg.meta.nabl2.terms.build.TermBuild.B;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.analysis.AnalysisException;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.messages.MessageFactory;
import org.metaborg.core.messages.MessageSeverity;
import org.metaborg.core.resource.IResourceService;
import org.metaborg.meta.nabl2.config.NaBL2DebugConfig;
import org.metaborg.meta.nabl2.constraints.messages.IMessageInfo;
import org.metaborg.meta.nabl2.constraints.messages.ImmutableMessageInfo;
import org.metaborg.meta.nabl2.constraints.messages.MessageContent;
import org.metaborg.meta.nabl2.constraints.messages.MessageKind;
import org.metaborg.meta.nabl2.scopegraph.terms.Scope;
import org.metaborg.meta.nabl2.solver.ISolution;
import org.metaborg.meta.nabl2.solver.SolverException;
import org.metaborg.meta.nabl2.solver.messages.IMessages;
import org.metaborg.meta.nabl2.solver.messages.Messages;
import org.metaborg.meta.nabl2.solver.solvers.BaseSolver.GraphSolution;
import org.metaborg.meta.nabl2.solver.solvers.ImmutableBaseSolution;
import org.metaborg.meta.nabl2.solver.solvers.SemiIncrementalMultiFileSolver;
import org.metaborg.meta.nabl2.spoofax.analysis.Actions;
import org.metaborg.meta.nabl2.spoofax.analysis.CustomSolution;
import org.metaborg.meta.nabl2.spoofax.analysis.FinalResult;
import org.metaborg.meta.nabl2.spoofax.analysis.InitialResult;
import org.metaborg.meta.nabl2.spoofax.analysis.UnitResult;
import org.metaborg.meta.nabl2.terms.ITerm;
import org.metaborg.meta.nabl2.terms.ITermVar;
import org.metaborg.meta.nabl2.terms.unification.PersistentUnifier;
import org.metaborg.meta.nabl2.util.collections.HashTrieRelation3;
import org.metaborg.meta.nabl2.util.collections.IRelation3;
import org.metaborg.spoofax.core.analysis.AnalysisCommon;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer;
import org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.context.scopegraph.IMultiFileScopeGraphContext;
import org.metaborg.spoofax.core.context.scopegraph.IMultiFileScopeGraphUnit;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService;
import org.metaborg.spoofax.core.unit.AnalyzeContrib;
import org.metaborg.spoofax.core.unit.AnalyzeUpdateData;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnitUpdate;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxUnitService;
import org.metaborg.util.functions.Function1;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.metaborg.util.optionals.Optionals;
import org.metaborg.util.stream.Collectors2;
import org.metaborg.util.task.ICancel;
import org.metaborg.util.task.IProgress;
import org.metaborg.util.time.AggregateTimer;
import org.metaborg.util.time.Timer;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.HybridInterpreter;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import meta.flowspec.java.solver.FixedPoint;
public class ConstraintMultiFileAnalyzer extends AbstractConstraintAnalyzer<IMultiFileScopeGraphContext>
implements ISpoofaxAnalyzer {
private static final ILogger logger = LoggerUtils.logger(ConstraintMultiFileAnalyzer.class);
public static final String name = "constraint-multifile";
private final ISpoofaxUnitService unitService;
@Inject public ConstraintMultiFileAnalyzer(final AnalysisCommon analysisCommon,
final ISpoofaxUnitService unitService, final IResourceService resourceService,
final IStrategoRuntimeService runtimeService, final IStrategoCommon strategoCommon,
final ITermFactoryService termFactoryService, final ISpoofaxTracingService tracingService) {
super(analysisCommon, resourceService, runtimeService, strategoCommon, termFactoryService, tracingService);
this.unitService = unitService;
}
@Override protected ISpoofaxAnalyzeResults analyzeAll(Map<String, ISpoofaxParseUnit> changed,
java.util.Set<String> removed, IMultiFileScopeGraphContext context, HybridInterpreter runtime,
String strategy, IProgress progress, ICancel cancel) throws AnalysisException {
if(context.config().incremental()) {
logger.error("Incremental analysis is not supported.");
}
return analyzeSemiIncremental(changed, removed, context, runtime, strategy, progress, cancel);
}
private ISpoofaxAnalyzeResults analyzeSemiIncremental(Map<String, ISpoofaxParseUnit> changed,
java.util.Set<String> removed, IMultiFileScopeGraphContext context, HybridInterpreter runtime,
String strategy, IProgress progress, ICancel cancel) throws AnalysisException {
final NaBL2DebugConfig debugConfig = context.config().debug();
final Timer totalTimer = new Timer(true);
final AggregateTimer collectionTimer = new AggregateTimer();
final AggregateTimer solverTimer = new AggregateTimer();
final AggregateTimer finalizeTimer = new AggregateTimer();
final String globalSource = "";
final Function1<String, String> globalFresh = base -> context.unit(globalSource).fresh().fresh(base);
for(String input : removed) {
context.removeUnit(input);
}
final int n = changed.size();
final int w = context.units().size() / 2;
progress.setWorkRemaining(n + w + 1);
if(debugConfig.analysis() || debugConfig.files()) {
logger.info("Analyzing {} files in {}.", n, context.location());
}
final Collection<ISpoofaxAnalyzeUnit> results = Lists.newArrayList();
final Collection<ISpoofaxAnalyzeUnitUpdate> updateResults = Lists.newArrayList();
try {
// initial
InitialResult initialResult;
final Optional<ITerm> customInitial;
{
if(debugConfig.collection()) {
logger.info("Collecting initial constraints.");
}
if(context.initialResult().isPresent()) {
initialResult = context.initialResult().get();
customInitial = context.initialResult().flatMap(r -> r.getCustomResult());
} else {
collectionTimer.start();
try {
final ITerm globalAST = Actions.sourceTerm(globalSource, B.EMPTY_TUPLE);
ITerm initialResultTerm =
doAction(strategy, Actions.analyzeInitial(globalSource, globalAST), context, runtime)
.orElseThrow(() -> new AnalysisException(context, "No initial result."));
initialResult = InitialResult.matcher().match(initialResultTerm)
.orElseThrow(() -> new AnalysisException(context, "Invalid initial results."));
customInitial = doCustomAction(strategy, Actions.customInitial(globalSource, globalAST),
context, runtime);
initialResult = initialResult.withCustomResult(customInitial);
context.setInitialResult(initialResult);
} finally {
collectionTimer.stop();
}
}
if(debugConfig.collection()) {
logger.info("Initial constraints collected.");
}
}
// global parameters, that form the interface for a single unit
final java.util.Set<ITermVar> intfVars = Sets.newHashSet();
{
initialResult.getArgs().getParams().stream().forEach(param -> intfVars.addAll(param.getVars()));
initialResult.getArgs().getType().ifPresent(type -> intfVars.addAll(type.getVars()));
}
final SemiIncrementalMultiFileSolver solver =
new SemiIncrementalMultiFileSolver(context.config().debug(), callExternal(runtime));
// global
ISolution initialSolution;
{
if(context.initialSolution().isPresent()) {
initialSolution = context.initialSolution().get();
} else {
try {
solverTimer.start();
final IProgress subprogress = progress.subProgress(1);
GraphSolution preSolution =
solver.solveGraph(
ImmutableBaseSolution.of(initialResult.getConfig(),
initialResult.getConstraints(), PersistentUnifier.Immutable.of()),
globalFresh, cancel, subprogress);
preSolution = solver.reportUnsolvedGraphConstraints(preSolution);
initialSolution =
solver.solveIntra(preSolution, intfVars, null, globalFresh, cancel, subprogress);
if(debugConfig.resolution()) {
logger.info("Reduced file constraints to {}.", initialSolution.constraints().size());
}
} catch(SolverException e) {
throw new AnalysisException(context, e);
} finally {
solverTimer.stop();
}
context.setInitialSolution(initialSolution);
}
}
final java.util.Set<Scope> intfScopes = Sets.newHashSet();
{
initialResult.getArgs().getParams().stream().forEach(
param -> Scope.matcher().match(param, initialSolution.unifier()).ifPresent(intfScopes::add));
}
// units
final Map<String, IStrategoTerm> astsByFile = Maps.newHashMap();
final Map<String, IMessage> failures = Maps.newHashMap();
final Multimap<String, IMessage> ambiguitiesByFile = HashMultimap.create();
for(Map.Entry<String, ISpoofaxParseUnit> input : changed.entrySet()) {
final String source = input.getKey();
final ISpoofaxParseUnit parseUnit = input.getValue();
final ITerm ast = strategoTerms.fromStratego(parseUnit.ast());
if(debugConfig.files()) {
logger.info("Analyzing {}.", source);
}
final IMultiFileScopeGraphUnit unit = context.unit(source);
unit.clear();
try {
UnitResult unitResult;
final Optional<ITerm> customUnit;
{
if(debugConfig.collection()) {
logger.info("Collecting constraints of {}.", source);
}
try {
collectionTimer.start();
final ITerm unitResultTerm = doAction(strategy,
Actions.analyzeUnit(source, ast, initialResult.getArgs()), context, runtime)
.orElseThrow(() -> new AnalysisException(context, "No unit result."));
unitResult = UnitResult.matcher().match(unitResultTerm)
.orElseThrow(() -> new MetaborgException("Invalid unit results."));
final ITerm desugaredAST = unitResult.getAST();
customUnit = doCustomAction(strategy,
Actions.customUnit(source, desugaredAST, customInitial.orElse(B.EMPTY_TUPLE)),
context, runtime);
unitResult = unitResult.withCustomResult(customUnit);
final IStrategoTerm analyzedAST = strategoTerms.toStratego(desugaredAST);
astsByFile.put(source, analyzedAST);
ambiguitiesByFile.putAll(source,
analysisCommon.ambiguityMessages(parseUnit.source(), analyzedAST));
unit.setUnitResult(unitResult);
} finally {
collectionTimer.stop();
}
if(debugConfig.collection()) {
logger.info("Collected {} constraints of {}.", unitResult.getConstraints().size(), source);
}
}
{
final ISolution unitSolution;
if(debugConfig.resolution()) {
logger.info("Reducing {} constraints of {}.", unitResult.getConstraints().size(), source);
}
try {
solverTimer.start();
final Function1<String, String> fresh = base -> context.unit(source).fresh().fresh(base);
final IProgress subprogress = progress.subProgress(1);
GraphSolution preSolution =
solver.solveGraph(
ImmutableBaseSolution.of(initialResult.getConfig(),
unitResult.getConstraints(), initialSolution.unifier()),
fresh, cancel, subprogress);
preSolution = solver.reportUnsolvedGraphConstraints(preSolution);
unitSolution =
solver.solveIntra(preSolution, intfVars, intfScopes, fresh, cancel, subprogress);
if(debugConfig.resolution()) {
logger.info("Reduced file constraints to {}.", unitSolution.constraints().size());
}
} catch(SolverException e) {
throw new AnalysisException(context, e);
} finally {
solverTimer.stop();
}
unit.setPartialSolution(unitSolution);
if(debugConfig.files() || debugConfig.resolution()) {
logger.info("Analyzed {}: {} errors, {} warnings, {} notes, {} unsolved constraints.",
source, unitSolution.messages().getErrors().size(),
unitSolution.messages().getWarnings().size(),
unitSolution.messages().getNotes().size(), unitSolution.constraints().size());
}
}
} catch(MetaborgException e) {
logger.warn("Analysis of " + source + " failed.", e);
failures.put(source,
MessageFactory.newAnalysisErrorAtTop(parseUnit.source(), "File analysis failed.", e));
}
}
// solve
final ISolution solution;
final List<Optional<ITerm>> customUnits = Lists.newArrayList();
{
final List<ISolution> partialSolutions = Lists.newArrayList();
for(IMultiFileScopeGraphUnit unit : context.units()) {
unit.partialSolution().ifPresent(partialSolutions::add);
unit.unitResult().map(UnitResult::getCustomResult).ifPresent(customUnits::add);
}
if(debugConfig.resolution()) {
logger.info("Solving {} partial solutions.", partialSolutions.size());
}
ISolution sol;
try {
solverTimer.start();
Function1<String, String> fresh = base -> context.unit(globalSource).fresh().fresh(base);
IMessageInfo message = ImmutableMessageInfo.of(MessageKind.ERROR, MessageContent.of(),
Actions.sourceTerm(globalSource));
sol = solver.solveInter(initialSolution, partialSolutions, message, fresh, cancel,
progress.subProgress(w));
sol = solver.reportUnsolvedConstraints(sol);
} catch(SolverException e) {
throw new AnalysisException(context, e);
} finally {
solverTimer.stop();
}
if (!sol.flowSpecSolution().controlFlowGraph().isEmpty()) {
logger.debug("CFG is not empty: calling FlowSpec dataflow solver");
sol= new FixedPoint().entryPoint(sol, getFlowSpecTransferFunctions(context.language()));
}
solution = sol;
context.setSolution(solution);
if(debugConfig.resolution()) {
logger.info("Project constraints solved.");
}
}
// final
FinalResult finalResult;
final Optional<ITerm> customFinal;
final Optional<CustomSolution> customSolution;
{
if(debugConfig.analysis()) {
logger.info("Finalizing project analysis.");
}
finalizeTimer.start();
try {
ITerm finalResultTerm = doAction(strategy, Actions.analyzeFinal(globalSource), context, runtime)
.orElseThrow(() -> new AnalysisException(context, "No final result."));
finalResult = FinalResult.matcher().match(finalResultTerm, solution.unifier())
.orElseThrow(() -> new AnalysisException(context, "Invalid final results."));
customFinal = doCustomAction(strategy, Actions.customFinal(globalSource,
customInitial.orElse(B.EMPTY_TUPLE), Optionals.filter(customUnits)), context, runtime);
finalResult = finalResult.withCustomResult(customFinal);
context.setFinalResult(finalResult);
customSolution = customFinal.flatMap(cs -> CustomSolution.matcher().match(cs, solution.unifier()));
customSolution.ifPresent(cs -> context.setCustomSolution(cs));
} finally {
finalizeTimer.stop();
}
if(debugConfig.analysis()) {
logger.info("Project analysis finalized.");
}
}
// errors
{
if(debugConfig.analysis()) {
logger.info("Processing project messages.");
}
Messages.Transient messageBuilder = Messages.Transient.of();
messageBuilder.addAll(Messages.unsolvedErrors(solution.constraints()));
messageBuilder.addAll(solution.messages().getAll());
customSolution.map(CustomSolution::getMessages).map(IMessages::getAll)
.ifPresent(messageBuilder::addAll);
IMessages messages = messageBuilder.freeze();
IRelation3.Transient<String, MessageSeverity, IMessage> messagesByFile =
HashTrieRelation3.Transient.of();
messagesByFile(failures.values(), messagesByFile, context);
messagesByFile(messages(messages.getAll(), solution.unifier(), context, context.location()),
messagesByFile, context);
// precondition: the messagesByFile should not contain any files that do not have corresponding units
for(IMultiFileScopeGraphUnit unit : context.units()) {
final String source = unit.resource();
final java.util.Set<IMessage> fileMessages = messagesByFile.get(source).stream()
.map(Map.Entry::getValue).collect(Collectors2.toHashSet());
if(changed.containsKey(source)) {
fileMessages.addAll(ambiguitiesByFile.get(source));
final boolean valid = !failures.containsKey(source);
final boolean success = valid && messagesByFile.get(source, MessageSeverity.ERROR).isEmpty();
final IStrategoTerm analyzedAST = astsByFile.get(source);
results.add(unitService.analyzeUnit(changed.get(source),
new AnalyzeContrib(valid, success, analyzedAST != null, analyzedAST, fileMessages, -1),
context));
} else {
try {
final FileObject file = context.location().resolveFile(source);
updateResults.add(
unitService.analyzeUnitUpdate(file, new AnalyzeUpdateData(fileMessages), context));
} catch(IOException ex) {
logger.error("Could not resolve {} to update messages", source);
}
}
messagesByFile.remove(source);
}
if(!messagesByFile.keySet().isEmpty()) {
logger.error("Found messages for unanalyzed files {}", messagesByFile.keySet());
}
if(debugConfig.analysis() || debugConfig.files() || debugConfig.resolution()) {
logger.info("Analyzed {} files: {} errors, {} warnings, {} notes.", n, messages.getErrors().size(),
messages.getWarnings().size(), messages.getNotes().size());
}
}
} catch(InterruptedException e) {
logger.debug("Analysis was interrupted.");
} finally {
totalTimer.stop();
}
final ConstraintDebugData debugData = new ConstraintDebugData(totalTimer.stop(), collectionTimer.total(),
solverTimer.total(), finalizeTimer.total());
if(debugConfig.analysis()) {
logger.info("{}", debugData);
}
return new SpoofaxAnalyzeResults(results, updateResults, context, debugData);
}
}
|
package luggage.controllers;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import luggage.database.models.UserModel;
import luggage.database.models.Model;
import luggage.helpers.StageHelper;
/**
* UsersController
*
* Controller for users/list.fxml
*
* @package luggage.controllers
* @author Alexander + Nick
*/
public class UsersController implements Initializable {
@FXML
private TableView listTableView;
@FXML
private TableColumn listTableViewUsername;
@FXML
private TableColumn listTableViewName;
@FXML
private TableColumn listTableViewInsurer;
@FXML
private TableColumn listTableViewAddress;
@FXML
private TableColumn listTableViewPhone;
@FXML
private TableColumn listTableViewEmail;
@FXML
private TableColumn listTableViewWorkplace;
@FXML
private TableColumn listTableViewRole;
@FXML
private TextField listSearchField;
@FXML
private Button newAdd;
@FXML
private Button newReset;
@FXML
private Button newCancel;
@FXML
private TextField addAddress;
@FXML
private TextField addPostalcode;
@FXML
private TextField addResidence;
@FXML
private TextField addEmail;
@FXML
private TextField addTelephone;
@FXML
private TextField addMobile;
@FXML
private TextField addFirstname;
@FXML
private TextField addMiddlename;
@FXML
private TextField addLastname;
@FXML
protected void listOnSearch() {
String[] keywords = listSearchField.getText().split("\\s+");
String[] params = new String[4 * keywords.length];
boolean firstColumn = true;
String query = "";
for (int i = 0; i < keywords.length; i++) {
if (firstColumn) {
params[0 + i] = "%" + keywords[i] + "%";
query += "username LIKE ?";
} else {
params[0 + i] = "%" + keywords[i] + "%";
query += " OR username LIKE ?";
}
params[1 + i] = "%" + keywords[i] + "%";
query += " OR firstname LIKE ?";
params[2 + i] = "%" + keywords[i] + "%";
query += " OR lastname LIKE ?";
params[3 + i] = "%" + keywords[i] + "%";
query += " OR residence LIKE ?";
firstColumn = false;
}
listResetTableView(query, params);
}
private ObservableList<UserModel> data = FXCollections.observableArrayList();
/**
* Called on controller start
*
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
listResetTableView("", new String[0]);
}
public void listResetTableView(String where, String... params) {
UserModel users = new UserModel();
List<Model> allUsers = users.findAll(where, params);
data = FXCollections.observableArrayList();
for (int i = 0; i < allUsers.size(); i++) {
UserModel user = (UserModel) allUsers.get(i);
data.add(user);
}
listTableViewUsername.setCellValueFactory(new PropertyValueFactory("username"));
listTableViewName.setCellValueFactory(new PropertyValueFactory("fullname"));
listTableViewWorkplace.setCellValueFactory(new PropertyValueFactory("workplace"));
listTableViewRole.setCellValueFactory(new PropertyValueFactory("role"));
listTableView.setItems(data);
}
@FXML
public void listNew() {
StageHelper.addStage("users/add", this.getClass(), false, true);
}
public void newCancel() {
Stage addStage = (Stage) newCancel.getScene().getWindow();
StageHelper.closeStage(addStage);
}
public void newReset() {
addFirstname.setText("");
addMiddlename.setText("");
addLastname.setText("");
addAddress.setText("");
addPostalcode.setText("");
addResidence.setText("");
addEmail.setText("");
addTelephone.setText("");
addMobile.setText("");
}
public void newSave() {
}
}
|
package hudson.scm;
import hudson.model.AbstractBuild;
import hudson.model.User;
import hudson.scm.SubversionChangeLogSet.LogEntry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.AbstractList;
/**
* {@link ChangeLogSet} for Subversion.
*
* @author Kohsuke Kawaguchi
*/
public final class SubversionChangeLogSet extends ChangeLogSet<LogEntry> {
private final List<LogEntry> logs;
/**
* @GuardedBy this
*/
private Map<String,Long> revisionMap;
/*package*/ SubversionChangeLogSet(AbstractBuild build, List<LogEntry> logs) {
super(build);
this.logs = Collections.unmodifiableList(logs);
for (LogEntry log : logs)
log.setParent(this);
}
public boolean isEmptySet() {
return logs.isEmpty();
}
public List<LogEntry> getLogs() {
return logs;
}
public Iterator<LogEntry> iterator() {
return logs.iterator();
}
public synchronized Map<String,Long> getRevisionMap() throws IOException {
if(revisionMap==null)
revisionMap = SubversionSCM.parseRevisionFile(build);
return revisionMap;
}
/**
* One commit.
* <p>
* Setter methods are public only so that the objects can be constructed from Digester.
* So please consider this object read-only.
*/
public static class LogEntry extends ChangeLogSet.Entry {
private int revision;
private User author;
private String date;
private String msg;
private List<Path> paths = new ArrayList<Path>();
/**
* Gets the revision of the commit.
*
* <p>
* If the commit made the repository revision 1532, this
* method returns 1532.
*/
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public User getAuthor() {
return author;
}
@Override
public Collection<String> getAffectedPaths() {
return new AbstractList<String>() {
public String get(int index) {
return paths.get(index).value;
}
public int size() {
return paths.size();
}
};
}
public void setUser(String author) {
this.author = User.get(author);
}
public String getUser() {// digester wants read/write property, even though it never reads. Duh.
return author.getDisplayName();
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void addPath( Path p ) {
p.entry = this;
paths.add(p);
}
/**
* Gets the files that are changed in this commit.
* @return
* can be empty but never null.
*/
public List<Path> getPaths() {
return paths;
}
}
/**
* A file in a commit.
* <p>
* Setter methods are public only so that the objects can be constructed from Digester.
* So please consider this object read-only.
*/
public static class Path {
private LogEntry entry;
private char action;
private String value;
/**
* Gets the {@link LogEntry} of which this path is a member.
*/
public LogEntry getLogEntry() {
return entry;
}
public void setAction(String action) {
this.action = action.charAt(0);
}
/**
* Path in the repository. Such as <tt>/test/trunk/foo.c</tt>
*/
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public EditType getEditType() {
if( action=='A' )
return EditType.ADD;
if( action=='D' )
return EditType.DELETE;
return EditType.EDIT;
}
}
}
|
//$HeadURL: svn+ssh://aionita@svn.wald.intevation.org/deegree/base/trunk/resources/eclipse/files_template.xml $
package org.deegree.cs.configuration.wkt;
import static org.deegree.cs.projections.SupportedProjectionParameters.FALSE_EASTING;
import static org.deegree.cs.projections.SupportedProjectionParameters.FALSE_NORTHING;
import static org.deegree.cs.projections.SupportedProjectionParameters.FIRST_PARALLEL_LATITUDE;
import static org.deegree.cs.projections.SupportedProjectionParameters.LATITUDE_OF_NATURAL_ORIGIN;
import static org.deegree.cs.projections.SupportedProjectionParameters.LONGITUDE_OF_NATURAL_ORIGIN;
import static org.deegree.cs.projections.SupportedProjectionParameters.SCALE_AT_NATURAL_ORIGIN;
import static org.deegree.cs.projections.SupportedProjectionParameters.SECOND_PARALLEL_LATITUDE;
import static org.deegree.cs.utilities.ProjectionUtils.DTR;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.vecmath.Point2d;
import org.deegree.cs.CRSCodeType;
import org.deegree.cs.CRSIdentifiable;
import org.deegree.cs.components.Axis;
import org.deegree.cs.components.Ellipsoid;
import org.deegree.cs.components.GeodeticDatum;
import org.deegree.cs.components.PrimeMeridian;
import org.deegree.cs.components.Unit;
import org.deegree.cs.components.VerticalDatum;
import org.deegree.cs.coordinatesystems.CompoundCRS;
import org.deegree.cs.coordinatesystems.CoordinateSystem;
import org.deegree.cs.coordinatesystems.GeocentricCRS;
import org.deegree.cs.coordinatesystems.GeographicCRS;
import org.deegree.cs.coordinatesystems.ProjectedCRS;
import org.deegree.cs.coordinatesystems.VerticalCRS;
import org.deegree.cs.exceptions.UnknownUnitException;
import org.deegree.cs.exceptions.WKTParsingException;
import org.deegree.cs.projections.SupportedProjectionParameters;
import org.deegree.cs.projections.azimuthal.StereographicAlternative;
import org.deegree.cs.projections.azimuthal.StereographicAzimuthal;
import org.deegree.cs.projections.conic.LambertConformalConic;
import org.deegree.cs.projections.cylindric.TransverseMercator;
import org.deegree.cs.transformations.helmert.Helmert;
import org.slf4j.Logger;
public class WKTParser {
private static final Logger LOG = getLogger( WKTParser.class );
private StreamTokenizer tokenizer;
private Reader buff;
/**
*
* @param candidate
* @param paramName
* @return true if the candidate stripped of underscores equals ignore case the param name (also stripped).
*/
protected boolean equalsParameterVariants( String candidate, String paramName ) {
String candidateVariant = candidate.replace( "_", "" );
String paramVariant = paramName.replaceAll( "_", "" );
if ( candidateVariant.equalsIgnoreCase( paramVariant ) ) {
return true;
}
return false;
}
protected String makeInvariantKey( String candidate ) {
return candidate.replaceAll( "_", "" ).toLowerCase();
}
/**
* Walk a character (comma or round/square bracket).
*
* @param ch
* @throws IOException
* if an I/O error occurs.
* @throws WKTParsingException
* if the expected character is not present at this position.
*/
protected void passOverChar( char ch )
throws IOException {
tokenizer.nextToken();
if ( tokenizer.ttype != ch ) {
throw new WKTParsingException( "The tokenizer expects the character " + ch + " while the current token is "
+ tokenizer.toString() );
}
}
/**
* Walk an opening bracket (round or square).
*
* @throws IOException
* if an I/O error occurs.
* @throws WKTParsingException
* if the opening bracket is not present at this position.
*/
protected void passOverOpeningBracket()
throws IOException {
tokenizer.nextToken();
if ( tokenizer.ttype != '[' && tokenizer.ttype != '(' ) {
throw new WKTParsingException(
"The tokenizer expects an opening square/round bracket while the current token is "
+ tokenizer.toString() );
}
}
/**
* Walk a closing bracket (round or square).
*
* @throws IOException
* if an I/O error occurs.
* @throws WKTParsingException
* if the closing bracket is not present at this position.
*/
protected void passOverClosingBracket()
throws IOException {
tokenizer.nextToken();
if ( tokenizer.ttype != ']' && tokenizer.ttype != ')' )
throw new WKTParsingException(
"The tokenizer expects a closing square/round bracket while the current token is "
+ tokenizer.toString() );
}
/**
* Walk a WKT keyword element (e.g. DATUM, AUTHORITY, UNIT, etc.)
*
* @param s
* the keyword element as a String
* @throws IOException
* if an I/O error occurs.
* @throws WKTParsingException
* if the keyword is not present at this position.
*/
protected void passOverWord( String s )
throws IOException {
tokenizer.nextToken();
if ( tokenizer.sval == null || !tokenizer.sval.equalsIgnoreCase( s ) )
throw new WKTParsingException( "The tokenizer expects the word " + s + " while the current token is "
+ tokenizer.toString() );
}
/**
* @return a CRSCodeType object based on the information in the AUTHORITY element
* @throws IOException
* if an I/O error occurs
*/
protected CRSCodeType parseAuthority()
throws IOException {
passOverWord( "AUTHORITY" );
passOverOpeningBracket();
String codespace = parseString();
passOverChar( ',' );
String code = parseString();
passOverClosingBracket();
return new CRSCodeType( code, codespace );
}
/**
* @return the string that is surrounded by double-quotes
* @throws IOException
* if an I/O error occurs
* @throws WKTParsingException
* if the string does not begin with have an opening double-quote.
*/
protected String parseString()
throws IOException {
tokenizer.nextToken();
if ( tokenizer.ttype != '"' )
throw new WKTParsingException( "The tokenizer expects the opening double quote while the current token is "
+ tokenizer.toString() );
return tokenizer.sval;
}
/**
* @return an Axis
* @throws IOException
* @throws WKTParsingException
* if the axis orientation is not one of the values defined in the WKT reference ( NORTH | SOUTH | WEST
* | EAST | UP | DOWN | OTHER )
*/
protected Axis parseAxis()
throws IOException {
passOverWord( "AXIS" );
passOverOpeningBracket();
String name = parseString();
passOverChar( ',' );
tokenizer.nextToken();
String orientation = tokenizer.sval;
if ( !( orientation.equalsIgnoreCase( "NORTH" ) || orientation.equalsIgnoreCase( "SOUTH" )
|| orientation.equalsIgnoreCase( "WEST" ) || orientation.equalsIgnoreCase( "EAST" )
|| orientation.equalsIgnoreCase( "UP" ) || orientation.equalsIgnoreCase( "DOWN" ) || orientation.equalsIgnoreCase( "OTHER" ) ) )
throw new WKTParsingException(
"The tokenizer expects a valid Axis Orientation: NORTH | SOUTH | WEST | EAST | UP | DOWN | OTHER. The current token is "
+ tokenizer.toString() );
passOverClosingBracket();
return new Axis( name, "AO_" + orientation );
}
/**
* @return a Unit.
* @throws IOException
* @throws UnknownUnitException
* if the unit name does not match any of the predefined units in the API
*/
protected Unit parseUnit()
throws IOException {
passOverWord( "UNIT" );
passOverOpeningBracket();
String name = null;
// Double conversionFactor = null; // we do not identify a unit based on the conversion factor, only on the name
// CRSCodeType code = CRSCodeType.getUndefined(); // currently Units are not identifiable so the code parsed
// here is of no use
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_NUMBER:
// conversionFactor = tokenizer.nval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
// code = parseAuthority();
} else
throw new WKTParsingException( "Unknown word encountered in the UNIT element: " + tokenizer );
break;
default:
throw new WKTParsingException( "Unknown token encountered in the UNIT element: " + tokenizer );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( name == null ) {
throw new UnknownUnitException( "Unit name is missing" );
}
return Unit.createUnitFromString( name );
}
/**
* @return a Prime Meridian
* @throws IOException
*/
protected PrimeMeridian parsePrimeMeridian()
throws IOException {
passOverWord( "PRIMEM" );
passOverOpeningBracket();
String name = null;
Double longitude = null;
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_NUMBER:
longitude = tokenizer.nval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "Unknown word encountered in the PRIMEM element: " + tokenizer );
break;
default:
throw new WKTParsingException( "Unknown token encountered in the PRIMEM element: " + tokenizer );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( longitude == null )
throw new WKTParsingException( "The PRIMEM element must containt the longitude paramaeter. Before line "
+ tokenizer.lineno() );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new PrimeMeridian( Unit.RADIAN /* temporarily, until parsing the Unit of the wrapping CRS */, longitude,
new CRSIdentifiable( new CRSCodeType[] { code }, new String[] { name }, null, null,
null ) );
}
/**
* @return the Ellipsoid parsed from a WKT 'SPHEROID'.
* @throws IOException
*/
protected Ellipsoid parseEllipsoid()
throws IOException {
passOverWord( "SPHEROID" );
passOverOpeningBracket();
String name = null;
Double semiMajorAxis = null;
Double inverseFlattening = null;
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_NUMBER:
semiMajorAxis = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
inverseFlattening = tokenizer.nval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "Unknown word encountered in the SPHEROID element: " + tokenizer );
break;
default:
throw new WKTParsingException( "Unknown token encountered in the SPHEROID element: " + tokenizer );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( semiMajorAxis == null || inverseFlattening == null )
throw new WKTParsingException(
"Te SPHEROID element must contain the semi-major axis and inverse flattening parameters. Before line "
+ tokenizer.lineno() );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new Ellipsoid( semiMajorAxis, Unit.METRE, inverseFlattening,
new CRSIdentifiable( new CRSCodeType[] { code }, new String[] { name }, null, null, null ) );
}
/**
* @return the Helmert transformatio parsed from the WKT 'TOWGS84'
* @throws IOException
*/
protected Helmert parseHelmert()
throws IOException {
passOverWord( "TOWGS84" );
passOverOpeningBracket();
Double dx = null;
Double dy = null;
Double dz = null;
Double ex = null;
Double ey = null;
Double ez = null;
Double ppm = null;
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case StreamTokenizer.TT_NUMBER:
dx = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
dy = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
dz = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
ex = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
ey = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
ez = tokenizer.nval;
passOverChar( ',' );
tokenizer.nextToken();
ppm = tokenizer.nval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "The TOWGS84 contains an unknown keyword: " + tokenizer.sval
+ " at line " + tokenizer.lineno() );
break;
default:
throw new WKTParsingException( "The TOWGS84 contains an unknown keyword: " + tokenizer );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( dx == null || dy == null || dz == null || ex == null || ey == null || ez == null || ppm == null )
throw new WKTParsingException( "The TOWGS84 must contain all 7 parameters." );
return new Helmert( dx, dy, dz, ex, ey, ez, ppm, null, GeographicCRS.WGS84, code );
}
/**
* @return a Geodetic Datum parsed from WKT 'DATUM'
* @throws IOException
*/
protected GeodeticDatum parseGeodeticDatum()
throws IOException {
passOverWord( "DATUM" );
passOverOpeningBracket();
String name = null;
Ellipsoid ellipsoid = null;
Helmert helmert = new Helmert( null, GeographicCRS.WGS84, CRSCodeType.getUndefined() ); // undefined Helmert
// transformation
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "SPHEROID" ) ) {
tokenizer.pushBack();
ellipsoid = parseEllipsoid();
} else if ( tokenizer.sval.equalsIgnoreCase( "TOWGS84" ) ) {
tokenizer.pushBack();
helmert = parseHelmert();
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "The DATUM contains an unknown keyword: " + tokenizer.sval
+ " at line " + tokenizer.lineno() );
break;
default:
throw new WKTParsingException( "The DATUM contains an unknown keyword: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( ellipsoid == null )
throw new WKTParsingException( "The DATUM element must contain a SPHEROID. Before line "
+ tokenizer.lineno() );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new GeodeticDatum( ellipsoid, helmert, code, name );
}
/**
* @return a Vertical Datum parsed from WKT 'VERT_DATUM'
* @throws IOException
*/
protected VerticalDatum parseVerticalDatum()
throws IOException {
passOverWord( "VERT_DATUM" );
passOverOpeningBracket();
String name = null;
// Double datumType = null; // cannot find its use!
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "The VERT_DATUM contains an unknown keyword: " + tokenizer.sval
+ " at line " + tokenizer.lineno() );
break;
case StreamTokenizer.TT_NUMBER:
// datumType = tokenizer.nval;
break;
default:
throw new WKTParsingException( "The VERT_DATUM contains an unknown token: " + tokenizer );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( name == null ) {
throw new WKTParsingException(
"The VERT_DATUM element must contain a name as a quoted String. Before line "
+ tokenizer.lineno() );
}
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new VerticalDatum( code, name, null, null, null );
}
private CoordinateSystem realParseCoordinateSystem()
throws IOException {
tokenizer.nextToken();
String crsType = tokenizer.sval; // expecting StreamTokenizer.TT_WORD
// COMPOUND CRS
if ( equalsParameterVariants( crsType, "COMPD_CS" ) ) {
return parseCompoundCRS();
// PROJECTED CRS
} else if ( equalsParameterVariants( crsType, "PROJ_CS" ) ) {
return parseProjectedCRS();
// GEOGRAPHIC CRS
} else if ( equalsParameterVariants( crsType, "GEOG_CS" ) ) {
return parseGeographiCRS();
// GEOCENTRIC CRS
} else if ( equalsParameterVariants( crsType, "GEOC_CS" ) ) {
return parseGeocentricCRS();
// VERTICAL CRS
} else if ( equalsParameterVariants( crsType, "VERT_CS" ) ) {
return parseVerticalCRS();
} else
throw new WKTParsingException( "Expected a CRS element but an unknown keyword was encountered: "
+ tokenizer.sval + " at line " + tokenizer.lineno() );
}
/**
* @return a {@link VerticalCRS} parsed from the current reader position.
* @throws IOException
*/
protected VerticalCRS parseVerticalCRS()
throws IOException {
passOverOpeningBracket();
String name = null;
VerticalDatum verticalDatum = null;
Unit unit = null;
Axis axis = new Axis( "", Axis.AO_OTHER ); // in case there is no axis defined
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "VERT_DATUM" ) ) {
tokenizer.pushBack();
verticalDatum = parseVerticalDatum();
} else if ( tokenizer.sval.equalsIgnoreCase( "UNIT" ) ) {
tokenizer.pushBack();
unit = parseUnit();
} else if ( tokenizer.sval.equalsIgnoreCase( "AXIS" ) ) {
tokenizer.pushBack();
axis = parseAxis();
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "An unexpected keyword was encountered in the GEOCCS element: "
+ tokenizer.sval + ". At line: " + tokenizer.lineno() );
break;
default:
throw new WKTParsingException( "The VERT_CS contains an unknown token: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( unit == null )
throw new WKTParsingException( "The VERT_CS element must contain a UNIT keyword element. Before line "
+ tokenizer.lineno() );
if ( verticalDatum == null )
throw new WKTParsingException( "The VERT_CS element must contain a VERT_DATUM. Before line "
+ tokenizer.lineno() );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new VerticalCRS( verticalDatum, new Axis[] { axis }, new CRSIdentifiable( new CRSCodeType[] { code },
new String[] { name }, null,
null, null ) );
}
/**
* @return a {@link GeocentricCRS} parsed from the current reader position.
* @throws IOException
*/
protected GeocentricCRS parseGeocentricCRS()
throws IOException {
passOverOpeningBracket();
String name = null;
GeodeticDatum datum = null;
PrimeMeridian pm = null;
Unit unit = null;
// the default values of GEOCCS axes, based on the OGC specification
Axis axis1 = new Axis( "X", Axis.AO_OTHER );
Axis axis2 = new Axis( "Y", Axis.AO_EAST );
Axis axis3 = new Axis( "Z", Axis.AO_NORTH );
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "DATUM" ) ) {
tokenizer.pushBack();
datum = parseGeodeticDatum();
} else if ( tokenizer.sval.equalsIgnoreCase( "PRIMEM" ) ) {
tokenizer.pushBack();
pm = parsePrimeMeridian();
} else if ( tokenizer.sval.equalsIgnoreCase( "UNIT" ) ) {
tokenizer.pushBack();
unit = parseUnit();
} else if ( tokenizer.sval.equalsIgnoreCase( "AXIS" ) ) {
tokenizer.pushBack();
axis1 = parseAxis();
passOverChar( ',' );
axis2 = parseAxis();
passOverChar( ',' );
axis3 = parseAxis();
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "An unexpected keyword was encountered in the GEOCCS element: "
+ tokenizer.sval + ". At line: " + tokenizer.lineno() );
break;
default:
throw new WKTParsingException( "The GEOCCS contains an unknown token: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( unit == null )
throw new WKTParsingException( "The GEOCCS element must contain a UNIT keyword element. Before line "
+ tokenizer.lineno() );
if ( datum == null )
throw new WKTParsingException( "The GEOCCS element must contain a DATUM. Before line " + tokenizer.lineno() );
if ( pm == null )
throw new WKTParsingException( "The GEOCCS element must contain a PRIMEM. Before line "
+ tokenizer.lineno() );
pm.setAngularUnit( unit );
datum.setPrimeMeridian( pm );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new GeocentricCRS( datum, new Axis[] { axis1, axis2, axis3 },
new CRSIdentifiable( new CRSCodeType[] { code }, new String[] { name }, null, null,
null ) );
}
/**
* @return a {@link GeographicCRS} parsed from the current reader position.
* @throws IOException
*/
protected GeographicCRS parseGeographiCRS()
throws IOException {
passOverOpeningBracket();
String name = null;
GeodeticDatum datum = null;
PrimeMeridian pm = null;
Unit unit = null;
Axis axis1 = new Axis( Unit.DEGREE, "Lon", Axis.AO_EAST );
Axis axis2 = new Axis( Unit.DEGREE, "Lat", Axis.AO_NORTH );
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( tokenizer.sval.equalsIgnoreCase( "DATUM" ) ) {
tokenizer.pushBack();
datum = parseGeodeticDatum();
} else if ( tokenizer.sval.equalsIgnoreCase( "PRIMEM" ) ) {
tokenizer.pushBack();
pm = parsePrimeMeridian();
} else if ( tokenizer.sval.equalsIgnoreCase( "UNIT" ) ) {
tokenizer.pushBack();
unit = parseUnit();
} else if ( tokenizer.sval.equalsIgnoreCase( "AXIS" ) ) {
tokenizer.pushBack();
axis1 = parseAxis();
passOverChar( ',' );
axis2 = parseAxis();
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else
throw new WKTParsingException( "An unexpected keyword was encountered in the GEOGCS element: "
+ tokenizer.sval + ". At line: " + tokenizer.lineno() );
break;
default:
throw new WKTParsingException( "The GEOGCS contains an unknown token: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' )
break;
}
if ( name == null )
throw new WKTParsingException( "The GEOGCS element must contain a name as a quoted String. Before line "
+ tokenizer.lineno() );
if ( unit == null )
throw new WKTParsingException( "The GEOGCS element must contain a UNIT keyword element. Before line "
+ tokenizer.lineno() );
if ( datum == null )
throw new WKTParsingException( "The GEOGCS element must contain a DATUM. Before line " + tokenizer.lineno() );
if ( pm == null )
throw new WKTParsingException( "The GEOGCS element must contain a PRIMEM. Before line "
+ tokenizer.lineno() );
pm.setAngularUnit( unit );
datum.setPrimeMeridian( pm );
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new GeographicCRS( datum, new Axis[] { axis1, axis2 }, new CRSIdentifiable( new CRSCodeType[] { code },
new String[] { name }, null,
null, null ) );
}
/**
* @return a {@link ProjectedCRS} parsed from the current reader position.
* @throws IOException
*/
protected ProjectedCRS parseProjectedCRS()
throws IOException {
passOverOpeningBracket();
String name = null;
GeographicCRS geographicCRS = null;
String projectionType = null;
CRSCodeType projectionCode = CRSCodeType.getUndefined();
Map<String, Double> params = new HashMap<String, Double>();
Unit unit = null;
Axis axis1 = new Axis( "X", Axis.AO_EAST ); // the default values for PROJCS axes, based on the OGC
// specification
Axis axis2 = new Axis( "Y", Axis.AO_NORTH );
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( equalsParameterVariants( tokenizer.sval, "GEOG_CS" ) ) {
tokenizer.pushBack();
geographicCRS = (GeographicCRS) realParseCoordinateSystem();
} else if ( tokenizer.sval.equalsIgnoreCase( "PROJECTION" ) ) {
passOverOpeningBracket();
tokenizer.nextToken();
if ( tokenizer.ttype != '"' ) {
throw new WKTParsingException( "The PROJECTION element must contain a quoted String. At line "
+ tokenizer.lineno() );
}
projectionType = tokenizer.sval;
tokenizer.nextToken();
if ( tokenizer.ttype == ',' ) {
projectionCode = parseAuthority();
tokenizer.nextToken();
}
tokenizer.pushBack();
passOverClosingBracket();
} else if ( tokenizer.sval.equalsIgnoreCase( "PARAMETER" ) ) {
passOverOpeningBracket();
tokenizer.nextToken();
if ( tokenizer.ttype != '"' ) {
String msg = "The PARAMETER element must contain a quoted String as parameter name. At line "
+ tokenizer.lineno();
throw new WKTParsingException( msg );
}
CRSCodeType crscode = new CRSCodeType( makeInvariantKey( tokenizer.sval ) );
String paramName = SupportedProjectionParameters.fromCodes( new CRSCodeType[] { crscode } ).toString();
passOverChar( ',' );
tokenizer.nextToken();
if ( tokenizer.ttype != StreamTokenizer.TT_NUMBER ) {
String msg = "The PARAMETER element must contain a number as parameter value. At line "
+ tokenizer.lineno();
throw new WKTParsingException( msg );
}
Double paramValue = tokenizer.nval;
params.put( paramName, paramValue );
passOverClosingBracket();
} else if ( tokenizer.sval.equalsIgnoreCase( "AXIS" ) ) {
tokenizer.pushBack();
axis1 = parseAxis();
passOverChar( ',' );
axis2 = parseAxis();
} else if ( tokenizer.sval.equalsIgnoreCase( "UNIT" ) ) {
tokenizer.pushBack();
unit = parseUnit();
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else {
throw new WKTParsingException( "An unexpected keyword was encountered in the PROJCS element: "
+ tokenizer.sval + ". At line: " + tokenizer.lineno() );
}
break;
default:
throw new WKTParsingException( "The PROJ_CS contains an unknown token: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' ) {
break;
}
}
if ( geographicCRS == null ) {
throw new WKTParsingException( "The PROJCS element must contain a GEOGCS. Before line "
+ tokenizer.lineno() );
}
if ( projectionType == null || params.size() == 0 ) {
String msg = "The PROJCS element must contain a PROJECTION type as a String and a series of PARAMETERS. Before line "
+ tokenizer.lineno();
throw new WKTParsingException( msg );
}
if ( unit == null ) {
throw new WKTParsingException( "The PROJCS element must contain a UNIT keyword element. Before line "
+ tokenizer.lineno() );
}
params = setDefaultParameterValues( params );
if ( projectionCode.equals( CRSCodeType.getUndefined() ) ) {
projectionCode = new CRSCodeType( projectionType );
}
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
CRSIdentifiable baseCRS = new CRSIdentifiable( new CRSCodeType[] { code }, new String[] { name }, null, null,
null );
CRSIdentifiable baseProjCRS = new CRSIdentifiable( new CRSCodeType[] { projectionCode },
new String[] { projectionType }, null, null, null );
Point2d pointOrigin = new Point2d( DTR * determineLongitude( params ), DTR * determineLatitude( params ) );
Axis[] axes = new Axis[] { axis1, axis2 };
if ( projectionType.equalsIgnoreCase( "transverse_mercator" )
|| ( projectionType.equalsIgnoreCase( "transverse mercator" ) )
|| projectionType.equalsIgnoreCase( "Gauss_Kruger" ) ) {
return new ProjectedCRS( new TransverseMercator( true, geographicCRS,
params.get( FALSE_NORTHING.toString() ),
params.get( FALSE_EASTING.toString() ), pointOrigin, unit,
params.get( SCALE_AT_NATURAL_ORIGIN.toString() ),
baseProjCRS ), axes, baseCRS );
} else if ( projectionType.equalsIgnoreCase( "Lambert_Conformal_Conic_1SP" ) ) {
return new ProjectedCRS( new LambertConformalConic( geographicCRS, params.get( FALSE_NORTHING.toString() ),
params.get( FALSE_EASTING.toString() ), pointOrigin,
unit, params.get( SCALE_AT_NATURAL_ORIGIN.toString() ),
baseProjCRS ), axes, baseCRS );
} else if ( projectionType.equalsIgnoreCase( "Lambert_Conformal_Conic_2SP" )
|| projectionType.equalsIgnoreCase( "Lambert_Conformal_Conic" ) ) {
return new ProjectedCRS(
new LambertConformalConic(
DTR * params.get( FIRST_PARALLEL_LATITUDE.toString() ),
DTR * params.get( SECOND_PARALLEL_LATITUDE.toString() ),
geographicCRS, params.get( FALSE_NORTHING.toString() ),
params.get( FALSE_EASTING.toString() ), pointOrigin,
unit, params.get( SCALE_AT_NATURAL_ORIGIN.toString() ),
baseProjCRS ), axes, baseCRS );
} else if ( projectionType.equalsIgnoreCase( "Stereographic_Alternative" )
|| projectionType.equalsIgnoreCase( "Double_Stereographic" )
|| projectionType.equalsIgnoreCase( "Oblique_Stereographic" ) ) {
return new ProjectedCRS( new StereographicAlternative( geographicCRS,
params.get( FALSE_NORTHING.toString() ),
params.get( FALSE_EASTING.toString() ), pointOrigin,
unit,
params.get( SCALE_AT_NATURAL_ORIGIN.toString() ),
baseProjCRS ), axes, baseCRS );
} else if ( projectionType.equalsIgnoreCase( "Stereographic_Azimuthal" ) ) {
LOG.warn( "True scale latitude is not read from the StereoGraphic azimuthal projection yet." );
return new ProjectedCRS( new StereographicAzimuthal( geographicCRS,
params.get( FALSE_NORTHING.toString() ),
params.get( FALSE_EASTING.toString() ), pointOrigin,
unit,
params.get( SCALE_AT_NATURAL_ORIGIN.toString() ),
baseProjCRS ), axes, baseCRS );
} else {
throw new WKTParsingException( "The projection type " + projectionType + " is not supported." );
}
}
/**
* Determine the latitude of natural origin based on all the documented names under which it may appear (i.e. from
* {@link SupportedProjectionParameters} javadoc).
*/
private double determineLatitude( Map<String, Double> params ) {
Double latNatOrigin = null;
if ( params.containsKey( LATITUDE_OF_NATURAL_ORIGIN.toString() ) ) {
latNatOrigin = params.get( LATITUDE_OF_NATURAL_ORIGIN.toString() );
} else if ( params.containsKey( "projectionlatitude" ) ) {
latNatOrigin = params.get( "projectionlatitude" );
} else if ( params.containsKey( "central_latitude" ) ) {
latNatOrigin = params.get( "central_latitude" );
}
return latNatOrigin;
}
/**
* Determine the longitude of natural origin based on all the documented names under which it may appear (i.e. from
* {@link SupportedProjectionParameters} javadoc).
*/
private double determineLongitude( Map<String, Double> params ) {
Double longNatOrigin = null;
if ( params.containsKey( LONGITUDE_OF_NATURAL_ORIGIN.toString() ) ) {
longNatOrigin = params.get( LONGITUDE_OF_NATURAL_ORIGIN.toString() );
} else if ( params.containsKey( "central_meridian" ) ) {
longNatOrigin = params.get( "central_meridian" );
} else if ( params.containsKey( "projectionlongitude" ) ) {
longNatOrigin = params.get( "projectionlongitude" );
} else if ( params.containsKey( "projection_meridian" ) ) {
longNatOrigin = params.get( "projection_meridian" );
}
return longNatOrigin;
}
private Map<String, Double> setDefaultParameterValues( Map<String, Double> params ) {
if ( params.get( "semimajor" ) == null ) {
params.put( "semimajor", 0.0 );
}
if ( params.get( "semiminor" ) == null ) {
params.put( "semiminor", 0.0 );
}
if ( params.get( "latitudeoforigin" ) == null ) {
params.put( "latitudeoforigin", 0.0 );
} else {
params.put( "latitudeoforigin", DTR * params.get( "latitudeoforigin" ) );
}
if ( params.get( "centralmeridian" ) == null ) {
params.put( "centralmeridian", 0.0 );
} else {
params.put( "centralmeridian", DTR * params.get( "centralmeridian" ) );
}
if ( params.get( "scalefactor" ) == null ) {
params.put( "scalefactor", 1.0 );
}
if ( params.get( "falseeasting" ) == null ) {
params.put( "falseeasting", 0.0 );
}
if ( params.get( "falsenorthing" ) == null ) {
params.put( "falsenorthing", 0.0 );
}
if ( params.get( "standardparallel1" ) == null ) {
params.put( "standardparallel1", 0.0 );
} else {
params.put( "standardparallel1", DTR * params.get( "standardparallel1" ) );
}
if ( params.get( "standardparallel2" ) == null ) {
params.put( "standardparallel2", 0.0 );
} else {
params.put( "standardparallel2", DTR * params.get( "standardparallel2" ) );
}
return params;
}
/**
* Parses a {@link CompoundCRS} from the current WKT location.
*
* @return a {@link CompoundCRS} parsed from the current reader position.
* @throws IOException
*/
protected CompoundCRS parseCompoundCRS()
throws IOException {
passOverOpeningBracket();
String name = null;
List<CoordinateSystem> twoCRSs = new ArrayList<CoordinateSystem>();
CRSCodeType code = CRSCodeType.getUndefined();
while ( true ) {
tokenizer.nextToken();
switch ( tokenizer.ttype ) {
case '"':
name = tokenizer.sval;
break;
case StreamTokenizer.TT_WORD:
if ( equalsParameterVariants( tokenizer.sval, "COMPD_CS" )
|| equalsParameterVariants( tokenizer.sval, "PROJ_CS" )
|| equalsParameterVariants( tokenizer.sval, "GEOG_CS" )
|| equalsParameterVariants( tokenizer.sval, "GEOC_CS" )
|| equalsParameterVariants( tokenizer.sval, "VERT_CS" ) ) {
tokenizer.pushBack();
twoCRSs.add( realParseCoordinateSystem() );
} else if ( tokenizer.sval.equalsIgnoreCase( "AUTHORITY" ) ) {
tokenizer.pushBack();
code = parseAuthority();
} else {
throw new WKTParsingException(
"Found a keyword different that AUTHORITY or any supported CRS inside the COMPD_CS. At line: "
+ tokenizer.lineno() );
}
break;
default:
throw new WKTParsingException( "The COMPD_CS contains an unknown token: " + tokenizer + " at line "
+ tokenizer.lineno() );
}
tokenizer.nextToken();
if ( tokenizer.ttype == ']' || tokenizer.ttype == ')' ) {
break;
}
}
if ( twoCRSs.size() != 2 ) {
throw new WKTParsingException( "The COMPD_CS element has two contain exactly 2 CRSs. Before line "
+ tokenizer.lineno() );
}
if ( name == null ) {
throw new WKTParsingException( "The COMPD_CS element must contain a name as a quoted String. Before line "
+ tokenizer.lineno() );
}
VerticalCRS verticalCRS = null;
CoordinateSystem underlyingCRS = null;
if ( twoCRSs.get( 0 ) instanceof VerticalCRS ) {
verticalCRS = (VerticalCRS) twoCRSs.get( 0 );
underlyingCRS = twoCRSs.get( 1 );
} else if ( twoCRSs.get( 1 ) instanceof VerticalCRS ) {
verticalCRS = (VerticalCRS) twoCRSs.get( 1 );
underlyingCRS = twoCRSs.get( 0 );
} else {
throw new WKTParsingException( "One of the CRSs from the COMPD_CS element must be a VERT_CS. Before line "
+ tokenizer.lineno() );
}
if ( code.equals( CRSCodeType.getUndefined() ) ) {
code = new CRSCodeType( name );
}
return new CompoundCRS( verticalCRS.getVerticalAxis(), underlyingCRS, 0.0,
new CRSIdentifiable( new CRSCodeType[] { code }, new String[] { name }, null, null,
null ) );
}
/**
* @return a Coordinate System ( Compound CRS, Projected CRS, Geographic CRS, Geocentric CRS, Vertical CRS)
* @throws IOException
* if the provided WKT has a syntax error
*/
public CoordinateSystem parseCoordinateSystem()
throws IOException {
try {
return realParseCoordinateSystem();
} finally {
buff.close();
}
}
/**
* Constructor
*
* @param fileName
* the file that contains a Coordinate System definition
* @throws IOException
* if the provided WKT has a syntax error
*/
public WKTParser( String fileName ) throws IOException {
this( new File( fileName ) );
}
/**
* Create a WKTParser which reads data from the given reader.
*/
private WKTParser( Reader reader ) {
this.buff = reader;
tokenizer = new StreamTokenizer( buff );
tokenizer.wordChars( '_', '_' );
}
/**
* @param fileName
* to read a wkt from.
* @throws FileNotFoundException
*/
public WKTParser( File fileName ) throws FileNotFoundException {
this( new BufferedReader( new FileReader( fileName ) ) );
}
/**
* @param wkt
* the wkt code as a {@link String}
* @return the parsed {@link CoordinateSystem}
* @throws IOException
* if the provided WKT has a syntax error
*/
public static CoordinateSystem parse( String wkt )
throws IOException {
WKTParser parse = new WKTParser( new BufferedReader( new StringReader( wkt ) ) );
return parse.parseCoordinateSystem();
}
}
|
package ch.rgw.compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.compress.bzip2.CBZip2InputStream;
import org.apache.commons.compress.bzip2.CBZip2OutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.rgw.tools.BinConverter;
import ch.rgw.tools.ExHandler;
import ch.rgw.tools.StringTool;
/**
* Compressor/Expander
*/
public class CompEx {
public static final Logger log = LoggerFactory.getLogger(CompEx.class);
public static final int NONE = 0;
public static final int GLZ = 1 << 29;
public static final int RLL = 2 << 29;
public static final int HUFF = 3 << 29;
public static final int BZIP2 = 4 << 29;
public static final int ZIP = 5 << 29;
public static final byte[] Compress(String in, int mode){
if (StringTool.isNothing(in)) {
return null;
}
try {
return Compress(in.getBytes(StringTool.getDefaultCharset()), mode);
} catch (Exception ex) {
ExHandler.handle(ex);
return null;
}
}
public static final byte[] Compress(byte[] in, int mode){
if (in == null) {
return null;
}
ByteArrayInputStream bais = new ByteArrayInputStream(in);
return Compress(bais, mode);
}
public static final byte[] Compress(InputStream in, int mode){
try {
switch (mode) {
case GLZ:
return CompressGLZ(in);
case BZIP2:
return CompressBZ2(in);
case ZIP:
return CompressZIP(in);
// case HUFF: return CompressHuff(in);
}
} catch (Exception ex) {
ExHandler.handle(ex);
}
return null;
}
public static byte[] CompressGLZ(InputStream in) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[4];
// BinConverter.intToByteArray(0,buf,0);
baos.write(buf);
GLZ glz = new GLZ();
long total = glz.compress(in, baos);
byte[] ret = baos.toByteArray();
total &= 0x1fffffff;
total |= GLZ;
BinConverter.intToByteArray((int) total, ret, 0);
return ret;
}
public static byte[] CompressBZ2(InputStream in) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
baos.write(buf, 0, 4);
CBZip2OutputStream bzo = new CBZip2OutputStream(baos);
int l;
int total = 0;
;
while ((l = in.read(buf, 0, buf.length)) != -1) {
bzo.write(buf, 0, l);
total += l;
}
bzo.close();
byte[] ret = baos.toByteArray();
total &= 0x1fffffff;
total |= BZIP2;
BinConverter.intToByteArray(total, ret, 0);
return ret;
}
public static byte[] CompressZIP(InputStream in) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
baos.write(buf, 0, 4);
ZipOutputStream zo = new ZipOutputStream(baos);
zo.putNextEntry(new ZipEntry("Data"));
int l;
long total = 0;
;
while ((l = in.read(buf, 0, buf.length)) != -1) {
zo.write(buf, 0, l);
total += l;
}
zo.close();
byte[] ret = baos.toByteArray();
total &= 0x1fffffff;
total |= ZIP;
BinConverter.intToByteArray((int) total, ret, 0);
return ret;
}
public static byte[] expand(byte[] in){
if (in == null) {
return null;
}
ByteArrayInputStream bais = new ByteArrayInputStream(in);
return expand(bais);
}
public static byte[] expand(InputStream in){
ByteArrayOutputStream baos;
byte[] siz = new byte[4];
try {
in.read(siz);
long size = BinConverter.byteArrayToInt(siz, 0);
long typ = size & ~0x1fffffff;
size &= 0x1fffffff;
// more than 100 MB
if (size > 100000000) {
log.warn("Given InputStream exceeds 100 MB please check DB");
String empty = "... Text nicht lesbar. \nBitte Datenbankeintrag prüfen!";
return empty.getBytes();
}
byte[] ret = new byte[(int) size];
switch ((int) typ) {
case BZIP2:
CBZip2InputStream bzi = new CBZip2InputStream(in);
int off = 0;
int l = 0;
while ((l = bzi.read(ret, off, ret.length - off)) > 0) {
off += l;
}
bzi.close();
in.close();
return ret;
case GLZ:
GLZ glz = new GLZ();
baos = new ByteArrayOutputStream();
glz.expand(in, baos);
return baos.toByteArray();
case HUFF:
HuffmanInputStream hin = new HuffmanInputStream(in);
off = 0;
l = 0;
while ((l = hin.read(ret, off, ret.length - off)) > 0) {
off += l;
}
hin.close();
return ret;
case ZIP:
ZipInputStream zi = new ZipInputStream(in);
zi.getNextEntry();
off = 0;
l = 0;
while ((l = zi.read(ret, off, ret.length - off)) > 0) {
off += l;
}
zi.close();
return ret;
default:
throw new Exception("Invalid compress format");
}
} catch (Exception ex) {
ExHandler.handle(ex);
return null;
}
}
}
|
package com.evolveum.midpoint.provisioning.ucf.impl;
import com.evolveum.midpoint.common.crypto.EncryptionException;
import com.evolveum.midpoint.common.crypto.Protector;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.ChangeType;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.schema.PrismSchema;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.provisioning.ucf.api.*;
import com.evolveum.midpoint.provisioning.ucf.query.FilterInterpreter;
import com.evolveum.midpoint.provisioning.ucf.util.UcfUtil;
import com.evolveum.midpoint.schema.constants.ConnectorTestOperation;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.holder.XPathHolder;
import com.evolveum.midpoint.schema.holder.XPathSegment;
import com.evolveum.midpoint.schema.processor.*;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceObjectShadowUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_2.*;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.*;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.ActivationCapabilityType.EnableDisable;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.ObjectFactory;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_2.ScriptCapabilityType.Host;
import com.evolveum.prism.xml.ns._public.query_2.QueryType;
import com.evolveum.prism.xml.ns._public.types_2.PolyStringType;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.Validate;
import org.identityconnectors.common.pooling.ObjectPoolConfiguration;
import org.identityconnectors.common.security.GuardedByteArray;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.framework.api.*;
import org.identityconnectors.framework.api.operations.*;
import org.identityconnectors.framework.common.objects.*;
import org.identityconnectors.framework.common.objects.AttributeInfo.Flags;
import org.identityconnectors.framework.common.objects.filter.EqualsFilter;
import org.identityconnectors.framework.common.objects.filter.Filter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.namespace.QName;
import java.io.File;
import java.lang.reflect.Array;
import java.util.*;
import static com.evolveum.midpoint.provisioning.ucf.impl.IcfUtil.processIcfException;
/**
* Implementation of ConnectorInstance for ICF connectors.
* <p/>
* This class implements the ConnectorInstance interface. The methods are
* converting the data from the "midPoint semantics" as seen by the
* ConnectorInstance interface to the "ICF semantics" as seen by the ICF
* framework.
*
* @author Radovan Semancik
*/
public class ConnectorInstanceIcfImpl implements ConnectorInstance {
private static final String CUSTOM_OBJECTCLASS_PREFIX = "Custom";
private static final String CUSTOM_OBJECTCLASS_SUFFIX = "ObjectClass";
private static final ObjectFactory capabilityObjectFactory = new ObjectFactory();
private static final Trace LOGGER = TraceManager.getTrace(ConnectorInstanceIcfImpl.class);
ConnectorInfo cinfo;
ConnectorType connectorType;
ConnectorFacade icfConnectorFacade;
String resourceSchemaNamespace;
Protector protector;
PrismContext prismContext;
private boolean initialized = false;
private ResourceSchema resourceSchema = null;
private PrismSchema connectorSchema;
Set<Object> capabilities = null;
public ConnectorInstanceIcfImpl(ConnectorInfo connectorInfo, ConnectorType connectorType,
String schemaNamespace, PrismSchema connectorSchema, Protector protector,
PrismContext prismContext) {
this.cinfo = connectorInfo;
this.connectorType = connectorType;
this.resourceSchemaNamespace = schemaNamespace;
this.connectorSchema = connectorSchema;
this.protector = protector;
this.prismContext = prismContext;
}
public String getSchemaNamespace() {
return resourceSchemaNamespace;
}
/*
* (non-Javadoc)
*
* @see
* com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance#configure
* (com.evolveum.midpoint.xml.ns._public.common.common_2.Configuration)
*/
@Override
public void configure(PrismContainerValue configuration, OperationResult parentResult)
throws CommunicationException, GenericFrameworkException, SchemaException, ConfigurationException {
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".configure");
result.addParam("configuration", configuration);
try {
// Get default configuration for the connector. This is important,
// as it contains types of connector configuration properties.
// Make sure that the proper configuration schema is applied. This
// will cause that all the "raw" elements are parsed
configuration.applyDefinition(getConfigurationContainerDefinition());
APIConfiguration apiConfig = cinfo.createDefaultAPIConfiguration();
// Transform XML configuration from the resource to the ICF
// connector
// configuration
try {
transformConnectorConfiguration(apiConfig, configuration);
} catch (SchemaException e) {
result.recordFatalError(e.getMessage(), e);
throw e;
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Configuring connector {}", connectorType);
for (String propName : apiConfig.getConfigurationProperties().getPropertyNames()) {
LOGGER.trace("P: {} = {}", propName,
apiConfig.getConfigurationProperties().getProperty(propName).getValue());
}
}
// Create new connector instance using the transformed configuration
icfConnectorFacade = ConnectorFacadeFactory.getInstance().newInstance(apiConfig);
result.recordSuccess();
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, result);
result.computeStatus("Removing attribute values failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof ConfigurationException) {
throw (ConfigurationException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
}
private PrismContainerDefinition getConfigurationContainerDefinition() throws SchemaException {
if (connectorSchema == null) {
generateConnectorSchema();
}
QName configContainerQName = new QName(connectorType.getNamespace(),
ResourceType.F_CONFIGURATION.getLocalPart());
PrismContainerDefinition configContainerDef = connectorSchema
.findContainerDefinitionByElementName(configContainerQName);
if (configContainerDef == null) {
throw new SchemaException("No definition of container " + configContainerQName
+ " in configuration schema for connector " + this);
}
return configContainerDef;
}
/**
* @param cinfo
* @param connectorType
*/
public PrismSchema generateConnectorSchema() {
LOGGER.trace("Generating configuration schema for {}", this);
APIConfiguration defaultAPIConfiguration = cinfo.createDefaultAPIConfiguration();
ConfigurationProperties icfConfigurationProperties = defaultAPIConfiguration
.getConfigurationProperties();
if (icfConfigurationProperties == null || icfConfigurationProperties.getPropertyNames() == null
|| icfConfigurationProperties.getPropertyNames().isEmpty()) {
LOGGER.debug("No configuration schema for {}", this);
return null;
}
PrismSchema mpSchema = new PrismSchema(connectorType.getNamespace(), prismContext);
// Create configuration type - the type used by the "configuration"
// element
PrismContainerDefinition configurationContainerDef = mpSchema.createPropertyContainerDefinition(
ResourceType.F_CONFIGURATION.getLocalPart(),
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_TYPE_LOCAL_NAME);
// element with "ConfigurationPropertiesType" - the dynamic part of
// configuration schema
ComplexTypeDefinition configPropertiesTypeDef = mpSchema.createComplexTypeDefinition(new QName(
connectorType.getNamespace(),
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_TYPE_LOCAL_NAME));
// Create definition of "configurationProperties" type
// (CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_TYPE_LOCAL_NAME)
for (String icfPropertyName : icfConfigurationProperties.getPropertyNames()) {
ConfigurationProperty icfProperty = icfConfigurationProperties.getProperty(icfPropertyName);
QName propXsdType = icfTypeToXsdType(icfProperty.getType(), icfProperty.isConfidential());
LOGGER.trace("{}: Mapping ICF config schema property {} from {} to {}", new Object[] { this,
icfPropertyName, icfProperty.getType(), propXsdType });
PrismPropertyDefinition propertyDefinifion = configPropertiesTypeDef.createPropertyDefinition(
icfPropertyName, propXsdType);
propertyDefinifion.setDisplayName(icfProperty.getDisplayName(null));
propertyDefinifion.setHelp(icfProperty.getHelpMessage(null));
if (isMultivaluedType(icfProperty.getType())) {
propertyDefinifion.setMaxOccurs(-1);
} else {
propertyDefinifion.setMaxOccurs(1);
}
if (icfProperty.isRequired()) {
propertyDefinifion.setMinOccurs(1);
} else {
propertyDefinifion.setMinOccurs(0);
}
}
// Create common ICF configuration property containers as a references
// to a static schema
configurationContainerDef.createContainerDefinition(
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_ELEMENT,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_TYPE, 0, 1);
configurationContainerDef.createPropertyDefinition(
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_ELEMENT,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_TYPE, 0, 1);
configurationContainerDef.createContainerDefinition(
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_TIMEOUTS_ELEMENT,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_TIMEOUTS_TYPE, 0, 1);
// No need to create definition of "configuration" element.
// midPoint will look for this element, but it will be generated as part
// of the PropertyContainer serialization to schema
configurationContainerDef.createContainerDefinition(
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME,
configPropertiesTypeDef, 1, 1);
LOGGER.debug("Generated configuration schema for {}: {} definitions", this, mpSchema.getDefinitions()
.size());
connectorSchema = mpSchema;
return mpSchema;
}
private QName icfTypeToXsdType(Class<?> type, boolean isConfidential) {
// For arrays we are only interested in the component type
if (isMultivaluedType(type)) {
type = type.getComponentType();
}
QName propXsdType = null;
if (GuardedString.class.equals(type) ||
(String.class.equals(type) && isConfidential)) {
// GuardedString is a special case. It is a ICF-specific
// type
// implementing Potemkin-like security. Use a temporary
// "nonsense" type for now, so this will fail in tests and
// will be fixed later
propXsdType = SchemaConstants.R_PROTECTED_STRING_TYPE;
} else if (GuardedByteArray.class.equals(type) ||
(Byte.class.equals(type) && isConfidential)) {
// GuardedString is a special case. It is a ICF-specific
// type
// implementing Potemkin-like security. Use a temporary
// "nonsense" type for now, so this will fail in tests and
// will be fixed later
propXsdType = SchemaConstants.R_PROTECTED_BYTE_ARRAY_TYPE;
} else {
propXsdType = XsdTypeMapper.toXsdType(type);
}
return propXsdType;
}
private boolean isMultivaluedType(Class<?> type) {
// We consider arrays to be multi-valued
// ... unless it is byte[] or char[]
return type.isArray() && !type.equals(byte[].class) && !type.equals(char[].class);
}
/**
* Retrieves schema from the resource.
* <p/>
* Transforms native ICF schema to the midPoint representation.
*
* @return midPoint resource schema.
* @see com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance#initialize(com.evolveum.midpoint.schema.result.OperationResult)
*/
@Override
public void initialize(OperationResult parentResult) throws CommunicationException,
GenericFrameworkException, ConfigurationException {
// Result type for this operation
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".initialize");
result.addContext("connector", connectorType);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ConnectorFactoryIcfImpl.class);
if (icfConnectorFacade == null) {
result.recordFatalError("Attempt to use unconfigured connector");
throw new IllegalStateException("Attempt to use unconfigured connector "
+ ObjectTypeUtil.toShortString(connectorType));
}
// Connector operation cannot create result for itself, so we need to
// create result for it
OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".schema");
icfResult.addContext("connector", icfConnectorFacade.getClass());
org.identityconnectors.framework.common.objects.Schema icfSchema = null;
try {
// Fetch the schema from the connector (which actually gets that
// from the resource).
icfSchema = icfConnectorFacade.schema();
icfResult.recordSuccess();
} catch (UnsupportedOperationException ex) {
// The connector does no support schema() operation.
result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Connector does not support schema");
resourceSchema = null;
initialized = true;
return;
} catch (Exception ex) {
// conditions.
// Therefore this kind of heavy artillery is necessary.
// ICF interface does not specify exceptions or other error
// TODO maybe we can try to catch at least some specific exceptions
Exception midpointEx = processIcfException(ex, icfResult);
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof CommunicationException) {
result.recordFatalError("ICF communication error: " + midpointEx.getMessage(), midpointEx);
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof ConfigurationException) {
result.recordFatalError("ICF configuration error: " + midpointEx.getMessage(), midpointEx);
throw (ConfigurationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
result.recordFatalError("ICF error: " + midpointEx.getMessage(), midpointEx);
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
result.recordFatalError("ICF error: " + midpointEx.getMessage(), midpointEx);
throw (RuntimeException) midpointEx;
} else {
result.recordFatalError("Internal error: " + midpointEx.getMessage(), midpointEx);
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
parseResourceSchema(icfSchema);
initialized = true;
result.recordSuccess();
}
@Override
public ResourceSchema getResourceSchema(OperationResult parentResult) throws CommunicationException,
GenericFrameworkException, ConfigurationException {
// Result type for this operation
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".getResourceSchema");
result.addContext("connector", connectorType);
if (!initialized) {
// initialize the connector if it was not initialized yet
try {
initialize(result);
} catch (CommunicationException ex) {
result.recordFatalError(ex);
throw ex;
} catch (ConfigurationException ex) {
result.recordFatalError(ex);
throw ex;
} catch (GenericFrameworkException ex) {
result.recordFatalError(ex);
throw ex;
}
}
result.recordSuccess();
return resourceSchema;
}
private void parseResourceSchema(org.identityconnectors.framework.common.objects.Schema icfSchema) {
boolean capPassword = false;
boolean capEnable = false;
// New instance of midPoint schema object
resourceSchema = new ResourceSchema(getSchemaNamespace(), prismContext);
// Let's convert every objectclass in the ICF schema ...
Set<ObjectClassInfo> objectClassInfoSet = icfSchema.getObjectClassInfo();
for (ObjectClassInfo objectClassInfo : objectClassInfoSet) {
// "Flat" ICF object class names needs to be mapped to QNames
QName objectClassXsdName = objectClassToQname(objectClassInfo.getType());
// ResourceObjectDefinition is a midPpoint way how to represent an
// object class.
// The important thing here is the last "type" parameter
// (objectClassXsdName). The rest is more-or-less cosmetics.
ObjectClassComplexTypeDefinition roDefinition = resourceSchema
.createObjectClassDefinition(objectClassXsdName);
// The __ACCOUNT__ objectclass in ICF is a default account
// objectclass. So mark it appropriately.
if (ObjectClass.ACCOUNT_NAME.equals(objectClassInfo.getType())) {
roDefinition.setAccountType(true);
roDefinition.setDefaultAccountType(true);
}
// Every object has UID in ICF, therefore add it right now
ResourceAttributeDefinition uidDefinition = roDefinition.createAttributeDefinition(
ConnectorFactoryIcfImpl.ICFS_UID, DOMUtil.XSD_STRING);
// DO NOT make it mandatory. It must not be present on create hence it cannot be mandatory.
uidDefinition.setMinOccurs(0);
uidDefinition.setMaxOccurs(1);
// Make it read-only
uidDefinition.setReadOnly();
// Set a default display name
uidDefinition.setDisplayName("ICF UID");
// Uid is a primary identifier of every object (this is the ICF way)
roDefinition.getIdentifiers().add(uidDefinition);
// Let's iterate over all attributes in this object class ...
Set<AttributeInfo> attributeInfoSet = objectClassInfo.getAttributeInfo();
for (AttributeInfo attributeInfo : attributeInfoSet) {
if (OperationalAttributes.PASSWORD_NAME.equals(attributeInfo.getName())) {
// This attribute will not go into the schema
// instead a "password" capability is used
capPassword = true;
// Skip this attribute, capability is sufficient
continue;
}
if (OperationalAttributes.ENABLE_NAME.equals(attributeInfo.getName())) {
capEnable = true;
// Skip this attribute, capability is sufficient
continue;
}
QName attrXsdName = convertAttributeNameToQName(attributeInfo.getName());
QName attrXsdType = icfTypeToXsdType(attributeInfo.getType(), false);
// Create ResourceObjectAttributeDefinition, which is midPoint
// way how to express attribute schema.
ResourceAttributeDefinition roaDefinition = roDefinition.createAttributeDefinition(
attrXsdName, attrXsdType);
if (attrXsdName.equals(ConnectorFactoryIcfImpl.ICFS_NAME)) {
// Set a better display name for __NAME__. The "name" is s very
// overloaded term, so let's try to make things
// a bit clearer
roaDefinition.setDisplayName("ICF NAME");
roDefinition.getSecondaryIdentifiers().add(roaDefinition);
}
// Now we are going to process flags such as optional and
// multi-valued
Set<Flags> flagsSet = attributeInfo.getFlags();
// System.out.println(flagsSet);
roaDefinition.setMinOccurs(0);
roaDefinition.setMaxOccurs(1);
boolean canCreate = true;
boolean canUpdate = true;
boolean canRead = true;
for (Flags flags : flagsSet) {
if (flags == Flags.REQUIRED) {
roaDefinition.setMinOccurs(1);
}
if (flags == Flags.MULTIVALUED) {
roaDefinition.setMaxOccurs(-1);
}
if (flags == Flags.NOT_CREATABLE) {
canCreate = false;
}
if (flags == Flags.NOT_READABLE) {
canRead = false;
}
if (flags == Flags.NOT_UPDATEABLE) {
canUpdate = false;
}
if (flags == Flags.NOT_RETURNED_BY_DEFAULT) {
// TODO
}
}
roaDefinition.setCreate(canCreate);
roaDefinition.setUpdate(canUpdate);
roaDefinition.setRead(canRead);
}
// Add schema annotations
roDefinition.setNativeObjectClass(objectClassInfo.getType());
roDefinition.setDisplayNameAttribute(ConnectorFactoryIcfImpl.ICFS_NAME);
roDefinition.setNamingAttribute(ConnectorFactoryIcfImpl.ICFS_NAME);
}
capabilities = new HashSet<Object>();
if (capEnable) {
ActivationCapabilityType capAct = new ActivationCapabilityType();
EnableDisable capEnableDisable = new EnableDisable();
capAct.setEnableDisable(capEnableDisable);
capabilities.add(capabilityObjectFactory.createActivation(capAct));
}
if (capPassword) {
CredentialsCapabilityType capCred = new CredentialsCapabilityType();
PasswordCapabilityType capPass = new PasswordCapabilityType();
capCred.setPassword(capPass);
capabilities.add(capabilityObjectFactory.createCredentials(capCred));
}
// Create capabilities from supported connector operations
Set<Class<? extends APIOperation>> supportedOperations = icfConnectorFacade.getSupportedOperations();
if (supportedOperations.contains(SyncApiOp.class)) {
LiveSyncCapabilityType capSync = new LiveSyncCapabilityType();
capabilities.add(capabilityObjectFactory.createLiveSync(capSync));
}
if (supportedOperations.contains(TestApiOp.class)) {
TestConnectionCapabilityType capTest = new TestConnectionCapabilityType();
capabilities.add(capabilityObjectFactory.createTestConnection(capTest));
}
if (supportedOperations.contains(ScriptOnResourceApiOp.class)
|| supportedOperations.contains(ScriptOnConnectorApiOp.class)) {
ScriptCapabilityType capScript = new ScriptCapabilityType();
if (supportedOperations.contains(ScriptOnResourceApiOp.class)) {
Host host = new Host();
host.setType(ScriptHostType.RESOURCE);
capScript.getHost().add(host);
// language is unknown here
}
if (supportedOperations.contains(ScriptOnConnectorApiOp.class)) {
Host host = new Host();
host.setType(ScriptHostType.CONNECTOR);
capScript.getHost().add(host);
// language is unknown here
}
capabilities.add(capabilityObjectFactory.createScript(capScript));
}
}
@Override
public Set<Object> getCapabilities(OperationResult parentResult) throws CommunicationException,
GenericFrameworkException, ConfigurationException {
// Result type for this operation
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".getCapabilities");
result.addContext("connector", connectorType);
if (!initialized) {
// initialize the connector if it was not initialized yet
try {
initialize(result);
} catch (CommunicationException ex) {
result.recordFatalError(ex);
throw ex;
} catch (ConfigurationException ex) {
result.recordFatalError(ex);
throw ex;
} catch (GenericFrameworkException ex) {
result.recordFatalError(ex);
throw ex;
}
}
result.recordSuccess();
return capabilities;
}
@Override
public <T extends ResourceObjectShadowType> PrismObject<T> fetchObject(Class<T> type,
ObjectClassComplexTypeDefinition objectClassDefinition,
Collection<? extends ResourceAttribute> identifiers, boolean returnDefaultAttributes,
Collection<? extends ResourceAttributeDefinition> attributesToReturn, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, GenericFrameworkException,
SchemaException {
// Result type for this operation
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".fetchObject");
result.addParam("resourceObjectDefinition", objectClassDefinition);
result.addParam("identifiers", identifiers);
result.addContext("connector", connectorType);
if (icfConnectorFacade == null) {
result.recordFatalError("Attempt to use unconfigured connector");
throw new IllegalStateException("Attempt to use unconfigured connector "
+ ObjectTypeUtil.toShortString(connectorType));
}
// Get UID from the set of identifiers
Uid uid = getUid(identifiers);
if (uid == null) {
result.recordFatalError("Required attribute UID not found in identification set while attempting to fetch object identified by "
+ identifiers + " from " + ObjectTypeUtil.toShortString(connectorType));
throw new IllegalArgumentException(
"Required attribute UID not found in identification set while attempting to fetch object identified by "
+ identifiers + " from " + ObjectTypeUtil.toShortString(connectorType));
}
ObjectClass icfObjectClass = objectClassToIcf(objectClassDefinition);
if (icfObjectClass == null) {
result.recordFatalError("Unable to detemine object class from QName "
+ objectClassDefinition.getTypeName()
+ " while attempting to fetch object identified by " + identifiers + " from "
+ ObjectTypeUtil.toShortString(connectorType));
throw new IllegalArgumentException("Unable to detemine object class from QName "
+ objectClassDefinition.getTypeName()
+ " while attempting to fetch object identified by " + identifiers + " from "
+ ObjectTypeUtil.toShortString(connectorType));
}
ConnectorObject co = null;
try {
// Invoke the ICF connector
co = fetchConnectorObject(icfObjectClass, uid, returnDefaultAttributes, attributesToReturn,
result);
} catch (CommunicationException ex) {
result.recordFatalError("ICF invocation failed due to communication problem");
// This is fatal. No point in continuing. Just re-throw the
// exception.
throw ex;
} catch (GenericFrameworkException ex) {
result.recordFatalError("ICF invocation failed due to a generic ICF framework problem");
// This is fatal. No point in continuing. Just re-throw the
// exception.
throw ex;
}
if (co == null) {
result.recordFatalError("Object not found");
throw new ObjectNotFoundException("Object identified by " + identifiers + " was not found by "
+ ObjectTypeUtil.toShortString(connectorType));
}
PrismObjectDefinition<T> shadowDefinition = toShadowDefinition(objectClassDefinition);
PrismObject<T> shadow = convertToResourceObject(co, shadowDefinition, true);
result.recordSuccess();
return shadow;
}
private <T extends ResourceObjectShadowType> PrismObjectDefinition<T> toShadowDefinition(
ObjectClassComplexTypeDefinition objectClassDefinition) {
ResourceAttributeContainerDefinition resourceAttributeContainerDefinition = objectClassDefinition
.toResourceAttributeContainerDefinition(ResourceObjectShadowType.F_ATTRIBUTES);
return resourceAttributeContainerDefinition.toShadowDefinition();
}
/**
* Returns null if nothing is found.
*/
private ConnectorObject fetchConnectorObject(ObjectClass icfObjectClass, Uid uid,
boolean returnDefaultAttributes,
Collection<? extends ResourceAttributeDefinition> attributesToReturn, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, GenericFrameworkException {
// Connector operation cannot create result for itself, so we need to
// create result for it
OperationResult icfResult = parentResult.createSubresult(ConnectorFacade.class.getName()
+ ".getObject");
icfResult.addParam("objectClass", icfObjectClass.toString());
icfResult.addParam("uid", uid.getUidValue());
icfResult.addContext("connector", icfConnectorFacade.getClass());
ConnectorObject co = null;
try {
OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
// Invoke the ICF connector
co = icfConnectorFacade.getObject(icfObjectClass, uid, optionsBuilder.build());
icfResult.recordSuccess();
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
icfResult.computeStatus("Add object failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
return co;
}
@Override
public Collection<ResourceAttribute<?>> addObject(PrismObject<? extends ResourceObjectShadowType> object,
Set<Operation> additionalOperations, OperationResult parentResult) throws CommunicationException,
GenericFrameworkException, SchemaException, ObjectAlreadyExistsException {
validateShadow(object, "add", false);
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(object);
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".addObject");
result.addParam("resourceObject", object);
result.addParam("additionalOperations", additionalOperations);
// getting icf object class from resource object class
ObjectClass objectClass = objectClassToIcf(object);
if (objectClass == null) {
result.recordFatalError("Couldn't get icf object class from " + object);
throw new IllegalArgumentException("Couldn't get icf object class from " + object);
}
// setting ifc attributes from resource object attributes
Set<Attribute> attributes = null;
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("midPoint object before conversion:\n{}", attributesContainer.dump());
}
attributes = convertFromResourceObject(attributesContainer, result);
if (object.asObjectable() instanceof AccountShadowType) {
AccountShadowType account = (AccountShadowType) object.asObjectable();
if (account.getCredentials() != null && account.getCredentials().getPassword() != null) {
PasswordType password = account.getCredentials().getPassword();
ProtectedStringType protectedString = password.getProtectedString();
GuardedString guardedPassword = toGuardedString(protectedString, "new password");
attributes.add(AttributeBuilder.build(OperationalAttributes.PASSWORD_NAME,
guardedPassword));
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("ICF attributes after conversion:\n{}", IcfUtil.dump(attributes));
}
} catch (SchemaException ex) {
result.recordFatalError(
"Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
throw new SchemaException("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
}
if (attributes == null) {
result.recordFatalError("Couldn't set attributes for icf.");
throw new IllegalStateException("Couldn't set attributes for icf.");
}
// Look for a password change operation
// if (additionalOperations != null) {
// for (Operation op : additionalOperations) {
// if (op instanceof PasswordChangeOperation) {
// PasswordChangeOperation passwordChangeOperation =
// (PasswordChangeOperation) op;
// // Activation change means modification of attributes
// convertFromPassword(attributes, passwordChangeOperation);
OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".create");
icfResult.addParam("objectClass", objectClass);
icfResult.addParam("attributes", attributes);
icfResult.addParam("options", null);
icfResult.addContext("connector", icfConnectorFacade);
Uid uid = null;
try {
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.BEFORE);
// CALL THE ICF FRAMEWORK
uid = icfConnectorFacade.create(objectClass, attributes, new OperationOptionsBuilder().build());
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.AFTER);
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
result.computeStatus("Add object failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof ObjectAlreadyExistsException) {
throw (ObjectAlreadyExistsException) midpointEx;
} else if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
if (uid == null || uid.getUidValue() == null || uid.getUidValue().isEmpty()) {
icfResult.recordFatalError("ICF did not returned UID after create");
result.computeStatus("Add object failed");
throw new GenericFrameworkException("ICF did not returned UID after create");
}
ResourceAttributeDefinition uidDefinition = getUidDefinition(attributesContainer.getDefinition());
if (uidDefinition == null) {
throw new IllegalArgumentException("No definition for ICF UID attribute found in definition "
+ attributesContainer.getDefinition());
}
ResourceAttribute attribute = createUidAttribute(uid, uidDefinition);
attributesContainer.getValue().addReplaceExisting(attribute);
icfResult.recordSuccess();
result.recordSuccess();
return attributesContainer.getAttributes();
}
private void validateShadow(PrismObject<? extends ResourceObjectShadowType> shadow, String operation,
boolean requireUid) {
if (shadow == null) {
throw new IllegalArgumentException("Cannot " + operation + " null " + shadow);
}
PrismContainer<?> attributesContainer = shadow.findContainer(ResourceObjectShadowType.F_ATTRIBUTES);
if (attributesContainer == null) {
throw new IllegalArgumentException("Cannot " + operation + " shadow without attributes container");
}
ResourceAttributeContainer resourceAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
if (resourceAttributesContainer == null) {
throw new IllegalArgumentException("Cannot " + operation
+ " shadow without attributes container of type ResourceAttributeContainer, got "
+ attributesContainer.getClass());
}
if (requireUid) {
Collection<ResourceAttribute<?>> identifiers = resourceAttributesContainer.getIdentifiers();
if (identifiers == null || identifiers.isEmpty()) {
throw new IllegalArgumentException("Cannot " + operation + " shadow without identifiers");
}
}
}
@Override
public Set<PropertyModificationOperation> modifyObject(ObjectClassComplexTypeDefinition objectClass,
Collection<? extends ResourceAttribute> identifiers, Set<Operation> changes,
OperationResult parentResult) throws ObjectNotFoundException, CommunicationException,
GenericFrameworkException, SchemaException {
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".modifyObject");
result.addParam("objectClass", objectClass);
result.addParam("identifiers", identifiers);
result.addParam("changes", changes);
if (changes.isEmpty()){
LOGGER.info("No modifications for connector object specified. Skipping processing.");
result.recordSuccess();
return new HashSet<PropertyModificationOperation>();
}
ObjectClass objClass = objectClassToIcf(objectClass);
Uid uid = getUid(identifiers);
String originalUid = uid.getUidValue();
Collection<ResourceAttribute<?>> addValues = new HashSet<ResourceAttribute<?>>();
Collection<ResourceAttribute<?>> updateValues = new HashSet<ResourceAttribute<?>>();
Collection<ResourceAttribute<?>> valuesToRemove = new HashSet<ResourceAttribute<?>>();
Set<Operation> additionalOperations = new HashSet<Operation>();
PasswordChangeOperation passwordChangeOperation = null;
Collection<PropertyDelta> activationDeltas = new HashSet<PropertyDelta>();
PropertyDelta<?> passwordDelta = null;
for (Operation operation : changes) {
if (operation instanceof PropertyModificationOperation) {
PropertyModificationOperation change = (PropertyModificationOperation) operation;
PropertyDelta<?> delta = change.getPropertyDelta();
if (delta.getParentPath().equals(new PropertyPath(ResourceObjectShadowType.F_ATTRIBUTES))) {
if (delta.getDefinition() == null || !(delta.getDefinition() instanceof ResourceAttributeDefinition)) {
ResourceAttributeDefinition def = objectClass
.findAttributeDefinition(delta.getName());
delta.applyDefinition(def);
}
// Change in (ordinary) attributes. Transform to the ICF
// attributes.
if (delta.isAdd()) {
ResourceAttribute addAttribute = (ResourceAttribute) delta.instantiateEmptyProperty();
addAttribute.addValues(PrismValue.cloneCollection(delta.getValuesToAdd()));
addValues.add(addAttribute);
}
if (delta.isDelete()) {
ResourceAttribute deleteAttribute = (ResourceAttribute) delta
.instantiateEmptyProperty();
deleteAttribute.addValues(PrismValue.cloneCollection(delta.getValuesToDelete()));
valuesToRemove.add(deleteAttribute);
}
if (delta.isReplace()) {
ResourceAttribute updateAttribute = (ResourceAttribute) delta
.instantiateEmptyProperty();
updateAttribute.addValues(PrismValue.cloneCollection(delta.getValuesToReplace()));
updateValues.add(updateAttribute);
}
} else if (delta.getParentPath().equals(new PropertyPath(AccountShadowType.F_ACTIVATION))) {
activationDeltas.add(delta);
} else if (delta.getParentPath().equals(
new PropertyPath(new PropertyPath(AccountShadowType.F_CREDENTIALS),
CredentialsType.F_PASSWORD))) {
passwordDelta = delta;
} else {
throw new SchemaException("Change of unknown attribute " + delta.getName());
}
} else if (operation instanceof PasswordChangeOperation) {
passwordChangeOperation = (PasswordChangeOperation) operation;
// TODO: check for multiple occurrences and fail
} else if (operation instanceof ExecuteScriptOperation) {
ExecuteScriptOperation scriptOperation = (ExecuteScriptOperation) operation;
additionalOperations.add(scriptOperation);
} else {
throw new IllegalArgumentException("Unknown operation type " + operation.getClass().getName()
+ ": " + operation);
}
}
// Needs three complete try-catch blocks because we need to create
// icfResult for each operation
// and handle the faults individually
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.BEFORE);
OperationResult icfResult = null;
try {
if (addValues != null && !addValues.isEmpty()) {
Set<Attribute> attributes = null;
try {
attributes = convertFromResourceObject(addValues, result);
} catch (SchemaException ex) {
result.recordFatalError("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
throw new SchemaException("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
}
OperationOptions options = new OperationOptionsBuilder().build();
icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".addAttributeValues");
icfResult.addParam("objectClass", objectClass);
icfResult.addParam("uid", uid.getUidValue());
icfResult.addParam("attributes", attributes);
icfResult.addParam("options", options);
icfResult.addContext("connector", icfConnectorFacade);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(
"Invoking ICF addAttributeValues(), objectclass={}, uid={}, attributes=\n{}",
new Object[] { objClass, uid, dumpAttributes(attributes) });
}
uid = icfConnectorFacade.addAttributeValues(objClass, uid, attributes, options);
icfResult.recordSuccess();
}
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
result.computeStatus("Adding attribute values failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof ObjectNotFoundException) {
throw (ObjectNotFoundException) midpointEx;
} else if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
if (updateValues != null && !updateValues.isEmpty() || activationDeltas != null
|| passwordDelta != null) {
Set<Attribute> updateAttributes = null;
try {
updateAttributes = convertFromResourceObject(updateValues, result);
} catch (SchemaException ex) {
result.recordFatalError(
"Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
throw new SchemaException("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
}
if (activationDeltas != null) {
// Activation change means modification of attributes
convertFromActivation(updateAttributes, activationDeltas);
}
if (passwordDelta != null) {
// Activation change means modification of attributes
convertFromPassword(updateAttributes, passwordDelta);
}
OperationOptions options = new OperationOptionsBuilder().build();
icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".update");
icfResult.addParam("objectClass", objectClass);
icfResult.addParam("uid", uid.getUidValue());
icfResult.addParam("attributes", updateAttributes);
icfResult.addParam("options", options);
icfResult.addContext("connector", icfConnectorFacade);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Invoking ICF update(), objectclass={}, uid={}, attributes=\n{}", new Object[] {
objClass, uid, dumpAttributes(updateAttributes) });
}
try {
// Call ICF
uid = icfConnectorFacade.update(objClass, uid, updateAttributes, options);
icfResult.recordSuccess();
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
result.computeStatus("Update failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof ObjectNotFoundException) {
throw (ObjectNotFoundException) midpointEx;
} else if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
}
try {
if (valuesToRemove != null && !valuesToRemove.isEmpty()) {
Set<Attribute> attributes = null;
try {
attributes = convertFromResourceObject(valuesToRemove, result);
} catch (SchemaException ex) {
result.recordFatalError("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
throw new SchemaException("Error while converting resource object attributes. Reason: "
+ ex.getMessage(), ex);
}
OperationOptions options = new OperationOptionsBuilder().build();
icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".update");
icfResult.addParam("objectClass", objectClass);
icfResult.addParam("uid", uid.getUidValue());
icfResult.addParam("attributes", attributes);
icfResult.addParam("options", options);
icfResult.addContext("connector", icfConnectorFacade);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(
"Invoking ICF removeAttributeValues(), objectclass={}, uid={}, attributes=\n{}",
new Object[] { objClass, uid, dumpAttributes(attributes) });
}
uid = icfConnectorFacade.removeAttributeValues(objClass, uid, attributes, options);
icfResult.recordSuccess();
}
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
result.computeStatus("Removing attribute values failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof ObjectNotFoundException) {
throw (ObjectNotFoundException) midpointEx;
} else if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.AFTER);
result.recordSuccess();
Set<PropertyModificationOperation> sideEffectChanges = new HashSet<PropertyModificationOperation>();
if (!originalUid.equals(uid.getUidValue())) {
// UID was changed during the operation, this is most likely a
// rename
PropertyDelta uidDelta = createUidDelta(uid, getUidDefinition(identifiers));
PropertyModificationOperation uidMod = new PropertyModificationOperation(uidDelta);
sideEffectChanges.add(uidMod);
}
return sideEffectChanges;
}
private PropertyDelta createUidDelta(Uid uid, ResourceAttributeDefinition uidDefinition) {
PropertyDelta uidDelta = new PropertyDelta(new PropertyPath(ResourceObjectShadowType.F_ATTRIBUTES),
uidDefinition);
uidDelta.setValueToReplace(new PrismPropertyValue<String>(uid.getUidValue()));
return uidDelta;
}
private String dumpAttributes(Set<Attribute> attributes) {
if (attributes == null) {
return "null";
}
StringBuilder sb = new StringBuilder();
for (Attribute attr : attributes) {
for (Object value : attr.getValue()) {
sb.append(attr.getName());
sb.append(" = ");
sb.append(value);
sb.append("\n");
}
}
return sb.toString();
}
@Override
public void deleteObject(ObjectClassComplexTypeDefinition objectClass,
Set<Operation> additionalOperations, Collection<? extends ResourceAttribute> identifiers,
OperationResult parentResult) throws ObjectNotFoundException, CommunicationException,
GenericFrameworkException {
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".deleteObject");
result.addParam("identifiers", identifiers);
ObjectClass objClass = objectClassToIcf(objectClass);
Uid uid = getUid(identifiers);
OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".delete");
icfResult.addParam("uid", uid);
icfResult.addParam("objectClass", objClass);
icfResult.addContext("connector", icfConnectorFacade);
try {
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.BEFORE);
icfConnectorFacade.delete(objClass, uid, new OperationOptionsBuilder().build());
checkAndExecuteAdditionalOperation(additionalOperations, ScriptOrderType.AFTER);
icfResult.recordSuccess();
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
result.computeStatus("Removing attribute values failed");
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof ObjectNotFoundException) {
throw (ObjectNotFoundException) midpointEx;
} else if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
// Schema exception during delete? It must be a missing UID
throw new IllegalArgumentException(midpointEx.getMessage(), midpointEx);
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
result.recordSuccess();
}
@Override
public PrismProperty deserializeToken(Object serializedToken) {
return createTokenProperty(serializedToken);
}
@Override
public PrismProperty fetchCurrentToken(ObjectClassComplexTypeDefinition objectClass,
OperationResult parentResult) throws CommunicationException, GenericFrameworkException {
OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".deleteObject");
result.addParam("objectClass", objectClass);
ObjectClass objClass = objectClassToIcf(objectClass);
SyncToken syncToken = icfConnectorFacade.getLatestSyncToken(objClass);
if (syncToken == null) {
result.recordFatalError("No token found");
throw new IllegalArgumentException("No token found.");
}
PrismProperty property = getToken(syncToken);
result.recordSuccess();
return property;
}
@Override
public List<Change> fetchChanges(ObjectClassComplexTypeDefinition objectClass, PrismProperty lastToken,
OperationResult parentResult) throws CommunicationException, GenericFrameworkException,
SchemaException, ConfigurationException {
OperationResult subresult = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".fetchChanges");
subresult.addContext("objectClass", objectClass);
subresult.addParam("lastToken", lastToken);
// create sync token from the property last token
SyncToken syncToken = null;
try {
syncToken = getSyncToken(lastToken);
LOGGER.trace("Sync token created from the property last token: {}", syncToken.getValue());
} catch (SchemaException ex) {
subresult.recordFatalError(ex.getMessage(), ex);
throw new SchemaException(ex.getMessage(), ex);
}
final List<SyncDelta> syncDeltas = new ArrayList<SyncDelta>();
// get icf object class
ObjectClass icfObjectClass = objectClassToIcf(objectClass);
SyncResultsHandler syncHandler = new SyncResultsHandler() {
@Override
public boolean handle(SyncDelta delta) {
LOGGER.trace("Detected sync delta: {}", delta);
return syncDeltas.add(delta);
}
};
OperationResult icfResult = subresult.createSubresult(ConnectorFacade.class.getName() + ".sync");
icfResult.addContext("connector", icfConnectorFacade);
icfResult.addParam("icfObjectClass", icfObjectClass);
icfResult.addParam("syncToken", syncToken);
icfResult.addParam("syncHandler", syncHandler);
try {
icfConnectorFacade.sync(icfObjectClass, syncToken, syncHandler,
new OperationOptionsBuilder().build());
icfResult.recordSuccess();
icfResult.addReturn(OperationResult.RETURN_COUNT, syncDeltas.size());
} catch (Exception ex) {
Exception midpointEx = processIcfException(ex, icfResult);
subresult.computeStatus();
// Do some kind of acrobatics to do proper throwing of checked
// exception
if (midpointEx instanceof CommunicationException) {
throw (CommunicationException) midpointEx;
} else if (midpointEx instanceof GenericFrameworkException) {
throw (GenericFrameworkException) midpointEx;
} else if (midpointEx instanceof SchemaException) {
throw (SchemaException) midpointEx;
} else if (midpointEx instanceof RuntimeException) {
throw (RuntimeException) midpointEx;
} else {
throw new SystemException("Got unexpected exception: " + ex.getClass().getName(), ex);
}
}
// convert changes from icf to midpoint Change
List<Change> changeList = null;
try {
PrismSchema schema = getResourceSchema(subresult);
changeList = getChangesFromSyncDeltas(icfObjectClass, syncDeltas, schema, subresult);
} catch (SchemaException ex) {
subresult.recordFatalError(ex.getMessage(), ex);
throw new SchemaException(ex.getMessage(), ex);
}
subresult.recordSuccess();
subresult.addReturn(OperationResult.RETURN_COUNT, changeList == null ? 0 : changeList.size());
return changeList;
}
@Override
public void test(OperationResult parentResult) {
OperationResult connectionResult = parentResult
.createSubresult(ConnectorTestOperation.CONNECTOR_CONNECTION.getOperation());
connectionResult.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ConnectorInstance.class);
connectionResult.addContext("connector", connectorType);
try {
icfConnectorFacade.test();
connectionResult.recordSuccess();
} catch (UnsupportedOperationException ex) {
// Connector does not support test connection.
connectionResult.recordStatus(OperationResultStatus.NOT_APPLICABLE,
"Operation not supported by the connector", ex);
// Do not rethrow. Recording the status is just OK.
} catch (Exception icfEx) {
Exception midPointEx = processIcfException(icfEx, connectionResult);
connectionResult.recordFatalError(midPointEx);
}
}
@Override
public <T extends ResourceObjectShadowType> void search(Class<T> type,
ObjectClassComplexTypeDefinition objectClassDefinition, ObjectQuery query,
final ResultHandler<T> handler, OperationResult parentResult) throws CommunicationException,
GenericFrameworkException, SchemaException {
// Result type for this operation
final OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName()
+ ".search");
result.addParam("objectClass", objectClassDefinition);
result.addContext("connector", connectorType);
if (objectClassDefinition == null) {
result.recordFatalError("Object class not defined");
throw new IllegalArgumentException("objectClass not defined");
}
ObjectClass icfObjectClass = objectClassToIcf(objectClassDefinition);
if (icfObjectClass == null) {
IllegalArgumentException ex = new IllegalArgumentException(
"Unable to detemine object class from QName " + objectClassDefinition
+ " while attempting to search objects by "
+ ObjectTypeUtil.toShortString(connectorType));
result.recordFatalError("Unable to detemine object class", ex);
throw ex;
}
final PrismObjectDefinition<T> objectDefinition = toShadowDefinition(objectClassDefinition);
ResultsHandler icfHandler = new ResultsHandler() {
@Override
public boolean handle(ConnectorObject connectorObject) {
// Convert ICF-specific connector object to a generic
// ResourceObject
PrismObject<T> resourceObject;
try {
resourceObject = convertToResourceObject(connectorObject, objectDefinition, true);
} catch (SchemaException e) {
throw new IntermediateException(e);
}
// .. and pass it to the handler
boolean cont = handler.handle(resourceObject);
if (!cont) {
result.recordPartialError("Stopped on request from the handler");
}
return cont;
}
};
// Connector operation cannot create result for itself, so we need to
// create result for it
OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".search");
icfResult.addParam("objectClass", icfObjectClass);
icfResult.addContext("connector", icfConnectorFacade.getClass());
try {
Filter filter = null;
if (query != null && query.getFilter() != null) {
// TODO : translation between connector filter and midpoint
// filter
FilterInterpreter interpreter = new FilterInterpreter(getSchemaNamespace());
LOGGER.trace("Start to convert filter: {}", query.getFilter().dump());
filter = interpreter.interpret(query.getFilter());
LOGGER.trace("ICF filter: {}", filter.toString());
}
icfConnectorFacade.search(icfObjectClass, filter, icfHandler, null);
icfResult.recordSuccess();
} catch (IntermediateException inex) {
SchemaException ex = (SchemaException) inex.getCause();
throw ex;
} catch (Exception ex) {
// ICF interface does not specify exceptions or other error
// conditions.
// Therefore this kind of heavy artillery is necessary.
// TODO maybe we can try to catch at least some specific exceptions
icfResult.recordFatalError(ex);
result.recordFatalError("ICF invocation failed");
// This is fatal. No point in continuing.
throw new GenericFrameworkException(ex);
}
if (result.isUnknown()) {
result.recordSuccess();
}
}
// UTILITY METHODS
private QName convertAttributeNameToQName(String icfAttrName) {
LOGGER.trace("icf attribute: {}", icfAttrName);
QName attrXsdName = new QName(getSchemaNamespace(), icfAttrName,
ConnectorFactoryIcfImpl.NS_ICF_RESOURCE_INSTANCE_PREFIX);
// Handle special cases
if (Name.NAME.equals(icfAttrName)) {
// this is ICF __NAME__ attribute. It will look ugly in XML and may
// even cause problems.
// so convert to something more friendly such as icfs:name
attrXsdName = ConnectorFactoryIcfImpl.ICFS_NAME;
}
LOGGER.trace("attr xsd name: {}", attrXsdName);
return attrXsdName;
}
// private String convertAttributeNameToIcf(QName attrQName, OperationResult parentResult)
// throws SchemaException {
// // Attribute QNames in the resource instance namespace are converted
// // "as is"
// if (attrQName.getNamespaceURI().equals(getSchemaNamespace())) {
// return attrQName.getLocalPart();
// // Other namespace are special cases
// if (ConnectorFactoryIcfImpl.ICFS_NAME.equals(attrQName)) {
// return Name.NAME;
// if (ConnectorFactoryIcfImpl.ICFS_UID.equals(attrQName)) {
// // UID is strictly speaking not an attribute. But it acts as an
// // attribute e.g. in create operation. Therefore we need to map it.
// return Uid.NAME;
// // No mapping available
// throw new SchemaException("No mapping from QName " + attrQName + " to an ICF attribute name");
/**
* Maps ICF native objectclass name to a midPoint QName objctclass name.
* <p/>
* The mapping is "stateless" - it does not keep any mapping database or any
* other state. There is a bi-directional mapping algorithm.
* <p/>
* TODO: mind the special characters in the ICF objectclass names.
*/
private QName objectClassToQname(String icfObjectClassString) {
if (ObjectClass.ACCOUNT_NAME.equals(icfObjectClassString)) {
return new QName(getSchemaNamespace(), ConnectorFactoryIcfImpl.ACCOUNT_OBJECT_CLASS_LOCAL_NAME,
ConnectorFactoryIcfImpl.NS_ICF_SCHEMA_PREFIX);
} else if (ObjectClass.GROUP_NAME.equals(icfObjectClassString)) {
return new QName(getSchemaNamespace(), ConnectorFactoryIcfImpl.GROUP_OBJECT_CLASS_LOCAL_NAME,
ConnectorFactoryIcfImpl.NS_ICF_SCHEMA_PREFIX);
} else {
return new QName(getSchemaNamespace(), CUSTOM_OBJECTCLASS_PREFIX + icfObjectClassString
+ CUSTOM_OBJECTCLASS_SUFFIX, ConnectorFactoryIcfImpl.NS_ICF_RESOURCE_INSTANCE_PREFIX);
}
}
private ObjectClass objectClassToIcf(PrismObject<? extends ResourceObjectShadowType> object) {
ResourceObjectShadowType shadowType = object.asObjectable();
QName qnameObjectClass = shadowType.getObjectClass();
if (qnameObjectClass == null) {
ResourceAttributeContainer attrContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadowType);
if (attrContainer == null) {
return null;
}
ResourceAttributeContainerDefinition objectClassDefinition = attrContainer.getDefinition();
qnameObjectClass = objectClassDefinition.getTypeName();
}
return objectClassToIcf(qnameObjectClass);
}
/**
* Maps a midPoint QName objctclass to the ICF native objectclass name.
* <p/>
* The mapping is "stateless" - it does not keep any mapping database or any
* other state. There is a bi-directional mapping algorithm.
* <p/>
* TODO: mind the special characters in the ICF objectclass names.
*/
private ObjectClass objectClassToIcf(ObjectClassComplexTypeDefinition objectClassDefinition) {
QName qnameObjectClass = objectClassDefinition.getTypeName();
return objectClassToIcf(qnameObjectClass);
}
private ObjectClass objectClassToIcf(QName qnameObjectClass) {
if (!getSchemaNamespace().equals(qnameObjectClass.getNamespaceURI())) {
throw new IllegalArgumentException("ObjectClass QName " + qnameObjectClass
+ " is not in the appropriate namespace for "
+ ObjectTypeUtil.toShortString(connectorType) + ", expected: " + getSchemaNamespace());
}
String lname = qnameObjectClass.getLocalPart();
if (ConnectorFactoryIcfImpl.ACCOUNT_OBJECT_CLASS_LOCAL_NAME.equals(lname)) {
return ObjectClass.ACCOUNT;
} else if (ConnectorFactoryIcfImpl.GROUP_OBJECT_CLASS_LOCAL_NAME.equals(lname)) {
return ObjectClass.GROUP;
} else if (lname.startsWith(CUSTOM_OBJECTCLASS_PREFIX) && lname.endsWith(CUSTOM_OBJECTCLASS_SUFFIX)) {
String icfObjectClassName = lname.substring(CUSTOM_OBJECTCLASS_PREFIX.length(), lname.length()
- CUSTOM_OBJECTCLASS_SUFFIX.length());
return new ObjectClass(icfObjectClassName);
} else {
throw new IllegalArgumentException("Cannot recognize objectclass QName " + qnameObjectClass
+ " for " + ObjectTypeUtil.toShortString(connectorType) + ", expected: "
+ getSchemaNamespace());
}
}
/**
* Looks up ICF Uid identifier in a (potentially multi-valued) set of
* identifiers. Handy method to convert midPoint identifier style to an ICF
* identifier style.
*
* @param identifiers
* midPoint resource object identifiers
* @return ICF UID or null
*/
private Uid getUid(Collection<? extends ResourceAttribute> identifiers) {
for (ResourceAttribute attr : identifiers) {
if (attr.getName().equals(ConnectorFactoryIcfImpl.ICFS_UID)) {
return new Uid(((ResourceAttribute<String>) attr).getValue().getValue());
}
}
return null;
}
private ResourceAttributeDefinition getUidDefinition(ResourceAttributeContainerDefinition def) {
return def.findAttributeDefinition(ConnectorFactoryIcfImpl.ICFS_UID);
}
private ResourceAttributeDefinition getUidDefinition(Collection<? extends ResourceAttribute> identifiers) {
for (ResourceAttribute attr : identifiers) {
if (attr.getName().equals(ConnectorFactoryIcfImpl.ICFS_UID)) {
return attr.getDefinition();
}
}
return null;
}
private ResourceAttribute createUidAttribute(Uid uid, ResourceAttributeDefinition uidDefinition) {
ResourceAttribute uidRoa = uidDefinition.instantiate();
uidRoa.setValue(new PrismPropertyValue<String>(uid.getUidValue()));
return uidRoa;
}
/**
* Converts ICF ConnectorObject to the midPoint ResourceObject.
* <p/>
* All the attributes are mapped using the same way as they are mapped in
* the schema (which is actually no mapping at all now).
* <p/>
* If an optional ResourceObjectDefinition was provided, the resulting
* ResourceObject is schema-aware (getDefinition() method works). If no
* ResourceObjectDefinition was provided, the object is schema-less. TODO:
* this still needs to be implemented.
*
* @param co
* ICF ConnectorObject to convert
* @param def
* ResourceObjectDefinition (from the schema) or null
* @param full
* if true it describes if the returned resource object should
* contain all of the attributes defined in the schema, if false
* the returned resource object will contain olny attributed with
* the non-null values.
* @return new mapped ResourceObject instance.
* @throws SchemaException
*/
private <T extends ResourceObjectShadowType> PrismObject<T> convertToResourceObject(ConnectorObject co,
PrismObjectDefinition<T> objectDefinition, boolean full) throws SchemaException {
PrismObject<T> shadowPrism = null;
if (objectDefinition != null) {
shadowPrism = objectDefinition.instantiate();
} else {
throw new SchemaException("No definition");
}
// LOGGER.trace("Instantiated prism object {} from connector object.",
// shadowPrism.dump());
T shadow = shadowPrism.asObjectable();
ResourceAttributeContainer attributesContainer = (ResourceAttributeContainer) shadowPrism
.findOrCreateContainer(ResourceObjectShadowType.F_ATTRIBUTES);
ResourceAttributeContainerDefinition attributesDefinition = attributesContainer.getDefinition();
shadow.setObjectClass(attributesDefinition.getTypeName());
LOGGER.trace("Resource attribute container definition {}.", attributesDefinition.dump());
// Uid is always there
Uid uid = co.getUid();
ResourceAttribute<?> uidRoa = createUidAttribute(uid, getUidDefinition(attributesDefinition));
attributesContainer.getValue().add(uidRoa);
for (Attribute icfAttr : co.getAttributes()) {
if (icfAttr.getName().equals(Uid.NAME)) {
// UID is handled specially (see above)
continue;
}
if (icfAttr.getName().equals(OperationalAttributes.PASSWORD_NAME)) {
// password has to go to the credentials section
if (shadow instanceof AccountShadowType) {
AccountShadowType accountShadowType = (AccountShadowType) shadow;
ProtectedStringType password = getSingleValue(icfAttr, ProtectedStringType.class);
ResourceObjectShadowUtil.setPassword(accountShadowType, password);
} else {
throw new SchemaException("Attempt to set password for non-account object type "
+ objectDefinition);
}
continue;
}
if (icfAttr.getName().equals(OperationalAttributes.ENABLE_NAME)) {
if (shadow instanceof AccountShadowType) {
AccountShadowType accountShadowType = (AccountShadowType) shadow;
Boolean enabled = getSingleValue(icfAttr, Boolean.class);
ActivationType activationType = ResourceObjectShadowUtil
.getOrCreateActivation(accountShadowType);
activationType.setEnabled(enabled);
} else {
throw new SchemaException(
"Attempt to set activation/enabled for non-account object type "
+ objectDefinition);
}
continue;
}
QName qname = convertAttributeNameToQName(icfAttr.getName());
ResourceAttributeDefinition attributeDefinition = attributesDefinition.findAttributeDefinition(qname);
if (attributeDefinition == null) {
throw new SchemaException("Unknown attribute "+qname+". Cannot create definition. Original ICF name: "+icfAttr.getName(), qname);
}
ResourceAttribute resourceAttribute = attributeDefinition.instantiate(qname);
LOGGER.trace("attribute name: " + qname);
LOGGER.trace("attribute value: " + icfAttr.getValue());
// if true, we need to convert whole connector object to the
// resource object also with the null-values attributes
if (full) {
if (icfAttr.getValue() != null) {
// Convert the values. While most values do not need
// conversions, some
// of them may need it (e.g. GuardedString)
for (Object icfValue : icfAttr.getValue()) {
Object value = convertValueFromIcf(icfValue, qname);
resourceAttribute.add(new PrismPropertyValue<Object>(value));
}
}
attributesContainer.getValue().add(resourceAttribute);
// in this case when false, we need only the attributes with the
// non-null values.
} else {
if (icfAttr.getValue() != null && !icfAttr.getValue().isEmpty()) {
// Convert the values. While most values do not need
// conversions, some
// of them may need it (e.g. GuardedString)
for (Object icfValue : icfAttr.getValue()) {
Object value = convertValueFromIcf(icfValue, qname);
resourceAttribute.add(new PrismPropertyValue<Object>(value));
}
attributesContainer.getValue().add(resourceAttribute);
}
}
}
return shadowPrism;
}
private <T> T getSingleValue(Attribute icfAttr, Class<T> type) throws SchemaException {
List<Object> values = icfAttr.getValue();
if (values != null && !values.isEmpty()) {
if (values.size() > 1) {
throw new SchemaException("Expected single value for " + icfAttr.getName());
}
Object val = convertValueFromIcf(values.get(0), null);
if (type.isAssignableFrom(val.getClass())) {
return (T) val;
} else {
throw new SchemaException("Expected type " + type.getName() + " for " + icfAttr.getName()
+ " but got " + val.getClass().getName());
}
} else {
throw new SchemaException("Empty value for " + icfAttr.getName());
}
}
private Set<Attribute> convertFromResourceObject(ResourceAttributeContainer attributesPrism,
OperationResult parentResult) throws SchemaException {
Collection<ResourceAttribute<?>> resourceAttributes = attributesPrism.getAttributes();
return convertFromResourceObject(resourceAttributes, parentResult);
}
private Set<Attribute> convertFromResourceObject(Collection<ResourceAttribute<?>> resourceAttributes,
OperationResult parentResult) throws SchemaException {
Set<Attribute> attributes = new HashSet<Attribute>();
if (resourceAttributes == null) {
// returning empty set
return attributes;
}
for (ResourceAttribute<?> attribute : resourceAttributes) {
String attrName = UcfUtil.convertAttributeNameToIcf(attribute.getName(), getSchemaNamespace(), parentResult);
Set<Object> convertedAttributeValues = new HashSet<Object>();
for (PrismPropertyValue<?> value : attribute.getValues()) {
convertedAttributeValues.add(UcfUtil.convertValueToIcf(value, protector, attribute.getName()));
}
Attribute connectorAttribute = AttributeBuilder.build(attrName, convertedAttributeValues);
attributes.add(connectorAttribute);
}
return attributes;
}
// private Object convertValueToIcf(Object value, QName propName) throws SchemaException {
// if (value == null) {
// return null;
// if (value instanceof PrismPropertyValue) {
// return convertValueToIcf(((PrismPropertyValue) value).getValue(), propName);
// if (value instanceof ProtectedStringType) {
// ProtectedStringType ps = (ProtectedStringType) value;
// return toGuardedString(ps, propName.toString());
// return value;
private Object convertValueFromIcf(Object icfValue, QName propName) {
if (icfValue == null) {
return null;
}
if (icfValue instanceof GuardedString) {
return fromGuardedString((GuardedString) icfValue);
}
return icfValue;
}
private void convertFromActivation(Set<Attribute> updateAttributes,
Collection<PropertyDelta> activationDeltas) throws SchemaException {
for (PropertyDelta propDelta : activationDeltas) {
if (propDelta.getName().equals(ActivationType.F_ENABLED)) {
// Not entirely correct, TODO: refactor later
updateAttributes.add(AttributeBuilder.build(OperationalAttributes.ENABLE_NAME, propDelta
.getPropertyNew().getValue(Boolean.class).getValue()));
} else {
throw new SchemaException("Got unknown activation attribute delta " + propDelta.getName());
}
}
}
private void convertFromPassword(Set<Attribute> attributes, PropertyDelta passwordDelta) {
if (passwordDelta == null) {
throw new IllegalArgumentException("No password was provided");
}
if (passwordDelta.getName().equals(PasswordType.F_PROTECTED_STRING)) {
GuardedString guardedPassword = toGuardedString((ProtectedStringType) passwordDelta
.getPropertyNew().getValue().getValue(), "new password");
attributes.add(AttributeBuilder.build(OperationalAttributes.PASSWORD_NAME, guardedPassword));
}
}
private List<Change> getChangesFromSyncDeltas(ObjectClass objClass, Collection<SyncDelta> icfDeltas, PrismSchema schema,
OperationResult parentResult) throws SchemaException, GenericFrameworkException {
List<Change> changeList = new ArrayList<Change>();
Validate.notNull(icfDeltas, "Sync result must not be null.");
for (SyncDelta icfDelta : icfDeltas) {
if (icfDelta.getObject() != null){
objClass = icfDelta.getObject().getObjectClass();
}
QName objectClass = objectClassToQname(objClass.getObjectClassValue());
ObjectClassComplexTypeDefinition objClassDefinition = (ObjectClassComplexTypeDefinition) schema
.findComplexTypeDefinition(objectClass);
// we don't want resource container deifinition, instead we need the
// objectClassDef
// ResourceAttributeContainerDefinition objectClassDefinition =
// (ResourceAttributeContainerDefinition) schema
// .findContainerDefinitionByType(objectClass);
// ResourceAttributeContainerDefinition resourceAttributeDef =
// (ResourceAttributeContainerDefinition) objClassDefinition
// .findContainerDefinition(ResourceObjectShadowType.F_ATTRIBUTES);
// FIXME: we are hadcoding Account here, but we should not
if (SyncDeltaType.DELETE.equals(icfDelta.getDeltaType())) {
LOGGER.debug("START creating delta of type DELETE");
ObjectDelta<ResourceObjectShadowType> objectDelta = new ObjectDelta<ResourceObjectShadowType>(
ResourceObjectShadowType.class, ChangeType.DELETE, prismContext);
ResourceAttribute uidAttribute = createUidAttribute(
icfDelta.getUid(),
getUidDefinition(objClassDefinition
.toResourceAttributeContainerDefinition(ResourceObjectShadowType.F_ATTRIBUTES)));
Collection<ResourceAttribute<?>> identifiers = new ArrayList<ResourceAttribute<?>>(1);
identifiers.add(uidAttribute);
Change change = new Change(identifiers, objectDelta, getToken(icfDelta.getToken()));
change.setObjectClassDefinition(objClassDefinition);
changeList.add(change);
LOGGER.debug("END creating delta of type DELETE");
} else if (SyncDeltaType.CREATE_OR_UPDATE.equals(icfDelta.getDeltaType())) {
PrismObjectDefinition<AccountShadowType> objectDefinition = toShadowDefinition(objClassDefinition);
LOGGER.trace("Object definition: {}", objectDefinition);
LOGGER.debug("START creating delta of type CREATE_OR_UPDATE");
PrismObject<AccountShadowType> currentShadow = convertToResourceObject(icfDelta.getObject(),
objectDefinition, false);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Got current shadow: {}", currentShadow.dump());
}
Collection<ResourceAttribute<?>> identifiers = ResourceObjectShadowUtil.getIdentifiers(currentShadow);
Change change = new Change(identifiers, currentShadow, getToken(icfDelta.getToken()));
change.setObjectClassDefinition(objClassDefinition);
changeList.add(change);
LOGGER.debug("END creating delta of type CREATE_OR_UPDATE");
} else {
throw new GenericFrameworkException("Unexpected sync delta type " + icfDelta.getDeltaType());
}
}
return changeList;
}
private Element getModificationPath(Document doc) {
List<XPathSegment> segments = new ArrayList<XPathSegment>();
XPathSegment attrSegment = new XPathSegment(SchemaConstants.I_ATTRIBUTES);
segments.add(attrSegment);
XPathHolder t = new XPathHolder(segments);
Element xpathElement = t.toElement(SchemaConstants.I_PROPERTY_CONTAINER_REFERENCE_PATH, doc);
return xpathElement;
}
private SyncToken getSyncToken(PrismProperty tokenProperty) throws SchemaException {
if (tokenProperty.getValue() == null) {
throw new IllegalArgumentException("Attempt to get token from a null property");
}
Object tokenValue = tokenProperty.getValue().getValue();
if (tokenValue == null) {
throw new IllegalArgumentException("Attempt to get token from a null-valued property");
}
// Document doc = DOMUtil.getDocument();
// List<Object> elements = null;
// try {
// elements = lastToken.serializeToJaxb(doc);
// } catch (SchemaException ex) {
// throw new
// SchemaException("Failed to serialize last token property to dom.",
// for (Object e : elements) {
// tokenValue = XsdTypeConverter.toJavaValue(e,
// lastToken.getDefinition().getTypeName());
SyncToken syncToken = new SyncToken(tokenValue);
return syncToken;
}
private PrismProperty<?> getToken(SyncToken syncToken) {
Object object = syncToken.getValue();
return createTokenProperty(object);
}
private <T> PrismProperty<T> createTokenProperty(T object) {
QName type = XsdTypeMapper.toXsdType(object.getClass());
Set<PrismPropertyValue<T>> syncTokenValues = new HashSet<PrismPropertyValue<T>>();
syncTokenValues.add(new PrismPropertyValue<T>(object));
PrismPropertyDefinition propDef = new PrismPropertyDefinition(SchemaConstants.SYNC_TOKEN,
SchemaConstants.SYNC_TOKEN, type, prismContext);
propDef.setDynamic(true);
PrismProperty<T> property = propDef.instantiate();
property.addValues(syncTokenValues);
return property;
}
/**
* check additional operation order, according to the order are scrip
* executed before or after operation..
*
* @param additionalOperations
* @param order
*/
private void checkAndExecuteAdditionalOperation(Set<Operation> additionalOperations, ScriptOrderType order) {
if (additionalOperations == null) {
// TODO: add warning to the result
return;
}
for (Operation op : additionalOperations) {
if (op instanceof ExecuteScriptOperation) {
ExecuteScriptOperation executeOp = (ExecuteScriptOperation) op;
LOGGER.trace("Find execute script operation: {}", SchemaDebugUtil.prettyPrint(executeOp));
// execute operation in the right order..
if (order.equals(executeOp.getScriptOrder())) {
executeScript(executeOp);
}
}
}
}
private void executeScript(ExecuteScriptOperation executeOp) {
// convert execute script operation to the script context required from
// the connector
ScriptContext scriptContext = convertToScriptContext(executeOp);
// check if the script should be executed on the connector or the
// resoruce...
if (executeOp.isConnectorHost()) {
LOGGER.debug("Start running script on connector.");
icfConnectorFacade.runScriptOnConnector(scriptContext, new OperationOptionsBuilder().build());
LOGGER.debug("Finish running script on connector.");
}
if (executeOp.isResourceHost()) {
LOGGER.debug("Start running script on resource.");
icfConnectorFacade.runScriptOnResource(scriptContext, new OperationOptionsBuilder().build());
LOGGER.debug("Finish running script on resource.");
}
}
private ScriptContext convertToScriptContext(ExecuteScriptOperation executeOp) {
// creating script arguments map form the execute script operation
// arguments
Map<String, Object> scriptArguments = new HashMap<String, Object>();
for (ExecuteScriptArgument argument : executeOp.getArgument()) {
scriptArguments.put(argument.getArgumentName(), argument.getArgumentValue());
}
ScriptContext scriptContext = new ScriptContext(executeOp.getLanguage(), executeOp.getTextCode(),
scriptArguments);
return scriptContext;
}
/**
* Transforms midPoint XML configuration of the connector to the ICF
* configuration.
* <p/>
* The "configuration" part of the XML resource definition will be used.
* <p/>
* The provided ICF APIConfiguration will be modified, some values may be
* overwritten.
*
* @param apiConfig
* ICF connector configuration
* @param resourceType
* midPoint XML configuration
* @throws SchemaException
* @throws ConfigurationException
*/
private void transformConnectorConfiguration(APIConfiguration apiConfig, PrismContainerValue configuration)
throws SchemaException, ConfigurationException {
ConfigurationProperties configProps = apiConfig.getConfigurationProperties();
// The namespace of all the configuration properties specific to the
// connector instance will have a connector instance namespace. This
// namespace can be found in the resource definition.
String connectorConfNs = connectorType.getNamespace();
PrismContainer configurationPropertiesContainer = configuration
.findContainer(ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME);
if (configurationPropertiesContainer == null) {
// Also try this. This is an older way.
configurationPropertiesContainer = configuration.findContainer(new QName(connectorConfNs,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_LOCAL_NAME));
}
int numConfingProperties = transformConnectorConfiguration(configProps,
configurationPropertiesContainer, connectorConfNs);
PrismContainer connectorPoolContainer = configuration.findContainer(new QName(
ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_XML_ELEMENT_NAME));
ObjectPoolConfiguration connectorPoolConfiguration = apiConfig.getConnectorPoolConfiguration();
transformConnectorPoolConfiguration(connectorPoolConfiguration, connectorPoolContainer);
PrismProperty producerBufferSizeProperty = configuration.findProperty(new QName(
ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_XML_ELEMENT_NAME));
if (producerBufferSizeProperty != null) {
apiConfig.setProducerBufferSize(parseInt(producerBufferSizeProperty));
}
PrismContainer connectorTimeoutsContainer = configuration.findContainer(new QName(
ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_TIMEOUTS_XML_ELEMENT_NAME));
transformConnectorTimeoutsConfiguration(apiConfig, connectorTimeoutsContainer);
if (numConfingProperties == 0) {
throw new SchemaException("No configuration properties found. Wrong namespace? (expected: "
+ connectorConfNs + ")");
}
}
private int transformConnectorConfiguration(ConfigurationProperties configProps,
PrismContainer<?> configurationPropertiesContainer, String connectorConfNs)
throws ConfigurationException {
int numConfingProperties = 0;
if (configurationPropertiesContainer == null || configurationPropertiesContainer.getValue() == null) {
LOGGER.warn("No configuration properties in connectorType.getOid()");
return numConfingProperties;
}
for (PrismProperty prismProperty : configurationPropertiesContainer.getValue().getProperties()) {
QName propertyQName = prismProperty.getName();
// All the elements must be in a connector instance
// namespace.
if (propertyQName.getNamespaceURI() == null
|| !propertyQName.getNamespaceURI().equals(connectorConfNs)) {
LOGGER.warn("Found element with a wrong namespace ({}) in connector OID={}",
propertyQName.getNamespaceURI(), connectorType.getOid());
} else {
numConfingProperties++;
// Local name of the element is the same as the name
// of ICF configuration property
String propertyName = propertyQName.getLocalPart();
ConfigurationProperty property = configProps.getProperty(propertyName);
if (property == null) {
throw new ConfigurationException("Unknown configuration property "+propertyName);
}
// Check (java) type of ICF configuration property,
// behave accordingly
Class<?> type = property.getType();
if (type.isArray()) {
property.setValue(convertToIcfArray(prismProperty, type.getComponentType()));
// property.setValue(prismProperty.getRealValuesArray(type.getComponentType()));
} else {
// Single-valued property are easy to convert
property.setValue(convertToIcfSingle(prismProperty, type));
// property.setValue(prismProperty.getRealValue(type));
}
}
}
return numConfingProperties;
}
private void transformConnectorPoolConfiguration(ObjectPoolConfiguration connectorPoolConfiguration,
PrismContainer<?> connectorPoolContainer) throws SchemaException {
if (connectorPoolContainer == null || connectorPoolContainer.getValue() == null) {
return;
}
for (PrismProperty prismProperty : connectorPoolContainer.getValue().getProperties()) {
QName propertyQName = prismProperty.getName();
if (propertyQName.getNamespaceURI().equals(ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION)) {
String subelementName = propertyQName.getLocalPart();
if (ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_MIN_EVICTABLE_IDLE_TIME_MILLIS
.equals(subelementName)) {
connectorPoolConfiguration.setMinEvictableIdleTimeMillis(parseLong(prismProperty));
} else if (ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_MIN_IDLE
.equals(subelementName)) {
connectorPoolConfiguration.setMinIdle(parseInt(prismProperty));
} else if (ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_MAX_IDLE
.equals(subelementName)) {
connectorPoolConfiguration.setMaxIdle(parseInt(prismProperty));
} else if (ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_MAX_OBJECTS
.equals(subelementName)) {
connectorPoolConfiguration.setMaxObjects(parseInt(prismProperty));
} else if (ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_MAX_WAIT
.equals(subelementName)) {
connectorPoolConfiguration.setMaxWait(parseLong(prismProperty));
} else {
throw new SchemaException(
"Unexpected element "
+ propertyQName
+ " in "
+ ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_XML_ELEMENT_NAME);
}
} else {
throw new SchemaException(
"Unexpected element "
+ propertyQName
+ " in "
+ ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_XML_ELEMENT_NAME);
}
}
}
private void transformConnectorTimeoutsConfiguration(APIConfiguration apiConfig,
PrismContainer<?> connectorTimeoutsContainer) throws SchemaException {
if (connectorTimeoutsContainer == null || connectorTimeoutsContainer.getValue() == null) {
return;
}
for (PrismProperty prismProperty : connectorTimeoutsContainer.getValue().getProperties()) {
QName propertQName = prismProperty.getName();
if (ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION.equals(propertQName.getNamespaceURI())) {
String opName = propertQName.getLocalPart();
Class<? extends APIOperation> apiOpClass = ConnectorFactoryIcfImpl.resolveApiOpClass(opName);
if (apiOpClass != null) {
apiConfig.setTimeout(apiOpClass, parseInt(prismProperty));
} else {
throw new SchemaException("Unknown operation name " + opName + " in "
+ ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_TIMEOUTS_XML_ELEMENT_NAME);
}
}
}
}
private int parseInt(PrismProperty<?> prop) {
return prop.getRealValue(Integer.class);
}
private long parseLong(PrismProperty<?> prop) {
Object realValue = prop.getRealValue();
if (realValue instanceof Long) {
return (Long) realValue;
} else if (realValue instanceof Integer) {
return ((Integer) realValue);
} else {
throw new IllegalArgumentException("Cannot convert " + realValue.getClass() + " to long");
}
}
private Object convertToIcfSingle(PrismProperty<?> configProperty, Class<?> expectedType)
throws ConfigurationException {
if (configProperty == null) {
return null;
}
PrismPropertyValue<?> pval = configProperty.getValue();
return convertToIcf(pval, expectedType);
}
private Object[] convertToIcfArray(PrismProperty prismProperty, Class<?> componentType)
throws ConfigurationException {
List<PrismPropertyValue> values = prismProperty.getValues();
Object valuesArrary = Array.newInstance(componentType, values.size());
for (int j = 0; j < values.size(); ++j) {
Object icfValue = convertToIcf(values.get(j), componentType);
Array.set(valuesArrary, j, icfValue);
}
return (Object[]) valuesArrary;
}
private Object convertToIcf(PrismPropertyValue<?> pval, Class<?> expectedType) throws ConfigurationException {
Object midPointRealValue = pval.getValue();
if (expectedType.equals(GuardedString.class)) {
// Guarded string is a special ICF beast
// The value must be ProtectedStringType
if (midPointRealValue instanceof ProtectedStringType) {
ProtectedStringType ps = (ProtectedStringType) pval.getValue();
return toGuardedString(ps, pval.getParent().getName().getLocalPart());
} else {
throw new ConfigurationException(
"Expected protected string as value of configuration property "
+ pval.getParent().getName().getLocalPart() + " but got "
+ midPointRealValue.getClass());
}
} else if (expectedType.equals(GuardedByteArray.class)) {
// Guarded string is a special ICF beast
// TODO
return new GuardedByteArray(Base64.decodeBase64((String) pval.getValue()));
} else if (midPointRealValue instanceof PolyString) {
return ((PolyString)midPointRealValue).getOrig();
} else if (midPointRealValue instanceof PolyStringType) {
return ((PolyStringType)midPointRealValue).getOrig();
} else if (expectedType.equals(File.class) && midPointRealValue instanceof String) {
return new File((String)midPointRealValue);
} else if (expectedType.equals(String.class) && midPointRealValue instanceof ProtectedStringType) {
try {
return protector.decryptString((ProtectedStringType)midPointRealValue);
} catch (EncryptionException e) {
throw new ConfigurationException(e);
}
} else {
return midPointRealValue;
}
}
private GuardedString toGuardedString(ProtectedStringType ps, String propertyName) {
if (ps == null) {
return null;
}
if (!protector.isEncrypted(ps)) {
if (ps.getClearValue() == null) {
return null;
}
LOGGER.warn("Using cleartext value for {}", propertyName);
return new GuardedString(ps.getClearValue().toCharArray());
}
try {
return new GuardedString(protector.decryptString(ps).toCharArray());
} catch (EncryptionException e) {
LOGGER.error("Unable to decrypt value of element {}: {}",
new Object[] { propertyName, e.getMessage(), e });
throw new SystemException("Unable to dectypt value of element " + propertyName + ": "
+ e.getMessage(), e);
}
}
private ProtectedStringType fromGuardedString(GuardedString icfValue) {
final ProtectedStringType ps = new ProtectedStringType();
icfValue.access(new GuardedString.Accessor() {
@Override
public void access(char[] passwordChars) {
try {
ps.setClearValue(new String(passwordChars));
protector.encrypt(ps);
} catch (EncryptionException e) {
throw new IllegalStateException("Protector failed to encrypt password");
}
}
});
return ps;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ConnectorInstanceIcfImpl(" + ObjectTypeUtil.toShortString(connectorType) + ")";
}
}
|
// PythonJxpSource.java
package ed.lang.python;
import java.io.*;
import java.util.*;
import org.python.core.*;
import org.python.Version;
import ed.js.*;
import ed.js.engine.*;
import ed.util.*;
import ed.appserver.*;
import ed.appserver.jxp.JxpSource;
import ed.log.Logger;
public class PythonJxpSource extends JxpSource {
static {
System.setProperty( "python.cachedir", ed.io.WorkingFiles.TMP_DIR + "/jython-cache/" + Version.PY_VERSION );
}
public synchronized JSFunction getFunction()
throws IOException {
final PyCode code = _getCode();
return new ed.js.func.JSFunctionCalls0(){
public Object call( Scope s , Object extra[] ){
final AppContext ac = getAppContext();
Scope siteScope;
if ( ac != null )
siteScope = ac.getScope();
else
siteScope = s.getGlobal( true );
SiteSystemState ss = Python.getSiteSystemState( ac , siteScope );
PyObject globals = new PyDictionary();
PyObject result = runPythonCode(code, ac, ss, globals, siteScope, _lib, _file);
if (usePassedInScope()){
PyObject keys = globals.invoke("keys");
if( ! ( keys instanceof PyList ) ){
throw new RuntimeException("couldn't use passed in scope: keys not dictionary [" + keys.getClass() + "]");
}
PyList keysL = (PyList)keys;
for(int i = 0; i < keysL.size(); i++){
PyObject key = keysL.pyget(i);
if( ! ( key instanceof PyString ) ){
System.out.println("Non-string key in globals : " + key + " [skipping]");
continue;
}
s.put( key.toString(), Python.toJS( globals.__finditem__(key) ) , true );
}
}
return Python.toJS( result );
}
};
}
public static PyObject runPythonCode(PyCode code, AppContext ac, SiteSystemState ss, PyObject globals,
Scope siteScope, JSFileLibrary lib, File file) {
PySystemState pyOld = Py.getSystemState();
ss.flushOld();
ss.ensurePath( file.getParent());
ss.ensurePath( lib.getRoot().getAbsolutePath() );
ss.ensurePath( lib.getTopParent().getRoot().getAbsolutePath() );
PyObject oldFile = globals.__finditem__( "__file__" );
PyObject oldName = globals.__finditem__( "__name__" );
PyObject result = null;
try {
Py.setSystemState( ss.getPyState() );
//Py.initClassExceptions( globals );
globals.__setitem__( "__file__", Py.newString( file.toString() ) );
// FIXME: Needs to use path info, so foo/bar.py -> foo.bar
// Right now I only want this for _init.py
String name = file.getName();
if( name.endsWith( ".py" ) )
name = name.substring( 0 , name.length() - 3 );
//globals.__setitem__( "__name__", Py.newString( name ) );
/*
* In order to track dependencies, we need to know what module is doing imports
* We just care that _init doing imports is registered at all.
*/
PyModule module = new PyModule( name , globals );
PyObject locals = module.__dict__;
result = Py.runCode( code, locals, globals );
if( ac != null ) ss.addRecursive( "_init" , ac );
}
finally {
_globalRestore( globals , siteScope , "__file__" , oldFile );
_globalRestore( globals , siteScope , "__name__" , oldName );
Py.setSystemState( pyOld );
}
return result;
}
private static void _globalRestore( PyObject globals , Scope siteScope , String name , PyObject value ){
if( value != null ){
globals.__setitem__( name , value );
}
else{
// FIXME -- delitem should really be deleting from siteScope
globals.__delitem__( name );
siteScope.set( name , null );
}
}
private PyCode _getCode()
throws IOException {
PyCode c = _code;
final long lastModified = _file.lastModified();
if ( c == null || _lastCompile < lastModified ){
c = Python.compile( _file );
_code = c;
_lastCompile = lastModified;
}
return c;
}
final File _file;
final JSFileLibrary _lib;
private PyCode _code;
private long _lastCompile;
void addDependency( String to ){
super.addDependency( new FileDependency( new File( to ) ) );
}
public PythonJxpSource( File f , JSFileLibrary lib ){
_file = f;
_lib = lib;
}
protected String getContent(){
throw new RuntimeException( "you can't do this" );
}
protected InputStream getInputStream(){
throw new RuntimeException( "you can't do this" );
}
public long lastUpdated(Set<Dependency> visitedDeps){
return _file.lastModified();
}
public String getName(){
return _file.toString();
}
public File getFile(){
return _file;
}
// static b/c it has to use ThreadLocal anyway
final static Logger _log = Logger.getLogger( "python" );
}
|
package net.darkmist.alib.collection;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Static utilities for {@link Set}s.
*/
public final class Sets
{
private Sets()
{
}
/**
* Create a new set.
* This allow's the default Set implementation to be swapped
* easily.
* @return a new empty set.
*/
public static <T> Set<T> newSet()
{
return new HashSet<T>();
}
/**
* Duplicate set.
* This allow's the default Set implementation to be swapped
* easily.
* @param set The set to dupplicate.
* @return a new empty set.
*/
public static <T> Set<T> dup(Collection<T> collection)
{
if(collection==null || collection.size()==0)
return new HashSet<T>();
return new HashSet<T>(collection);
}
/**
* Duplicate set.
* This allows the default Set implementation to be swapped
* easily.
* @param set The set to duplicate.
* @return a new empty set.
*/
public static <T> Set<T> dup(Collection<T> contents)
{
if(contents==null || contents.size()==0)
return new HashSet<T>();
return new HashSet<T>(contents);
}
/**
* Create a new set with an initial size.
* This allow's the default Set implementation to be swapped
* easily.
* @param initialSize hint defining the initial size.
* @return a new set with the initial capacity
*/
public static <T> Set<T> newSet(int initialSize)
{
return new HashSet<T>(initialSize);
}
/**
* Create a set with contents.
* @param contents The contents of the set.
* @return A set containing contents.
*/
public static <T> Set<T> newSet(T...contents)
{
Set<T> set;
if(contents == null || contents.length==0)
return newSet();
set = newSet(contents.length);
Collections.addAll(set, contents);
return set;
}
/**
* Create a unmodifiable set with contents.
* @param contents The contents of the set.
* @return A unmodifiable set containing contents.
*/
public static <T> Set<T> newUnmodifiableSet(T...contents)
{
Set<T> set;
if(contents == null || contents.length==0)
return Collections.emptySet();
if(contents.length == 1)
return Collections.singleton(contents[0]);
set = newSet(contents.length);
Collections.addAll(set, contents);
return Collections.unmodifiableSet(set);
}
public static <T> Set<T> asUnmodifiable(Set<T> contents)
{
if(contents == null || contents.size()==0)
return Collections.emptySet();
if(contents.size() == 1)
return Collections.singleton(contents.iterator().next());
return Collections.unmodifiableSet(contents);
}
public static <T> Set<T> unmodifiableCopy(Collection<T> contents)
{
if(contents == null || contents.size()==0)
return Collections.emptySet();
if(contents.size() == 1)
return Collections.singleton(contents.iterator().next());
return asUnmodifiable(dup(contents));
}
/**
* Create a unmodifiable set with contents.
* @param contents The contents of the set.
* @return A unmodifiable set containing contents.
*/
public static <T> Set<T> newUnmodifiableSet(Collection<T> contents)
{
if(contents == null || contents.size()==0)
return Collections.emptySet();
if(contents.size() == 1)
return Collections.singleton(contents.iterator().next());
return Collections.unmodifiableSet(dup(contents));
}
}
|
package bisq.desktop.main.offer.takeoffer;
import bisq.desktop.Navigation;
import bisq.desktop.common.view.ActivatableViewAndModel;
import bisq.desktop.common.view.FxmlView;
import bisq.desktop.components.AddressTextField;
import bisq.desktop.components.AutoTooltipButton;
import bisq.desktop.components.AutoTooltipLabel;
import bisq.desktop.components.AutoTooltipSlideToggleButton;
import bisq.desktop.components.BalanceTextField;
import bisq.desktop.components.BusyAnimation;
import bisq.desktop.components.FundsTextField;
import bisq.desktop.components.InfoInputTextField;
import bisq.desktop.components.InputTextField;
import bisq.desktop.components.TitledGroupBg;
import bisq.desktop.main.MainView;
import bisq.desktop.main.dao.DaoView;
import bisq.desktop.main.dao.wallet.BsqWalletView;
import bisq.desktop.main.dao.wallet.receive.BsqReceiveView;
import bisq.desktop.main.funds.FundsView;
import bisq.desktop.main.funds.withdrawal.WithdrawalView;
import bisq.desktop.main.offer.OfferView;
import bisq.desktop.main.overlays.notifications.Notification;
import bisq.desktop.main.overlays.popups.Popup;
import bisq.desktop.main.overlays.windows.OfferDetailsWindow;
import bisq.desktop.main.overlays.windows.QRCodeWindow;
import bisq.desktop.main.portfolio.PortfolioView;
import bisq.desktop.main.portfolio.pendingtrades.PendingTradesView;
import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.Layout;
import bisq.desktop.util.Transitions;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferPayload;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.payload.PaymentMethod;
import bisq.core.user.DontShowAgainLookup;
import bisq.core.util.BSFormatter;
import bisq.core.util.BsqFormatter;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.util.Tuple2;
import bisq.common.util.Tuple3;
import bisq.common.util.Tuple4;
import bisq.common.util.Utilities;
import org.bitcoinj.core.Coin;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import javax.inject.Inject;
import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon;
import com.jfoenix.controls.JFXTextField;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.Subscription;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import java.net.URI;
import java.io.ByteArrayInputStream;
import java.util.concurrent.TimeUnit;
import org.jetbrains.annotations.NotNull;
import static bisq.desktop.util.FormBuilder.*;
import static javafx.beans.binding.Bindings.createStringBinding;
@FxmlView
public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOfferViewModel> {
private final Navigation navigation;
private final BSFormatter formatter;
private final BsqFormatter bsqFormatter;
private final OfferDetailsWindow offerDetailsWindow;
private final Transitions transitions;
private ScrollPane scrollPane;
private GridPane gridPane;
private TitledGroupBg payFundsTitledGroupBg, paymentAccountTitledGroupBg, advancedOptionsGroup;
private VBox priceAsPercentageInputBox, amountRangeBox;
private HBox fundingHBox, amountValueCurrencyBox, priceValueCurrencyBox, volumeValueCurrencyBox,
priceAsPercentageValueCurrencyBox, minAmountValueCurrencyBox, advancedOptionsBox,
takeOfferBox, buttonBox, firstRowHBox;
private ComboBox<PaymentAccount> paymentAccountsComboBox;
private Label amountDescriptionLabel,
paymentMethodLabel,
priceCurrencyLabel, priceAsPercentageLabel,
volumeCurrencyLabel, priceDescriptionLabel, volumeDescriptionLabel,
waitingForFundsLabel, offerAvailabilityLabel, amountCurrency, priceAsPercentageDescription,
tradeFeeDescriptionLabel, resultLabel, tradeFeeInBtcLabel, tradeFeeInBsqLabel, xLabel,
fakeXLabel;
private InputTextField amountTextField;
private TextField paymentMethodTextField, currencyTextField, priceTextField, priceAsPercentageTextField,
volumeTextField, amountRangeTextField;
private FundsTextField totalToPayTextField;
private AddressTextField addressTextField;
private BalanceTextField balanceTextField;
private Text xIcon, fakeXIcon;
private Button nextButton, cancelButton1, cancelButton2;
private AutoTooltipButton takeOfferButton;
private ImageView qrCodeImageView;
private BusyAnimation waitingForFundsBusyAnimation, offerAvailabilityBusyAnimation;
private Notification walletFundedNotification;
private OfferView.CloseHandler closeHandler;
private Subscription cancelButton2StyleSubscription, balanceSubscription,
showTransactionPublishedScreenSubscription, showWarningInvalidBtcDecimalPlacesSubscription,
isWaitingForFundsSubscription, offerWarningSubscription, errorMessageSubscription,
isOfferAvailableSubscription;
private int gridRow = 0;
private boolean offerDetailsWindowDisplayed, clearXchangeWarningDisplayed;
private SimpleBooleanProperty errorPopupDisplayed;
private ChangeListener<Boolean> amountFocusedListener, getShowWalletFundedNotificationListener;
private InfoInputTextField volumeInfoTextField;
private AutoTooltipSlideToggleButton tradeFeeInBtcToggle, tradeFeeInBsqToggle;
private ChangeListener<Boolean> tradeFeeInBtcToggleListener, tradeFeeInBsqToggleListener,
tradeFeeVisibleListener;
// Constructor, lifecycle
@Inject
private TakeOfferView(TakeOfferViewModel model,
Navigation navigation,
BSFormatter formatter,
BsqFormatter bsqFormatter,
OfferDetailsWindow offerDetailsWindow,
Transitions transitions) {
super(model);
this.navigation = navigation;
this.formatter = formatter;
this.bsqFormatter = bsqFormatter;
this.offerDetailsWindow = offerDetailsWindow;
this.transitions = transitions;
}
@Override
protected void initialize() {
addScrollPane();
addGridPane();
addPaymentGroup();
addAmountPriceGroup();
addOptionsGroup();
addButtons();
addOfferAvailabilityLabel();
addFundingGroup();
balanceTextField.setFormatter(model.getBtcFormatter());
amountFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutAmountTextField(oldValue, newValue, amountTextField.getText());
amountTextField.setText(model.amount.get());
};
getShowWalletFundedNotificationListener = (observable, oldValue, newValue) -> {
if (newValue) {
Notification walletFundedNotification = new Notification()
.headLine(Res.get("notification.walletUpdate.headline"))
.notification(Res.get("notification.walletUpdate.msg", formatter.formatCoinWithCode(model.dataModel.getTotalToPayAsCoin().get())))
.autoClose();
walletFundedNotification.show();
}
};
tradeFeeInBtcToggleListener = (observable, oldValue, newValue) -> {
if (newValue && tradeFeeInBsqToggle.isSelected())
tradeFeeInBsqToggle.setSelected(false);
if (!newValue && !tradeFeeInBsqToggle.isSelected())
tradeFeeInBsqToggle.setSelected(true);
setIsCurrencyForMakerFeeBtc(newValue);
};
tradeFeeInBsqToggleListener = (observable, oldValue, newValue) -> {
if (newValue && tradeFeeInBtcToggle.isSelected())
tradeFeeInBtcToggle.setSelected(false);
if (!newValue && !tradeFeeInBtcToggle.isSelected())
tradeFeeInBtcToggle.setSelected(true);
setIsCurrencyForMakerFeeBtc(!newValue);
};
tradeFeeVisibleListener = (observable, oldValue, newValue) -> {
if (DevEnv.isDaoActivated()) {
tradeFeeInBtcToggle.setVisible(newValue);
tradeFeeInBsqToggle.setVisible(newValue);
}
};
GUIUtil.focusWhenAddedToScene(amountTextField);
}
private void setIsCurrencyForMakerFeeBtc(boolean isCurrencyForMakerFeeBtc) {
model.setIsCurrencyForTakerFeeBtc(isCurrencyForMakerFeeBtc);
if (DevEnv.isDaoActivated()) {
tradeFeeInBtcLabel.setOpacity(isCurrencyForMakerFeeBtc ? 1 : 0.3);
tradeFeeInBsqLabel.setOpacity(isCurrencyForMakerFeeBtc ? 0.3 : 1);
}
}
@Override
protected void activate() {
addBindings();
addSubscriptions();
addListeners();
if (offerAvailabilityBusyAnimation != null && !model.showPayFundsScreenDisplayed.get()) {
offerAvailabilityBusyAnimation.play();
offerAvailabilityLabel.setVisible(true);
offerAvailabilityLabel.setManaged(true);
} else {
offerAvailabilityLabel.setVisible(false);
offerAvailabilityLabel.setManaged(false);
}
if (waitingForFundsBusyAnimation != null && model.isWaitingForFunds.get()) {
waitingForFundsBusyAnimation.play();
waitingForFundsLabel.setVisible(true);
waitingForFundsLabel.setManaged(true);
} else {
waitingForFundsLabel.setVisible(false);
waitingForFundsLabel.setManaged(false);
}
String currencyCode = model.dataModel.getCurrencyCode();
volumeCurrencyLabel.setText(currencyCode);
priceDescriptionLabel.setText(formatter.getPriceWithCurrencyCode(currencyCode));
volumeDescriptionLabel.setText(model.volumeDescriptionLabel.get());
if (model.getPossiblePaymentAccounts().size() > 1) {
paymentAccountsComboBox.setItems(model.getPossiblePaymentAccounts());
paymentAccountsComboBox.getSelectionModel().select(0);
paymentAccountTitledGroupBg.setText(Res.get("shared.selectTradingAccount"));
// TODO if we have multiple payment accounts we should show some info/warning to
// make sure the user has selected the account he wants to use.
// To use a popup is not recommended as we have already 3 popups at the first time (if user has not clicked
// don't show again).
// @Christoph Maybe a similar warn triangle as used in create offer might work?
}
balanceTextField.setTargetAmount(model.dataModel.getTotalToPayAsCoin().get());
maybeShowClearXchangeWarning();
if (!DevEnv.isDaoActivated() && !model.isRange()) {
nextButton.setVisible(false);
cancelButton1.setVisible(false);
if (model.isOfferAvailable.get())
showNextStepAfterAmountIsSet();
}
if (CurrencyUtil.isFiatCurrency(model.getOffer().getCurrencyCode()) && !DevEnv.isDevMode()) {
new Popup<>().headLine(Res.get("popup.roundedFiatValues.headline"))
.information(Res.get("popup.roundedFiatValues.msg", model.getOffer().getCurrencyCode()))
.dontShowAgainId("FiatValuesRoundedWarning")
.show();
}
boolean currencyForMakerFeeBtc = model.dataModel.isCurrencyForTakerFeeBtc();
tradeFeeInBtcToggle.setSelected(currencyForMakerFeeBtc);
tradeFeeInBsqToggle.setSelected(!currencyForMakerFeeBtc);
if (!DevEnv.isDaoActivated()) {
tradeFeeInBtcToggle.setVisible(false);
tradeFeeInBtcToggle.setManaged(false);
tradeFeeInBsqToggle.setVisible(false);
tradeFeeInBsqToggle.setManaged(false);
}
}
@Override
protected void deactivate() {
removeBindings();
removeSubscriptions();
removeListeners();
if (offerAvailabilityBusyAnimation != null)
offerAvailabilityBusyAnimation.stop();
if (waitingForFundsBusyAnimation != null)
waitingForFundsBusyAnimation.stop();
}
// API
public void initWithData(Offer offer) {
model.initWithData(offer);
priceAsPercentageInputBox.setVisible(offer.isUseMarketBasedPrice());
if (model.getOffer().getDirection() == OfferPayload.Direction.SELL) {
takeOfferButton.setId("buy-button-big");
takeOfferButton.updateText(Res.get("takeOffer.takeOfferButton", Res.get("shared.buy")));
nextButton.setId("buy-button");
priceAsPercentageDescription.setText(Res.get("shared.aboveInPercent"));
} else {
takeOfferButton.setId("sell-button-big");
nextButton.setId("sell-button");
takeOfferButton.updateText(Res.get("takeOffer.takeOfferButton", Res.get("shared.sell")));
priceAsPercentageDescription.setText(Res.get("shared.belowInPercent"));
}
boolean showComboBox = model.getPossiblePaymentAccounts().size() > 1;
paymentAccountsComboBox.setVisible(showComboBox);
paymentAccountsComboBox.setManaged(showComboBox);
paymentAccountsComboBox.setMouseTransparent(!showComboBox);
paymentMethodTextField.setVisible(!showComboBox);
paymentMethodTextField.setManaged(!showComboBox);
paymentMethodLabel.setVisible(!showComboBox);
paymentMethodLabel.setManaged(!showComboBox);
if (!showComboBox) {
paymentMethodTextField.setText(model.getPossiblePaymentAccounts().get(0).getAccountName());
}
currencyTextField.setText(model.dataModel.getCurrencyNameAndCode());
amountDescriptionLabel.setText(model.getAmountDescription());
if (model.isRange()) {
amountRangeTextField.setText(model.getAmountRange());
amountRangeBox.setVisible(true);
} else {
amountTextField.setDisable(true);
}
priceTextField.setText(model.getPrice());
priceAsPercentageTextField.setText(model.marketPriceMargin);
addressTextField.setPaymentLabel(model.getPaymentLabel());
addressTextField.setAddress(model.dataModel.getAddressEntry().getAddressString());
if (CurrencyUtil.isFiatCurrency(offer.getCurrencyCode()))
volumeInfoTextField.setContentForPrivacyPopOver(createPopoverLabel(Res.get("offerbook.info.roundedFiatVolume")));
if (offer.getPrice() == null)
new Popup<>().warning(Res.get("takeOffer.noPriceFeedAvailable"))
.onClose(this::close)
.show();
}
public void setCloseHandler(OfferView.CloseHandler closeHandler) {
this.closeHandler = closeHandler;
}
// called form parent as the view does not get notified when the tab is closed
@SuppressWarnings("PointlessBooleanExpression")
public void onClose() {
Coin balance = model.dataModel.getBalance().get();
//noinspection ConstantConditions,ConstantConditions
if (balance != null && balance.isPositive() && !model.takeOfferCompleted.get() && !DevEnv.isDevMode()) {
model.dataModel.swapTradeToSavings();
new Popup<>().information(Res.get("takeOffer.alreadyFunded.movedFunds"))
.actionButtonTextWithGoTo("navigation.funds.availableForWithdrawal")
.onAction(() -> navigation.navigateTo(MainView.class, FundsView.class, WithdrawalView.class))
.show();
}
// TODO need other implementation as it is displayed also if there are old funds in the wallet
/*
if (model.dataModel.getIsWalletFunded().get())
new Popup<>().warning("You have already funds paid in.\nIn the <Funds/Open for withdrawal> section you can withdraw those funds.").show();*/
}
public void onTabSelected(boolean isSelected) {
model.dataModel.onTabSelected(isSelected);
}
// UI actions
@SuppressWarnings("PointlessBooleanExpression")
private void onTakeOffer() {
if (model.isReadyForTxBroadcast()) {
if (model.dataModel.isTakerFeeValid()) {
if (model.hasAcceptedArbitrators()) {
if (!DevEnv.isDevMode()) {
offerDetailsWindow.onTakeOffer(() ->
model.onTakeOffer(() -> {
offerDetailsWindow.hide();
offerDetailsWindowDisplayed = false;
})
).show(model.getOffer(), model.dataModel.getAmount().get(), model.dataModel.tradePrice);
offerDetailsWindowDisplayed = true;
} else {
balanceSubscription.unsubscribe();
model.onTakeOffer(() -> {
});
}
} else {
new Popup<>().warning(Res.get("popup.warning.noArbitratorsAvailable")).show();
}
} else {
showInsufficientBsqFundsForBtcFeePaymentPopup();
}
} else {
model.showNotReadyForTxBroadcastPopups();
}
}
@SuppressWarnings("PointlessBooleanExpression")
private void onShowPayFundsScreen() {
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
nextButton.setVisible(false);
nextButton.setManaged(false);
nextButton.setOnAction(null);
cancelButton1.setVisible(false);
cancelButton1.setManaged(false);
cancelButton1.setOnAction(null);
offerAvailabilityBusyAnimation.stop();
offerAvailabilityBusyAnimation.setVisible(false);
offerAvailabilityBusyAnimation.setManaged(false);
offerAvailabilityLabel.setVisible(false);
offerAvailabilityLabel.setManaged(false);
tradeFeeInBtcToggle.setMouseTransparent(true);
tradeFeeInBsqToggle.setMouseTransparent(true);
int delay = 500;
int diff = 100;
transitions.fadeOutAndRemove(advancedOptionsGroup, delay, (event) -> {
});
delay -= diff;
transitions.fadeOutAndRemove(advancedOptionsBox, delay);
model.onShowPayFundsScreen();
amountTextField.setMouseTransparent(true);
amountTextField.setDisable(false);
amountTextField.setFocusTraversable(false);
amountRangeTextField.setMouseTransparent(true);
amountRangeTextField.setDisable(false);
amountRangeTextField.setFocusTraversable(false);
priceTextField.setMouseTransparent(true);
priceTextField.setDisable(false);
priceTextField.setFocusTraversable(false);
priceAsPercentageTextField.setMouseTransparent(true);
priceAsPercentageTextField.setDisable(false);
priceAsPercentageTextField.setFocusTraversable(false);
volumeTextField.setMouseTransparent(true);
volumeTextField.setDisable(false);
volumeTextField.setFocusTraversable(false);
updateOfferElementsStyle();
balanceTextField.setTargetAmount(model.dataModel.getTotalToPayAsCoin().get());
if (!DevEnv.isDevMode()) {
String key = "securityDepositInfo";
new Popup<>().backgroundInfo(Res.get("popup.info.securityDepositInfo"))
.actionButtonText(Res.get("shared.faq"))
.onAction(() -> GUIUtil.openWebPage("https://bisq.network/faq
.useIUnderstandButton()
.dontShowAgainId(key)
.show();
String tradeAmountText = model.isSeller() ? Res.get("takeOffer.takeOfferFundWalletInfo.tradeAmount", model.getTradeAmount()) : "";
String message = Res.get("takeOffer.takeOfferFundWalletInfo.msg",
model.totalToPay.get(),
tradeAmountText,
model.getSecurityDepositInfo(),
model.getTradeFee(),
model.getTxFee()
);
key = "takeOfferFundWalletInfo";
new Popup<>().headLine(Res.get("takeOffer.takeOfferFundWalletInfo.headline"))
.instruction(message)
.dontShowAgainId(key)
.show();
}
cancelButton2.setVisible(true);
waitingForFundsBusyAnimation.play();
payFundsTitledGroupBg.setVisible(true);
totalToPayTextField.setVisible(true);
addressTextField.setVisible(true);
qrCodeImageView.setVisible(true);
balanceTextField.setVisible(true);
totalToPayTextField.setFundsStructure(Res.get("takeOffer.fundsBox.fundsStructure",
model.getSecurityDepositWithCode(), model.getTakerFeePercentage(), model.getTxFeePercentage()));
totalToPayTextField.setContentForInfoPopOver(createInfoPopover());
if (model.dataModel.getIsBtcWalletFunded().get()) {
if (walletFundedNotification == null) {
walletFundedNotification = new Notification()
.headLine(Res.get("notification.walletUpdate.headline"))
.notification(Res.get("notification.takeOffer.walletUpdate.msg", formatter.formatCoinWithCode(model.dataModel.getTotalToPayAsCoin().get())))
.autoClose();
walletFundedNotification.show();
}
}
final byte[] imageBytes = QRCode
.from(getBitcoinURI())
.withSize(98, 98) // code has 41 elements 8 px is border with 98 we get double scale and min. border
.to(ImageType.PNG)
.stream()
.toByteArray();
Image qrImage = new Image(new ByteArrayInputStream(imageBytes));
qrCodeImageView.setImage(qrImage);
}
private void updateOfferElementsStyle() {
GridPane.setColumnSpan(firstRowHBox, 1);
final String activeInputStyle = "input-with-border";
final String readOnlyInputStyle = "input-with-border-readonly";
amountValueCurrencyBox.getStyleClass().remove(activeInputStyle);
amountValueCurrencyBox.getStyleClass().add(readOnlyInputStyle);
priceAsPercentageValueCurrencyBox.getStyleClass().remove(activeInputStyle);
priceAsPercentageValueCurrencyBox.getStyleClass().add(readOnlyInputStyle);
volumeValueCurrencyBox.getStyleClass().remove(activeInputStyle);
volumeValueCurrencyBox.getStyleClass().add(readOnlyInputStyle);
priceValueCurrencyBox.getStyleClass().remove(activeInputStyle);
priceValueCurrencyBox.getStyleClass().add(readOnlyInputStyle);
minAmountValueCurrencyBox.getStyleClass().remove(activeInputStyle);
minAmountValueCurrencyBox.getStyleClass().add(readOnlyInputStyle);
resultLabel.getStyleClass().add("small");
xLabel.getStyleClass().add("small");
xIcon.setStyle(String.format("-fx-font-family: %s; -fx-font-size: %s;", MaterialDesignIcon.CLOSE.fontFamily(), "1em"));
fakeXIcon.setStyle(String.format("-fx-font-family: %s; -fx-font-size: %s;", MaterialDesignIcon.CLOSE.fontFamily(), "1em"));
fakeXLabel.getStyleClass().add("small");
}
// Navigation
private void close() {
model.dataModel.onClose();
if (closeHandler != null)
closeHandler.close();
}
// Bindings, Listeners
private void addBindings() {
amountTextField.textProperty().bindBidirectional(model.amount);
volumeTextField.textProperty().bindBidirectional(model.volume);
totalToPayTextField.textProperty().bind(model.totalToPay);
addressTextField.amountAsCoinProperty().bind(model.dataModel.getMissingCoin());
amountTextField.validationResultProperty().bind(model.amountValidationResult);
priceCurrencyLabel.textProperty().bind(createStringBinding(() -> formatter.getCounterCurrency(model.dataModel.getCurrencyCode())));
priceAsPercentageLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty());
nextButton.disableProperty().bind(model.isNextButtonDisabled);
tradeFeeInBtcLabel.textProperty().bind(model.tradeFeeInBtcWithFiat);
tradeFeeInBsqLabel.textProperty().bind(model.tradeFeeInBsqWithFiat);
tradeFeeDescriptionLabel.textProperty().bind(model.tradeFeeDescription);
tradeFeeInBtcLabel.visibleProperty().bind(model.isTradeFeeVisible);
tradeFeeInBsqLabel.visibleProperty().bind(model.isTradeFeeVisible);
tradeFeeDescriptionLabel.visibleProperty().bind(model.isTradeFeeVisible);
// funding
fundingHBox.visibleProperty().bind(model.dataModel.getIsBtcWalletFunded().not().and(model.showPayFundsScreenDisplayed));
fundingHBox.managedProperty().bind(model.dataModel.getIsBtcWalletFunded().not().and(model.showPayFundsScreenDisplayed));
waitingForFundsLabel.textProperty().bind(model.spinnerInfoText);
takeOfferBox.visibleProperty().bind(model.dataModel.getIsBtcWalletFunded().and(model.showPayFundsScreenDisplayed));
takeOfferBox.managedProperty().bind(model.dataModel.getIsBtcWalletFunded().and(model.showPayFundsScreenDisplayed));
takeOfferButton.disableProperty().bind(model.isTakeOfferButtonDisabled);
}
private void removeBindings() {
amountTextField.textProperty().unbindBidirectional(model.amount);
volumeTextField.textProperty().unbindBidirectional(model.volume);
totalToPayTextField.textProperty().unbind();
addressTextField.amountAsCoinProperty().unbind();
amountTextField.validationResultProperty().unbind();
priceCurrencyLabel.textProperty().unbind();
priceAsPercentageLabel.prefWidthProperty().unbind();
nextButton.disableProperty().unbind();
tradeFeeInBtcLabel.textProperty().unbind();
tradeFeeInBsqLabel.textProperty().unbind();
tradeFeeDescriptionLabel.textProperty().unbind();
tradeFeeInBtcLabel.visibleProperty().unbind();
tradeFeeInBsqLabel.visibleProperty().unbind();
tradeFeeDescriptionLabel.visibleProperty().unbind();
// funding
fundingHBox.visibleProperty().unbind();
fundingHBox.managedProperty().unbind();
waitingForFundsLabel.textProperty().unbind();
takeOfferBox.visibleProperty().unbind();
takeOfferBox.managedProperty().unbind();
takeOfferButton.disableProperty().unbind();
}
@SuppressWarnings("PointlessBooleanExpression")
private void addSubscriptions() {
errorPopupDisplayed = new SimpleBooleanProperty();
offerWarningSubscription = EasyBind.subscribe(model.offerWarning, newValue -> {
if (newValue != null) {
if (offerDetailsWindowDisplayed)
offerDetailsWindow.hide();
UserThread.runAfter(() -> new Popup<>().warning(newValue + "\n\n" +
Res.get("takeOffer.alreadyPaidInFunds"))
.actionButtonTextWithGoTo("navigation.funds.availableForWithdrawal")
.onAction(() -> {
errorPopupDisplayed.set(true);
model.resetOfferWarning();
close();
navigation.navigateTo(MainView.class, FundsView.class, WithdrawalView.class);
})
.onClose(() -> {
errorPopupDisplayed.set(true);
model.resetOfferWarning();
close();
})
.show(), 100, TimeUnit.MILLISECONDS);
}
});
errorMessageSubscription = EasyBind.subscribe(model.errorMessage, newValue -> {
if (newValue != null) {
new Popup<>().error(Res.get("takeOffer.error.message", model.errorMessage.get()) +
Res.get("popup.error.tryRestart"))
.onClose(() -> {
errorPopupDisplayed.set(true);
model.resetErrorMessage();
close();
})
.show();
}
});
isOfferAvailableSubscription = EasyBind.subscribe(model.isOfferAvailable, isOfferAvailable -> {
if (isOfferAvailable) {
offerAvailabilityBusyAnimation.stop();
offerAvailabilityBusyAnimation.setVisible(false);
if (!DevEnv.isDaoActivated() && !model.isRange() && !model.showPayFundsScreenDisplayed.get())
showNextStepAfterAmountIsSet();
}
offerAvailabilityLabel.setVisible(!isOfferAvailable);
offerAvailabilityLabel.setManaged(!isOfferAvailable);
});
isWaitingForFundsSubscription = EasyBind.subscribe(model.isWaitingForFunds, isWaitingForFunds -> {
waitingForFundsBusyAnimation.play();
waitingForFundsLabel.setVisible(isWaitingForFunds);
waitingForFundsLabel.setManaged(isWaitingForFunds);
});
showWarningInvalidBtcDecimalPlacesSubscription = EasyBind.subscribe(model.showWarningInvalidBtcDecimalPlaces, newValue -> {
if (newValue) {
new Popup<>().warning(Res.get("takeOffer.amountPriceBox.warning.invalidBtcDecimalPlaces")).show();
model.showWarningInvalidBtcDecimalPlaces.set(false);
}
});
showTransactionPublishedScreenSubscription = EasyBind.subscribe(model.showTransactionPublishedScreen, newValue -> {
//noinspection ConstantConditions
if (newValue && DevEnv.isDevMode()) {
close();
} else //noinspection ConstantConditions,ConstantConditions
if (newValue && model.getTrade() != null && !model.getTrade().hasFailed()) {
String key = "takeOfferSuccessInfo";
if (DontShowAgainLookup.showAgain(key)) {
UserThread.runAfter(() -> new Popup<>().headLine(Res.get("takeOffer.success.headline"))
.feedback(Res.get("takeOffer.success.info"))
.actionButtonTextWithGoTo("navigation.portfolio.pending")
.dontShowAgainId(key)
.onAction(() -> {
UserThread.runAfter(
() -> navigation.navigateTo(MainView.class, PortfolioView.class, PendingTradesView.class)
, 100, TimeUnit.MILLISECONDS);
close();
})
.onClose(this::close)
.show(), 1);
} else {
close();
}
}
});
/* noSufficientFeeBinding = EasyBind.combine(model.dataModel.getIsWalletFunded(), model.dataModel.isMainNet, model.dataModel.isFeeFromFundingTxSufficient,
(getIsWalletFunded(), isMainNet, isFeeSufficient) -> getIsWalletFunded() && isMainNet && !isFeeSufficient);
noSufficientFeeSubscription = noSufficientFeeBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue)
new Popup<>().warning("The mining fee from your funding transaction is not sufficiently high.\n\n" +
"You need to use at least a mining fee of " +
model.formatter.formatCoinWithCode(FeePolicy.getMinRequiredFeeForFundingTx()) + ".\n\n" +
"The fee used in your funding transaction was only " +
model.formatter.formatCoinWithCode(model.dataModel.feeFromFundingTx) + ".\n\n" +
"The trade transactions might take too much time to be included in " +
"a block if the fee is too low.\n" +
"Please check at your external wallet that you set the required fee and " +
"do a funding again with the correct fee.\n\n" +
"In the \"Funds/Open for withdrawal\" section you can withdraw those funds.")
.closeButtonText(Res.get("shared.close"))
.onClose(() -> {
close();
navigation.navigateTo(MainView.class, FundsView.class, WithdrawalView.class);
})
.show();
});*/
balanceSubscription = EasyBind.subscribe(model.dataModel.getBalance(), balanceTextField::setBalance);
cancelButton2StyleSubscription = EasyBind.subscribe(takeOfferButton.visibleProperty(),
isVisible -> cancelButton2.setId(isVisible ? "cancel-button" : null));
}
private void removeSubscriptions() {
offerWarningSubscription.unsubscribe();
errorMessageSubscription.unsubscribe();
isOfferAvailableSubscription.unsubscribe();
isWaitingForFundsSubscription.unsubscribe();
showWarningInvalidBtcDecimalPlacesSubscription.unsubscribe();
showTransactionPublishedScreenSubscription.unsubscribe();
// noSufficientFeeSubscription.unsubscribe();
balanceSubscription.unsubscribe();
cancelButton2StyleSubscription.unsubscribe();
}
private void addListeners() {
amountTextField.focusedProperty().addListener(amountFocusedListener);
model.dataModel.getShowWalletFundedNotification().addListener(getShowWalletFundedNotificationListener);
model.isTradeFeeVisible.addListener(tradeFeeVisibleListener);
tradeFeeInBtcToggle.selectedProperty().addListener(tradeFeeInBtcToggleListener);
tradeFeeInBsqToggle.selectedProperty().addListener(tradeFeeInBsqToggleListener);
}
private void removeListeners() {
amountTextField.focusedProperty().removeListener(amountFocusedListener);
model.dataModel.getShowWalletFundedNotification().removeListener(getShowWalletFundedNotificationListener);
model.isTradeFeeVisible.removeListener(tradeFeeVisibleListener);
tradeFeeInBtcToggle.selectedProperty().removeListener(tradeFeeInBtcToggleListener);
tradeFeeInBsqToggle.selectedProperty().removeListener(tradeFeeInBsqToggleListener);
}
// Build UI elements
private void addScrollPane() {
scrollPane = new ScrollPane();
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
AnchorPane.setLeftAnchor(scrollPane, 0d);
AnchorPane.setTopAnchor(scrollPane, 0d);
AnchorPane.setRightAnchor(scrollPane, 0d);
AnchorPane.setBottomAnchor(scrollPane, 0d);
root.getChildren().add(scrollPane);
}
private void addGridPane() {
gridPane = new GridPane();
gridPane.getStyleClass().add("content-pane");
gridPane.setPadding(new Insets(30, 25, -1, 25));
gridPane.setHgap(5);
gridPane.setVgap(5);
ColumnConstraints columnConstraints1 = new ColumnConstraints();
columnConstraints1.setHalignment(HPos.RIGHT);
columnConstraints1.setHgrow(Priority.NEVER);
columnConstraints1.setMinWidth(200);
ColumnConstraints columnConstraints2 = new ColumnConstraints();
columnConstraints2.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints().addAll(columnConstraints1, columnConstraints2);
scrollPane.setContent(gridPane);
}
private void addPaymentGroup() {
paymentAccountTitledGroupBg = addTitledGroupBg(gridPane, gridRow, 1, Res.get("takeOffer.paymentInfo"));
GridPane.setColumnSpan(paymentAccountTitledGroupBg, 2);
final Tuple4<ComboBox<PaymentAccount>, Label, TextField, HBox> paymentAccountTuple = addComboBoxTopLabelTextField(gridPane,
gridRow, Res.get("shared.selectTradingAccount"),
Res.get("shared.paymentMethod"), Layout.FIRST_ROW_DISTANCE);
paymentAccountsComboBox = paymentAccountTuple.first;
HBox.setMargin(paymentAccountsComboBox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
paymentAccountsComboBox.setConverter(GUIUtil.getPaymentAccountsComboBoxStringConverter());
paymentAccountsComboBox.setVisible(false);
paymentAccountsComboBox.setManaged(false);
paymentAccountsComboBox.setOnAction(e -> {
maybeShowClearXchangeWarning();
model.onPaymentAccountSelected(paymentAccountsComboBox.getSelectionModel().getSelectedItem());
});
paymentMethodLabel = paymentAccountTuple.second;
paymentMethodTextField = paymentAccountTuple.third;
paymentMethodTextField.setMinWidth(250);
paymentMethodTextField.setEditable(false);
paymentMethodTextField.setMouseTransparent(true);
paymentMethodTextField.setFocusTraversable(false);
currencyTextField = new JFXTextField();
currencyTextField.setMinWidth(250);
currencyTextField.setEditable(false);
currencyTextField.setMouseTransparent(true);
currencyTextField.setFocusTraversable(false);
final Tuple2<Label, VBox> tradeCurrencyTuple = getTopLabelWithVBox(Res.get("shared.tradeCurrency"), currencyTextField);
HBox.setMargin(tradeCurrencyTuple.second, new Insets(5, 0, 0, 0));
final HBox hBox = paymentAccountTuple.forth;
hBox.setSpacing(30);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setPadding(new Insets(10, 0, 18, 0));
hBox.getChildren().add(tradeCurrencyTuple.second);
}
private void addAmountPriceGroup() {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 2,
Res.get("takeOffer.setAmountPrice"), Layout.COMPACT_GROUP_DISTANCE);
GridPane.setColumnSpan(titledGroupBg, 2);
addAmountPriceFields();
addSecondRow();
}
private void addOptionsGroup() {
advancedOptionsGroup = addTitledGroupBg(gridPane, ++gridRow, 1, Res.get("shared.advancedOptions"), Layout.COMPACT_GROUP_DISTANCE);
advancedOptionsBox = new HBox();
advancedOptionsBox.setSpacing(40);
GridPane.setRowIndex(advancedOptionsBox, gridRow);
GridPane.setColumnIndex(advancedOptionsBox, 0);
GridPane.setHalignment(advancedOptionsBox, HPos.LEFT);
GridPane.setMargin(advancedOptionsBox, new Insets(Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(advancedOptionsBox);
advancedOptionsBox.getChildren().addAll(getTradeFeeFieldsBox());
}
private void addButtons() {
Tuple3<Button, Button, HBox> tuple = add2ButtonsWithBox(gridPane, ++gridRow,
Res.get("shared.nextStep"), Res.get("shared.cancel"), 15, true);
buttonBox = tuple.third;
nextButton = tuple.first;
nextButton.setMaxWidth(200);
nextButton.setDefaultButton(true);
nextButton.setOnAction(e -> {
showNextStepAfterAmountIsSet();
});
cancelButton1 = tuple.second;
cancelButton1.setMaxWidth(200);
cancelButton1.setDefaultButton(false);
cancelButton1.setOnAction(e -> {
model.dataModel.swapTradeToSavings();
close();
});
}
private void showNextStepAfterAmountIsSet() {
if (DevEnv.isDaoTradingActivated())
showFeeOption();
else
onShowPayFundsScreen();
}
private void showFeeOption() {
boolean isPreferredFeeCurrencyBtc = model.dataModel.isPreferredFeeCurrencyBtc();
boolean isBsqForFeeAvailable = model.dataModel.isBsqForFeeAvailable();
if (!isPreferredFeeCurrencyBtc && !isBsqForFeeAvailable) {
Coin takerFee = model.dataModel.getTakerFee(false);
String missingBsq = null;
if (takerFee != null) {
missingBsq = Res.get("popup.warning.insufficientBsqFundsForBtcFeePayment",
bsqFormatter.formatCoinWithCode(takerFee.subtract(model.dataModel.getBsqBalance())));
} else if (model.dataModel.getBsqBalance().isZero()) {
missingBsq = Res.get("popup.warning.noBsqFundsForBtcFeePayment");
}
if (missingBsq != null) {
new Popup().warning(missingBsq)
.actionButtonText(Res.get("feeOptionWindow.useBTC"))
.onAction(() -> {
tradeFeeInBtcToggle.setSelected(true);
onShowPayFundsScreen();
})
.show();
} else {
onShowPayFundsScreen();
}
} else {
onShowPayFundsScreen();
}
}
private void addOfferAvailabilityLabel() {
offerAvailabilityBusyAnimation = new BusyAnimation(false);
offerAvailabilityLabel = new AutoTooltipLabel(Res.get("takeOffer.fundsBox.isOfferAvailable"));
buttonBox.getChildren().addAll(offerAvailabilityBusyAnimation, offerAvailabilityLabel);
}
private void addFundingGroup() {
// don't increase gridRow as we removed button when this gets visible
payFundsTitledGroupBg = addTitledGroupBg(gridPane, gridRow, 3,
Res.get("takeOffer.fundsBox.title"), Layout.COMPACT_GROUP_DISTANCE);
payFundsTitledGroupBg.getStyleClass().add("last");
GridPane.setColumnSpan(payFundsTitledGroupBg, 2);
payFundsTitledGroupBg.setVisible(false);
totalToPayTextField = addFundsTextfield(gridPane, gridRow,
Res.get("shared.totalsNeeded"), Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE);
totalToPayTextField.setVisible(false);
qrCodeImageView = new ImageView();
qrCodeImageView.setVisible(false);
qrCodeImageView.setFitHeight(150);
qrCodeImageView.setFitWidth(150);
qrCodeImageView.getStyleClass().add("qr-code");
Tooltip.install(qrCodeImageView, new Tooltip(Res.get("shared.openLargeQRWindow")));
qrCodeImageView.setOnMouseClicked(e -> GUIUtil.showFeeInfoBeforeExecute(
() -> UserThread.runAfter(
() -> new QRCodeWindow(getBitcoinURI()).show(),
200, TimeUnit.MILLISECONDS)));
GridPane.setRowIndex(qrCodeImageView, gridRow);
GridPane.setColumnIndex(qrCodeImageView, 1);
GridPane.setRowSpan(qrCodeImageView, 3);
GridPane.setValignment(qrCodeImageView, VPos.BOTTOM);
GridPane.setMargin(qrCodeImageView, new Insets(Layout.FIRST_ROW_DISTANCE - 9, 0, 0, 10));
gridPane.getChildren().add(qrCodeImageView);
addressTextField = addAddressTextField(gridPane, ++gridRow, Res.get("shared.tradeWalletAddress"));
addressTextField.setVisible(false);
balanceTextField = addBalanceTextField(gridPane, ++gridRow, Res.get("shared.tradeWalletBalance"));
balanceTextField.setVisible(false);
fundingHBox = new HBox();
fundingHBox.setVisible(false);
fundingHBox.setManaged(false);
fundingHBox.setSpacing(10);
Button fundFromSavingsWalletButton = new AutoTooltipButton(Res.get("shared.fundFromSavingsWalletButton"));
fundFromSavingsWalletButton.setDefaultButton(true);
fundFromSavingsWalletButton.getStyleClass().add("action-button");
fundFromSavingsWalletButton.setOnAction(e -> model.fundFromSavingsWallet());
Label label = new AutoTooltipLabel(Res.get("shared.OR"));
label.setPadding(new Insets(5, 0, 0, 0));
Button fundFromExternalWalletButton = new AutoTooltipButton(Res.get("shared.fundFromExternalWalletButton"));
fundFromExternalWalletButton.setDefaultButton(false);
fundFromExternalWalletButton.setOnAction(e -> GUIUtil.showFeeInfoBeforeExecute(this::openWallet));
waitingForFundsBusyAnimation = new BusyAnimation(false);
waitingForFundsLabel = new AutoTooltipLabel();
waitingForFundsLabel.setPadding(new Insets(5, 0, 0, 0));
fundingHBox.getChildren().addAll(fundFromSavingsWalletButton,
label,
fundFromExternalWalletButton,
waitingForFundsBusyAnimation,
waitingForFundsLabel);
GridPane.setRowIndex(fundingHBox, ++gridRow);
GridPane.setMargin(fundingHBox, new Insets(5, 0, 0, 0));
gridPane.getChildren().add(fundingHBox);
takeOfferBox = new HBox();
takeOfferBox.setSpacing(10);
GridPane.setRowIndex(takeOfferBox, gridRow);
GridPane.setColumnSpan(takeOfferBox, 2);
GridPane.setMargin(takeOfferBox, new Insets(5, 20, 0, 0));
gridPane.getChildren().add(takeOfferBox);
takeOfferButton = new AutoTooltipButton();
takeOfferButton.setOnAction(e -> onTakeOffer());
takeOfferButton.setMinHeight(40);
takeOfferButton.setPadding(new Insets(0, 20, 0, 20));
takeOfferBox.getChildren().add(takeOfferButton);
takeOfferBox.visibleProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
fundingHBox.getChildren().remove(cancelButton2);
takeOfferBox.getChildren().add(cancelButton2);
} else if (!fundingHBox.getChildren().contains(cancelButton2)) {
takeOfferBox.getChildren().remove(cancelButton2);
fundingHBox.getChildren().add(cancelButton2);
}
});
cancelButton2 = new AutoTooltipButton(Res.get("shared.cancel"));
fundingHBox.getChildren().add(cancelButton2);
cancelButton2.setOnAction(e -> {
if (model.dataModel.getIsBtcWalletFunded().get()) {
new Popup<>().warning(Res.get("takeOffer.alreadyFunded.askCancel"))
.closeButtonText(Res.get("shared.no"))
.actionButtonText(Res.get("shared.yesCancel"))
.onAction(() -> {
model.dataModel.swapTradeToSavings();
close();
})
.show();
} else {
close();
model.dataModel.swapTradeToSavings();
}
});
cancelButton2.setDefaultButton(false);
cancelButton2.setVisible(false);
}
private void openWallet() {
try {
Utilities.openURI(URI.create(getBitcoinURI()));
} catch (Exception ex) {
log.warn(ex.getMessage());
new Popup<>().warning(Res.get("shared.openDefaultWalletFailed")).show();
}
}
@NotNull
private String getBitcoinURI() {
return GUIUtil.getBitcoinURI(model.dataModel.getAddressEntry().getAddressString(),
model.dataModel.getMissingCoin().get(),
model.getPaymentLabel());
}
private void addAmountPriceFields() {
// amountBox
Tuple3<HBox, InputTextField, Label> amountValueCurrencyBoxTuple = getEditableValueBox(Res.get("takeOffer.amount.prompt"));
amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
amountTextField = amountValueCurrencyBoxTuple.second;
amountCurrency = amountValueCurrencyBoxTuple.third;
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox, model.getAmountDescription());
amountDescriptionLabel = amountInputBoxTuple.first;
VBox amountBox = amountInputBoxTuple.second;
xLabel = new Label();
xIcon = getIconForLabel(MaterialDesignIcon.CLOSE, "2em", xLabel);
xIcon.getStyleClass().add("opaque-icon");
xLabel.getStyleClass().addAll("opaque-icon-character");
// price
Tuple3<HBox, TextField, Label> priceValueCurrencyBoxTuple = getNonEditableValueBox();
priceValueCurrencyBox = priceValueCurrencyBoxTuple.first;
priceTextField = priceValueCurrencyBoxTuple.second;
priceCurrencyLabel = priceValueCurrencyBoxTuple.third;
Tuple2<Label, VBox> priceInputBoxTuple = getTradeInputBox(priceValueCurrencyBox,
Res.get("takeOffer.amountPriceBox.priceDescription"));
priceDescriptionLabel = priceInputBoxTuple.first;
getSmallIconForLabel(MaterialDesignIcon.LOCK, priceDescriptionLabel);
VBox priceBox = priceInputBoxTuple.second;
resultLabel = new AutoTooltipLabel("=");
resultLabel.getStyleClass().addAll("opaque-icon-character");
// volume
Tuple3<HBox, InfoInputTextField, Label> volumeValueCurrencyBoxTuple = getNonEditableValueBoxWithInfo();
volumeValueCurrencyBox = volumeValueCurrencyBoxTuple.first;
volumeInfoTextField = volumeValueCurrencyBoxTuple.second;
volumeTextField = volumeInfoTextField.getInputTextField();
volumeCurrencyLabel = volumeValueCurrencyBoxTuple.third;
Tuple2<Label, VBox> volumeInputBoxTuple = getTradeInputBox(volumeValueCurrencyBox, model.volumeDescriptionLabel.get());
volumeDescriptionLabel = volumeInputBoxTuple.first;
VBox volumeBox = volumeInputBoxTuple.second;
firstRowHBox = new HBox();
firstRowHBox.setSpacing(5);
firstRowHBox.setAlignment(Pos.CENTER_LEFT);
firstRowHBox.getChildren().addAll(amountBox, xLabel, priceBox, resultLabel, volumeBox);
GridPane.setColumnSpan(firstRowHBox, 2);
GridPane.setRowIndex(firstRowHBox, gridRow);
GridPane.setMargin(firstRowHBox, new Insets(Layout.COMPACT_FIRST_ROW_AND_GROUP_DISTANCE, 10, 0, 0));
gridPane.getChildren().add(firstRowHBox);
}
private void addSecondRow() {
Tuple3<HBox, TextField, Label> priceAsPercentageTuple = getNonEditableValueBox();
priceAsPercentageValueCurrencyBox = priceAsPercentageTuple.first;
priceAsPercentageTextField = priceAsPercentageTuple.second;
priceAsPercentageLabel = priceAsPercentageTuple.third;
Tuple2<Label, VBox> priceAsPercentageInputBoxTuple = getTradeInputBox(priceAsPercentageValueCurrencyBox,
Res.get("shared.distanceInPercent"));
priceAsPercentageDescription = priceAsPercentageInputBoxTuple.first;
getSmallIconForLabel(MaterialDesignIcon.CHART_LINE, priceAsPercentageDescription);
priceAsPercentageInputBox = priceAsPercentageInputBoxTuple.second;
priceAsPercentageLabel.setText("%");
Tuple3<HBox, TextField, Label> amountValueCurrencyBoxTuple = getNonEditableValueBox();
amountRangeTextField = amountValueCurrencyBoxTuple.second;
minAmountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(minAmountValueCurrencyBox,
Res.get("takeOffer.amountPriceBox.amountRangeDescription"));
amountRangeBox = amountInputBoxTuple.second;
amountRangeBox.setVisible(false);
fakeXLabel = new Label();
fakeXIcon = getIconForLabel(MaterialDesignIcon.CLOSE, "2em", fakeXLabel);
fakeXLabel.setVisible(false); // we just use it to get the same layout as the upper row
fakeXLabel.getStyleClass().add("opaque-icon-character");
HBox hBox = new HBox();
hBox.setSpacing(5);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(amountRangeBox, fakeXLabel, priceAsPercentageInputBox);
GridPane.setRowIndex(hBox, ++gridRow);
GridPane.setMargin(hBox, new Insets(0, 10, 10, 0));
gridPane.getChildren().add(hBox);
}
private VBox getTradeFeeFieldsBox() {
tradeFeeInBtcLabel = new Label();
tradeFeeInBtcLabel.setMouseTransparent(true);
tradeFeeInBtcLabel.setId("trade-fee-textfield");
tradeFeeInBsqLabel = new Label();
tradeFeeInBsqLabel.setMouseTransparent(true);
tradeFeeInBsqLabel.setId("trade-fee-textfield");
VBox vBox = new VBox();
vBox.setSpacing(6);
vBox.setMaxWidth(300);
vBox.setAlignment(DevEnv.isDaoActivated() ? Pos.CENTER_RIGHT : Pos.CENTER_LEFT);
vBox.getChildren().addAll(tradeFeeInBtcLabel, tradeFeeInBsqLabel);
tradeFeeInBtcToggle = new AutoTooltipSlideToggleButton();
tradeFeeInBtcToggle.setText("BTC");
tradeFeeInBtcToggle.setPadding(new Insets(-8, 5, -10, 5));
tradeFeeInBsqToggle = new AutoTooltipSlideToggleButton();
tradeFeeInBsqToggle.setText("BSQ");
tradeFeeInBsqToggle.setPadding(new Insets(-9, 5, -9, 5));
VBox tradeFeeToggleButtonBox = new VBox();
tradeFeeToggleButtonBox.getChildren().addAll(tradeFeeInBtcToggle, tradeFeeInBsqToggle);
HBox hBox = new HBox();
hBox.getChildren().addAll(vBox, tradeFeeToggleButtonBox);
hBox.setMinHeight(47);
hBox.setMaxHeight(hBox.getMinHeight());
HBox.setHgrow(vBox, Priority.ALWAYS);
HBox.setHgrow(tradeFeeToggleButtonBox, Priority.NEVER);
final Tuple2<Label, VBox> tradeInputBox = getTradeInputBox(hBox, Res.get("createOffer.tradeFee.descriptionBSQEnabled"));
tradeFeeDescriptionLabel = tradeInputBox.first;
return tradeInputBox.second;
}
// Utils
private void showInsufficientBsqFundsForBtcFeePaymentPopup() {
Coin takerFee = model.dataModel.getTakerFee(false);
String message = null;
if (takerFee != null)
message = Res.get("popup.warning.insufficientBsqFundsForBtcFeePayment",
bsqFormatter.formatCoinWithCode(takerFee.subtract(model.dataModel.getBsqBalance())));
else if (model.dataModel.getBsqBalance().isZero())
message = Res.get("popup.warning.noBsqFundsForBtcFeePayment");
if (message != null)
new Popup<>().warning(message)
.actionButtonTextWithGoTo("navigation.dao.wallet.receive")
.onAction(() -> navigation.navigateTo(MainView.class, DaoView.class, BsqWalletView.class, BsqReceiveView.class))
.show();
}
private void maybeShowClearXchangeWarning() {
if (model.getPaymentMethod().getId().equals(PaymentMethod.CLEAR_X_CHANGE_ID) &&
!clearXchangeWarningDisplayed) {
clearXchangeWarningDisplayed = true;
UserThread.runAfter(GUIUtil::showClearXchangeWarning,
500, TimeUnit.MILLISECONDS);
}
}
private Tuple2<Label, VBox> getTradeInputBox(HBox amountValueBox, String promptText) {
Label descriptionLabel = new AutoTooltipLabel(promptText);
descriptionLabel.setId("input-description-label");
descriptionLabel.setPrefWidth(170);
VBox box = new VBox();
box.setPadding(new Insets(10, 0, 0, 0));
box.setSpacing(2);
box.getChildren().addAll(descriptionLabel, amountValueBox);
return new Tuple2<>(descriptionLabel, box);
}
// As we don't use binding here we need to recreate it on mouse over to reflect the current state
private GridPane createInfoPopover() {
GridPane infoGridPane = new GridPane();
infoGridPane.setHgap(5);
infoGridPane.setVgap(5);
infoGridPane.setPadding(new Insets(10, 10, 10, 10));
int i = 0;
if (model.isSeller())
addPayInfoEntry(infoGridPane, i++, Res.get("takeOffer.fundsBox.tradeAmount"), model.getTradeAmount());
addPayInfoEntry(infoGridPane, i++, Res.getWithCol("shared.yourSecurityDeposit"), model.getSecurityDepositInfo());
addPayInfoEntry(infoGridPane, i++, Res.get("takeOffer.fundsBox.offerFee"), model.getTradeFee());
addPayInfoEntry(infoGridPane, i++, Res.get("takeOffer.fundsBox.networkFee"), model.getTxFee());
Separator separator = new Separator();
separator.setOrientation(Orientation.HORIZONTAL);
separator.getStyleClass().add("offer-separator");
GridPane.setConstraints(separator, 1, i++);
infoGridPane.getChildren().add(separator);
addPayInfoEntry(infoGridPane, i, Res.getWithCol("shared.total"),
model.getTotalToPayInfo());
return infoGridPane;
}
private Label createPopoverLabel(String text) {
final Label label = new Label(text);
label.setPrefWidth(300);
label.setWrapText(true);
label.setPadding(new Insets(10));
return label;
}
private void addPayInfoEntry(GridPane infoGridPane, int row, String labelText, String value) {
Label label = new AutoTooltipLabel(labelText);
TextField textField = new TextField(value);
textField.setMinWidth(500);
textField.setEditable(false);
textField.setFocusTraversable(false);
textField.setId("payment-info");
GridPane.setConstraints(label, 0, row, 1, 1, HPos.RIGHT, VPos.CENTER);
GridPane.setConstraints(textField, 1, row);
infoGridPane.getChildren().addAll(label, textField);
}
}
|
package org.mockitousage.stubbing;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.exceptions.verification.ArgumentsAreDifferent;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@SuppressWarnings("unchecked")
public class BasicStubbingTest extends TestBase {
private IMethods mock;
@Before
public void setup() {
mock = mock(IMethods.class);
}
@Test
public void shouldEvaluateLatestStubbingFirst() throws Exception {
when(mock.objectReturningMethod(isA(Integer.class))).thenReturn(100);
when(mock.objectReturningMethod(200)).thenReturn(200);
assertEquals(200, mock.objectReturningMethod(200));
assertEquals(100, mock.objectReturningMethod(666));
assertEquals("default behavior should return null", null, mock.objectReturningMethod("blah"));
}
@Test
public void shouldStubbingBeTreatedAsInteraction() throws Exception {
when(mock.booleanReturningMethod()).thenReturn(true);
mock.booleanReturningMethod();
try {
verifyNoMoreInteractions(mock);
fail();
} catch (NoInteractionsWanted e) {}
}
@Test
public void shouldAllowStubbingToString() throws Exception {
IMethods mockTwo = mock(IMethods.class);
when(mockTwo.toString()).thenReturn("test");
assertThat(mock.toString(), contains("Mock for IMethods"));
assertEquals("test", mockTwo.toString());
}
@SuppressWarnings("deprecation")
@Test
public void shouldStubbingWithThrowableFailVerification() {
when(mock.simpleMethod("one")).thenThrow(new RuntimeException());
stubVoid(mock).toThrow(new RuntimeException()).on().simpleMethod("two");
verifyZeroInteractions(mock);
mock.simpleMethod("foo");
try {
verify(mock).simpleMethod("one");
fail();
} catch (ArgumentsAreDifferent e) {}
try {
verify(mock).simpleMethod("two");
fail();
} catch (ArgumentsAreDifferent e) {}
try {
verifyNoMoreInteractions(mock);
fail();
} catch (NoInteractionsWanted e) {}
}
}
|
package net.mabako.steamgifts.tasks;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import net.mabako.Constants;
import net.mabako.steamgifts.data.Comment;
import net.mabako.steamgifts.data.Game;
import net.mabako.steamgifts.data.Giveaway;
import net.mabako.steamgifts.data.ICommentHolder;
import net.mabako.steamgifts.data.IImageHolder;
import net.mabako.steamgifts.data.Image;
import net.mabako.steamgifts.data.Rating;
import net.mabako.steamgifts.persistentdata.SavedRatings;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class Utils {
private Utils() {
}
/**
* Extract comments recursively.
*
* @param commentNode Jsoup-Node of the parent node.
* @param parent
*/
public static void loadComments(Element commentNode, ICommentHolder parent) {
loadComments(commentNode, parent, 0, false);
}
public static void loadComments(Element commentNode, ICommentHolder parent, int depth, boolean reversed) {
if (commentNode == null)
return;
Elements children = commentNode.children();
if (reversed)
Collections.reverse(children);
for (Element c : children) {
long commentId = 0;
try {
commentId = Integer.parseInt(c.attr("data-comment-id"));
} catch (NumberFormatException e) {
/* do nothing */
}
Comment comment = loadComment(c.child(0), commentId, depth);
// add this
parent.addComment(comment);
// Add all children
loadComments(c.select(".comment__children").first(), parent, depth + 1, false);
}
}
/**
* Load a single comment
*
* @param element comment HTML element
* @param commentId the id of the comment to be loaded
* @param depth the depth at which to display said comment
* @return the new comment
*/
@NonNull
public static Comment loadComment(Element element, long commentId, int depth) {
// Save the content of the edit state for a bit & remove the edit state from being rendered.
Element editState = element.select(".comment__edit-state.is-hidden textarea[name=description]").first();
String editableContent = null;
if (editState != null)
editableContent = editState.text();
element.select(".comment__edit-state").html("");
Element authorNode = element.select(".comment__username").first();
String author = authorNode.text();
boolean isOp = authorNode.hasClass("comment__username--op");
String avatar = null;
Element avatarNode = element.select(".global__image-inner-wrap").first();
if (avatarNode != null)
avatar = extractAvatar(avatarNode.attr("style"));
Element timeCreated = element.select(".comment__actions > div span").first();
Uri permalinkUri = Uri.parse(element.select(".comment__actions a[href^=/go/comment").first().attr("href"));
Comment comment = new Comment(commentId, author, depth, avatar, isOp);
comment.setPermalinkId(permalinkUri.getPathSegments().get(2));
comment.setEditableContent(editableContent);
comment.setCreatedTime(timeCreated.attr("title"));
Element desc = element.select(".comment__description").first();
String content = loadAttachedImages(comment, desc);
comment.setContent(content);
// check if the comment is deleted
comment.setDeleted(element.select(".comment__summary").first().select(".comment__delete-state").size() == 1);
comment.setHighlighted(element.select(".comment__parent > .comment__envelope").size() != 0);
Element roleName = element.select(".comment__role-name").first();
if (roleName != null)
comment.setAuthorRole(roleName.text().replace("(", "").replace(")", ""));
// Do we have either a delete or undelete link?
comment.setDeletable(element.select(".comment__actions__button.js__comment-delete").size() + element.select(".comment__actions__button.js__comment-undelete").size() == 1);
return comment;
}
public static String extractAvatar(String style) {
return style.replace("background-image:url(", "").replace(");", "").replace("_medium", "_full");
}
/**
* Load some details for the giveaway. Some items must be loaded outside of this.
*/
public static void loadGiveaway(Giveaway giveaway, Element element, String cssNode, String headerHintCssNode, Uri steamUri) {
// Copies & Points. They do not have separate markup classes, it's basically "if one thin markup element exists, it's one copy only"
Elements hints = element.select("." + headerHintCssNode);
if (!hints.isEmpty()) {
String copiesT = hints.first().text();
String pointsT = hints.last().text();
int copies = hints.size() == 1 ? 1 : Integer.parseInt(copiesT.replace("(", "").replace(" Copies)", "").replace(",", ""));
int points = Integer.parseInt(pointsT.replace("(", "").replace("P)", ""));
giveaway.setCopies(copies);
giveaway.setPoints(points);
} else {
giveaway.setCopies(1);
giveaway.setPoints(0);
}
// Steam link
if (steamUri != null) {
List<String> pathSegments = steamUri.getPathSegments();
if (pathSegments.size() >= 2) {
giveaway.setGame(new Game("app".equals(pathSegments.get(0)) ? Game.Type.APP : Game.Type.SUB, Integer.parseInt(pathSegments.get(1))));
}
}
// Time remaining
Element end = element.select("." + cssNode + "__columns > div span").first();
giveaway.setEndTime(end.attr("title"), end.text());
giveaway.setCreatedTime(element.select("." + cssNode + "__columns > div span").last().attr("title"));
// Flags
giveaway.setWhitelist(!element.select("." + cssNode + "__column--whitelist").isEmpty());
giveaway.setGroup(!element.select("." + cssNode + "__column--group").isEmpty());
giveaway.setPrivate(!element.select("." + cssNode + "__column--invite-only").isEmpty());
giveaway.setRegionRestricted(!element.select("." + cssNode + "__column--region-restricted").isEmpty());
Element level = element.select("." + cssNode + "__column--contributor-level").first();
if (level != null)
giveaway.setLevel(Integer.parseInt(level.text().replace("Level", "").replace("+", "").trim()));
// Internal ID for blacklisting
Element popup = element.select(".giveaway__hide.trigger-popup").first();
if (popup != null)
giveaway.setInternalGameId(Integer.parseInt(popup.attr("data-game-id")));
}
/**
* Loads giveaways from a list page.
* <p>This is not suitable for loading individual giveaway instances from the featured list, as the HTML layout differs (see {@link LoadGiveawayDetailsTask#loadGiveaway(Document, Uri)}</p>
*
* @param document the loaded document
* @return list of giveaways
*/
public static List<Giveaway> loadGiveawaysFromList(Document document, SavedRatings ratings) {
Elements giveaways = document.select(".giveaway__row-inner-wrap");
List<Giveaway> giveawayList = new ArrayList<>();
for (Element element : giveaways) {
// Basic information
Element link = element.select("h2 a").first();
Giveaway giveaway = null;
if (link.hasAttr("href")) {
Uri linkUri = Uri.parse(link.attr("href"));
String giveawayLink = linkUri.getPathSegments().get(1);
String giveawayName = linkUri.getPathSegments().get(2);
giveaway = new Giveaway(giveawayLink);
giveaway.setName(giveawayName);
} else {
giveaway = new Giveaway(null);
giveaway.setName(null);
}
giveaway.setTitle(link.text());
giveaway.setCreator(element.select(".giveaway__username").text());
// Entries, would usually have comment count too... but we don't display that anywhere.
Elements links = element.select(".giveaway__links a span");
giveaway.setEntries(Integer.parseInt(links.first().text().split(" ")[0].replace(",", "")));
giveaway.setEntered(element.hasClass("is-faded"));
// More details
Element icon = element.select("h2 a").last();
Uri uriIcon = icon == link ? null : Uri.parse(icon.attr("href"));
Utils.loadGiveaway(giveaway, element, "giveaway", "giveaway__heading__thin", uriIcon);
giveawayList.add(giveaway);
applyGiveawayRating(giveaway, ratings);
}
return giveawayList;
}
public static void applyGiveawayRating(Giveaway giveaway, SavedRatings ratings) {
Rating rating = ratings.get(giveaway.getGameId());
if (rating == null || !rating.isRatingValid()) {
int ratingForGame = fetchGiveawayRating(giveaway);
rating = new Rating(System.currentTimeMillis(), ratingForGame, giveaway.getGameId());
ratings.add(rating, giveaway.getGameId());
}
giveaway.setRating(rating.getRating());
}
public static int fetchGiveawayRating(Giveaway giveaway) {
Game game = giveaway.getGame();
if (game == null) {
return 0;
}
int gameId = game.getGameId();
Integer ratingFromSteamDB = getRatingFromSteamDB(gameId);
if (ratingFromSteamDB != null) {
return ratingFromSteamDB;
}
Integer ratingFromMetacritics = getRatingFromMetacritics(gameId);
Integer ratingFromSteamPowered = getRatingFromSteamPowered(gameId);
int rating = 0;
if (ratingFromMetacritics != null) {
rating = ratingFromMetacritics;
}
if (ratingFromSteamPowered != null && ratingFromSteamPowered>rating) {
rating = ratingFromSteamPowered;
}
return rating;
}
private static Integer getRatingFromSteamDB(int gameId) {
try {
Connection connect = Jsoup.connect("https://steamdb.info/app/" + gameId)
.userAgent(Constants.JSOUP_USER_AGENT)
.timeout(Constants.JSOUP_TIMEOUT);
Document document = connect.get();
String s = document.toString();
String ratingText = getValueFromHtml(s, "ratingValue");
if (ratingText != null) {
return Integer.parseInt(ratingText);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Integer getRatingFromSteamPowered(int gameId) {
try {
Connection connect = Jsoup.connect("http://store.steampowered.com/app/" + gameId)
.userAgent(Constants.JSOUP_USER_AGENT)
.timeout(Constants.JSOUP_TIMEOUT);
Document document = connect.get();
String s = document.toString();
String ratingText = getValueFromHtml(s, "ratingValue");
if (ratingText != null) {
return Integer.parseInt(ratingText) * 10;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Integer getRatingFromMetacritics(int gameId) {
String fileData = doGet("http://store.steampowered.com/api/appdetails?appids=" + gameId);
try {
JSONObject jsonObject = new JSONObject(fileData);
JSONObject gameJsonObject = jsonObject.getJSONObject(Integer.toString(gameId));
JSONObject dataJsonObject = gameJsonObject.getJSONObject("data");
JSONObject metacriticJsonObject = dataJsonObject.getJSONObject("metacritic");
return metacriticJsonObject.getInt("score");
} catch (JSONException e) {
return null;
}
}
@NonNull
private static String doGet(String urlPath) {
StringBuilder total = new StringBuilder();
try {
URL url = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
private static String getValueFromHtml(String body, String valueName) {
int startIdx = body.indexOf(valueName);
if (startIdx != -1) {
int contentStartIndex = body.indexOf("content=\"", startIdx);
if (contentStartIndex != -1) {
int contentStart = contentStartIndex + "content=\"".length();
if (contentStart != -1) {
int contentEnd = body.indexOf("\"", contentStart);
if (contentEnd != -1) {
String value = body.substring(contentStart, contentEnd);
return value;
}
}
}
}
return null;
}
/**
* The document title is in the format "Game Title - Page X" if we're on /giveaways/id/name/search?page=X,
* so we strip out the page number.
*/
public static String getPageTitle(Document document) {
String title = document.title();
return title.replaceAll(" - Page ([\\d,]+)$", "");
}
/**
* Extracts all images from the description.
*
* @param imageHolder item to save this into
* @param description description of the element
* @return the description, minus attached images
*/
public static String loadAttachedImages(IImageHolder imageHolder, Element description) {
// find all "View attached image" segments
Elements images = description.select("div > a > img.is-hidden");
for (Element image : images) {
// Extract the link.
String src = image.attr("src");
if (!TextUtils.isEmpty(src))
imageHolder.attachImage(new Image(src, image.attr("title")));
// Remove this image.
image.parent().parent().html("");
}
return description.html();
}
public static boolean isConnectedToWifi(final String tag, final Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected() || activeNetworkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
Log.v(tag, "Not checking for messages due to network info: " + activeNetworkInfo);
return false;
}
return true;
}
}
|
package io.opentelemetry.sdk.autoconfigure.spi;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder;
import io.opentelemetry.sdk.logs.export.LogExporter;
import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder;
import io.opentelemetry.sdk.metrics.export.MetricExporter;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Supplier;
/** A builder for customizing OpenTelemetry auto-configuration. */
public interface AutoConfigurationCustomizer {
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link TextMapPropagator}
* to allow customization. The return value of the {@link BiFunction} will replace the passed-in
* argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
AutoConfigurationCustomizer addPropagatorCustomizer(
BiFunction<? super TextMapPropagator, ConfigProperties, ? extends TextMapPropagator>
propagatorCustomizer);
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link Resource} to allow
* customization. The return value of the {@link BiFunction} will replace the passed-in argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
AutoConfigurationCustomizer addResourceCustomizer(
BiFunction<? super Resource, ConfigProperties, ? extends Resource> resourceCustomizer);
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link Sampler} to allow
* customization. The return value of the {@link BiFunction} will replace the passed-in argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
AutoConfigurationCustomizer addSamplerCustomizer(
BiFunction<? super Sampler, ConfigProperties, ? extends Sampler> samplerCustomizer);
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link SpanExporter} to
* allow customization. The return value of the {@link BiFunction} will replace the passed-in
* argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
AutoConfigurationCustomizer addSpanExporterCustomizer(
BiFunction<? super SpanExporter, ConfigProperties, ? extends SpanExporter>
exporterCustomizer);
/**
* Adds a {@link Supplier} of a map of property names and values to use as defaults for the {@link
* ConfigProperties} used during auto-configuration. The order of precedence of properties is
* system properties > environment variables > the suppliers registered with this method.
*
* <p>Multiple calls will cause properties to be merged in order, with later ones overwriting
* duplicate keys in earlier ones.
*/
AutoConfigurationCustomizer addPropertiesSupplier(
Supplier<Map<String, String>> propertiesSupplier);
/**
* Adds a {@link BiFunction} to invoke the with the {@link SdkTracerProviderBuilder} to allow
* customization. The return value of the {@link BiFunction} will replace the passed-in argument.
*
* <p>Multiple calls will execute the customizers in order.
*
* <p>Note: calling {@link SdkTracerProviderBuilder#setSampler(Sampler)} inside of your
* configuration function will cause any sampler customizers to be ignored that were configured
* via {@link #addSamplerCustomizer(BiFunction)}. If you want to replace the default sampler,
* check out {@link io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider} and
* use {@link #addPropertiesSupplier(Supplier)} to set `otel.traces.sampler` to your named
* sampler.
*
* <p>Similarly, calling {@link SdkTracerProviderBuilder#setResource(Resource)} inside of your
* configuration function will cause any resource customizers to be ignored that were configured
* via {@link #addResourceCustomizer(BiFunction)}.
*/
default AutoConfigurationCustomizer addTracerProviderCustomizer(
BiFunction<SdkTracerProviderBuilder, ConfigProperties, SdkTracerProviderBuilder>
tracerProviderCustomizer) {
return this;
}
/**
* Adds a {@link BiFunction} to invoke the with the {@link SdkMeterProviderBuilder} to allow
* customization. The return value of the {@link BiFunction} will replace the passed-in argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
default AutoConfigurationCustomizer addMeterProviderCustomizer(
BiFunction<SdkMeterProviderBuilder, ConfigProperties, SdkMeterProviderBuilder>
meterProviderCustomizer) {
return this;
}
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link MetricExporter} to
* allow customization. The return value of the {@link BiFunction} will replace the passed-in
* argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
default AutoConfigurationCustomizer addMetricExporterCustomizer(
BiFunction<? super MetricExporter, ConfigProperties, ? extends MetricExporter>
exporterCustomizer) {
return this;
}
/**
* Adds a {@link BiFunction} to invoke the with the {@link SdkLogEmitterProviderBuilder} to allow
* customization. The return value of the {@link BiFunction} will replace the passed-in argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
default AutoConfigurationCustomizer addLogEmitterProviderCustomizer(
BiFunction<SdkLogEmitterProviderBuilder, ConfigProperties, SdkLogEmitterProviderBuilder>
meterProviderCustomizer) {
return this;
}
/**
* Adds a {@link BiFunction} to invoke with the default autoconfigured {@link LogExporter} to
* allow customization. The return value of the {@link BiFunction} will replace the passed-in
* argument.
*
* <p>Multiple calls will execute the customizers in order.
*/
default AutoConfigurationCustomizer addLogExporterCustomizer(
BiFunction<? super LogExporter, ConfigProperties, ? extends LogExporter> exporterCustomizer) {
return this;
}
}
|
package nl.mpi.kinnate.gedcomimport;
import java.util.ArrayList;
public abstract class ImportLineStructure {
int gedcomLevel = 0;
String currentID = null;
String entityType = null;
boolean isFileHeader = false;
boolean incompleteLine = false;
private int currentFieldIndex = 0;
protected class FieldEntry {
protected String lineContents = null;
protected String currentName = null;
protected FieldEntry(String currentName, String lineContents) throws ImportException {
if (currentName == null) {
throw new ImportException("Cannot have null names to a field.");
}
this.currentName = currentName.trim();
if (lineContents != null) {
this.lineContents = lineContents.trim();
}
}
}
ArrayList<FieldEntry> fieldEntryList = new ArrayList<FieldEntry>();
public ImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) {
}
protected void addFieldEntry(String currentName, String lineContents) throws ImportException {
fieldEntryList.add(new FieldEntry(currentName, lineContents));
}
protected FieldEntry getCurrent() {
return fieldEntryList.get(currentFieldIndex);
}
protected void moveToNext() {
currentFieldIndex++;
}
protected boolean hasCurrent() {
return currentFieldIndex < fieldEntryList.size();
}
public String getCurrentID() throws ImportException {
if (currentID == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentID has not been set");
}
return currentID;
}
public String getCurrentName() throws ImportException {
if (getCurrent().currentName == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentName has not been set");
}
return getCurrent().currentName;
}
public int getGedcomLevel() {
return gedcomLevel;
}
public boolean hasLineContents() {
return hasCurrent() && getCurrent().lineContents != null;
}
public String getLineContents() throws ImportException {
if (!hasCurrent() || getCurrent().lineContents == null) {
// new Exception().printStackTrace();
throw new ImportException("LineContents has not been set");
}
return getCurrent().lineContents;
}
public String getEntityType() {
return entityType;
}
public boolean isFileHeader() {
return isFileHeader;
}
public boolean isContinueLine() {
return false;
}
public boolean isContinueLineBreak() {
return false;
}
public boolean isEndOfFileMarker() {
return false;
}
public boolean isIncompleteLine() {
return incompleteLine;
}
abstract boolean isRelation();
}
|
package SimpleOpenNI;
// FIXME - make simple direct pathing
//import processing.core.*;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.openni.PImage;
import org.myrobotlab.openni.PMatrix3D;
import org.myrobotlab.openni.PVector;
import org.myrobotlab.service.OpenNi;
import org.slf4j.Logger;
//import SimpleOpenNI.ContextWrapper;
public class SimpleOpenNI extends ContextWrapper implements SimpleOpenNIConstants {
public final static Logger log = LoggerFactory.getLogger(SimpleOpenNI.class);
static String nativDepLibPath = "";
static String nativLibPath = "";
static { // load the nativ shared lib
String sysStr = System.getProperty("os.name").toLowerCase();
String libName = "SimpleOpenNI";
String archStr = System.getProperty("os.arch").toLowerCase();
// String depLib;
try {
// check which system + architecture
if (sysStr.indexOf("win") >= 0) { // windows
if (archStr.indexOf("86") >= 0) { // 32bit
libName += "32.dll";
nativLibPath = getLibraryPathWin();
// "libraries/native/";
// recent change
nativDepLibPath = nativLibPath;// + "win32/"; recent change
} else if (archStr.indexOf("64") >= 0) {
libName += "64.dll";
// nativLibPath = getLibraryPathWin() +
// "libraries/native/";
nativLibPath = getLibraryPathWin();
// nativDepLibPath = nativLibPath + "win64/"; GroG ...
// recent change
nativDepLibPath = nativLibPath;
}
// load dependencies
System.load(nativDepLibPath + "OpenNI2.dll");
System.load(nativDepLibPath + "NiTE2.dll");
} else if (sysStr.indexOf("nix") >= 0 || sysStr.indexOf("linux") >= 0) { // unix
nativLibPath = "libraries/native/linux";
if (archStr.indexOf("86") >= 0) { // 32bit
libName += "32";
} else if (archStr.indexOf("64") >= 0) {
libName = "lib" + libName + "64.so";
nativLibPath = System.getProperty("user.dir") + "/libraries/native/";
nativDepLibPath = nativLibPath + "linux64/";
}
// log.info("nativDepLibPath = " + nativDepLibPath);
} else if (sysStr.indexOf("mac") >= 0) { // mac
libName = "lib" + libName + ".jnilib";
// nativLibPath = getLibraryPathLinux() +
// "libraries/native/";
nativLibPath = getLibraryPathMac();
nativDepLibPath = nativLibPath + "osx/";
// log.info("nativDepLibPath = " + nativDepLibPath);
}
// log.info("-- " + System.getProperty("user.dir"));
System.load(nativLibPath + libName);
} catch (UnsatisfiedLinkError e) {
log.error("Can't load SimpleOpenNI library (" + libName + ") : " + e);
log.error("Verify if you installed SimpleOpenNI correctly.\nhttp://code.google.com/p/simple-openni/wiki/Installation");
} catch (Exception ex) {
Logging.logError(ex);
}
}
// callback vars
protected Object _userCbObject;
protected Object _calibrationCbObject;
protected Object _poseCbObject;
protected Object _handCbObject;
protected Object _gestureCbObject;
protected Object _sessionCbObject;
protected Method _newUserMethod;
protected Method _lostUserMethod;
protected Method _outOfSceneUserMethod;
protected Method _visibleUserMethod;
// hands cb
protected Method _newHandMethod;
protected Method _trackedHandMethod;
protected Method _lostHandMethod;
// gesture cb
protected Method _newGestureMethod;
protected Method _inProgressGestureMethod;
protected Method _abortedGestureMethod;
protected Method _completedGestureMethod;
// nite session cb
protected Method _startSessionMethod;
protected Method _endSessionMethod;
protected Method _focusSessionMethod;
protected String _filename;
protected OpenNi _parent;
protected PImage _depthImage;
protected int[] _depthRaw;
protected PVector[] _depthMapRealWorld;
protected float[] _depthMapRealWorldXn;
// protected XnPoint3DArray _depthMapRealWorldArray;
protected PImage _rgbImage;
protected PImage _irImage;
protected PImage _sceneImage;
protected int[] _sceneRaw;
protected PImage _userImage;
protected int[] _userRaw;
// update flags
protected long _depthMapTimeStamp;
protected long _depthImageTimeStamp;
protected long _depthRealWorldTimeStamp;
protected long _rgbTimeStamp;
protected long _irImageTimeStamp;
protected long _userMapTimeStamp;
protected long _userImageTimeStamp;
protected float[] _tempVec = new float[3];
static protected boolean _initFlag = false;
public static int deviceCount() {
start();
return ContextWrapper.deviceCount();
}
public static int deviceNames(StrVector nodeNames) {
start();
return ContextWrapper.deviceNames(nodeNames);
}
public static String getLibraryPathLinux() {
URL url = SimpleOpenNI.class.getResource("SimpleOpenNI.class");
if (url != null) {
// Convert URL to string, taking care of spaces represented by the
// string.
String path = url.toString().replace("%20", " ");
int n0 = path.indexOf('/');
int n1 = -1;
n1 = path.indexOf("/SimpleOpenNI/library");
// exported apps.
if ((-1 < n0) && (-1 < n1))
return path.substring(n0, n1);
else
return "";
} else
return "";
}
public static String getLibraryPathMac() {
File f = new File("libraries/native/");
return f.getAbsolutePath() + "/";
}
public static String getLibraryPathWin() {
/*
* FIXME -- need a different way URL url =
* SimpleOpenNI.class.getResource("SimpleOpenNI.class"); //log.info("url = "
* + url); if (url != null) { // Convert URL to string, taking care of
* spaces represented by the "%20" // string. String path =
* url.toString().replace("%20", " "); int n0 = path.indexOf('/');
*
* int n1 = -1; n1 = path.indexOf("/SimpleOpenNI/library"); // exported
* apps.
*
* // In Windows, path string starts with "jar file/C:/..." // so the
* substring up to the first / is removed. n0++;
*
* if ((-1 < n0) && (-1 < n1)) return path.substring(n0, n1); else return
* ""; } else return "";
*/
// FIXME - get a Platform.instance - to support 32 bit
File f = new File("libraries/native/");
return f.getAbsolutePath().replace("\\", "/") + "/";
}
public static Method getMethodRef(Object obj, String methodName, Class[] paraList) {
Method ret = null;
try {
ret = obj.getClass().getMethod(methodName, paraList);
} catch (Exception e) { // no such method, or an error.. which is fine,
// just ignore
}
return ret;
}
public static int raySphereIntersection(PVector p, PVector dir, PVector sphereCenter, float sphereRadius, PVector hit1, PVector hit2) {
float[] hit1Ret = new float[3];
float[] hit2Ret = new float[3];
int ret = raySphereIntersection(p.array(), dir.array(), sphereCenter.array(), sphereRadius, hit1Ret, hit2Ret);
if (ret > 0) {
hit1.set(hit1Ret);
if (ret > 1)
hit2.set(hit2Ret);
}
return ret;
}
public static boolean rayTriangleIntersection(PVector p, PVector dir, PVector vec0, PVector vec1, PVector vec2, PVector hit) {
float[] hitRet = new float[3];
if (rayTriangleIntersection(p.array(), dir.array(), vec0.array(), vec1.array(), vec2.array(), hitRet)) {
hit.set(hitRet);
return true;
} else
return false;
}
public static void start() {
if (_initFlag)
return;
String curPath = ContextWrapper.getcwd();
ContextWrapper.chdir(new String(nativDepLibPath));
_initFlag = true;
initContext();
ContextWrapper.chdir(curPath);
}
/**
* Creates the OpenNI context ands inits the modules
*
* @param parent
* PApplet
*/
public SimpleOpenNI(OpenNi parent) {
initEnv(parent, RUN_MODE_SINGLE_THREADED, -1);
}
/**
* Creates the OpenNI context ands inits the modules
*
* @param parent
* OpenNI
* @param recordPath
* String, path to the record file
*/
public SimpleOpenNI(OpenNi parent, String recordPath) {
String path = parent.dataPath(recordPath);
String curPath = ContextWrapper.getcwd();
ContextWrapper.chdir(new String(nativDepLibPath));
this._parent = parent;
parent.registerDispose(this);
initVars();
// setup the callbacks
setupCallbackFunc();
// start openni
this.init(path, RUN_MODE_DEFAULT);
if ((nodes() & NODE_DEPTH) > 0)
setupDepth();
if ((nodes() & NODE_IMAGE) > 0)
setupRGB();
if ((nodes() & NODE_IR) > 0)
setupIR();
ContextWrapper.chdir(curPath);
}
/**
* Creates the OpenNI context ands inits the modules
*
* @param parent
* OpenNI
* @param recordPath
* String, path to the record file
* @param runMode
* - RUN_MODE_DEFAULT, RunMode_SingleThreaded = Runs all in a single
* thread - RunMode_MultiThreaded = Runs the openNI/NIITE in another
* thread than processing
*/
public SimpleOpenNI(OpenNi parent, String recordPath, int runMode) {
String path = parent.dataPath(recordPath);
String curPath = ContextWrapper.getcwd();
ContextWrapper.chdir(new String(nativDepLibPath));
this._parent = parent;
parent.registerDispose(this);
initVars();
// setup the callbacks
setupCallbackFunc();
// start openni
this.init(path, runMode);
// start openni
this.init(path, RUN_MODE_DEFAULT);
if ((nodes() & NODE_DEPTH) > 0)
setupDepth();
if ((nodes() & NODE_IMAGE) > 0)
setupRGB();
if ((nodes() & NODE_IR) > 0)
setupIR();
ContextWrapper.chdir(curPath);
}
/**
* Applies only the rotation part of 'mat' to
*
* @param mat
* PMatrix3D
*/
public void calcUserCoordsys(PMatrix3D mat) {
if (hasUserCoordsys() == false)
return;
float[] matRet = new float[9];
matRet[0] = mat.m00;
matRet[1] = mat.m01;
matRet[2] = mat.m02;
matRet[3] = mat.m10;
matRet[4] = mat.m11;
matRet[5] = mat.m12;
matRet[6] = mat.m20;
matRet[7] = mat.m21;
matRet[8] = mat.m22;
calcUserCoordsys(matRet);
mat.set(matRet[0], matRet[1], matRet[2], 0, matRet[3], matRet[4], matRet[5], 0, matRet[6], matRet[7], matRet[8], 0, 0, 0, 0, 1);
}
/**
* Calculates a point in the user defined coordinate system back to the 3d
* system of the 3d camera
*
* @param point
* PVector
*/
public void calcUserCoordsys(PVector point) {
if (hasUserCoordsys() == false)
return;
float[] p = new float[3];
calcUserCoordsys(p);
point.set(p[0], p[1], p[2]);
}
/**
* Calculates a point in origninal 3d camera coordinate system to the
* coordinate system defined by the user
*
* @param mat
* PMatrix3D
*/
public void calcUserCoordsysBack(PMatrix3D mat) {
if (hasUserCoordsys() == false)
return;
float[] matRet = new float[9];
matRet[0] = mat.m00;
matRet[1] = mat.m01;
matRet[2] = mat.m02;
matRet[3] = mat.m10;
matRet[4] = mat.m11;
matRet[5] = mat.m12;
matRet[6] = mat.m20;
matRet[7] = mat.m21;
matRet[8] = mat.m22;
calcUserCoordsysBack(matRet);
mat.set(matRet[0], matRet[1], matRet[2], 0, matRet[3], matRet[4], matRet[5], 0, matRet[6], matRet[7], matRet[8], 0, 0, 0, 0, 1);
}
/**
* Calculates a point in origninal 3d camera coordinate system to the
* coordinate system defined by the user
*
* @param point
* PVector
*/
public void calcUserCoordsysBack(PVector point) {
if (hasUserCoordsys() == false)
return;
float[] p = new float[3];
calcUserCoordsysBack(p);
point.set(p[0], p[1], p[2]);
}
public void convertProjectiveToRealWorld(PVector proj, PVector world) {
convertProjectiveToRealWorld(proj.array(), _tempVec);
world.set(_tempVec);
}
public void convertRealWorldToProjective(PVector world, PVector proj) {
convertRealWorldToProjective(world.array(), _tempVec);
proj.set(_tempVec);
}
/*
* Enable the depthMap data collection
*
* @param width int
*
* @param height int
*
* @param fps int
*
* @return returns true if depthMap generation was succesfull
*/
/*
* public boolean enableDepth(int width,int height,int fps) {
* if(super.enableDepth(width,height,fps)) { // setup the var for depth calc
* setupDepth(); return true; } else return false; }
*/
public PImage depthImage() {
updateDepthImage();
return _depthImage;
}
public int[] depthMap() {
updateDepthRaw();
return _depthRaw;
}
public PVector[] depthMapRealWorld() {
updateDepthRealWorld();
return _depthMapRealWorld;
}
public void dispose() {
close();
}
// helper methods
/**
* Helper method that draw the 3d camera and the frustum of the camera
*
*/
public void drawCamFrustum() {
/*
* _parent.g.pushStyle(); _parent.g.pushMatrix();
*
* if(hasUserCoordsys()) { // move the camera to the real nullpoint
* PMatrix3D mat = new PMatrix3D(); getUserCoordsys(mat);
* _parent.g.applyMatrix(mat); }
*
* // draw cam case _parent.stroke(200,200,0); _parent.noFill();
* _parent.g.beginShape(); _parent.g.vertex(270 * .5f,40 * .5f,0.0f);
* _parent.g.vertex(-270 * .5f,40 * .5f,0.0f); _parent.g.vertex(-270 *
* .5f,-40 * .5f,0.0f); _parent.g.vertex(270 * .5f,-40 * .5f,0.0f);
* _parent.g.endShape(PConstants.CLOSE);
*
* _parent.g.beginShape(); _parent.g.vertex(220 * .5f,40 * .5f,-50.0f);
* _parent.g.vertex(-220 * .5f,40 * .5f,-50.0f); _parent.g.vertex(-220 *
* .5f,-40 * .5f,-50.0f); _parent.g.vertex(220 * .5f,-40 * .5f,-50.0f);
* _parent.g.endShape(PConstants.CLOSE);
*
* _parent.g.beginShape(PConstants.LINES); _parent.g.vertex(270 * .5f,40 *
* .5f,0.0f); _parent.g.vertex(220 * .5f,40 * .5f,-50.0f);
*
* _parent.g.vertex(-270 * .5f,40 * .5f,0.0f); _parent.g.vertex(-220 *
* .5f,40 * .5f,-50.0f);
*
* _parent.g.vertex(-270 * .5f,-40 * .5f,0.0f); _parent.g.vertex(-220 *
* .5f,-40 * .5f,-50.0f);
*
* _parent.g.vertex(270 * .5f,-40 * .5f,0.0f); _parent.g.vertex(220 *
* .5f,-40 * .5f,-50.0f); _parent.g.endShape();
*
* // draw cam opening angles _parent.stroke(200,200,0,50);
* _parent.g.line(0.0f,0.0f,0.0f, 0.0f,0.0f,1000.0f);
*
* // calculate the angles of the cam, values are in radians, radius is 10m
* float distDepth = 10000;
*
* float valueH = distDepth * _parent.tan(hFieldOfView() * .5f); float
* valueV = distDepth * _parent.tan(vFieldOfView() * .5f);
*
* _parent.stroke(200,200,0,100); _parent.g.line(0.0f,0.0f,0.0f,
* valueH,valueV,distDepth); _parent.g.line(0.0f,0.0f,0.0f,
* -valueH,valueV,distDepth); _parent.g.line(0.0f,0.0f,0.0f,
* valueH,-valueV,distDepth); _parent.g.line(0.0f,0.0f,0.0f,
* -valueH,-valueV,distDepth); _parent.g.beginShape();
* _parent.g.vertex(valueH,valueV,distDepth);
* _parent.g.vertex(-valueH,valueV,distDepth);
* _parent.g.vertex(-valueH,-valueV,distDepth);
* _parent.g.vertex(valueH,-valueV,distDepth);
* _parent.g.endShape(PConstants.CLOSE);
*
* _parent.g.popMatrix(); _parent.g.popStyle();
*/
}
/**
* Draws a limb from joint1 to joint2
*
* @param userId
* int
* @param joint1
* int
* @param joint2
* int
*/
public void drawLimb(int userId, int joint1, int joint2) {
PVector joint1Pos = new PVector();
PVector joint2Pos = new PVector();
getJointPositionSkeleton(userId, joint1, joint1Pos);
getJointPositionSkeleton(userId, joint2, joint2Pos);
PVector joint1Pos2d = new PVector();
PVector joint2Pos2d = new PVector();
convertRealWorldToProjective(joint1Pos, joint1Pos2d);
convertRealWorldToProjective(joint2Pos, joint2Pos2d);
_parent.line(joint1Pos2d.x, joint1Pos2d.y, joint2Pos2d.x, joint2Pos2d.y, userId, joint1, joint2);
}
/**
* Enable the depthMap data collection
*/
@Override
public boolean enableDepth() {
if (super.enableDepth()) { // setup the var for depth calc
setupDepth();
return true;
} else
return false;
}
/**
* Enable hands
*/
@Override
public boolean enableHand() {
return enableHand(_parent);
}
/**
* Enable hands
*
* @param cbObject
* c
* @return true/false
*/
public boolean enableHand(Object cbObject) {
_handCbObject = cbObject;
if (super.enableHand()) {
setupHandCB(_handCbObject);
return true;
} else
return false;
}
/**
* Enable the irMap data collection ir is only available if there is no
* rgbImage activated at the same time
*/
@Override
public boolean enableIR() {
if (super.enableIR()) { // setup the var for depth calc
setupIR();
return true;
} else
return false;
}
/**
* Enable the irMap data collection ir is only available if there is no
* irImage activated at the same time
*
* @param width
* int
* @param height
* int
* @param fps
* int
* @return returns true if irMap generation was succesfull
*/
@Override
public boolean enableIR(int width, int height, int fps) {
if (super.enableIR(width, height, fps)) { // setup the var for depth
// calc
setupIR();
return true;
} else
return false;
}
// private void setupScene()
// _sceneImage = new PImage(sceneWidth(), sceneHeight(),PConstants.RGB);
// _sceneRaw = new int[sceneWidth() * sceneHeight()];
// /**
// * Enable the scene data collection
// */
// public boolean enableScene()
// if(super.enableScene())
// { // setup the var for depth calc
// setupScene();
// return true;
// else
// return false;
// /**
// * Enable the scene data collection
// *
// * @param width
// * int
// * @param height
// * int
// * @param fps
// * int
// * @return returns true if sceneMap generation was succesfull
// */
// public boolean enableScene(int width,int height,int fps)
// if(super.enableScene(width,height,fps))
// { // setup the var for depth calc
// setupScene();
// return true;
// else
// return false;
// public PImage sceneImage()
// updateSceneImage();
// return _sceneImage;
// public int[] sceneMap()
// updateSceneRaw();
// return _sceneRaw;
// public void getSceneFloor(PVector point,PVector normal)
// XnVector3D p = new XnVector3D();
// XnVector3D n = new XnVector3D();
// super.getSceneFloor(p, n);
// point.set(p.getX(),p.getY(),p.getZ());
// normal.set(n.getX(),n.getY(),n.getZ());
/**
* Enable recorder
*/
@Override
public boolean enableRecorder(String filePath) {
String path = _parent.dataPath(filePath);
_parent.createPath(path);
if (super.enableRecorder(path))
return true;
else
return false;
}
/**
* Enable the camera image collection
*/
@Override
public boolean enableRGB() {
if (super.enableRGB()) { // setup the var for depth calc
setupRGB();
return true;
} else
return false;
}
/**
* Enable the camera image collection
*
* @param width
* int
* @param height
* int
* @param fps
* int
* @return returns true if rgbMap generation was succesfull
*/
@Override
public boolean enableRGB(int width, int height, int fps) {
if (super.enableRGB(width, height, fps)) { // setup the var for depth
// calc
setupRGB();
return true;
} else
return false;
}
/**
* Enable user
*/
@Override
public boolean enableUser() {
return enableUser(_parent);
}
/**
* Enable user
*
* @param cbObject
* c
* @return true/false
*/
public boolean enableUser(Object cbObject) {
String curPath = ContextWrapper.getcwd();
ContextWrapper.chdir(new String(nativDepLibPath));
boolean ret = super.enableUser();
ContextWrapper.chdir(curPath);
if (ret) {
setupUserCB(cbObject);
setupUser();
return true;
} else
return false;
}
@Override
public void finalize() {
close();
}
public boolean getBoundingBox(int user, PVector bbMin, PVector bbMax) {
boolean ret;
float[] vec = new float[6];
ret = super.getBoundingBox(user, vec);
bbMin.set(vec[0], vec[1], vec[2]);
bbMax.set(vec[3], vec[4], vec[5]);
return ret;
}
public boolean getCoM(int user, PVector com) {
boolean ret;
float[] vec = new float[3];
ret = super.getCoM(user, vec);
com.set(vec);
return ret;
}
/**
* gets the orientation of a joint
*
* @param userId
* int
* @param joint
* int
* @param jointOrientation
* PMatrix3D
* @return The confidence of this joint float
*/
public float getJointOrientationSkeleton(int userId, int joint, PMatrix3D jointOrientation) {
float[] mat = new float[9];
float ret = getJointOrientationSkeleton(userId, joint, mat);
jointOrientation.set(mat[0], mat[1], mat[2], 0, mat[3], mat[4], mat[5], 0, mat[6], mat[7], mat[8], 0, 0, 0, 0, 1);
return ret;
}
/**
* gets the coordinates of a joint
*
* @param userId
* int
* @param joint
* int
* @param jointPos
* PVector
* @return The confidence of this joint float
*/
public float getJointPositionSkeleton(int userId, int joint, PVector jointPos) {
float ret = getJointPositionSkeleton(userId, joint, _tempVec);
jointPos.set(_tempVec);
jointPos.quality = ret;
return ret;
}
protected Method getMethodRef(String methodName, Class<Object>[] paraList) {
Method ret = null;
try {
ret = _parent.getClass().getMethod(methodName, paraList);
} catch (Exception e) { // no such method, or an error.. which is fine,
// just ignore
}
return ret;
}
public void getUserCoordsys(PMatrix3D mat) {
if (hasUserCoordsys() == false)
return;
float matRet[] = new float[16];
getUserCoordsys(matRet);
mat.set(matRet[0], matRet[1], matRet[2], matRet[3], matRet[4], matRet[5], matRet[6], matRet[7], matRet[8], matRet[9], matRet[10], matRet[11], matRet[12], matRet[13],
matRet[14], matRet[15]);
}
public void getUserCoordsysBack(PMatrix3D mat) {
if (hasUserCoordsys() == false)
return;
float matRet[] = new float[16];
getUserCoordsysBack(matRet);
mat.set(matRet[0], matRet[1], matRet[2], matRet[3], matRet[4], matRet[5], matRet[6], matRet[7], matRet[8], matRet[9], matRet[10], matRet[11], matRet[12], matRet[13],
matRet[14], matRet[15]);
}
// private void setupGesture()
// // gesture
// _recognizeGestureMethod =
// getMethodRef(_gestureCbObject,"onRecognizeGesture",new Class[] {
// String.class,PVector.class,PVector.class });
// _progressGestureMethod =
// getMethodRef(_gestureCbObject,"onProgressGesture",new Class[] {
// String.class,PVector.class,float.class });
// /**
// * Enable hands
// */
// public boolean enableGesture()
// return enableGesture(_parent);
// /**
// * Enable gesture
// */
// public boolean enableGesture(Object cbObject)
// _gestureCbObject = cbObject;
// if(super.enableGesture())
// setupGesture();
// return true;
// else
// return false;
/**
* gets the transformation matrix of a user defined coordinatesystem
*
* @param xformMat
* PMatrix3D
*/
public void getUserCoordsysTransMat(PMatrix3D xformMat) {
// xformMat.identity();
if (hasUserCoordsys() == false)
return;
float[] mat = new float[16];
getUserCoordsysTransMat(mat);
xformMat.set(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]);
}
// /**
// * Enable the player
// */
// public boolean openFileRecording(String filePath)
// String path = _parent.dataPath(filePath);
// if(super.openFileRecording(path))
// { // get all the nodes that are in use and init them
// if((nodes() & NODE_DEPTH) > 0)
// setupDepth();
// if((nodes() & NODE_IMAGE) > 0)
// setupRGB();
// if((nodes() & NODE_IR) > 0)
// setupIR();
// if((nodes() & NODE_SCENE) > 0)
// setupScene();
// if((nodes() & NODE_USER) > 0)
// setupUser();
// if((nodes() & NODE_GESTURE) > 0)
// setupGesture();
// if((nodes() & NODE_HANDS) > 0)
// setupHands();
// return true;
// else
// return false;
public int[] getUsers() {
IntVector intVec = new IntVector();
getUsers(intVec);
int[] userList = new int[(int) intVec.size()];
for (int i = 0; i < intVec.size(); i++)
userList[i] = intVec.get(i);
return userList;
}
protected void initEnv(OpenNi parent, int runMode, int deviceIndex) {
String curPath = ContextWrapper.getcwd();
ContextWrapper.chdir(new String(nativDepLibPath));
this._parent = parent;
parent.registerDispose(this);
initVars();
// setup the callbacks
setupCallbackFunc();
if (deviceIndex < 0)
this.init(runMode);
else
this.init(deviceIndex, runMode);
ContextWrapper.chdir(curPath);
}
protected void initVars() {
_depthMapTimeStamp = -1;
_depthImageTimeStamp = -1;
_depthRealWorldTimeStamp = -1;
_rgbTimeStamp = -1;
_irImageTimeStamp = -1;
_userMapTimeStamp = -1;
_userImageTimeStamp = -1;
}
public PImage irImage() {
updateIrImage();
return _irImage;
}
@Override
protected void onAbortedGestureCb(int gestureId) {
log.info("onAbortedGestureCb");
try {
_abortedGestureMethod.invoke(_handCbObject, new Object[] { this, (int) gestureId });
} catch (Exception e) {
}
}
@Override
protected void onCompletedGestureCb(int gestureId, Vec3f pos) {
try {
_completedGestureMethod.invoke(_handCbObject, new Object[] { this, (int) gestureId, new PVector(pos.x(), pos.y(), pos.z()) });
} catch (Exception e) {
}
}
@Override
protected void onInProgressGestureCb(int gestureId) {
try {
_inProgressGestureMethod.invoke(_handCbObject, new Object[] { this, (int) gestureId });
} catch (Exception e) {
}
}
@Override
protected void onLostHandCb(int handId) {
try {
_lostHandMethod.invoke(_handCbObject, new Object[] { this, (int) handId });
} catch (Exception e) {
}
}
@Override
protected void onLostUserCb(int userId) {
try {
_lostUserMethod.invoke(_userCbObject, new Object[] { this, (int) userId });
} catch (Exception e) {
}
}
// gesture
@Override
protected void onNewGestureCb(int gestureId) {
try {
_newGestureMethod.invoke(_handCbObject, new Object[] { this, (int) gestureId });
} catch (Exception e) {
}
}
// hand
@Override
protected void onNewHandCb(int handId, Vec3f pos) {
try {
_newHandMethod.invoke(_handCbObject, new Object[] { this, (int) handId, new PVector(pos.x(), pos.y(), pos.z()) });
} catch (Exception e) {
}
}
// user
@Override
protected void onNewUserCb(int userId) {
try {
_newUserMethod.invoke(_userCbObject, new Object[] { this, (int) userId });
} catch (Exception e) {
}
}
// /*
// public void convertRealWorldToProjective(Vector3D worldArray, Vector3D
// projArray)
// {
// }
// */
@Override
protected void onOutOfSceneUserCb(int userId) {
try {
_outOfSceneUserMethod.invoke(_userCbObject, new Object[] { this, (int) userId });
} catch (Exception e) {
}
}
// /*
// public void convertProjectiveToRealWorld(Vector3D projArray, Vector3D
// worldArray)
// {
// }
// */
@Override
protected void onTrackedHandCb(int handId, Vec3f pos) {
try {
_trackedHandMethod.invoke(_handCbObject, new Object[] { this, (int) handId, new PVector(pos.x(), pos.y(), pos.z()) });
} catch (Exception e) {
}
}
@Override
protected void onVisibleUserCb(int userId) {
try {
_visibleUserMethod.invoke(_userCbObject, new Object[] { this, (int) userId });
} catch (Exception e) {
}
}
public PImage rgbImage() {
updateImage();
return _rgbImage;
}
protected void setupCallbackFunc() {
_userCbObject = _parent;
_handCbObject = _parent;
_gestureCbObject = _parent;
_calibrationCbObject = _parent;
_poseCbObject = _parent;
_sessionCbObject = _parent;
_newUserMethod = null;
_lostUserMethod = null;
_outOfSceneUserMethod = null;
_visibleUserMethod = null;
_newHandMethod = null;
_trackedHandMethod = null;
_lostHandMethod = null;
_newGestureMethod = null;
_inProgressGestureMethod = null;
_abortedGestureMethod = null;
_completedGestureMethod = null;
// user callbacks
setupUserCB(_parent);
// hands
setupHandCB(_parent);
}
private void setupDepth() {
_depthImage = new PImage(depthWidth(), depthHeight());
_depthRaw = new int[depthMapSize()];
_depthMapRealWorld = new PVector[depthMapSize()];
_depthMapRealWorldXn = new float[depthMapSize() * 3];
for (int i = 0; i < depthMapSize(); i++)
_depthMapRealWorld[i] = new PVector();
}
private void setupHandCB(Object obj) {
_newHandMethod = getMethodRef(obj, "onNewHand", new Class[] { SimpleOpenNI.class, int.class, PVector.class });
_trackedHandMethod = getMethodRef(obj, "onTrackedHand", new Class[] { SimpleOpenNI.class, int.class, PVector.class });
_lostHandMethod = getMethodRef(obj, "onLostHand", new Class[] { SimpleOpenNI.class, int.class });
// gesture
_newGestureMethod = getMethodRef(obj, "onNewGesture", new Class[] { SimpleOpenNI.class, int.class });
_inProgressGestureMethod = getMethodRef(obj, "onProgressGesture", new Class[] { SimpleOpenNI.class, int.class });
_abortedGestureMethod = getMethodRef(obj, "onAbortedGesture", new Class[] { SimpleOpenNI.class, int.class });
_completedGestureMethod = getMethodRef(obj, "onCompletedGesture", new Class[] { SimpleOpenNI.class, int.class, PVector.class });
}
private void setupIR() {
_irImage = new PImage(irWidth(), irHeight());
}
private void setupRGB() {
_rgbImage = new PImage(rgbWidth(), rgbHeight());
}
// geometry helper functions
private void setupUser() {
_userRaw = new int[userWidth() * userHeight()];
_userImage = new PImage(userWidth(), userHeight());
}
private void setupUserCB(Object obj) {
_newUserMethod = getMethodRef(obj, "onNewUser", new Class[] { SimpleOpenNI.class, int.class });
_lostUserMethod = getMethodRef(obj, "onLostUser", new Class[] { SimpleOpenNI.class, int.class });
_outOfSceneUserMethod = getMethodRef(obj, "onOutOfSceneUser", new Class[] { SimpleOpenNI.class, int.class });
_visibleUserMethod = getMethodRef(obj, "onVisibleUser", new Class[] { SimpleOpenNI.class, int.class });
}
// callbacks
public int startTrackingHand(PVector pos) {
return super.startTrackingHand(pos.array());
}
/**
* Enable the user data collection
*/
@Override
public void update() {
super.update();
}
protected void updateDepthImage() {
if ((nodes() & NODE_DEPTH) == 0)
return;
if (_depthImageTimeStamp == updateTimeStamp())
return;
_depthImage.loadPixels();
depthImage(_depthImage.pixels);
_depthImage.updatePixels();
_depthImageTimeStamp = updateTimeStamp();
}
protected void updateDepthRaw() {
if ((nodes() & NODE_DEPTH) == 0)
return;
if (_depthMapTimeStamp == updateTimeStamp())
return;
depthMap(_depthRaw);
_depthMapTimeStamp = updateTimeStamp();
}
protected void updateDepthRealWorld() {
if ((nodes() & NODE_DEPTH) == 0)
return;
if (_depthRealWorldTimeStamp == updateTimeStamp())
return;
/*
* float[] depth3dArray = depthMapRealWorldA(); int index=0; for(int i=0;i <
* _depthMapRealWorld.length;i++) {
* _depthMapRealWorld[i].set(depth3dArray[index++], depth3dArray[index++],
* depth3dArray[index++]); }
*/
depthMapRealWorld(_depthMapRealWorldXn);
int index = 0;
for (int i = 0; i < _depthMapRealWorld.length; i++) {
_depthMapRealWorld[i].set(_depthMapRealWorldXn[index++], _depthMapRealWorldXn[index++], _depthMapRealWorldXn[index++]);
}
_depthRealWorldTimeStamp = updateTimeStamp();
}
protected void updateImage() {
if ((nodes() & NODE_IMAGE) == 0)
return;
if (_rgbTimeStamp == updateTimeStamp())
return;
// copy the rgb map
_rgbImage.loadPixels();
rgbImage(_rgbImage.pixels);
_rgbImage.updatePixels();
_rgbTimeStamp = updateTimeStamp();
}
protected void updateIrImage() {
if ((nodes() & NODE_IR) == 0)
return;
if (_irImageTimeStamp == updateTimeStamp())
return;
_irImage.loadPixels();
irImage(_irImage.pixels);
_irImage.updatePixels();
_irImageTimeStamp = updateTimeStamp();
}
protected void updateUserImage() {
if ((nodes() & NODE_USER) == 0)
return;
if (_userImageTimeStamp == updateTimeStamp())
return;
// copy the scene map
_userImage.loadPixels();
userImage(_userImage.pixels);
_userImage.updatePixels();
_userImageTimeStamp = updateTimeStamp();
}
protected void updateUserRaw() {
if ((nodes() & NODE_USER) == 0)
return;
if (_userImageTimeStamp == updateTimeStamp())
return;
userMap(_userRaw);
_userImageTimeStamp = updateTimeStamp();
}
/*
* public int[] getUsersPixels(int user) { int size = userWidth() *
* userHeight(); if(size == 0) return _userRaw;
*
* if(_userRaw.length != userWidth() * userHeight()) { // resize the array
* _userRaw = new int[userWidth() * userHeight()]; }
*
* super.getUserPixels(user,_userRaw); return _userRaw; }
*/
public PImage userImage() {
updateUserImage();
return _userImage;
}
public int[] userMap() {
updateUserRaw();
return _userRaw;
}
/*
* protected void onStartCalibrationCb(long userId) { try {
* _startCalibrationMethod.invoke(_calibrationCbObject, new Object[] {
* (int)userId }); } catch (Exception e) { } }
*
* protected void onEndCalibrationCb(long userId, boolean successFlag) { try {
* _endCalibrationMethod.invoke(_calibrationCbObject, new Object[] {
* (int)userId, successFlag}); } catch (Exception e) { } }
*
* protected void onStartPoseCb(String strPose, long userId) { try {
* _startPoseMethod.invoke(_poseCbObject, new Object[] { strPose,(int)userId
* }); } catch (Exception e) { } }
*
* protected void onEndPoseCb(String strPose, long userId) { try {
* _endPoseMethod.invoke(_poseCbObject, new Object[] { strPose,(int)userId });
* } catch (Exception e) { } }
*
* // hands protected void onCreateHandsCb(long nId, XnPoint3D pPosition,
* float fTime) { try { _createHandsMethod.invoke(_handCbObject, new Object[]
* { (int)nId,new
* PVector(pPosition.getX(),pPosition.getY(),pPosition.getZ()),fTime}); }
* catch (Exception e) {} }
*
* protected void onUpdateHandsCb(long nId, XnPoint3D pPosition, float fTime)
* { try { _updateHandsMethod.invoke(_handCbObject, new Object[] {
* (int)nId,new
* PVector(pPosition.getX(),pPosition.getY(),pPosition.getZ()),fTime}); }
* catch (Exception e) {} }
*
* protected void onDestroyHandsCb(long nId, float fTime) { try {
* _destroyHandsMethod.invoke(_handCbObject, new Object[] { (int)nId,fTime});
* } catch (Exception e) {} }
*
* protected void onRecognizeGestureCb(String strGesture, XnPoint3D
* pIdPosition, XnPoint3D pEndPosition) { try {
* _recognizeGestureMethod.invoke(_gestureCbObject, new Object[] { strGesture,
* new PVector(pIdPosition.getX(),pIdPosition.getY(),pIdPosition.getZ()), new
* PVector(pEndPosition.getX(),pEndPosition.getY(),pEndPosition.getZ()) }); }
* catch (Exception e) {} }
*
* protected void onProgressGestureCb(String strGesture, XnPoint3D pPosition,
* float fProgress) { try { _progressGestureMethod.invoke(_gestureCbObject,
* new Object[] { strGesture, new
* PVector(pPosition.getX(),pPosition.getY(),pPosition.getZ()), fProgress });
* } catch (Exception e) {} }
*
* // nite callbacks protected void onStartSessionCb(XnPoint3D ptPosition) {
* try { _startSessionMethod.invoke(_sessionCbObject, new Object[] { new
* PVector(ptPosition.getX(),ptPosition.getY(),ptPosition.getZ()) }); } catch
* (Exception e) {} }
*
* protected void onEndSessionCb() { try {
* _endSessionMethod.invoke(_sessionCbObject, new Object[] { }); } catch
* (Exception e) {} }
*
* protected void onFocusSessionCb(String strFocus, XnPoint3D ptPosition,
* float fProgress) { try { _focusSessionMethod.invoke(_sessionCbObject, new
* Object[] {strFocus, new
* PVector(ptPosition.getX(),ptPosition.getY(),ptPosition.getZ()), fProgress
* }); } catch (Exception e) {}
*
* }
*/
}
|
package org.fungsi.concurrent;
import org.fungsi.Either;
import org.fungsi.function.UnsafeFunction;
import java.time.Duration;
import java.time.Instant;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Optional;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
final class PromiseImpl<T> implements Promise<T> {
private Optional<Either<T, Throwable>> opt = Optional.empty();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Deque<Consumer<Either<T, Throwable>>> listeners = new LinkedList<>();
@Override
public void set(Either<T, Throwable> e) {
if (opt.isPresent()) return;
lock.writeLock().lock();
try {
this.opt = Optional.of(e);
} finally {
lock.writeLock().unlock();
}
while (!listeners.isEmpty()) {
listeners.removeFirst().accept(e);
}
}
@Override
public Optional<Either<T, Throwable>> poll() {
lock.readLock().lock();
try {
return opt;
} finally {
lock.readLock().unlock();
}
}
@Override
public T get() {
Either<T, Throwable> result;
while (true) {
Optional<Either<T, Throwable>> value = poll();
if (value.isPresent()) {
result = value.get();
break;
} else {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new Error(e);
}
}
}
return Either.unsafe(result);
}
@Override
public T get(Duration timeout) {
Instant deadline = Instant.now().plus(timeout);
Either<T, Throwable> result;
while (true) {
Optional<Either<T, Throwable>> value = poll();
if (value.isPresent()) {
result = value.get();
break;
} else {
if (Instant.now().isAfter(deadline)) {
throw new TimeoutException();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new Error(e);
}
}
}
return Either.unsafe(result);
}
@Override
public Future<T> respond(Consumer<Either<T, Throwable>> fn) {
listeners.addFirst(fn);
return this;
}
@Override
public <TT> Future<TT> bind(UnsafeFunction<T, Future<TT>> fn) {
return new BoundFuture<>(this, fn);
}
@Override
public String toString() {
return "Promise(" +
(isDone()
? isSuccess()
? "success"
: "failure"
: "pending") +
", " +
"listeners=" + listeners.size() +
")";
}
}
|
package algorithms.tsp;
import algorithms.SubsetChooser;
import algorithms.misc.MiscMath0;
import gnu.trove.list.TLongList;
import gnu.trove.list.array.TLongArrayList;
import java.util.Arrays;
public class TSPDynamic {
private long minCost = Long.MAX_VALUE;
private TLongList minPath = new TLongArrayList();
private final int startNode = 0;
private final int[][] dist;
private final long[][] memo;
private final long sentinel = Long.MAX_VALUE;
private final long totalNPerm;
private final long totalNSubSeq;
private final long w; // number of bits a city takes in a path where path is a long bitstring
public TSPDynamic(int[][] dist) {
this.dist = dist;
int n = dist.length;
long nPerm = MiscMath0.factorial(n); // max for n=13 for limit of array length
totalNPerm = nPerm/n;
totalNSubSeq = countTotalNumSubSeq(n); // max for n=507 for limit of array length
if (totalNSubSeq > Integer.MAX_VALUE) {
throw new IllegalArgumentException("this class can solve for 13 cities at most."
+ " one could design a datastructure to hold more than (1<<31)-1 items, "
+ " but the algorithms in this class have exponential runtime complexity,"
+ " so it would be better to choose a good approximate TSP.");
}
n = (int)totalNPerm;
w = (long)Math.ceil(Math.log(n-1)/Math.log(2));
memo = new long[n][];
for (int i = 0; i < n; ++i) {
memo[i] = new long[n];
Arrays.fill(memo[i], sentinel);
}
/*
//find max n cities for limit of array length
int nc = 100;
long wc, nb;
while (true) {
long c = countTotalNumSubSeq(nc);
if (c > Integer.MAX_VALUE) {
break;
}
wc = (long)Math.ceil(Math.log(nc-1)/Math.log(2)); // 1 city encoding in bits
nb = (Long.MAX_VALUE/wc); // the number of cities one could fit into a long if using wc
System.out.printf("nc=%d, ns=%d wc=%d nb=%d ns*1e-9=%e\n", nc, c, wc, nb, c*1.e-9);
nc = (int)Math.round(nc*1.5);
}
*/
}
public void test0() {
//nP = C(n-1,k) for 1 fixed node
int n = 10;
int k = 3;
long nPerm = MiscMath0.factorial(n);
nPerm = nPerm/n;
long nTotalPerm = countTotalNumSubSeq(n);
System.out.printf("nPerm=%d, nTotalPerm=%d\n", nPerm, nTotalPerm);
SubsetChooser chooser = new SubsetChooser(n-1, k);
int c = 0;
long s, sInv;
StringBuilder sb;
long all1s = 1 << (n-1);
all1s = all1s|all1s-1;
int nSetBits;
long tZeros;
while (true) {
s = chooser.getNextSubset64Bitstring();
if (s == -1) {
break;
}
s <<= 1;
sb = new StringBuilder(Long.toBinaryString(s));
while (sb.length() < n) {
sb = sb.insert(0, "0");
}
sInv = s^all1s;
sInv &= ~1; // clear bit 0
nSetBits = Long.bitCount(sInv);
tZeros = Long.numberOfTrailingZeros(sInv);
System.out.printf("%d (%7s) (%7s) nSetBits=%d tz=%d\n",
s, sb, Long.toBinaryString(sInv), nSetBits, tZeros);
// this permutation of nSetBits can be used for all 84 of the first
// 3-node paths.
// each use of the permutation can be left shifted by tZeros
// then assigned positions relative to the set bits in sInv
// to get the remaining permutations for this specific si
SubsetChooser chooseri = new SubsetChooser(nSetBits, k);
long si;
while (true) {
si = chooseri.getNextSubset64Bitstring();
if (si == -1) {
break;
}
long s2 = si << tZeros;
// the nSetBits in si are to be shifted by tZeros
// then converted to the si set bit positions
}
c++;
}
System.out.printf("n=%d count=%d\n", n, c);
}
// total number of subchooser invocations. max n = 507 for count < Integer.MAX_VALUE
private long countTotalNumSubSeq(int n) {
int k=3, n2=n;
long c = 0;
while (n2 > k) {
c += MiscMath0.computeNDivKTimesNMinusK(n2, k);
n2 -= k;
}
return c;
}
/**
* given a pathNodeNumber such as 0 being the first node in the path bit-string,
* uses path node bit-string length w to read the set bits and
* return the base 10 number (which can be used with the distance matrix
* or in writing the final solution of ordered nodes).
* @param path
* @param pathNodeNumber number of the node within the path. NOTE: this excludes
* start node 0 and end node 0 (pathNodeNumber=0 corresponds to the
* 2nd node in the final solution for the completed path for the algorithm instance).
* @return
*/
private int getBase10NodeIndex(final long pathNodeNumber, final long path) {
// read bits pathNodeNumber*w to pathNodeNumber*w + w
long sum = 0;
long b = pathNodeNumber*w;
long end = b + w;
int s = 0;
for (b = pathNodeNumber*w, s=0; b < end; ++b, s++) {
if ((path & (1 << b)) != 0) { // test bit b in path
sum += (b << s);
}
}
return (int)sum;
}
/**
* for the pathNodeNumber which is the order number of the node in the path
* (e.g. second node in the path), set the node number to be the base10Node.
* @param base10Node
* @param path
* @param pathNodeNumber number of the node within the path. NOTE: this excludes
* start node 0 and end node 0 (pathNodeNumber=0 corresponds to the
* 2nd node in the final solution for the completed path for the algorithm instance).
* @return
*/
private long setBits(final int base10Node, final long path, final int pathNodeNumber) {
long bitstring = path;
long b = pathNodeNumber*w;
long end = b + w;
int b0;
for (b = pathNodeNumber*w, b0=0; b < end; ++b, b0++) {
if ((base10Node & (1 << b0)) != 0) { // test bit b0 in base10Node
bitstring |= (1 << b); // set bit b in bitstring
}
}
return bitstring;
}
/**
* set the bits in bit-string path which are set in subPath
* @param path
* @param base10Nodes base10 indexes of nodes to set. NOTE: the startNode
* should not be in this array.
* @return
*/
/*private long concatenate(long path, int[] base10Nodes) {
}*/
private void compareToMin(long path, long sum) {
int node1 = getBase10NodeIndex(0, path);
int noden1 = getBase10NodeIndex(dist.length - 2, path);
int ends = dist[startNode][node1] + dist[noden1][startNode];
sum += ends;
if (sum == minCost) {
minPath.add(path);
} else if (sum < minCost) {
minCost = sum;
minPath.clear();
minPath.add(path);
}
}
}
|
package org.javarosa.core.model;
import org.javarosa.core.model.instance.TreeReference;
import java.util.Vector;
/**
* A Form Index is an immutable index into a specific question definition that
* will appear in an interaction with a user.
*
* An index is represented by different levels into hierarchical groups.
*
* Indices can represent both questions and groups.
*
* It is absolutely essential that there be no circularity of reference in
* FormIndex's, IE, no form index's ancestor can be itself.
*
* Datatype Productions:
* FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location)
* Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int)
*
* @author Clayton Sims
*/
public class FormIndex {
private boolean beginningOfForm = false;
private boolean endOfForm = false;
/**
* The index of the questiondef in the current context
*/
private final int localIndex;
/**
* The multiplicity of the current instance of a repeated question or group
*/
private int instanceIndex = -1;
/**
* The next level of this index
*/
private FormIndex nextLevel;
private TreeReference reference;
public static FormIndex createBeginningOfFormIndex() {
FormIndex begin = new FormIndex(-1, null);
begin.beginningOfForm = true;
return begin;
}
public static FormIndex createEndOfFormIndex() {
FormIndex end = new FormIndex(-1, null);
end.endOfForm = true;
return end;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, TreeReference reference) {
this.localIndex = localIndex;
this.reference = reference;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param instanceIndex An integer index expressing the multiplicity
* of the current level
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, int instanceIndex, TreeReference reference) {
this.localIndex = localIndex;
this.instanceIndex = instanceIndex;
this.reference = reference;
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) {
this(localIndex, reference);
this.nextLevel = nextLevel;
}
/**
* Constructs an index which references an element past the level of
* specificity of the current context, founded by the currentLevel
* index.
* (currentLevel, (nextLevel...))
*/
public FormIndex(FormIndex nextLevel, FormIndex currentLevel) {
if (currentLevel == null) {
this.nextLevel = nextLevel.nextLevel;
this.localIndex = nextLevel.localIndex;
this.instanceIndex = nextLevel.instanceIndex;
this.reference = nextLevel.reference;
} else {
this.nextLevel = nextLevel;
this.localIndex = currentLevel.getLocalIndex();
this.instanceIndex = currentLevel.getInstanceIndex();
this.reference = currentLevel.reference;
}
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children, along with the current index of a
* repeated instance.
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param instanceIndex How many times the element referenced has been
* repeated.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) {
this(nextLevel, localIndex, reference);
this.instanceIndex = instanceIndex;
}
public boolean isInForm() {
return !beginningOfForm && !endOfForm;
}
/**
* @return The index of the element in the current context
*/
public int getLocalIndex() {
return localIndex;
}
/**
* @return The multiplicity of the current instance of a repeated question or group
*/
public int getInstanceIndex() {
return instanceIndex;
}
/**
* For the fully qualified element, get the multiplicity of the element's reference
*
* @return The terminal element (fully qualified)'s instance index
*/
public int getElementMultiplicity() {
return getTerminal().instanceIndex;
}
/**
* @return An index into the next level of specificity past the current context. An
* example would be an index into an element that is a child of the element referenced
* by the local index.
*/
public FormIndex getNextLevel() {
return nextLevel;
}
public TreeReference getLocalReference() {
return reference;
}
/**
* @return The TreeReference of the fully qualified element described by this
* FormIndex.
*/
public TreeReference getReference() {
return getTerminal().reference;
}
public FormIndex getTerminal() {
FormIndex walker = this;
while (walker.nextLevel != null) {
walker = walker.nextLevel;
}
return walker;
}
/**
* Identifies whether this is a terminal index, in other words whether this
* index references with more specificity than the current context
*/
public boolean isTerminal() {
return nextLevel == null;
}
public boolean isEndOfFormIndex() {
return endOfForm;
}
public boolean isBeginningOfFormIndex() {
return beginningOfForm;
}
@Override
public int hashCode() {
return (beginningOfForm ? 0 : 31)
^ (endOfForm ? 0 : 31)
^ localIndex
^ instanceIndex
^ (nextLevel == null ? 0 : nextLevel.hashCode());
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FormIndex))
return false;
FormIndex a = this;
FormIndex b = (FormIndex)o;
return (a.compareTo(b) == 0);
}
public int compareTo(Object o) {
if (!(o instanceof FormIndex))
throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex");
FormIndex a = this;
FormIndex b = (FormIndex)o;
if (a.beginningOfForm) {
return (b.beginningOfForm ? 0 : -1);
} else if (a.endOfForm) {
return (b.endOfForm ? 0 : 1);
} else {
//a is in form
if (b.beginningOfForm) {
return 1;
} else if (b.endOfForm) {
return -1;
}
}
if (a.localIndex != b.localIndex) {
return (a.localIndex < b.localIndex ? -1 : 1);
} else if (a.instanceIndex != b.instanceIndex) {
return (a.instanceIndex < b.instanceIndex ? -1 : 1);
} else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) {
return (a.getNextLevel() == null ? -1 : 1);
} else if (a.getNextLevel() != null) {
return a.getNextLevel().compareTo(b.getNextLevel());
} else {
return 0;
}
}
/**
* @return Only the local component of this Form Index.
*/
public FormIndex snip() {
return new FormIndex(localIndex, instanceIndex, reference);
}
/**
* Takes in a form index which is a subset of this index, and returns the
* total difference between them. This is useful for stepping up the level
* of index specificty. If the subIndex is not a valid subIndex of this index,
* null is returned. Since the FormIndex represented by null is always a subset,
* if null is passed in as a subIndex, the full index is returned
*
* For example:
* Indices
* a = 1_0,2,1,3
* b = 1,3
*
* a.diff(b) = 1_0,2
*/
public FormIndex diff(FormIndex subIndex) {
if (subIndex == null) {
return this;
}
if (!isSubIndex(this, subIndex)) {
return null;
}
if (subIndex.equals(this)) {
return null;
}
return new FormIndex(nextLevel.diff(subIndex), this.snip());
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
FormIndex ref = this;
while (ref != null) {
ret.append(ref.getLocalIndex())
.append(ref.getInstanceIndex() == -1 ? "," : "_" + ref.getInstanceIndex() + ",");
ref = ref.nextLevel;
}
return ret.toString().substring(0, ret.lastIndexOf(","));
}
/**
* @return the level of this index relative to the top level of the form
*/
public int getDepth() {
int depth = 0;
FormIndex ref = this;
while (ref != null) {
ref = ref.nextLevel;
depth++;
}
return depth;
}
private static boolean isSubIndex(FormIndex parent, FormIndex child) {
return child.equals(parent) ||
(parent != null && isSubIndex(parent.nextLevel, child));
}
public static boolean isSubElement(FormIndex parent, FormIndex child) {
while (!parent.isTerminal() && !child.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
if (parent.getInstanceIndex() != child.getInstanceIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
//If we've gotten this far, at least one of the two is terminal
if (!parent.isTerminal() && child.isTerminal()) {
//can't be the parent if the child is earlier on
return false;
} else if (parent.getLocalIndex() != child.getLocalIndex()) {
//Either they're at the same level, in which case only
//identical indices should match, or they should have
//the same root
return false;
} else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) {
return false;
}
//Barring all of these cases, it should be true.
return true;
}
/**
* @return Do all the entries of two FormIndexes match except for the last instance index?
*/
public static boolean areSiblings(FormIndex a, FormIndex b) {
if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) {
return true;
}
if (!a.isTerminal() && !b.isTerminal()) {
return a.getLocalIndex() == b.getLocalIndex() &&
areSiblings(a.nextLevel, b.nextLevel);
}
return false;
}
/**
* @return Do all the local indexes in the 'parent' FormIndex match the
* corresponding ones in 'child'?
*/
public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) {
if (parent.getDepth() > child.getDepth()) {
return false;
}
while (!parent.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
return parent.getLocalIndex() == child.getLocalIndex();
}
/**
* Used by Touchforms
*/
@SuppressWarnings("unused")
public void assignRefs(FormDef f) {
FormIndex cur = this;
Vector<Integer> indexes = new Vector<Integer>();
Vector<Integer> multiplicities = new Vector<Integer>();
Vector<IFormElement> elements = new Vector<IFormElement>();
f.collapseIndex(this, indexes, multiplicities, elements);
Vector<Integer> curMults = new Vector<Integer>();
Vector<IFormElement> curElems = new Vector<IFormElement>();
int i = 0;
while (cur != null) {
curMults.addElement(multiplicities.elementAt(i));
curElems.addElement(elements.elementAt(i));
cur.reference = f.getChildInstanceRef(curElems, curMults);
cur = cur.getNextLevel();
i++;
}
}
}
|
package br.net.mirante.singular.server.commons.wicket.view.form;
import br.net.mirante.singular.flow.core.Flow;
import br.net.mirante.singular.flow.core.MTransition;
import br.net.mirante.singular.flow.core.ProcessDefinition;
import br.net.mirante.singular.form.SIComposite;
import br.net.mirante.singular.form.SInstance;
import br.net.mirante.singular.form.STypeComposite;
import br.net.mirante.singular.form.context.SFormConfig;
import br.net.mirante.singular.form.document.RefType;
import br.net.mirante.singular.form.document.SDocumentFactory;
import br.net.mirante.singular.form.persistence.FormKey;
import br.net.mirante.singular.form.service.IFormService;
import br.net.mirante.singular.form.wicket.component.SingularButton;
import br.net.mirante.singular.form.wicket.component.SingularSaveButton;
import br.net.mirante.singular.form.wicket.enums.AnnotationMode;
import br.net.mirante.singular.form.wicket.enums.ViewMode;
import br.net.mirante.singular.persistence.entity.ProcessInstanceEntity;
import br.net.mirante.singular.server.commons.config.ConfigProperties;
import br.net.mirante.singular.server.commons.exception.SingularServerException;
import br.net.mirante.singular.server.commons.flow.metadata.ServerContextMetaData;
import br.net.mirante.singular.server.commons.persistence.entity.form.AbstractPetitionEntity;
import br.net.mirante.singular.server.commons.service.PetitionService;
import br.net.mirante.singular.server.commons.wicket.SingularSession;
import br.net.mirante.singular.server.commons.wicket.view.template.Content;
import br.net.mirante.singular.server.commons.wicket.view.template.Template;
import br.net.mirante.singular.util.wicket.bootstrap.layout.BSContainer;
import br.net.mirante.singular.util.wicket.bootstrap.layout.TemplatePanel;
import br.net.mirante.singular.util.wicket.modal.BSModalBorder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.flow.RedirectToUrlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import static br.net.mirante.singular.util.wicket.util.WicketUtils.$m;
public abstract class AbstractFormPage<T extends AbstractPetitionEntity> extends Template {
protected static final String URL_PATH_ACOMPANHAMENTO = "/singular/peticionamento/acompanhamento";
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFormPage.class);
protected final FormPageConfig config;
protected AbstractFormContent content;
protected final IModel<T> currentModel = $m.ofValue();
protected final IModel<FormKey> formModel = $m.ofValue();
private final Class<T> petitionClass;
@Inject
@Named("formConfigWithDatabase")
private SFormConfig<String> singularFormConfig;
@Inject
protected PetitionService<T> petitionService;
@Inject
private IFormService formService;
public AbstractFormPage(Class<T> petitionClass, FormPageConfig config) {
if (config == null) {
throw new RedirectToUrlException("/singular");
}
this.petitionClass = Objects.requireNonNull(petitionClass);
this.config = Objects.requireNonNull(config);
Objects.requireNonNull(config.getFormType());
}
@Override
protected boolean withMenu() {
return false;
}
@Override
protected void onInitialize() {
T petition;
if (StringUtils.isBlank(config.getFormId())) {
try {
petition = petitionClass.newInstance();
} catch (Exception e) {
throw new SingularServerException("Error creating new petition instance", e);
}
petition.setType(config.getFormType());
if (config.containsProcessDefinition()) {
petition.setProcessType(Flow.getProcessDefinition(config.getProcessDefinition()).getKey());
}
petition.setCreationDate(new Date());
petition.setProcessName(getTypeLabel(config.getFormType()));
onNewPetitionCreation(petition, config);
} else {
petition = petitionService.find(Long.valueOf(config.getFormId()));
}
if (petition.getCodForm() != null) {
FormKey formKey = formService.keyFromObject(petition.getCodForm());
formModel.setObject(formKey);
}
currentModel.setObject(petition);
super.onInitialize();
}
@Override
protected Content getContent(String id) {
if (config.getFormType() == null && config.getFormId() == null) {
String urlServidorSingular = ConfigProperties.get(ConfigProperties.SINGULAR_SERVIDOR_ENDERECO);
throw new RedirectToUrlException(urlServidorSingular);
}
content = new AbstractFormContent(id, config.getFormType(), config.getViewMode(), config.getAnnotationMode()) {
@Override
protected SInstance createInstance(SDocumentFactory documentFactory, RefType refType) {
return AbstractFormPage.this.createInstance(documentFactory, refType);
}
@Override
protected IModel<?> getContentTitleModel() {
return AbstractFormPage.this.getContentTitleModel();
}
@Override
protected IModel<?> getContentSubtitleModel() {
return AbstractFormPage.this.getContentSubtitleModel();
}
@Override
protected void configureCustomButtons(BSContainer<?> buttonContainer, BSContainer<?> modalContainer, ViewMode viewMode, AnnotationMode annotationMode, IModel<? extends SInstance> currentInstance) {
AbstractFormPage.this.configureCustomButtons(buttonContainer, modalContainer, viewMode, annotationMode, currentInstance);
}
@Override
protected BSModalBorder buildConfirmationModal(BSContainer<?> modalContainer, IModel<? extends SInstance> instanceModel) {
return AbstractFormPage.this.buildConfirmationModal(modalContainer, instanceModel);
}
@Override
protected ProcessInstanceEntity getProcessInstance() {
return AbstractFormPage.this.getProcessInstance();
}
// @Override
// protected void setProcessInstance(ProcessInstanceEntity pie) {
// AbstractFormPage.this.setProcessInstance(pie);
@Override
protected void saveForm(IModel<? extends SInstance> currentInstance) {
AbstractFormPage.this.saveForm(currentInstance);
}
@Override
protected IModel<? extends AbstractPetitionEntity> getFormModel() {
return currentModel;
}
@Override
protected boolean hasProcess() {
return AbstractFormPage.this.hasProcess();
}
@Override
protected String getIdentifier() {
return AbstractFormPage.this.getIdentifier();
}
};
return content;
}
protected abstract IModel<?> getContentSubtitleModel();
protected abstract String getIdentifier();
protected void onNewPetitionCreation(T petition, FormPageConfig config) {
}
protected void configureCustomButtons(BSContainer<?> buttonContainer, BSContainer<?> modalContainer, ViewMode viewMode, AnnotationMode annotationMode, IModel<? extends SInstance> currentInstance) {
List<MTransition> trans = petitionService.listCurrentTaskTransitions(config.getFormId());
if (CollectionUtils.isNotEmpty(trans) && (ViewMode.EDITION.equals(viewMode) || AnnotationMode.EDIT.equals(annotationMode))) {
int index = 0;
for (MTransition t : trans) {
if (t.getMetaDataValue(ServerContextMetaData.KEY) != null && t.getMetaDataValue(ServerContextMetaData.KEY).isEnabledOn(SingularSession.get().getServerContext())) {
String btnId = "flow-btn" + index;
buildFlowTransitionButton(
btnId, buttonContainer,
modalContainer, t.getName(),
currentInstance, viewMode);
}
}
} else {
buttonContainer.setVisible(false).setEnabled(false);
}
}
protected final T getUpdatedPetitionFromInstance(IModel<? extends SInstance> currentInstance) {
T petition = currentModel.getObject();
if (currentInstance.getObject() instanceof SIComposite) {
petition.setDescription(createPetitionDescriptionFromForm(currentInstance.getObject()));
}
return petition;
}
protected String createPetitionDescriptionFromForm(SInstance instance) {
return instance.toStringDisplay();
}
protected final SInstance createInstance(SDocumentFactory documentFactory, RefType refType) {
if (formModel.getObject() == null) {
return documentFactory.createInstance(refType);
} else {
return formService.loadFormInstance(formModel.getObject(), refType, documentFactory);
}
}
protected void buildFlowTransitionButton(String buttonId, BSContainer<?> buttonContainer, BSContainer<?> modalContainer, String transitionName, IModel<? extends SInstance> instanceModel, ViewMode viewMode) {
BSModalBorder modal = buildFlowConfirmationModal(buttonId, modalContainer, transitionName, instanceModel, viewMode);
buildFlowButton(buttonId, buttonContainer, transitionName, instanceModel, modal);
}
public void atualizarContentWorklist(AjaxRequestTarget target) {
target.appendJavaScript("Singular.atualizarContentWorklist();");
}
protected BSModalBorder buildConfirmationModal(BSContainer<?> modalContainer, IModel<? extends SInstance> instanceModel) {
TemplatePanel tpModal = modalContainer.newTemplateTag(tt ->
"<div wicket:id='send-modal' class='portlet-body form'>\n"
+ "<wicket:message key=\"label.confirm.message\"/>\n"
+ "</div>\n");
BSModalBorder enviarModal = new BSModalBorder("send-modal", getMessage("label.title.send"));
enviarModal
.addButton(BSModalBorder.ButtonStyle.EMPTY, "label.button.close", new AjaxButton("cancel-btn") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
enviarModal.hide(target);
}
})
.addButton(BSModalBorder.ButtonStyle.DANGER, "label.button.confirm", new SingularSaveButton("confirm-btn", instanceModel) {
protected void onValidationSuccess(AjaxRequestTarget target, Form<?> form, IModel<? extends SInstance> instanceModel) {
AbstractFormPage.this.send(instanceModel);
atualizarContentWorklist(target);
if (getIdentifier() == null) {
addToastrSuccessMessageWorklist("message.send.success", URL_PATH_ACOMPANHAMENTO);
} else {
addToastrSuccessMessageWorklist("message.send.success.identifier", getIdentifier(), URL_PATH_ACOMPANHAMENTO);
}
target.appendJavaScript("; window.close();");
}
@Override
protected void onValidationError(AjaxRequestTarget target, Form<?> form, IModel<? extends SInstance> instanceModel) {
enviarModal.hide(target);
target.add(form);
addToastrErrorMessage("message.send.error");
}
});
tpModal.add(enviarModal);
return enviarModal;
}
protected void saveForm(IModel<? extends SInstance> currentInstance) {
onBeforeSave(currentInstance);
FormKey key = petitionService.saveOrUpdate(getUpdatedPetitionFromInstance(currentInstance),
currentInstance.getObject());
formModel.setObject(key);
}
protected void onBeforeSend(IModel<? extends SInstance> currentInstance) {
configureLazyFlowIfNeeded(currentInstance, currentModel.getObject(), config);
}
protected void onBeforeSave(IModel<? extends SInstance> currentInstance) {
configureLazyFlowIfNeeded(currentInstance, currentModel.getObject(), config);
}
protected void configureLazyFlowIfNeeded(IModel<? extends SInstance> currentInstance, T petition, FormPageConfig cfg){
if (petition.getProcessType() == null && cfg.isWithLazyProcessResolver()) {
final Class<? extends ProcessDefinition> dc = cfg.getLazyFlowDefinitionResolver().resolve(cfg, (SIComposite) currentInstance.getObject());
petition.setProcessType(Flow.getProcessDefinition(dc).getKey());
}
}
protected void send(IModel<? extends SInstance> currentInstance) {
onBeforeSend(currentInstance);
FormKey key = petitionService.send(getUpdatedPetitionFromInstance(currentInstance), currentInstance.getObject());
formModel.setObject(key);
}
protected void executeTransition(String transitionName, IModel<? extends SInstance> currentInstance) {
FormKey key = petitionService.saveAndExecuteTransition(transitionName, currentModel.getObject(),
currentInstance.getObject());
formModel.setObject(key);
}
protected boolean hasProcess() {
return currentModel.getObject().getProcessInstanceEntity() != null;
}
protected ProcessInstanceEntity getProcessInstance() {
return currentModel.getObject().getProcessInstanceEntity();
}
protected void setProcessInstance(ProcessInstanceEntity pie) {
currentModel.getObject().setProcessInstanceEntity(pie);
}
protected IModel<?> getContentTitleModel() {
return new ResourceModel("label.form.content.title");
}
private void buildFlowButton(String buttonId, BSContainer<?> buttonContainer, String transitionName, IModel<? extends SInstance> instanceModel, BSModalBorder confirmarAcaoFlowModal) {
TemplatePanel tp = buttonContainer
.newTemplateTag(tt -> "<button type='submit' class='btn' wicket:id='" + buttonId +
"'>\n <span wicket:id='flowButtonLabel' /> \n</button>\n");
SingularButton singularButton = new SingularButton(buttonId, content.getFormInstance()) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
confirmarAcaoFlowModal.show(target);
}
};
singularButton.add(new Label("flowButtonLabel", transitionName).setRenderBodyOnly(true));
tp.add(singularButton);
}
private BSModalBorder buildFlowConfirmationModal(String buttonId, BSContainer<?> modalContainer, String transitionName, IModel<? extends SInstance> instanceModel, ViewMode viewMode) {
TemplatePanel tpModal = modalContainer.newTemplateTag(
tt -> "<div wicket:id='flow-modal" + buttonId + "' class='portlet-body form'>\n" +
"<div wicket:id='flow-msg'/>\n" + "</div>\n");
BSModalBorder confirmarAcaoFlowModal = new BSModalBorder("flow-modal" + buttonId, getMessage("label.button.confirm"));
tpModal.add(confirmarAcaoFlowModal);
confirmarAcaoFlowModal
.addButton(BSModalBorder.ButtonStyle.EMPTY, "label.button.cancel", new AjaxButton("cancel-btn") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
confirmarAcaoFlowModal.hide(target);
}
});
confirmarAcaoFlowModal.addButton(BSModalBorder.ButtonStyle.DANGER, "label.button.confirm",
new SingularSaveButton("confirm-btn", instanceModel, ViewMode.EDITION.equals(viewMode)) {
protected void onValidationSuccess(AjaxRequestTarget target, Form<?> form,
IModel<? extends SInstance> instanceModel) {
try {
AbstractFormPage.this.executeTransition(transitionName, instanceModel);
target.appendJavaScript("Singular.atualizarContentWorklist();");
addToastrSuccessMessageWorklist("message.action.success", transitionName);
target.appendJavaScript("window.close();");
} catch (Exception e) { // org.hibernate.StaleObjectStateException
LOGGER.error("Erro ao salvar o XML", e);
addToastrErrorMessage("message.save.concurrent_error");
}
}
@Override
protected void onValidationError(AjaxRequestTarget target, Form<?> form,
IModel<? extends SInstance> instanceModel) {
confirmarAcaoFlowModal.hide(target);
target.add(form);
}
});
confirmarAcaoFlowModal.add(new Label("flow-msg", String.format("Tem certeza que deseja %s ?", transitionName)));
return confirmarAcaoFlowModal;
}
private String getTypeLabel(String typeName) {
STypeComposite<?> type = (STypeComposite<?>) singularFormConfig
.getTypeLoader().loadType(typeName).orElseThrow(() -> new SingularServerException("Não foi possivel carregar o tipo"));
return type.asAtr().getLabel();
}
}
|
package bio.terra.stairway;
import static bio.terra.stairway.FlightStatus.READY;
import static bio.terra.stairway.FlightStatus.WAITING;
import bio.terra.stairway.exception.DatabaseOperationException;
import bio.terra.stairway.exception.RetryException;
import bio.terra.stairway.exception.StairwayExecutionException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Flight implements Runnable {
static class StepRetry {
private Step step;
private RetryRule retryRule;
StepRetry(Step step, RetryRule retryRule) {
this.step = step;
this.retryRule = retryRule;
}
}
private static Logger logger = LoggerFactory.getLogger(Flight.class);
private List<StepRetry> steps;
private FlightDao flightDao;
private FlightContext flightContext;
private Object applicationContext;
public Flight(FlightMap inputParameters, Object applicationContext) {
flightContext = new FlightContext(inputParameters, this.getClass().getName());
this.applicationContext = applicationContext;
steps = new LinkedList<>();
}
public HookWrapper wrapper() {
return new HookWrapper(flightContext.getStairway());
}
public FlightContext context() {
return flightContext;
}
public Object getApplicationContext() {
return applicationContext;
}
public void setFlightContext(FlightContext flightContext) {
this.flightContext = flightContext;
}
// Used by subclasses to build the step list with default no-retry rule
protected void addStep(Step step) {
steps.add(new StepRetry(step, RetryRuleNone.getRetryRuleNone()));
}
// Used by subclasses to build the step list with a retry rule
protected void addStep(Step step, RetryRule retryRule) {
steps.add(new StepRetry(step, retryRule));
}
/**
* Execute the flight starting wherever the flight context says we are. We may be headed either
* direction.
*/
public void run() {
wrapper().startFlight(flightContext);
try {
// We use flightDao all over the place, so we put it in a private to avoid passing it through
// all of
// the method argument lists.
flightDao = context().getStairway().getFlightDao();
if (context().getStairway().isQuietingDown()) {
logger.info("Disowning flight starting during quietDown: " + context().getFlightId());
flightExit(READY);
return;
}
logger.debug("Executing: " + context().toString());
FlightStatus flightStatus = fly();
flightExit(flightStatus);
wrapper().endFlight(flightContext);
} catch (InterruptedException ex) {
// Shutdown - try disowning the flight
logger.warn("Flight interrupted: " + context().getFlightId());
flightExit(READY);
} catch (Exception ex) {
logger.error("Flight failed with exception", ex);
}
}
private void flightExit(FlightStatus flightStatus) {
try {
context().setFlightStatus(flightStatus);
context().getStairway().exitFlight(context());
} catch (Exception ex) {
logger.error("Failed to exit flight cleanly", ex);
}
}
/**
* Perform the flight, until we do all steps, undo to the beginning, or declare a dismal failure.
*/
private FlightStatus fly() throws InterruptedException {
try {
// Part 1 - running forward (doing). We either succeed or we record the failure and
// fall through to running backward (undoing)
if (context().isDoing()) {
StepResult doResult = runSteps();
if (doResult.isSuccess()) {
if (doResult.getStepStatus() == StepStatus.STEP_RESULT_STOP) {
return READY;
}
if (doResult.getStepStatus() == StepStatus.STEP_RESULT_WAIT) {
return WAITING;
}
return FlightStatus.SUCCESS;
}
// Remember the failure from the do; that is what we want to return
// after undo completes
context().setResult(doResult);
context().setDirection(Direction.SWITCH);
// Record the step failure and direction change in the database
flightDao.step(context());
}
// Part 2 - running backwards. We either succeed and return the original failure
// status or we have a 'dismal failure'
StepResult undoResult = runSteps();
if (undoResult.isSuccess()) {
// Return the error from the doResult - that is why we failed
return FlightStatus.ERROR;
}
// Part 3 - dismal failure
// Record the undo failure
flightDao.step(context());
// Dismal failure - undo failed!
context().setResult(undoResult);
} catch (Exception ex) {
logger.error("Unhandled flight exception", ex);
context().setResult(new StepResult(StepStatus.STEP_RESULT_FAILURE_FATAL, ex));
}
return FlightStatus.FATAL;
}
/**
* run the steps in sequence, either forward or backward, until either we complete successfully or
* we encounter an error. Note that this only records the step in the database if there is
* success. Otherwise, it returns out and lets the outer logic setup the failure state before
* recording it into the database.
*
* @return StepResult recording the success or failure of the most recent step
* @throws InterruptedException
*/
private StepResult runSteps()
throws InterruptedException, StairwayExecutionException, DatabaseOperationException {
// Initialize with current result, in case we are all done already
StepResult result = context().getResult();
while (context().haveStepToDo(steps.size())) {
result = stepWithRetry();
// Exit if we hit a failure (result shows failed)
if (!result.isSuccess()) {
return result;
}
// If we SWITCHed from do to undo, make the direction UNDO
if (context().getDirection() == Direction.SWITCH) {
context().setDirection(Direction.UNDO);
}
switch (result.getStepStatus()) {
case STEP_RESULT_SUCCESS:
// Finished a step; run the next one
context().setRerun(false);
flightDao.step(context());
context().nextStepIndex();
break;
case STEP_RESULT_RERUN:
// Rerun the same step
context().setRerun(true);
flightDao.step(context());
break;
case STEP_RESULT_WAIT:
// Finished a step; yield execution
context().setRerun(false);
flightDao.step(context());
return result;
case STEP_RESULT_STOP:
// Stop executing - leave rerun setting as is; we'll need to pick up where we left off
flightDao.step(context());
return result;
case STEP_RESULT_FAILURE_RETRY:
case STEP_RESULT_FAILURE_FATAL:
default:
throw new StairwayExecutionException("Unexpected step status: " + result.getStepStatus());
}
}
return result;
}
private StepResult stepWithRetry() throws InterruptedException, StairwayExecutionException {
logger.debug("Executing " + context().prettyStepState());
StepRetry currentStep = getCurrentStep();
currentStep.retryRule.initialize();
StepResult result;
// Retry loop
do {
try {
// Do or undo based on direction we are headed
wrapper().startStep(flightContext);
if (context().isDoing()) {
result = currentStep.step.doStep(context());
} else {
result = currentStep.step.undoStep(context());
}
wrapper().endStep(flightContext);
} catch (InterruptedException ex) {
// Interrupted exception - we assume this means that the thread pool is shutting down and
// forcibly
// stopping all threads. We treat this as a STOP.
result = new StepResult(StepStatus.STEP_RESULT_STOP);
} catch (Exception ex) {
// The purpose of this catch is to relieve steps of implementing their own repetitive
// try-catch
// simply to turn exceptions into StepResults.
logger.info("Caught exception: (" + ex.toString() + ") " + context().prettyStepState());
StepStatus stepStatus =
(ex instanceof RetryException)
? StepStatus.STEP_RESULT_FAILURE_RETRY
: StepStatus.STEP_RESULT_FAILURE_FATAL;
result = new StepResult(stepStatus, ex);
}
switch (result.getStepStatus()) {
case STEP_RESULT_SUCCESS:
case STEP_RESULT_RERUN:
if (context().getStairway().isQuietingDown()) {
// If we are quieting down, we force a stop
result = new StepResult(StepStatus.STEP_RESULT_STOP, null);
}
return result;
case STEP_RESULT_FAILURE_FATAL:
case STEP_RESULT_STOP:
case STEP_RESULT_WAIT:
return result;
case STEP_RESULT_FAILURE_RETRY:
if (context().getStairway().isQuietingDown()) {
logger.info("Quieting down - not retrying: " + context().prettyStepState());
return result;
}
logger.info("Retrying: " + context().prettyStepState());
break;
default:
// Invalid step status returned from a step!
throw new StairwayExecutionException(
"Invalid step status returned: "
+ result.getStepStatus()
+ context().prettyStepState());
}
} while (currentStep.retryRule
.retrySleep()); // retry rule decides if we should try again or not
return result;
}
private StepRetry getCurrentStep() throws StairwayExecutionException {
int stepIndex = context().getStepIndex();
if (stepIndex < 0 || stepIndex >= steps.size()) {
throw new StairwayExecutionException("Invalid step index: " + stepIndex);
}
return steps.get(stepIndex);
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("steps", steps)
.append("flightContext", flightContext)
.toString();
}
}
|
package org.opensingular.server.commons.wicket.view.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.opensingular.server.commons.exception.SingularServerException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
public class ParameterHttpSerializer {
private static final Charset ENCODING = StandardCharsets.UTF_8;
public static String encode(LinkedHashMap<String, String> params) {
try {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> e : params.entrySet()) {
if (sb.length() > 0) {
sb.append('&');
}
if (e.getValue() != null) {
sb.append(String.format("%s=%s", URLEncoder.encode(e.getKey(), ENCODING.name()), URLEncoder.encode(e.getValue(), ENCODING.name())));
} else {
sb.append(String.format("%s", URLEncoder.encode(e.getKey(), ENCODING.name())));
}
}
return sb.toString();
} catch (Exception e) {
throw SingularServerException.rethrow(e.getMessage(), e);
}
}
public static LinkedHashMap<String, String> decode(String query) {
try {
if (StringUtils.isEmpty(query)){
return new LinkedHashMap<>();
}
String cleanQueryString = clearQueryString(query);
LinkedHashMap<String, String> decoded = new LinkedHashMap<>();
String[] params = cleanQueryString.split("&");
for (String paramString : params) {
Pair<String, String> param = parseParamValue(paramString);
decoded.put(param.getKey(), param.getValue());
}
return decoded;
} catch (Exception e) {
throw SingularServerException.rethrow(e.getMessage(), e);
}
}
private static Pair<String, String> parseParamValue(String paramString) throws UnsupportedEncodingException {
String[] param = paramString.split("=");
String key = URLDecoder.decode(param[0], ENCODING.name());
String value = null;
if (param.length > 1) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < param.length; i++) {
sb.append(param[i]);
}
value = URLDecoder.decode(sb.toString(), ENCODING.name());
}
return Pair.of(key, value);
}
private static String clearQueryString(String queryString) {
String result = queryString;
//Remove url fragment - usually anchor links
if (queryString.contains("
result = result.substring(0, result.indexOf('
}
return result;
}
public static String encodeAndCompress(LinkedHashMap<String, String> params) {
try {
return compress(encode(params));
} catch (Exception e) {
throw SingularServerException.rethrow(e.getMessage(), e);
}
}
public static Map<String, String> decodeCompressed(String query) {
try {
return decode(decompress(query));
} catch (Exception e) {
throw SingularServerException.rethrow(e.getMessage(), e);
}
}
private static String compress(String s) throws UnsupportedEncodingException {
return URLEncoder.encode(
new String(
Base64.getUrlEncoder().encode(
compressAlgorithm(s.getBytes(ENCODING))
), ENCODING
),
ENCODING.name());
}
private static String decompress(String s) throws UnsupportedEncodingException {
return new String(
decompressAlgorithm(
Base64.getUrlDecoder().decode(
URLDecoder.decode(s, ENCODING.name())
.getBytes(ENCODING)
)
),
ENCODING);
}
private static byte[] compressAlgorithm(byte[] bytes) {
return bytes;
}
private static byte[] decompressAlgorithm(byte[] bytes) {
return bytes;
}
}
|
package biz.blha303.foobar;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.entity.Player;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.Command;
public class Foobar extends JavaPlugin {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
sender.sendMessage("[Foobar] foo");
} else if (sender instanceof ConsoleCommandSender) {
sender.sendMessage("[Foobar] bar");
} else {
sender.sendMessage("[Foobar] foobar");
}
return true;
}
}
|
package br.senac.tads;
/**
*
* @author marcelo.bdamaceno
*/
public class Exercicio01 {
public static void main(String[] args) {
System.out.println("Teste");
}
public String Teste(){
System.out.println("Teste2");
return null;
}
public String Teste2(){
return null;
}
}
|
package cn.cerc.mis.ado;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cerc.db.core.DataRow;
import cn.cerc.db.core.DataSet;
import cn.cerc.db.core.EntityImpl;
import cn.cerc.db.core.IHandle;
import cn.cerc.db.core.SqlText;
import cn.cerc.db.core.SqlWhere;
public class EntityOne<T extends EntityImpl> extends EntityHome<T> {
private static final Logger log = LoggerFactory.getLogger(EntityOne.class);
public static <T extends EntityImpl> EntityOne<T> open(IHandle handle, Class<T> clazz, String... values) {
SqlText sql = SqlWhere.create(handle, clazz, values).build();
return new EntityOne<T>(handle, clazz, sql, false, false);
}
public static <T extends EntityImpl> EntityOne<T> open(IHandle handle, Class<T> clazz, SqlText sqlText) {
return new EntityOne<T>(handle, clazz, sqlText, false, false);
}
public static <T extends EntityImpl> EntityOne<T> open(IHandle handle, Class<T> clazz,
Consumer<SqlWhere> consumer) {
Objects.requireNonNull(consumer);
SqlWhere where = SqlWhere.create(handle, clazz);
consumer.accept(where);
return new EntityOne<T>(handle, clazz, where.build(), false, false);
}
public static <T extends EntityImpl> EntityOne<T> open(IHandle handle, Class<T> clazz, long uid) {
SqlText sql = SqlWhere.create(clazz).eq("UID_", uid).build();
return new EntityOne<T>(handle, clazz, sql, false, false);
}
public EntityOne(IHandle handle, Class<T> clazz, SqlText sql, boolean useSlaveServer, boolean writeCacheAtOpen) {
super(handle, clazz, sql, useSlaveServer, writeCacheAtOpen);
if (query.size() > 1) {
log.error("There are too many records. Entity {} sqlText {}", clazz.getName(), sql.text());
throw new RuntimeException("There are too many records.");
}
}
@Override
public <X extends Throwable> EntityOne<T> isEmptyThrow(Supplier<? extends X> exceptionSupplier) throws X {
super.isEmptyThrow(exceptionSupplier);
return this;
}
@Override
public <X extends Throwable> EntityOne<T> isPresentThrow(Supplier<? extends X> exceptionSupplier) throws X {
super.isPresentThrow(exceptionSupplier);
return this;
}
public T get() {
if (query.size() == 0)
return null;
T entity = query.records().get(0).asEntity(clazz);
entity.setEntityHome(this);
return entity;
}
// entity
public <X extends Throwable> T getElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (query.size() == 0)
throw exceptionSupplier.get();
return query.records().get(0).asEntity(clazz);
}
// update.orElseInsert: entity
@Override
public EntityOne<T> update(Consumer<T> action) {
super.update(action);
return this;
}
// loadOne.orElseInsert:
public T orElseInsert(Consumer<T> action) {
if (this.isEmpty())
return super.insert(action);
else
return this.get();
}
public T delete() {
if (query.size() == 0)
return null;
query.setReadonly(false);
T entity = null;
try {
entity = query.current().asEntity(clazz);
query.delete();
} finally {
query.setReadonly(true);
}
return entity;
}
public DataRow current() {
return query.current();
}
public DataSet dataSet() {
return query;
}
}
|
package org.opendaylight.ovsdb.southbound.transactions.md;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.ovsdb.lib.message.TableUpdates;
import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
import org.opendaylight.ovsdb.southbound.SouthboundMapper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
public class OvsdbNodeRemoveCommand extends AbstractTransactionCommand {
private static final Logger LOG = LoggerFactory.getLogger(OvsdbNodeRemoveCommand.class);
public OvsdbNodeRemoveCommand(ConnectionInfo key,TableUpdates updates,DatabaseSchema dbSchema) {
super(key,updates,dbSchema);
}
@Override
public void execute(ReadWriteTransaction transaction) {
CheckedFuture<Optional<Node>, ReadFailedException> ovsdbNodeFuture = transaction.read(
LogicalDatastoreType.OPERATIONAL, SouthboundMapper.createInstanceIdentifier(getConnectionInfo()));
Optional<Node> ovsdbNodeOptional;
try {
ovsdbNodeOptional = ovsdbNodeFuture.get();
if (ovsdbNodeOptional.isPresent()) {
Node ovsdbNode = ovsdbNodeOptional.get();
OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
if (ovsdbNodeAugmentation != null && ovsdbNodeAugmentation.getManagedNodeEntry() != null) {
for (ManagedNodeEntry managedNode : ovsdbNodeAugmentation.getManagedNodeEntry()) {
transaction.delete(LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
}
} else {
LOG.warn("{} had no OvsdbNodeAugmentation", ovsdbNode);
}
transaction.delete(LogicalDatastoreType.OPERATIONAL,
SouthboundMapper.createInstanceIdentifier(getConnectionInfo()));
}
} catch (Exception e) {
LOG.warn("Failure to delete ovsdbNode {}",e);
}
}
}
|
package com.cisco.trex;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cisco.trex.stateless.TRexCommand;
import com.cisco.trex.stateless.TRexTransport;
import com.cisco.trex.stateless.exception.TRexConnectionException;
import com.cisco.trex.stateless.model.L2Configuration;
import com.cisco.trex.stateless.model.Port;
import com.cisco.trex.stateless.model.PortStatus;
import com.cisco.trex.stateless.model.RPCResponse;
import com.cisco.trex.stateless.model.StubResult;
import com.cisco.trex.stateless.model.SystemInfo;
import com.cisco.trex.stateless.model.TRexClientResult;
import com.cisco.trex.stateless.model.capture.CaptureInfo;
import com.cisco.trex.stateless.model.capture.CaptureMonitor;
import com.cisco.trex.stateless.model.capture.CaptureMonitorStop;
import com.cisco.trex.stateless.model.capture.CapturedPackets;
import com.cisco.trex.stateless.model.stats.ExtendedPortStatistics;
import com.cisco.trex.stateless.model.stats.PortStatistics;
import com.cisco.trex.stateless.model.stats.XstatsNames;
import com.cisco.trex.stateless.util.DoubleAsIntDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
/**
* Base class for stateful and stateless classes
*/
public abstract class ClientBase {
protected static final Logger LOGGER = LoggerFactory.getLogger(ClientBase.class);
protected static final String JSON_RPC_VERSION = "2.0";
protected static final Gson GSON = buildGson();
protected String host;
protected String port;
protected String userName = "";
protected final Map<Integer, String> portHandlers = new HashMap<>();
protected final Set<String> supportedCmds = new HashSet<>();
protected final Random randomizer = new Random();
protected TRexTransport transport;
protected String apiH;
protected String masterHandler;
private static Gson buildGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<Map<String, Object>>() {}.getType(),
new DoubleAsIntDeserializer());
return gsonBuilder.create();
}
private String buildRequest(String methodName, Map<String, Object> payload) {
if (payload == null) {
payload = new HashMap<>();
}
Map<String, Object> parameters = new HashMap<>();
parameters.put("id", "aggogxls");
parameters.put("jsonrpc", JSON_RPC_VERSION);
parameters.put("method", methodName);
payload.put("api_h", apiH);
parameters.put("params", payload);
return GSON.toJson(parameters);
}
private String call(String json) {
return this.transport.sendJson(json);
}
private List<TRexCommand> buildRemoveCaptureCommand(List<Integer> capture_ids) {
return capture_ids.stream()
.map(captureId -> {
Map<String, Object> parameters = new HashMap<>();
parameters.put("command", "remove");
parameters.put("capture_id", captureId);
return buildCommand("capture", parameters);
})
.collect(Collectors.toList());
}
private class SystemInfoResponse {
private String id;
private String jsonrpc;
private SystemInfo result;
public SystemInfo getResult() {
return result;
}
}
/**
* Get Ports
*
* @return port list
*/
public List<Port> getPorts() {
LOGGER.info("Getting ports list.");
List<Port> ports = getSystemInfo().getPorts();
ports.stream().forEach(port -> {
TRexClientResult<PortStatus> result = getPortStatus(port.getIndex());
if (result.isFailed()) {
return;
}
PortStatus status = result.get();
L2Configuration l2config = status.getAttr().getLayerConiguration().getL2Configuration();
port.hw_mac = l2config.getSrc();
port.dst_macaddr = l2config.getDst();
});
return ports;
}
/**
* @param portIndex
* @return Port
*/
public Port getPortByIndex(int portIndex) {
List<Port> ports = getPorts();
if (ports.stream().noneMatch(p -> p.getIndex() == portIndex)) {
LOGGER.error(String.format("Port with index %s was not found. Returning empty port", portIndex));
}
return getPorts().stream()
.filter(p -> p.getIndex() == portIndex)
.findFirst()
.orElse(new Port());
}
/**
* call Method
*
* @param methodName
* @param payload
* @return result
*/
public String callMethod(String methodName, Map<String, Object> payload) {
LOGGER.info("Call {} method.", methodName);
if (!this.supportedCmds.contains(methodName)) {
LOGGER.error("Unsupported {} method.", methodName);
throw new UnsupportedOperationException();
}
String req = this.buildRequest(methodName, payload);
return call(req);
}
/**
* call Methods
*
* @param commands
* @return results
*/
public TRexClientResult<List<RPCResponse>> callMethods(List<TRexCommand> commands) {
TRexClientResult<List<RPCResponse>> result = new TRexClientResult<>();
try {
RPCResponse[] rpcResponses = transport.sendCommands(commands);
result.set(Arrays.asList(rpcResponses));
} catch (IOException e) {
String msg = "Unable to send RPC Batch";
result.setError(msg);
LOGGER.error(msg, e);
}
return result;
}
/**
* call method
*
* @param <T>
* @param methodName
* @param parameters
* @param responseType
* @return result
*/
public <T> TRexClientResult<T> callMethod(String methodName, Map<String, Object> parameters,
Class<T> responseType) {
LOGGER.info("Call {} method.", methodName);
if (!this.supportedCmds.contains(methodName)) {
LOGGER.error("Unsupported {} method.", methodName);
throw new UnsupportedOperationException();
}
TRexClientResult<T> result = new TRexClientResult<>();
try {
RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters));
if (!response.isFailed()) {
T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType);
result.set(resutlObject);
} else {
result.setError(response.getError().getMessage() + " " + response.getError().getSpecificErr());
}
return result;
} catch (IOException var7) {
String errorMsg = "Error occurred during processing '" + methodName + "' method with params: "
+ parameters.toString();
LOGGER.error(errorMsg, var7);
result.setError(errorMsg);
return result;
}
}
/**
* Build Command
*
* @param methodName
* @param parameters
* @return TRexCommand
*/
public TRexCommand buildCommand(String methodName, Map<String, Object> parameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put("api_h", apiH);
Map<String, Object> payload = new HashMap<>();
int cmdId = randomizer.nextInt() & Integer.MAX_VALUE; //get a positive random value
payload.put("id", cmdId);
payload.put("jsonrpc", JSON_RPC_VERSION);
payload.put("method", methodName);
if (!StringUtils.isEmpty(this.masterHandler)) {
payload.put("handler", this.masterHandler);
}
payload.put("params", parameters);
return new TRexCommand(cmdId, methodName, payload);
}
/**
* Disconnect from trex
*/
public void disconnect() {
if (transport != null) {
transport.close();
transport = null;
LOGGER.info("Disconnected");
} else {
LOGGER.info("Already disconnected");
}
}
/**
* Reconnect
*
* @throws TRexConnectionException
*/
public void reconnect() throws TRexConnectionException {
disconnect();
connect();
}
/**
* connect with default timeout 3000 mSec
*
* @throws TRexConnectionException
*/
public final void connect() throws TRexConnectionException {
connect(3000);
}
/**
* connect with timeout
*
* @param timeout
* @throws TRexConnectionException
*/
public void connect(int timeout) throws TRexConnectionException {
transport = new TRexTransport(this.host, this.port, timeout);
serverAPISync();
supportedCmds.addAll(getSupportedCommands());
}
/**
* Get Supported Commands
*
* @return Supported Commands
*/
public List<String> getSupportedCommands() {
Map<String, Object> payload = new HashMap<>();
payload.put("api_h", apiH);
String json = callMethod("get_supported_cmds", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray cmds = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray();
return StreamSupport.stream(cmds.spliterator(), false)
.map(JsonElement::getAsString)
.collect(Collectors.toList());
}
/**
* Get Port Status
*
* @param portIdx
* @return PortStatus
*/
public TRexClientResult<PortStatus> getPortStatus(int portIdx) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIdx);
parameters.put("block", false);
return callMethod("get_port_status", parameters, PortStatus.class);
}
/**
* @param portIndex
* @return PortStatistics
*/
public PortStatistics getPortStatistics(int portIndex) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIndex);
return callMethod("get_port_stats", parameters, PortStatistics.class).get();
}
/**
* @param portIndex
* @return ExtendedPortStatistics
*/
public ExtendedPortStatistics getExtendedPortStatistics(int portIndex) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIndex);
return callMethod("get_port_xstats_values", parameters, ExtendedPortStatistics.class).get()
.setValueNames(getPortStatNames(portIndex));
}
private XstatsNames getPortStatNames(int portIndex) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIndex);
return callMethod("get_port_xstats_names", parameters, XstatsNames.class).get();
}
/**
* Get Active Captures
*
* @return CaptureInfo
*/
public TRexClientResult<CaptureInfo[]> getActiveCaptures() {
Map<String, Object> payload = new HashMap<>();
payload.put("command", "status");
return callMethod("capture", payload, CaptureInfo[].class);
}
/**
* Start Capture Monitor
*
* @param rxPorts
* @param txPorts
* @param filter
* @return CaptureMonitor
*/
public TRexClientResult<CaptureMonitor> captureMonitorStart(
List<Integer> rxPorts,
List<Integer> txPorts,
String filter) {
return startCapture(rxPorts, txPorts, "cyclic", 100, filter);
}
/**
* Start Capture Recorder
*
* @param rxPorts
* @param txPorts
* @param filter
* @param limit
* @return CaptureMonitor
*/
public TRexClientResult<CaptureMonitor> captureRecorderStart(
List<Integer> rxPorts,
List<Integer> txPorts,
String filter,
int limit) {
return startCapture(rxPorts, txPorts, "fixed", limit, filter);
}
/**
* Start Capture
*
* @param rxPorts
* @param txPorts
* @param mode
* @param limit
* @param filter
* @return CaptureMonitor
*/
public TRexClientResult<CaptureMonitor> startCapture(
List<Integer> rxPorts,
List<Integer> txPorts,
String mode,
int limit,
String filter) {
Map<String, Object> payload = new HashMap<>();
payload.put("command", "start");
payload.put("limit", limit);
payload.put("mode", mode);
payload.put("rx", rxPorts);
payload.put("tx", txPorts);
payload.put("filter", filter);
return callMethod("capture", payload, CaptureMonitor.class);
}
/**
* Remove All Captures
*
* @return response
*/
public TRexClientResult<List<RPCResponse>> removeAllCaptures() {
TRexClientResult<CaptureInfo[]> activeCaptures = getActiveCaptures();
List<Integer> captureIds = Arrays.stream(activeCaptures.get()).map(CaptureInfo::getId)
.collect(Collectors.toList());
List<TRexCommand> commands = buildRemoveCaptureCommand(captureIds);
return callMethods(commands);
}
/**
* Stop Capture Monitor
*
* @param captureId
* @return CaptureMonitorStop
*/
public TRexClientResult<CaptureMonitorStop> captureMonitorStop(int captureId) {
Map<String, Object> payload = new HashMap<>();
payload.put("command", "stop");
payload.put("capture_id", captureId);
return callMethod("capture", payload, CaptureMonitorStop.class);
}
/**
* Remove Capture Monitor
*
* @param captureId
* @return successfully removed
*/
public boolean captureMonitorRemove(int captureId) {
List<TRexCommand> commands = buildRemoveCaptureCommand(Collections.singletonList(captureId));
TRexClientResult<List<RPCResponse>> result = callMethods(commands);
if (result.isFailed()) {
LOGGER.error("Unable to remove recorder due to: {}", result.getError());
return false;
}
Optional<RPCResponse> failed = result.get().stream().filter(RPCResponse::isFailed).findFirst();
return !failed.isPresent();
}
/**
* Fetch Captured Packets
*
* @param captureId
* @param chunkSize
* @return CapturedPackets
*/
public TRexClientResult<CapturedPackets> captureFetchPkts(int captureId, int chunkSize) {
Map<String, Object> payload = new HashMap<>();
payload.put("command", "fetch");
payload.put("capture_id", captureId);
payload.put("pkt_limit", chunkSize);
return callMethod("capture", payload, CapturedPackets.class);
}
/**
* Set Vlan
*
* @param portIdx
* @param vlanIds
* @return StubResult
*/
public TRexClientResult<StubResult> setVlan(int portIdx, List<Integer> vlanIds) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIdx);
parameters.put("vlan", vlanIds);
parameters.put("block", false);
return callMethod("set_vlan", parameters, StubResult.class);
}
/**
* Get System Information
*
* @return SystemInfo
*/
public SystemInfo getSystemInfo() {
String json = callMethod("get_system_info", null);
SystemInfoResponse response = GSON.fromJson(json, SystemInfoResponse[].class)[0];
return response.getResult();
}
protected abstract void serverAPISync() throws TRexConnectionException;
/**
* Acquire Port to be able to apply configuration to it
*
* @param port
* @param force
* @return PortStatus
*/
public abstract PortStatus acquirePort(int port, Boolean force);
/**
* Release Port
*
* @param portIndex
* @return PortStatus
*/
public abstract PortStatus releasePort(int portIndex);
}
|
package com.frankhpe.gittest;
public class Main {
public static void main(String [] args) {
System.out.println("Hello 4");
}
}
|
package org.openntf.domino.config;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import org.openntf.domino.Database;
import org.openntf.domino.Document;
import org.openntf.domino.thread.DominoExecutor;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xots.Tasklet;
public class XotsConfiguration extends ConfigurationObject {
private String apiPath_;
private String taskletName_;
private boolean isDatabase_;
private String bundle_;
public XotsConfiguration(final String path, final String taskletName, final boolean isDatabase) {
if (isDatabase) {
bundle_ = "";
if (path.indexOf("!!") < 0) {
apiPath_ = Factory.getLocalServerName() + "!!" + path;
} else {
apiPath_ = path;
}
} else {
bundle_ = path;
apiPath_ = Factory.getLocalServerName() + "!!bundle:" + path;
}
taskletName_ = taskletName;
isDatabase_ = isDatabase;
}
@Override
protected Object[] schema() {
// @formatter:off
return new Object[] {
"Schedules", String[].class,
"SchedulesDefault", String[].class,
"OnAllServers", Boolean.class,
"RunOnServer", String[].class,
"TaskletName", String.class,
"ApiPaths", String[].class,
"Enabled", Boolean.class,
"Location", String.class,
"ReplicaId", String.class,
"Bundle", String.class,
"ApplicationName", String.class
};
// @formatter:on
}
public String[] getSchedules() {
return get("Schedules");
}
public String[] getSchedulesDefault() {
return get("SchedulesDefault");
}
public void setSchedulesDefault(final String[] schedules) {
if (get("Schedules") == null) {
put("Schedules", schedules);
}
put("SchedulesDefault", schedules);
}
public Boolean isOnAllServers() {
return get("OnAllServers");
}
public void setOnAllServers(final boolean onAllServers) {
if (onAllServers) {
put("RunOnServer", "*");// not changeable
} else {
if (get("RunOnServer") == null) {
put("RunOnServer", "$CLUSTER1");
}
}
put("OnAllServers", onAllServers);
}
public String getTaskletName() {
return get("TaskletName");
}
public String[] getApiPaths() {
return get("ApiPaths");
}
public Boolean isEnabled() {
return get("Enabled");
}
public String getLocation() {
return get("Location");
}
public String getReplicaId() {
return get("ReplicaId");
}
public String getBundle() {
return get("Bundle");
}
public String getApplicationName() {
return get("ApplicationName");
}
/**
* Returns the document for this server
*
* @return
*/
@Override
protected Document getDocument(final boolean create) {
Database odaDb_ = Configuration.getOdaDb();
if (odaDb_ == null)
return null;
Database db = null;
String unid;
boolean dirty = false;
if (isDatabase_) {
db = odaDb_.getAncestorSession().getDatabase(apiPath_);
unid = Configuration.computeUNID(taskletName_, db);
} else {
unid = Configuration.computeUNID(bundle_ + ":" + taskletName_, odaDb_);// use a valid ReplicaID
}
Document currentConfig = odaDb_.getDocumentByUNID(unid);
if (currentConfig == null) {
if (!create)
return null;
currentConfig = odaDb_.createDocument();
currentConfig.setUniversalID(unid);
currentConfig.replaceItemValue("Form", "XotsTasklet");
currentConfig.replaceItemValue("TaskletName", taskletName_);
currentConfig.replaceItemValue("ApiPaths", apiPath_);// APIPath is just for UI - internally we always use replica ID
currentConfig.replaceItemValue("Enabled", true);
if (isDatabase_) {
if (db != null) {
// Java's wrong about this potentially being null
currentConfig.replaceItemValue("ReplicaId", db.getReplicaID());
}
currentConfig.replaceItemValue("Location", "NSF");
} else {
currentConfig.replaceItemValue("Bundle", bundle_);
currentConfig.replaceItemValue("Location", "BUNDLE");
}
currentConfig.replaceItemValue("$ConflictAction", "3");// merge - no conflicts
dirty = true;
}
// update the DB-Title in document
if (db != null && !db.getTitle().equals(currentConfig.getItemValueString("ApplicationName"))) {
currentConfig.replaceItemValue("ApplicationName", db.getTitle());
dirty = true;
}
// add all api-paths of all servers
boolean found = false;
List<String> paths = currentConfig.getItemValues("ApiPaths", String.class);
for (String apiPath : paths) {
if (apiPath.equalsIgnoreCase(apiPath_)) {
found = true;
break;
}
}
if (!found) {
paths.add(apiPath_);
currentConfig.replaceItemValue("ApiPaths", paths);
dirty = true;
}
if (dirty) {
currentConfig.save();
}
return currentConfig;
}
/**
* Queuing and synchronization is indispensable to avoid that LogEntries overtake each other (in case of a very soon finishing task) and
* thus wrong data are written to the XotsLog-document.
*/
protected LinkedBlockingQueue<_LogEntry> _logQueue = new LinkedBlockingQueue<_LogEntry>();
protected class _LogEntry {
String[] _keys;
Object[] _values;
_LogEntry(final Object... kvPairs) {
int numPairs = kvPairs.length >>> 1;
_keys = new String[numPairs];
_values = new Object[numPairs];
for (int i = 0; i < numPairs; i++) {
_keys[i] = (String) kvPairs[2 * i];
_values[i] = kvPairs[2 * i + 1];
}
}
}
@Tasklet(session = Tasklet.Session.NATIVE, threadConfig = Tasklet.ThreadConfig.STRICT)
protected class _Logger implements Runnable {
protected Document getLogDocument() {
Document taskletDoc = getDocument(true);
if (taskletDoc == null)
return null;
for (Document resp : taskletDoc.getResponses())
if (resp.getItemValueString("Server").equals(Factory.getLocalServerName()))
return resp;
Document srvDoc = new ServerConfiguration(Factory.getLocalServerName()).getDocument(true);
Document resp = taskletDoc.getAncestorDatabase().createDocument();
resp.makeResponse(srvDoc, "$REFServer");
resp.makeResponse(taskletDoc);
resp.replaceItemValue("Server", Factory.getLocalServerName()).setNames(true);
resp.replaceItemValue("Form", "XotsLog");
resp.replaceItemValue("Tasklet", taskletName_);
resp.replaceItemValue("ApiPath", apiPath_);
resp.save();
return resp;
}
@Override
public void run() {
synchronized (_logQueue) {
Document doc = getLogDocument();
if (doc == null)
return;
_LogEntry next;
while ((next = _logQueue.poll()) != null) {
for (int i = 0; i < next._keys.length; i++) {
System.out.println("Writing " + next._keys[i] + "=" + next._values[i]);
doc.put(next._keys[i], next._values[i]);
}
}
doc.save();
}
}
}
public void logStart() {
System.out.println("### LOGSTART");
logCommon("Start", new Date(),
"Stop", null,
"State", "RUNNING");
}
public void logError(final Exception e) {
System.out.println("### LOGERR " + e);
logCommon("Stop", new Date(),
"State", "ERROR",
"ErrorDate", new Date(),
"ErrorMessage", "[" + e.getClass().getName() + "]: " + e.getMessage());
}
public void logSuccess() {
System.out.println("### LOGSUCCESS");
logCommon("Stop", new Date(),
"State", "IDLE");
}
private void logCommon(final Object... kvPairs) {
DominoExecutor executor = Configuration.getExecutor();
if (executor == null)
return;
synchronized (_logQueue) {
for (int i = 0; i < 100; i++) {
try {
_logQueue.put(new _LogEntry(kvPairs));
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
executor.submit(new _Logger());
}
}
|
package com.thinkaurelius.titan.diskstorage.cassandra.thrift.thriftpool;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.thinkaurelius.titan.diskstorage.PermanentStorageException;
import com.thinkaurelius.titan.diskstorage.StorageException;
import com.thinkaurelius.titan.diskstorage.TemporaryStorageException;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.db.marshal.TimeUUIDType;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/**
* A factory compatible with Apache commons-pool for Cassandra Thrift API
* connections.
*
* @author Dan LaRocque <dalaro@hopcount.org>
*/
public class CTConnectionFactory implements KeyedPoolableObjectFactory<String, CTConnection> {
private static final Logger log = LoggerFactory.getLogger(CTConnectionFactory.class);
private static final long SCHEMA_WAIT_MAX = 5000L;
private static final long SCHEMA_WAIT_INCREMENT = 25L;
private final AtomicReference<Config> cfgRef;
private CTConnectionFactory(Config config) {
this.cfgRef = new AtomicReference<Config>(config);
}
@Override
public void activateObject(String key, CTConnection c) throws Exception {
// Do nothing, as in passivateObject
}
@Override
public void destroyObject(String key, CTConnection c) throws Exception {
TTransport t = c.getTransport();
if (t.isOpen())
t.close();
}
@Override
public CTConnection makeObject(String key) throws Exception {
CTConnection conn = makeRawConnection();
Cassandra.Client client = conn.getClient();
client.set_keyspace(key);
return conn;
}
/**
* Create a Cassandra-Thrift connection, but do not attempt to
* set a keyspace on the connection.
*
* @return A CTConnection ready to talk to a Cassandra cluster
* @throws TTransportException on any Thrift transport failure
*/
public CTConnection makeRawConnection() throws TTransportException {
final Config cfg = cfgRef.get();
String hostname = cfg.getRandomHost();
if (log.isDebugEnabled())
log.debug("Creating TSocket({}, {}, {}, {}, {})", hostname, cfg.port, cfg.username, cfg.password, cfg.timeoutMS);
TSocket socket;
if (!cfg.sslTruststoreLocation.isEmpty()) {
TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters() {{
setKeyStore(cfg.sslTruststoreLocation, cfg.sslTruststorePassword);
}};
socket = TSSLTransportFactory.getClientSocket(hostname, cfg.port, cfg.timeoutMS, params);
} else {
socket = new TSocket(hostname, cfg.port, cfg.timeoutMS);
}
TTransport transport = new TFramedTransport(socket, cfg.frameSize);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
Cassandra.Client client = new Cassandra.Client(protocol);
transport.open();
if (cfg.username != null) {
Map<String, String> credentials = new HashMap<String, String>() {{
put(IAuthenticator.USERNAME_KEY, cfg.username);
put(IAuthenticator.PASSWORD_KEY, cfg.password);
}};
try {
client.login(new AuthenticationRequest(credentials));
} catch (Exception e) { // TTransportException will propagate authentication/authorization failure
throw new TTransportException(e);
}
}
return new CTConnection(transport, client, cfg);
}
@Override
public void passivateObject(String key, CTConnection o) throws Exception {
// Do nothing, as in activateObject
}
@Override
public boolean validateObject(String key, CTConnection c) {
Config curCfg = cfgRef.get();
boolean isSameConfig = c.getConfig().equals(curCfg);
if (log.isDebugEnabled()) {
if (isSameConfig) {
log.debug("Validated Thrift connection {}", c);
} else {
log.debug("Rejected Thrift connection {}; current config is {}; connection config is {}",
c, curCfg, c.getConfig());
}
}
return isSameConfig && c.isOpen();
}
public Config getConfig() {
return cfgRef.get();
}
public void setConfig(Config newCfg) {
cfgRef.set(newCfg);
log.debug("Updated Thrift connection factory config to {}", newCfg);
}
public static class Config {
// this is to keep backward compatibility with JDK 1.6, can be changed to ThreadLocalRandom once we fully switch
private static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = new ThreadLocal<Random>() {
@Override
public Random initialValue() {
return new Random();
}
};
private final String[] hostnames;
private final int port;
private final String username;
private final String password;
private int timeoutMS;
private int frameSize;
private String sslTruststoreLocation;
private String sslTruststorePassword;
private boolean isBuilt;
public Config(String[] hostnames, int port, String username, String password) {
this.hostnames = hostnames;
this.port = port;
this.username = username;
this.password = password;
}
// TODO: we don't really need getters/setters here as all of the fields are final and immutable
public String getHostname() {
return hostnames[0];
}
public int getPort() {
return port;
}
public String getRandomHost() {
return hostnames.length == 1 ? hostnames[0] : hostnames[THREAD_LOCAL_RANDOM.get().nextInt(hostnames.length)];
}
public Config setTimeoutMS(int timeoutMS) {
checkIfAlreadyBuilt();
this.timeoutMS = timeoutMS;
return this;
}
public Config setFrameSize(int frameSize) {
checkIfAlreadyBuilt();
this.frameSize = frameSize;
return this;
}
public Config setSSLTruststoreLocation(String location) {
checkIfAlreadyBuilt();
this.sslTruststoreLocation = location;
return this;
}
public Config setSSLTruststorePassword(String password) {
checkIfAlreadyBuilt();
this.sslTruststorePassword = password;
return this;
}
public CTConnectionFactory build() {
isBuilt = true;
return new CTConnectionFactory(this);
}
public void checkIfAlreadyBuilt() {
if (isBuilt)
throw new IllegalStateException("Can't accept modifications when used with built factory.");
}
@Override
public String toString() {
return "Config[hostnames=" + StringUtils.join(hostnames, ',') + ", port=" + port
+ ", timeoutMS=" + timeoutMS + ", frameSize=" + frameSize
+ "]";
}
}
}
|
package com.github.totomz.mm;
import com.google.gson.Gson;
import io.restassured.RestAssured;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javaslang.Function1;
import javaslang.Function2;
import javaslang.Function3;
import javaslang.Tuple6;
import javaslang.collection.Stream;
import org.jenetics.Genotype;
import org.jenetics.IntegerChromosome;
import org.jenetics.IntegerGene;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import spark.Spark;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
// Functions //
/**
* Download the drawings of SuperEnalotto for a given year
*/
public static final Function1<Integer, List<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >>> downloadExtractedSequenceByYear = (year) -> {
log.info("Downloading SuperEnalotto drawings for year " + year);
List<String> numbers = RestAssured
.get("http:
.htmlPath()
.getList("**.findAll { it.@class == 'ball-24px' }");
// Create batch of 6 numbers
return Stream.ofAll(numbers)
.map(Integer::parseInt)
.grouped(6)
.map(s -> {
List<Integer> l = s.toJavaList();
return new Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >(l.get(0), l.get(1), l.get(2), l.get(3), l.get(4), l.get(5));
})
.toJavaList();
};
private static final Function1<String, Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>> loadDrawingsFromFile = file -> {
log.info("Loading drawings from file " + file);
try {
URI uri = ClassLoader.getSystemResource(file).toURI();
Map<String, String> env = new HashMap<>();
env.put("create", "true");
FileSystem zipfs = FileSystems.newFileSystem(uri, env);
java.util.stream.Stream<String> stream = Files.lines(Paths.get(ClassLoader.getSystemResource(file).toURI()));
HashMap<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long> res = new HashMap<>();
stream.skip(1).forEach(line -> {
Integer[] t = Stream.of(line.split(",")).map(String::trim).map(Integer::parseInt).toJavaArray(Integer.class);
res.put(new Tuple6<>(t[1], t[2], t[3], t[4], t[5], t[6]),
new Long(t[0]));
});
return res;
}
catch(URISyntaxException | IOException | NullPointerException e) {
log.error("Error loading drawings from file", e);
}
return null;
};
/**
* Writes a Map in a file and return the map
*/
private static final Function2<String,
Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>,
Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>> writeToFile = (filename, map) -> {
log.info("Writing data to file " + filename);
String header = "frequency, n1, n2, n3, n4, n5, n6 \n";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)))) {
bw.write(header);
map.forEach((tuple, num) -> {
try {
bw.write(num + ", " + tuple.toSeq().mkString(",") + "\n");
} catch (IOException ex) {
log.error("Error writing a line of drawings", ex);
}
});
bw.close();
}
catch (Exception ex) {
log.error("Error writing drawings on file", ex);
}
return map;
};
/**
* Load the historical drawings from a remote service
*/
private static final Function2<Integer, Integer, Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long> >
loadSisalData = (startInclusive, endExclusive) -> {
return IntStream.range(startInclusive, endExclusive).parallel()
.mapToObj(downloadExtractedSequenceByYear::apply)
.flatMap(List::stream)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
};
protected static int getHerokuAssignedPort() {
ProcessBuilder processBuilder = new ProcessBuilder();
if (processBuilder.environment().get("PORT") != null) {
return Integer.parseInt(processBuilder.environment().get("PORT"));
}
return 4567;
}
// Genetic algorithm eval strategies //
private static final Function1<Genotype<IntegerGene>, int[]> mapGeneToValues = (gt) -> {
return gt.getChromosome().stream().mapToInt(IntegerGene::intValue).distinct().sorted().toArray();
};
/**
* Simply returns 1 if the sequence is unknown
*/
protected static final Function2<Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>, int[], Integer >
doesNotExistsFitness = (map, n) -> {
int score = (n.length == 6)?
map.containsKey(new Tuple6<>(n[0], n[1], n[2], n[3], n[4], n[5]))?0:1
:0;
return score;
};
/**
* Return a number [100,0] that depends on the uniqueness of each number in each position in the sequence
* IF the sequence is present in memeory, returns 0
*
* This algorithm sucks, the best sequence is 1,2,3,4,5,6 !
*/
protected static final Function3<List<ConcurrentHashMap<Integer, AtomicInteger>>, Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>, int[], Integer >
preferNeverSeenNumbers = (occurrencies, map, n) -> {
if( (n.length != 6) ||(map.containsKey(new Tuple6<>(n[0], n[1], n[2], n[3], n[4], n[5]))) ) {
return 0;
}
int score = map.size() * 6;
for(int i=0;i<6;i++){
if(occurrencies.get(i).get(n[i]).get() > 0){
score -= occurrencies.get(i).get(n[i]).get();
}
}
return (int)((double)score/(map.size() * 6) * 100);
};
protected static Function1<Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long>, List<ConcurrentHashMap<Integer, AtomicInteger>>>
getStatistics = (draws) -> {
List<ConcurrentHashMap<Integer, AtomicInteger>> occurenciesByPosition = Stream.of(
new ConcurrentHashMap<Integer, AtomicInteger>(), new ConcurrentHashMap<Integer, AtomicInteger>(),
new ConcurrentHashMap<Integer, AtomicInteger>(), new ConcurrentHashMap<Integer, AtomicInteger>(),
new ConcurrentHashMap<Integer, AtomicInteger>(), new ConcurrentHashMap<Integer, AtomicInteger>()).toJavaList();
// Initialize the occurrencies
IntStream.range(1, 91).forEachOrdered(n -> {
occurenciesByPosition.forEach(occ -> {
occ.put(n, new AtomicInteger(0));
});
});
draws.keySet().stream().forEach(t -> {
occurenciesByPosition.get(0).get(t._1).incrementAndGet();
occurenciesByPosition.get(1).get(t._2).incrementAndGet();
occurenciesByPosition.get(2).get(t._3).incrementAndGet();
occurenciesByPosition.get(3).get(t._4).incrementAndGet();
occurenciesByPosition.get(4).get(t._5).incrementAndGet();
occurenciesByPosition.get(5).get(t._6).incrementAndGet();
});
return occurenciesByPosition;
};
private static final AtomicBoolean keepRunning = new AtomicBoolean(true);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Map<Tuple6<Integer, Integer, Integer, Integer, Integer, Integer >, Long> drawings =
loadDrawingsFromFile.andThen((map) -> {
map.putAll(loadSisalData.apply(2016, 2017));
return map;
}).apply("drawings.txt");
// Count occurrencies on the i-th element
List<ConcurrentHashMap<Integer, AtomicInteger>> occurenciesByPosition = getStatistics.apply(drawings);
// occurenciesByPosition.forEach(occ -> {
// System.out.print("{");
// occ.keySet().stream().sorted().forEach(n -> {
// System.out.print(String.format(" [%s, %s] ", n, occ.getOrDefault(n, new AtomicInteger(0)).get()));
// Choose the evaluating strategy
final Function<Genotype<IntegerGene>, Integer> evalFunction = mapGeneToValues.andThen(doesNotExistsFitness.curried().apply(drawings));
// Function<Genotype<IntegerGene>, Integer> evalFunction = mapGeneToValues.andThen(preferNeverSeenNumbers.curried().apply(occurenciesByPosition).curried().apply(drawings));
// Use this function to give a score to the user
final Function<Genotype<IntegerGene>, Integer> publicScore = mapGeneToValues.andThen(preferNeverSeenNumbers.curried().apply(occurenciesByPosition).curried().apply(drawings));
// Set-up a genetic algorithm to find an unknown sequence
final Factory<Genotype<IntegerGene>> factory = Genotype.of(IntegerChromosome.of(1, 90, 6));
final Engine<IntegerGene, Integer> engine = Engine.builder(evalFunction, factory).build();
// Answer to clients!
log.info("Starting web server");
Spark.port(getHerokuAssignedPort());
Spark.staticFileLocation("/public");
Gson gson = new Gson();
// WEB SERVICES //
Spark.get("/magicnumbers.json", (req, resp)-> {
Genotype<IntegerGene> result = engine.stream().limit(1000).collect(EvolutionResult.toBestGenotype());
int score = publicScore.apply(result);
resp.type("application/json");
return new Result(score, result.getChromosome().stream().mapToInt(IntegerGene::intValue).sorted().toArray());
}, gson::toJson);
Spark.get("/stop", (req, resp)-> {
if(req.host().equals("localhost:4567")) {
keepRunning.set(false);
}
return "Byeeeeeeee";
}, gson::toJson);
Spark.get("/jack", (req, res) -> {
try(Jedis jedis = Settings.jedis()) {
String counter = jedis.incr("test:redis").toString();
res.type("application/json");
return String.format("{\"acounter\": %s}", counter);
}
});
// Cleanup & boh //
Spark.awaitInitialization();
log.info("Main Thread is going to sleep forever");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {keepRunning.set(false);}));
while(keepRunning.get()){
try{Thread.sleep(1000);}
catch(Exception e){}
}
log.info("Shutting down");
Spark.stop();
log.info("Bye");
}
}
class Result {
private final int score;
private final int[] numbers;
public Result(int score, int[] numbers) {
this.score = score;
this.numbers = numbers;
}
}
|
package org.drools.runtime.pipeline.impl;
import java.io.Serializable;
import org.drools.runtime.pipeline.Action;
import org.drools.runtime.pipeline.PipelineContext;
import org.drools.runtime.pipeline.Receiver;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.compiler.ExpressionCompiler;
public class MvelAction extends BaseEmitter
implements
Action,
Receiver {
private Serializable expr;
public MvelAction(String text) {
final ParserContext parserContext = new ParserContext();
parserContext.setStrictTypeEnforcement( false );
ExpressionCompiler compiler = new ExpressionCompiler( text );
this.expr = compiler.compile( );
}
public void receive(Object object,
PipelineContext context) {
try {
MVEL.executeExpression( this.expr,
object );
} catch ( Exception e ) {
handleException( this,
object,
e );
}
emit( object,
context );
}
}
|
package com.example.db;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DbImplConfig {
@Bean
public BookRepository bookRepository() {
BookRepositoryImpl bookRepository = new BookRepositoryImpl();
bookRepository.insert(new BookEntity.Builder()
.withName("Wprowadzenie do algorytmow")
.withPrice(Price.of("210.00"))
.build()
);
bookRepository.insert(new BookEntity.Builder()
.withName("Java Podstawy")
.withPrice(Price.of("100.00"))
.build()
);
return bookRepository;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-09-11");
this.setApiVersion("15.7.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-05-21");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package net.spy.memcached;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.config.ChainedDynamicProperty;
import com.netflix.evcache.EVCacheGetOperationListener;
import com.netflix.evcache.EVCacheLatch;
import com.netflix.evcache.metrics.EVCacheMetricsFactory;
import com.netflix.evcache.operation.EVCacheBulkGetFuture;
import com.netflix.evcache.operation.EVCacheLatchImpl;
import com.netflix.evcache.operation.EVCacheOperationFuture;
import com.netflix.evcache.pool.ServerGroup;
import com.netflix.servo.tag.BasicTag;
import com.netflix.servo.tag.Tag;
import net.spy.memcached.internal.GetFuture;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.ops.DeleteOperation;
import net.spy.memcached.ops.GetAndTouchOperation;
import net.spy.memcached.ops.GetOperation;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatusCode;
import net.spy.memcached.ops.StoreOperation;
import net.spy.memcached.ops.StoreType;
import net.spy.memcached.protocol.binary.BinaryOperationFactory;
import net.spy.memcached.transcoders.Transcoder;
import net.spy.memcached.util.StringUtils;
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS",
"SIC_INNER_SHOULD_BE_STATIC_ANON" })
public class EVCacheMemcachedClient extends MemcachedClient {
private static final Logger log = LoggerFactory.getLogger(EVCacheMemcachedClient.class);
private final int id;
private final String appName;
private final String zone;
private final ChainedDynamicProperty.IntProperty readTimeout;
private final ServerGroup serverGroup;
public EVCacheMemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs,
ChainedDynamicProperty.IntProperty readTimeout, String appName, String zone, int id,
ServerGroup serverGroup) throws IOException {
super(cf, addrs);
this.id = id;
this.appName = appName;
this.zone = zone;
this.readTimeout = readTimeout;
this.serverGroup = serverGroup;
}
public NodeLocator getNodeLocator() {
return this.mconn.getLocator();
}
public MemcachedNode getEVCacheNode(String key) {
return this.mconn.getLocator().getPrimary(key);
}
public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) {
throw new UnsupportedOperationException("asyncGet");
}
public <T> EVCacheOperationFuture<T> asyncGet(final String key, final Transcoder<T> tc,
EVCacheGetOperationListener<T> listener) {
final CountDownLatch latch = new CountDownLatch(1);
final EVCacheOperationFuture<T> rv = new EVCacheOperationFuture<T>(key, latch, new AtomicReference<T>(null), readTimeout.get().intValue(), executorService, appName, serverGroup, "LatencyGet");
Operation op = opFact.get(key, new GetOperation.Callback() {
private Future<T> val = null;
public void receivedStatus(OperationStatus status) {
try {
if (val != null) {
rv.set(val.get(), status);
} else {
rv.set(null, status);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
rv.set(null, status);
}
}
@SuppressWarnings("unchecked")
public void gotData(String k, int flags, byte[] data) {
if (!key.equals(k)) log.warn("Wrong key returned. Key - " + key + "; Returned Key " + k);
if (tc == null) {
if (tcService == null) {
log.error("tcService is null, will not be able to decode");
throw new RuntimeException("TranscoderSevice is null. Not able to decode");
} else {
final Transcoder<T> t = (Transcoder<T>) getTranscoder();
val = tcService.decode(t, new CachedData(flags, data, t.getMaxSize()));
}
} else {
if (tcService == null) {
log.error("tcService is null, will not be able to decode");
throw new RuntimeException("TranscoderSevice is null. Not able to decode");
} else {
val = tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize()));
}
}
}
public void complete() {
latch.countDown();
rv.signalComplete();
}
});
rv.setOperation(op);
if (listener != null) rv.addListener(listener);
mconn.enqueueOperation(key, op);
return rv;
}
public <T> EVCacheBulkGetFuture<T> asyncGetBulk(Collection<String> keys, final Transcoder<T> tc,
EVCacheGetOperationListener<T> listener) {
final Map<String, Future<T>> m = new ConcurrentHashMap<String, Future<T>>();
// Break the gets down into groups by key
final Map<MemcachedNode, Collection<String>> chunks = new HashMap<MemcachedNode, Collection<String>>();
final NodeLocator locator = mconn.getLocator();
final Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
final String key = keyIter.next();
StringUtils.validateKey(key, opFact instanceof BinaryOperationFactory);
final MemcachedNode primaryNode = locator.getPrimary(key);
if (primaryNode.isActive()) {
Collection<String> ks = chunks.get(primaryNode);
if (ks == null) {
ks = new ArrayList<String>();
chunks.put(primaryNode, ks);
}
ks.add(key);
}
}
final AtomicInteger pendingChunks = new AtomicInteger(chunks.size());
int initialLatchCount = chunks.isEmpty() ? 0 : 1;
final CountDownLatch latch = new CountDownLatch(initialLatchCount);
final Collection<Operation> ops = new ArrayList<Operation>(chunks.size());
final EVCacheBulkGetFuture<T> rv = new EVCacheBulkGetFuture<T>(appName, m, ops, latch, executorService, serverGroup);
GetOperation.Callback cb = new GetOperation.Callback() {
@Override
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
rv.setStatus(status);
}
@Override
public void gotData(String k, int flags, byte[] data) {
m.put(k, tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize())));
}
@Override
public void complete() {
if (pendingChunks.decrementAndGet() <= 0) {
latch.countDown();
rv.signalComplete();
}
}
};
// Now that we know how many servers it breaks down into, and the latch
// is all set up, convert all of these strings collections to operations
final Map<MemcachedNode, Operation> mops = new HashMap<MemcachedNode, Operation>();
for (Map.Entry<MemcachedNode, Collection<String>> me : chunks.entrySet()) {
Operation op = opFact.get(me.getValue(), cb);
mops.put(me.getKey(), op);
ops.add(op);
}
assert mops.size() == chunks.size();
mconn.checkState();
mconn.addOperations(mops);
return rv;
}
public <T> EVCacheOperationFuture<CASValue<T>> asyncGetAndTouch(final String key, final int exp,
final Transcoder<T> tc) {
final CountDownLatch latch = new CountDownLatch(1);
final EVCacheOperationFuture<CASValue<T>> rv = new EVCacheOperationFuture<CASValue<T>>(key, latch, new AtomicReference<CASValue<T>>(null), operationTimeout, executorService, appName, serverGroup, "LatencyGet");
Operation op = opFact.getAndTouch(key, exp, new GetAndTouchOperation.Callback() {
private CASValue<T> val = null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void complete() {
latch.countDown();
rv.signalComplete();
}
public void gotData(String k, int flags, long cas, byte[] data) {
if (!key.equals(k)) log.warn("Wrong key returned. Key - " + key + "; Returned Key " + k);
val = new CASValue<T>(cas, tc.decode(new CachedData(flags, data, tc.getMaxSize())));
}
});
rv.setOperation(op);
mconn.enqueueOperation(key, op);
return rv;
}
public <T> OperationFuture<Boolean> set(String key, int exp, T o, final Transcoder<T> tc) {
return asyncStore(StoreType.set, key, exp, o, tc, null);
}
public OperationFuture<Boolean> set(String key, int exp, Object o) {
return asyncStore(StoreType.set, key, exp, o, transcoder, null);
}
@SuppressWarnings("unchecked")
public <T> OperationFuture<Boolean> set(String key, int exp, T o, final Transcoder<T> tc, EVCacheLatch latch) {
Transcoder<T> t = (Transcoder<T>) ((tc == null) ? transcoder : tc);
return asyncStore(StoreType.set, key, exp, o, t, latch);
}
@SuppressWarnings("unchecked")
public <T> OperationFuture<Boolean> replace(String key, int exp, T o, final Transcoder<T> tc, EVCacheLatch latch) {
Transcoder<T> t = (Transcoder<T>) ((tc == null) ? transcoder : tc);
return asyncStore(StoreType.replace, key, exp, o, t, latch);
}
public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.add, key, exp, o, tc, null);
}
public OperationFuture<Boolean> delete(String key, EVCacheLatch evcacheLatch) {
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Boolean> rv = new OperationFuture<Boolean>(key, latch, operationTimeout, executorService);
final DeleteOperation.Callback callback = new DeleteOperation.Callback() {
@Override
public void receivedStatus(OperationStatus s) {
rv.set(Boolean.TRUE, s);
}
@Override
public void gotData(long cas) {
rv.setCas(cas);
}
@Override
public void complete() {
latch.countDown();
rv.signalComplete();
}
};
final DeleteOperation op = opFact.delete(key, callback);
rv.setOperation(op);
if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl) ((EVCacheLatchImpl) evcacheLatch)
.addFuture(rv);
mconn.enqueueOperation(key, op);
return rv;
}
private <T> OperationFuture<Boolean> asyncStore(final StoreType storeType, final String key, int exp, T value,
Transcoder<T> tc, EVCacheLatch evcacheLatch) {
CachedData co;
if (value instanceof CachedData) {
co = (CachedData) value;
} else {
co = tc.encode(value);
}
final CountDownLatch latch = new CountDownLatch(1);
final String operationStr;
if (storeType == StoreType.set) {
operationStr = "Set";
} else if (storeType == StoreType.add) {
operationStr = "Add";
} else {
operationStr = "Replace";
}
final OperationFuture<Boolean> rv = new EVCacheOperationFuture<Boolean>(key, latch, new AtomicReference<Boolean>(null), operationTimeout, executorService, appName, serverGroup, "Latency" + operationStr);
Operation op = opFact.store(storeType, key, co.getFlags(), exp, co.getData(), new StoreOperation.Callback() {
private final long startTime = System.currentTimeMillis();
@Override
public void receivedStatus(OperationStatus val) {
if (log.isDebugEnabled()) log.debug("Storing Key : " + key + "; Status : " + val.getStatusCode().name()
+ "; Message : " + val.getMessage() + "; Elapsed Time - "
+ (System.currentTimeMillis() - startTime));
Tag tag = null;
final MemcachedNode node = getEVCacheNode(key);
if (node.getSocketAddress() instanceof InetSocketAddress) {
tag = new BasicTag("HOST", ((InetSocketAddress) node.getSocketAddress()).getHostName());
}
if (val.getStatusCode().equals(StatusCode.SUCCESS)) {
EVCacheMetricsFactory.getCounter(appName + "-" + serverGroup.getName() + "-" + operationStr
+ "Call-SUCCESS").increment();
} else if (val.getStatusCode().equals(StatusCode.TIMEDOUT)) {
EVCacheMetricsFactory.getCounter(appName + "-" + serverGroup.getName() + "-" + operationStr
+ "Call-TIMEDOUT", tag).increment();
} else {
EVCacheMetricsFactory.getCounter(appName + "-" + serverGroup.getName() + "-" + operationStr
+ "Call-" + val.getStatusCode().name(), tag).increment();
}
rv.set(val.isSuccess(), val);
}
@Override
public void gotData(String key, long cas) {
rv.setCas(cas);
}
@Override
public void complete() {
latch.countDown();
rv.signalComplete();
}
});
rv.setOperation(op);
if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl) ((EVCacheLatchImpl) evcacheLatch)
.addFuture(rv);
mconn.enqueueOperation(key, op);
return rv;
}
public String toString() {
return appName + "_" + zone + " _" + id;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-06-25");
this.setApiVersion("17.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.psddev.dari.db;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodAdapter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.psddev.dari.util.ClassEnhancer;
import com.psddev.dari.util.ObjectUtils;
public class LazyLoadEnhancer extends ClassEnhancer {
private static final String ANNOTATION_DESCRIPTOR = Type.getDescriptor(LazyLoad.class);
private static final Logger LOGGER = LoggerFactory.getLogger(LazyLoadEnhancer.class);
private boolean missingClasses;
private String enhancedClassName;
private boolean alreadyEnhanced;
private final Set<String> transientFields = new HashSet<String>();
private final Set<String> recordableFields = new HashSet<String>();
// Returns the class associated with the given className
// only if it's compatible with Recordable.
private Class<?> findRecordableClass(String className) {
Class<?> objectClass = ObjectUtils.getClassByName(className.replace('/', '.'));
if (objectClass == null) {
LOGGER.warn("Can't find [{}] referenced by [{}]!", className, enhancedClassName);
missingClasses = true;
return null;
} else if (Recordable.class.isAssignableFrom(objectClass)) {
return objectClass;
} else {
return null;
}
}
@Override
public boolean canEnhance(ClassReader reader) {
enhancedClassName = reader.getClassName();
return !enhancedClassName.startsWith("com/psddev/dari/") &&
findRecordableClass(enhancedClassName) != null;
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (!alreadyEnhanced && desc.equals(ANNOTATION_DESCRIPTOR)) {
alreadyEnhanced = true;
}
return super.visitAnnotation(desc, visible);
}
@Override
public FieldVisitor visitField(
int access,
String name,
String desc,
String signature,
Object value) {
if ((access & Opcodes.ACC_TRANSIENT) != 0) {
transientFields.add(name);
} else {
Class<?> objectClass = findRecordableClass(Type.getType(desc).getClassName());
if (objectClass != null) {
Recordable.Embedded embedded = objectClass.getAnnotation(Recordable.Embedded.class);
if (embedded == null || !embedded.value()) {
recordableFields.add(name);
}
}
}
return super.visitField(access, name, desc, signature, value);
}
@Override
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions) {
MethodVisitor visitor = super.visitMethod(access, name, desc, signature, exceptions);
if (alreadyEnhanced) {
return visitor;
} else {
return new MethodAdapter(visitor) {
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if (!transientFields.contains(name)) {
if (opcode == Opcodes.GETFIELD) {
if (recordableFields.contains(name)) {
visitInsn(Opcodes.DUP);
visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/psddev/dari/db/Recordable", "getState", "()Lcom/psddev/dari/db/State;");
visitInsn(Opcodes.DUP);
visitLdcInsn(name);
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "com/psddev/dari/db/State", "beforeFieldGet", "(Ljava/lang/String;)V");
visitLdcInsn(name);
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "com/psddev/dari/db/State", "resolveReference", "(Ljava/lang/String;)V");
} else {
visitInsn(Opcodes.DUP);
visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/psddev/dari/db/Recordable", "getState", "()Lcom/psddev/dari/db/State;");
visitLdcInsn(name);
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "com/psddev/dari/db/State", "beforeFieldGet", "(Ljava/lang/String;)V");
}
} else if (opcode == Opcodes.PUTFIELD &&
recordableFields.contains(name)) {
visitInsn(Opcodes.SWAP);
visitInsn(Opcodes.DUP);
visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/psddev/dari/db/Recordable", "getState", "()Lcom/psddev/dari/db/State;");
visitLdcInsn(name);
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "com/psddev/dari/db/State", "resolveReference", "(Ljava/lang/String;)V");
visitInsn(Opcodes.SWAP);
}
}
super.visitFieldInsn(opcode, owner, name, desc);
}
};
}
}
@Override
public void visitEnd() {
if (!missingClasses && !alreadyEnhanced) {
AnnotationVisitor annotation = super.visitAnnotation(ANNOTATION_DESCRIPTOR, true);
annotation.visitEnd();
}
super.visitEnd();
}
}
|
package org.nakedobjects.example.exploration;
import org.nakedobjects.NakedObjects;
import org.nakedobjects.NakedObjectsClient;
import org.nakedobjects.application.NakedObjectRuntimeException;
import org.nakedobjects.container.configuration.Configuration;
import org.nakedobjects.container.configuration.ConfigurationFactory;
import org.nakedobjects.container.configuration.ConfigurationPropertiesLoader;
import org.nakedobjects.object.defaults.LocalReflectionFactory;
import org.nakedobjects.object.defaults.NakedObjectSpecificationImpl;
import org.nakedobjects.object.defaults.NakedObjectSpecificationLoaderImpl;
import org.nakedobjects.object.fixture.Fixture;
import org.nakedobjects.object.help.HelpManagerAssist;
import org.nakedobjects.object.help.SimpleHelpManager;
import org.nakedobjects.object.persistence.OidGenerator;
import org.nakedobjects.object.persistence.defaults.LocalObjectManager;
import org.nakedobjects.object.persistence.defaults.SimpleOidGenerator;
import org.nakedobjects.object.persistence.defaults.TransientObjectStore;
import org.nakedobjects.object.reflect.PojoAdapterFactoryImpl;
import org.nakedobjects.object.reflect.PojoAdapterHashImpl;
import org.nakedobjects.reflector.java.JavaBusinessObjectContainer;
import org.nakedobjects.reflector.java.JavaObjectFactory;
import org.nakedobjects.reflector.java.control.SimpleSession;
import org.nakedobjects.reflector.java.fixture.JavaFixtureBuilder;
import org.nakedobjects.reflector.java.reflect.JavaReflectorFactory;
import org.nakedobjects.system.AboutNakedObjects;
import org.nakedobjects.system.SplashWindow;
import org.nakedobjects.utility.StartupException;
import org.nakedobjects.viewer.skylark.SkylarkViewer;
import java.util.Locale;
import java.util.Properties;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class JavaExploration {
private static final String DEFAULT_CONFIG = "nakedobjects.properties";
private static final Logger LOG = Logger.getLogger(JavaExploration.class);
private static final String SHOW_EXPLORATION_OPTIONS = "nakedobjects.viewer.skylark.show-exploration";
private SplashWindow splash;
private JavaFixtureBuilder builder;
public JavaExploration() {
ConfigurationPropertiesLoader loadedProperties = new ConfigurationPropertiesLoader("log4j.properties", false);
Properties p = loadedProperties.getProperties();
if (p.size() == 0) {
BasicConfigurator.configure();
} else {
PropertyConfigurator.configure(p);
}
Logger.getRootLogger().setLevel(Level.WARN);
splash = null;
try {
String name = this.getClass().getName();
name = name.substring(name.lastIndexOf('.') + 1);
Configuration configuration = new Configuration(new ConfigurationPropertiesLoader(DEFAULT_CONFIG, false));
NakedObjects nakedObjects = new NakedObjectsClient();
nakedObjects.setConfiguration(configuration);
ConfigurationFactory.setConfiguration(configuration);
PropertyConfigurator.configure(ConfigurationFactory.getConfiguration().getProperties("log4j"));
Logger log = Logger.getLogger("Naked Objects");
log.info(AboutNakedObjects.getName());
log.info(AboutNakedObjects.getVersion());
log.info(AboutNakedObjects.getBuildId());
boolean noSplash = ConfigurationFactory.getConfiguration().getBoolean("nosplash", false);
if (!noSplash) {
splash = new SplashWindow();
}
setUpLocale();
JavaBusinessObjectContainer container = new JavaBusinessObjectContainer();
JavaObjectFactory objectFactory = new JavaObjectFactory();
objectFactory.setContainer(container);
container.setObjectFactory(objectFactory);
TransientObjectStore objectStore = new TransientObjectStore();
OidGenerator oidGenerator = new SimpleOidGenerator();
LocalObjectManager objectManager = new LocalObjectManager();
objectManager.setObjectStore(objectStore);
objectManager.setObjectFactory(objectFactory);
objectManager.setOidGenerator(oidGenerator);
nakedObjects.setObjectManager(objectManager);
NakedObjectSpecificationLoaderImpl specificationLoader = new NakedObjectSpecificationLoaderImpl();
nakedObjects.setSpecificationLoader(specificationLoader);
LocalReflectionFactory reflectionFactory = new LocalReflectionFactory();
HelpManagerAssist helpManager = new HelpManagerAssist();
helpManager.setDecorated(new SimpleHelpManager());
reflectionFactory.setHelpManager(helpManager);
JavaReflectorFactory reflectorFactory = new JavaReflectorFactory();
PojoAdapterFactoryImpl pojoAdapterFactory = new PojoAdapterFactoryImpl();
pojoAdapterFactory.setPojoAdapterHash(new PojoAdapterHashImpl());
pojoAdapterFactory.setReflectorFactory(reflectorFactory);
nakedObjects.setPojoAdapterFactory(pojoAdapterFactory);
NakedObjectSpecificationImpl.setReflectionFactory(reflectionFactory);
specificationLoader.setReflectorFactory(reflectorFactory);
reflectorFactory.setObjectFactory(objectFactory);
nakedObjects.setSession(new SimpleSession());
try {
objectManager.init();
} catch (StartupException e) {
throw new NakedObjectRuntimeException(e);
}
builder = new JavaFixtureBuilder();
// explorationFixture = new ExplorationFixture(builder);
// builder.addFixture(explorationFixture);
} finally {
if (splash != null) {
splash.removeAfterDelay(4);
}
}
}
private void setUpLocale() {
String localeSpec = ConfigurationFactory.getConfiguration().getString("locale");
if (localeSpec != null) {
int pos = localeSpec.indexOf('_');
Locale locale;
if (pos == -1) {
locale = new Locale(localeSpec, "");
} else {
String language = localeSpec.substring(0, pos);
String country = localeSpec.substring(pos + 1);
locale = new Locale(language, country);
}
Locale.setDefault(locale);
LOG.info("Locale set to " + locale);
}
LOG.debug("locale is " + Locale.getDefault());
}
public void addFixture(Fixture fixture) {
builder.addFixture(fixture);
}
public void display() {
builder.installFixtures();
SkylarkViewer viewer = new SkylarkViewer();
viewer.setExploration(true);
String[] classes = builder.getClasses();
JavaExplorationContext context = new JavaExplorationContext();
for (int i = 0; i < classes.length; i++) {
context.addClass(classes[i]);
}
viewer.setApplication(context);
viewer.show();
if (splash != null) {
splash.toFront();
splash.removeAfterDelay(4);
}
}
public void registerClass(Class cls) {
builder.registerClass(cls.getName());
}
public Object createInstance(Class cls) {
return builder.createInstance(cls.getName());
}
/*
private static class ExplorationFixture extends JavaFixture {
private final FixtureBuilder builder;
public ExplorationFixture(FixtureBuilder builder) {
this. builder = builder;
}
protected FixtureBuilder getBuilder() {
return builder;
}
public void setBuilder(FixtureBuilder builder) {}
public void install() {}
protected final void addClass(Class cls) {
builder.registerClass(cls.getName());
}
}
*/
}
|
package com.daimajia.swipedemo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.nineoldandroids.view.ViewHelper;
public class MyActivity extends Activity {
private SwipeLayout sample1, sample2, sample3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// SwipeLayout swipeLayout = (SwipeLayout)findViewById(R.id.godfather);
// swipeLayout.setDragEdge(SwipeLayout.DragEdge.Bottom); // Set in XML
//sample1
sample1 = (SwipeLayout) findViewById(R.id.sample1);
sample1.setShowMode(SwipeLayout.ShowMode.LayDown);
sample1.setDragEdges(SwipeLayout.DragEdge.Left, SwipeLayout.DragEdge.Right);
Toast.makeText(this, sample1.getDragEdge() + " is the drag edge", Toast.LENGTH_LONG).show();
sample1.addRevealListener(R.id.delete, new SwipeLayout.OnRevealListener() {
@Override
public void onReveal(View child, SwipeLayout.DragEdge edge, float fraction, int distance) {
}
});
sample1.findViewById(R.id.star2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Star", Toast.LENGTH_SHORT).show();
}
});
sample1.findViewById(R.id.trash2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Trash Bin", Toast.LENGTH_SHORT).show();
}
});
sample1.findViewById(R.id.magnifier2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Magnifier", Toast.LENGTH_SHORT).show();
}
});
//sample2
sample2 = (SwipeLayout) findViewById(R.id.sample2);
sample2.setShowMode(SwipeLayout.ShowMode.LayDown);
sample2.setDragEdge(SwipeLayout.DragEdge.Right);
// sample2.setShowMode(SwipeLayout.ShowMode.PullOut);
sample2.findViewById(R.id.star).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Star", Toast.LENGTH_SHORT).show();
}
});
sample2.findViewById(R.id.trash).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Trash Bin", Toast.LENGTH_SHORT).show();
}
});
sample2.findViewById(R.id.magnifier).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Magnifier", Toast.LENGTH_SHORT).show();
}
});
sample2.findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Yo", Toast.LENGTH_SHORT).show();
}
});
//sample3
sample3 = (SwipeLayout) findViewById(R.id.sample3);
sample3.setDragEdge(SwipeLayout.DragEdge.Top);
sample3.addRevealListener(R.id.bottom_wrapper_child1, new SwipeLayout.OnRevealListener() {
@Override
public void onReveal(View child, SwipeLayout.DragEdge edge, float fraction, int distance) {
View star = child.findViewById(R.id.star);
float d = child.getHeight() / 2 - star.getHeight() / 2;
ViewHelper.setTranslationY(star, d * fraction);
ViewHelper.setScaleX(star, fraction + 0.6f);
ViewHelper.setScaleY(star, fraction + 0.6f);
int c = (Integer) evaluate(fraction, Color.parseColor("#dddddd"), Color.parseColor("#4C535B"));
child.setBackgroundColor(c);
}
});
sample3.findViewById(R.id.star).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Yo!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_listview) {
startActivity(new Intent(this, ListViewExample.class));
return true;
} else if (id == R.id.action_gridview) {
startActivity(new Intent(this, GridViewExample.class));
return true;
} else if(id == R.id.action_nexted){
startActivity(new Intent(this, NestedExample.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/*
Color transition method.
*/
public Object evaluate(float fraction, Object startValue, Object endValue) {
int startInt = (Integer) startValue;
int startA = (startInt >> 24) & 0xff;
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24) & 0xff;
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int) ((startA + (int) (fraction * (endA - startA))) << 24) |
(int) ((startR + (int) (fraction * (endR - startR))) << 16) |
(int) ((startG + (int) (fraction * (endG - startG))) << 8) |
(int) ((startB + (int) (fraction * (endB - startB))));
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-07-27");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* Kaltura API session
*
* @param ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param responseProfile
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.