answer
stringlengths 17
10.2M
|
|---|
package org.usfirst.frc4959.StaleyRobotics2014.commands;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc4959.StaleyRobotics2014.Robot;
import org.usfirst.frc4959.StaleyRobotics2014.RobotMap;
/**
* @author Lucas Wyland, Ian, Dustin, & Saul
*/
public class RunCompressor extends Command
{
Relay compressorSpike = RobotMap.compressorSpike;
DigitalInput pressureSwitch = RobotMap.pressureSwitch;
public RunCompressor()
{
requires(Robot.shooter);
}
// Called just before this Command runs the first time
protected void initialize()
{
}
// Called repeatedly when this Command is scheduled to run
protected void execute()
{
compressorSpike.set(Relay.Value.kOn);
System.out.println(pressureSwitch.get());
}
// Make this return true when this Commrand no longer needs to run execute()
protected boolean isFinished()
{
return false;
}
// Called once after isFinished returns true
protected void end()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted()
{
compressorSpike.set(Relay.Value.kOff);
}
}
|
package verification.platu.markovianAnalysis;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
import lpn.parser.Transition;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
public class ProbGlobalState extends PrjState {
private int color;
private double currentProb;
private double nextProb;
private double piProb;
/**
* This maps stores transition rate for each outgoing transition.
*/
private HashMap<Transition, Double> nextGlobalTranRateMap;
/**
* Sum of all outgoing transition rates from this state.
*/
private double tranRateSum;
/**
* This map stores for each state the probability value computed when checking
* a nested property.
* key: "Pr" + nestedPropString.hashCode() or "St" + nestedPropString.hashCode()
* value: success probability
*/
private HashMap<String, String> nestedProbValues;
public Semaphore lock;
private boolean isAbsorbing;
public ProbGlobalState(State[] other) {
super(other);
tranRateSum = 0.0;
nextGlobalStateMap = new HashMap<Transition, PrjState>();
nextGlobalTranRateMap = new HashMap<Transition, Double>();
lock = new Semaphore(1);
isAbsorbing = false;
}
public boolean isAbsorbing() {
return isAbsorbing;
}
public void setAbsorbing(boolean isAbsorbing) {
this.isAbsorbing = isAbsorbing;
}
public HashMap<String, String> getNestedProbValues() {
return nestedProbValues;
}
public void addNestedProb(String id, String value) {
if (nestedProbValues == null)
nestedProbValues = new HashMap<String, String>();
nestedProbValues.put(id, value);
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public double getCurrentProb() {
return currentProb;
}
public void setCurrentProb(double currentProb) {
this.currentProb = currentProb;
}
public double getNextProb() {
return nextProb;
}
public void setNextProb(double nextProb) {
this.nextProb = nextProb;
}
public void setCurrentProbToNext() {
currentProb = nextProb;
}
// public double getOutgoingTranRate(Transition tran) {
// int curLocalStIndex = tran.getLpn().getLpnIndex();
// State curLocalState = this.toStateArray()[curLocalStIndex];
// double tranRate = ((ProbLocalStateGraph) curLocalState.getStateGraph()).getTranRate(curLocalState, tran);
// return tranRate;
public double getOutgoingTranRate(Transition tran) {
return nextGlobalTranRateMap.get(tran);
}
public double getTranProb(Transition tran) {
double tranProb = 0.0;
if (tranRateSum != 0)
tranProb = getOutgoingTranRate(tran)/tranRateSum;
else
tranProb = 0.0;
return tranProb;
}
public double getPiProb() {
return piProb;
}
public void setPiProb(double piProb) {
this.piProb = piProb;
}
// /**
// * If nextProbGlobalStateMap exists, this method returns the value field of it.
// * If not, this method uses local state-transition information to search for the next global states of
// * this current global state, and returns a set of such next global states. The search
// * is performed based on the local states that this current global state is composed of. For example, assume a current
// * global state S0 is composed of n (n>=1) local states: s_00,s_10,s_20...,s_n0. For each outgoing transition, t_k, of
// * s_00, it finds in each of the local state, namely s_00, s_10, s_20, ..., s_n0, their next local states. It then
// * pieces them together to form a next global state. Next, it grabs the equivalent one from the global state set. The obtained is a
// * next global state reached from S0 by taking t_k. The whole process repeats for s_10, s_20, ..., s_n0. All obtained
// * next global states are added to a set and returned by this method.
// * @param globalStateSet
// * @return
// */
// public HashSet<ProbGlobalState> getNextProbGlobalStateSet(ProbGlobalStateSet globalStateSet) {
// HashSet<ProbGlobalState> nextProbGlobalStateSet = new HashSet<ProbGlobalState>();
// for (Transition outTran : nextGlobalStateMap.keySet())
// nextProbGlobalStateSet.add((ProbGlobalState) getNextGlobalState(outTran));
// return nextProbGlobalStateSet;
//if (Options.getBuildGlobalStateGraph()) {
// for (Transition outTran : nextGlobalStateMap.keySet())
// nextProbGlobalStateSet.add((ProbGlobalState) getNextGlobalState(outTran));
// return nextProbGlobalStateSet;
// else {
// for (State localSt : this.toStateArray())
// for (Transition outTran : localSt.getOutgoingTranSet())
// nextProbGlobalStateSet.add((ProbGlobalState) getNextGlobalState(outTran, globalStateSet));
// return nextProbGlobalStateSet;
// /**
// * If nextProbGlobalStateMap exists, this method returns the value for the given outTran, else it calls
// * getNextPrjState(Transition, HashMap<PrjState, PrjState>) in PrjState.java.
// * @param outTran
// * @param globalStateSet
// * @return
// */
// public PrjState getNextGlobalState(Transition outTran, ProbGlobalStateSet globalStateSet) {
// if (Options.getBuildGlobalStateGraph())
// return nextGlobalStateMap.get(outTran);
// else {
// State[] tmpNextStateArray = new State[this.toStateArray().length];
// for (State curLocalSt : this.toStateArray()) {
// State nextLocalSt = curLocalSt.getNextLocalState(outTran);
// if (nextLocalSt != null) { // outTran leads curLocalSt to a next state.
// tmpNextStateArray[curLocalSt.getLpn().getLpnIndex()] = nextLocalSt;
// else { // No nextLocalSt was found. Transition outTran did not change this local state.
// tmpNextStateArray[curLocalSt.getLpn().getLpnIndex()] = curLocalSt;
// PrjState tmpPrjSt = new ProbGlobalState(tmpNextStateArray);
// if (((ProbGlobalStateSet)globalStateSet).get(tmpPrjSt) == null) {
// String curGlobalStLabel = "";
// String tmpPrjStLabel = "";
// for (State s : this.toStateArray()) {
// curGlobalStLabel += s.getFullLabel() + "_";
// for (State s : tmpPrjSt.toStateArray()) {
// tmpPrjStLabel += s.getFullLabel() + "_";
// String message = "Next global state was not found for current global state: "
// + curGlobalStLabel.substring(0, curGlobalStLabel.length()-1) + ","
// + "\ngiven transition " + outTran.getFullLabel()
// + ".\ntmpPrjSt = " + tmpPrjStLabel.substring(0, tmpPrjStLabel.length()-1) + ".\n"
// + "Next local state map:\n";
// for (State s : this.toStateArray()) {
// if (s.getNextLocalState(outTran) == null)
// message += s.getFullLabel() + " -> null\n";
// else
// message += s.getFullLabel() + " ->" + s.getNextLocalState(outTran).getFullLabel() + "\n";
// NullPointerException npe = new NullPointerException(message);
// throw npe;
// return ((ProbGlobalStateSet) globalStateSet).get(tmpPrjSt);
// /**
// * If nextProbGlobalStateMap exists, this method returns the keySet of it. Otherwise, it calls
// * getOutgoingTrans() in PrjState.java.
// * @return
// */
// public Set<Transition> getOutgoingTranSetForProbGlobalState() {
// return nextGlobalStateMap.keySet();
//// if (Options.getBuildGlobalStateGraph())
//// return nextGlobalStateMap.keySet();
//// else {
//// Set<Transition> outgoingTrans = new HashSet<Transition>();
//// for (State curLocalSt : this.toStateArray())
//// outgoingTrans.addAll(curLocalSt.getOutgoingTranSet());
//// return outgoingTrans;
public void computeTranRateSum() {
for (Transition tran : nextGlobalStateMap.keySet()) {
tranRateSum += getOutgoingTranRate(tran);
}
}
public double getTranRateSum() {
return tranRateSum;
}
// public boolean isExplored() {
// return isExplored;
// public void markAsExplored() {
// isExplored = true;
// public void resetExplored() {
// isExplored = false;
public void setCurrentProbToPi() {
currentProb = piProb;
}
public void setTranRateSum(double tranRateSum) {
this.tranRateSum = tranRateSum;
}
public HashMap<String, String> getVariables() {
HashMap<String, String> varMap = new HashMap<String, String>();
for (State localSt : this.toStateArray()) {
varMap.putAll(localSt.getLpn().getAllVarsWithValuesAsString(localSt.getVariableVector()));
}
if (nestedProbValues != null)
varMap.putAll(nestedProbValues);
return varMap;
}
public void addNextGlobalTranRate(Transition t, double tranRate) {
this.nextGlobalTranRateMap.put(t, tranRate);
}
}
|
package com.fi.fimanagment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import org.zeromq.*;
import com.fi.finamanagment.model.DataBaseManager;
import com.fi.finamanagment.model.DbButton;
public class MainActivity extends Activity {
private Integer MAX_SOCKET_NUMBER = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataBaseManager dbManager = new DataBaseManager(this);
if (dbManager.size()==0){
dbManager.initDb(MAX_SOCKET_NUMBER);
}
dbManager.close();
}
// @INFO - often remove buttons and add it again, to be sure if user change their labels, it will get properly label.
@Override
public void onStart(){
super.onStart();
this.bindButtons();
}
@Override
public void onResume(){
super.onResume();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
linearLayout.removeAllViews();
this.bindButtons();
}
@Override
public void onRestart(){
super.onRestart();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
linearLayout.removeAllViews();
};
@Override
public void onPause(){
super.onPause();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
linearLayout.removeAllViews();
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle press on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
Context context = getApplicationContext();
Intent intent = new Intent(context, SettingsActivity.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
/*
* Private auxiliary functions
*/
// create buttons for view
private void bindButtons(){
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
DataBaseManager dbManager = new DataBaseManager(this);
int buttonID;
DbButton buttonDB;
for (int i = 0; i < MAX_SOCKET_NUMBER ; i++){
final Button button = new Button(this);
buttonID = i+1;
button.setId(buttonID);
buttonDB = dbManager.getDbButtonBySocketNumber(i);
button.setText(buttonDB.getLabel());
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
changeIoState(button.getId());
}
});
linearLayout.addView(button);
}
dbManager.close();
}
// Proxy to FiManagment Unit
private void changeIoState(int v){
final Integer pinID = v;
new Thread(new Runnable() {
@Override
public void run() {
/* ZMQ open connection*/
String host = "tcp://192.168.0.34:5555";
/* ZMQ open connection*/
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket requester = context.socket(ZMQ.REQ);
requester.connect(host);
/* Set pin */
String command = "set:"+pinID.toString()+";";
Log.d("command", command);
requester.send(command.getBytes(), 0);
requester.recv(0);
/* ZMQ close */
requester.close();
context.term();
};
}).start();
}
}
|
package org.apache.mesos.hdfs;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.CommandInfo;
import org.apache.mesos.Protos.Environment;
import org.apache.mesos.Protos.ExecutorID;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.FrameworkID;
import org.apache.mesos.Protos.FrameworkInfo;
import org.apache.mesos.Protos.MasterInfo;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.OfferID;
import org.apache.mesos.Protos.Resource;
import org.apache.mesos.Protos.SlaveID;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.mesos.Protos.TaskState;
import org.apache.mesos.Protos.TaskStatus;
import org.apache.mesos.Protos.Value;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.hdfs.config.HdfsFrameworkConfig;
import org.apache.mesos.hdfs.state.AcquisitionPhase;
import org.apache.mesos.hdfs.state.LiveState;
import org.apache.mesos.hdfs.state.PersistentState;
import org.apache.mesos.hdfs.util.DnsResolver;
import org.apache.mesos.hdfs.util.HDFSConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
// TODO (elingg) remove as much logic as possible from Scheduler to clean up code
public class Scheduler implements org.apache.mesos.Scheduler, Runnable {
public static final Log log = LogFactory.getLog(Scheduler.class);
private static final int SECONDS_FROM_MILLIS = 1000;
private final HdfsFrameworkConfig frameworkConfig;
private final LiveState liveState;
private final PersistentState persistentState;
private final DnsResolver dnsResolver;
@Inject
public Scheduler(HdfsFrameworkConfig frameworkConfig, LiveState liveState, PersistentState persistentState) {
this.frameworkConfig = frameworkConfig;
this.liveState = liveState;
this.persistentState = persistentState;
this.dnsResolver = new DnsResolver(this, frameworkConfig);
}
@Override
public void disconnected(SchedulerDriver driver) {
log.info("Scheduler driver disconnected");
}
@Override
public void error(SchedulerDriver driver, String message) {
log.error("Scheduler driver error: " + message);
}
@Override
public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
int status) {
log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " status=" + status);
}
@Override
public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
byte[] data) {
log.info("Framework message: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " data='" + Arrays.toString(data) + "'");
}
@Override
public void offerRescinded(SchedulerDriver driver, OfferID offerId) {
log.info("Offer rescinded: offerId=" + offerId.getValue());
}
@Override
public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) {
try {
persistentState.setFrameworkId(frameworkId);
} catch (InterruptedException | ExecutionException e) {
// these are zk exceptions... we are unable to maintain state.
final String msg = "Error setting framework id in persistent state";
log.error(msg, e);
throw new SchedulerException(msg);
}
log.info("Registered framework frameworkId=" + frameworkId.getValue());
// reconcile tasks upon registration
reconcileTasks(driver);
}
@Override
public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) {
log.info("Reregistered framework: starting task reconciliation");
// reconcile tasks upon reregistration
reconcileTasks(driver);
}
@Override
public void statusUpdate(SchedulerDriver driver, TaskStatus status) {
log.info(String.format(
"Received status update for taskId=%s state=%s message='%s' stagingTasks.size=%d",
status.getTaskId().getValue(),
status.getState().toString(),
status.getMessage(),
liveState.getStagingTasksSize()));
if (!isStagingState(status)) {
liveState.removeStagingTask(status.getTaskId());
}
if (isTerminalState(status)) {
liveState.removeRunningTask(status.getTaskId());
persistentState.removeTaskId(status.getTaskId().getValue());
// Correct the phase when a task dies after the reconcile period is over
if (!liveState.getCurrentAcquisitionPhase().equals(AcquisitionPhase.RECONCILING_TASKS)) {
correctCurrentPhase();
}
} else if (isRunningState(status)) {
liveState.updateTaskForStatus(status);
log.info(String.format("Current Acquisition Phase: %s", liveState
.getCurrentAcquisitionPhase().toString()));
switch (liveState.getCurrentAcquisitionPhase()) {
case RECONCILING_TASKS:
break;
case JOURNAL_NODES:
if (liveState.getJournalNodeSize() == frameworkConfig.getJournalNodeCount()) {
// TODO (elingg) move the reload to correctCurrentPhase and make it idempotent
reloadConfigsOnAllRunningTasks(driver);
correctCurrentPhase();
}
break;
case START_NAME_NODES:
if (liveState.getNameNodeSize() == (HDFSConstants.TOTAL_NAME_NODES)) {
// TODO (elingg) move the reload to correctCurrentPhase and make it idempotent
reloadConfigsOnAllRunningTasks(driver);
correctCurrentPhase();
}
break;
case FORMAT_NAME_NODES:
if (!liveState.isNameNode1Initialized()
&& !liveState.isNameNode2Initialized()) {
dnsResolver.sendMessageAfterNNResolvable(
driver,
liveState.getFirstNameNodeTaskId(),
liveState.getFirstNameNodeSlaveId(),
HDFSConstants.NAME_NODE_INIT_MESSAGE);
} else if (!liveState.isNameNode1Initialized()) {
dnsResolver.sendMessageAfterNNResolvable(
driver,
liveState.getFirstNameNodeTaskId(),
liveState.getFirstNameNodeSlaveId(),
HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE);
} else if (!liveState.isNameNode2Initialized()) {
dnsResolver.sendMessageAfterNNResolvable(
driver,
liveState.getSecondNameNodeTaskId(),
liveState.getSecondNameNodeSlaveId(),
HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE);
} else {
correctCurrentPhase();
}
break;
// TODO (elingg) add a configurable number of data nodes
case DATA_NODES:
break;
}
} else {
log.warn(String.format("Don't know how to handle state=%s for taskId=%s",
status.getState(), status.getTaskId().getValue()));
}
}
@Override
public void resourceOffers(SchedulerDriver driver, List<Offer> offers) {
log.info(String.format("Received %d offers", offers.size()));
// TODO (elingg) within each phase, accept offers based on the number of nodes you need
boolean acceptedOffer = false;
boolean journalNodesResolvable = false;
if (liveState.getCurrentAcquisitionPhase() == AcquisitionPhase.START_NAME_NODES) {
journalNodesResolvable = dnsResolver.journalNodesResolvable();
}
for (Offer offer : offers) {
if (acceptedOffer) {
driver.declineOffer(offer.getId());
} else {
switch (liveState.getCurrentAcquisitionPhase()) {
case RECONCILING_TASKS:
log.info("Declining offers while reconciling tasks");
driver.declineOffer(offer.getId());
break;
case JOURNAL_NODES:
if (tryToLaunchJournalNode(driver, offer)) {
acceptedOffer = true;
} else {
driver.declineOffer(offer.getId());
}
break;
case START_NAME_NODES:
if (journalNodesResolvable && tryToLaunchNameNode(driver, offer)) {
acceptedOffer = true;
} else {
driver.declineOffer(offer.getId());
}
break;
case FORMAT_NAME_NODES:
driver.declineOffer(offer.getId());
break;
case DATA_NODES:
if (tryToLaunchDataNode(driver, offer)) {
acceptedOffer = true;
} else {
driver.declineOffer(offer.getId());
}
break;
}
}
}
}
@Override
public void slaveLost(SchedulerDriver driver, SlaveID slaveId) {
log.info("Slave lost slaveId=" + slaveId.getValue());
}
@Override
public void run() {
FrameworkInfo.Builder frameworkInfo = FrameworkInfo.newBuilder()
.setName(frameworkConfig.getFrameworkName())
.setFailoverTimeout(frameworkConfig.getFailoverTimeout())
.setUser(frameworkConfig.getHdfsUser())
.setRole(frameworkConfig.getHdfsRole())
.setCheckpoint(true);
try {
FrameworkID frameworkID = persistentState.getFrameworkID();
if (frameworkID != null) {
frameworkInfo.setId(frameworkID);
}
} catch (InterruptedException | ExecutionException | InvalidProtocolBufferException e) {
final String msg = "Error recovering framework id";
log.error(msg, e);
throw new SchedulerException(msg);
}
MesosSchedulerDriver driver = new MesosSchedulerDriver(this, frameworkInfo.build(),
frameworkConfig.getMesosMasterUri());
driver.run();
}
private boolean launchNode(SchedulerDriver driver, Offer offer,
String nodeName, List<String> taskTypes, String executorName) {
// nodeName is the type of executor to launch
// executorName is to distinguish different types of nodes
// taskType is the type of task in mesos to launch on the node
// taskName is a name chosen to identify the task in mesos and mesos-dns (if used)
log.info(String.format("Launching node of type %s with tasks %s", nodeName,
taskTypes.toString()));
String taskIdName = String.format("%s.%s.%d", nodeName, executorName,
System.currentTimeMillis());
List<Resource> resources = getExecutorResources();
ExecutorInfo executorInfo = createExecutor(taskIdName, nodeName, executorName, resources);
List<TaskInfo> tasks = new ArrayList<>();
for (String taskType : taskTypes) {
List<Resource> taskResources = getTaskResources(taskType);
String taskName = getNextTaskName(taskType);
TaskID taskId = TaskID.newBuilder()
.setValue(String.format("task.%s.%s", taskType, taskIdName))
.build();
TaskInfo task = TaskInfo.newBuilder()
.setExecutor(executorInfo)
.setName(taskName)
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addAllResources(taskResources)
.setData(ByteString.copyFromUtf8(
String.format("bin/hdfs-mesos-%s", taskType)))
.build();
tasks.add(task);
liveState.addStagingTask(task.getTaskId());
persistentState.addHdfsNode(taskId, offer.getHostname(), taskType, taskName);
}
driver.launchTasks(Arrays.asList(offer.getId()), tasks);
return true;
}
private String getNextTaskName(String taskType) {
if (taskType.equals(HDFSConstants.NAME_NODE_ID)) {
Collection<String> nameNodeTaskNames = persistentState.getNameNodeTaskNames().values();
for (int i = 1; i <= HDFSConstants.TOTAL_NAME_NODES; i++) {
if (!nameNodeTaskNames.contains(HDFSConstants.NAME_NODE_ID + i)) {
return HDFSConstants.NAME_NODE_ID + i;
}
}
String errorStr = "Cluster is in inconsistent state. Trying to launch more namenodes, but they are all already running.";
log.error(errorStr);
throw new SchedulerException(errorStr);
}
if (taskType.equals(HDFSConstants.JOURNAL_NODE_ID)) {
Collection<String> journalNodeTaskNames = persistentState.getJournalNodeTaskNames().values();
for (int i = 1; i <= frameworkConfig.getJournalNodeCount(); i++) {
if (!journalNodeTaskNames.contains(HDFSConstants.JOURNAL_NODE_ID + i)) {
return HDFSConstants.JOURNAL_NODE_ID + i;
}
}
String errorStr = "Cluster is in inconsistent state. Trying to launch more journalnodes, but they all are already running.";
log.error(errorStr);
throw new SchedulerException(errorStr);
}
return taskType;
}
private ExecutorInfo createExecutor(String taskIdName, String nodeName, String executorName,
List<Resource> resources) {
int confServerPort = frameworkConfig.getConfigServerPort();
return ExecutorInfo
.newBuilder()
.setName(nodeName + " executor")
.setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build())
.addAllResources(resources)
.setCommand(
CommandInfo
.newBuilder()
.addAllUris(
Arrays.asList(
CommandInfo.URI
.newBuilder()
.setValue(
String.format("http://%s:%d/%s", frameworkConfig.getFrameworkHostAddress(),
confServerPort,
HDFSConstants.HDFS_BINARY_FILE_NAME))
.build(),
CommandInfo.URI
.newBuilder()
.setValue(
String.format("http://%s:%d/%s", frameworkConfig.getFrameworkHostAddress(),
confServerPort,
HDFSConstants.HDFS_CONFIG_FILE_NAME))
.build()))
.setEnvironment(Environment.newBuilder()
.addAllVariables(Arrays.asList(
Environment.Variable.newBuilder()
.setName("HADOOP_OPTS")
.setValue(frameworkConfig.getJvmOpts()).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue(String.format("%d", frameworkConfig.getHadoopHeapSize())).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_NAMENODE_OPTS")
.setValue("-Xmx" + frameworkConfig.getNameNodeHeapSize()
+ "m -Xms" + frameworkConfig.getNameNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("HADOOP_DATANODE_OPTS")
.setValue("-Xmx" + frameworkConfig.getDataNodeHeapSize()
+ "m -Xms" + frameworkConfig.getDataNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("EXECUTOR_OPTS")
.setValue("-Xmx" + frameworkConfig.getExecutorHeap()
+ "m -Xms" + frameworkConfig.getExecutorHeap() + "m").build())))
.setValue(
"env ; cd hdfs-mesos-* && "
+ "exec `if [ -z \"$JAVA_HOME\" ]; then echo java; "
+ "else echo $JAVA_HOME/bin/java; fi` "
+ "$HADOOP_OPTS "
+ "$EXECUTOR_OPTS "
|
package com.fsck.k9;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Folder.OpenMode;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.mail.store.LocalStore.PendingCommand;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable
{
private static final int MAX_SMALL_MESSAGE_SIZE = Store.FETCH_BODY_SANE_SUGGESTED_SIZE;
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newFixedThreadPool(5);
public enum SORT_TYPE
{
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending)
{
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending)
{
if (ascending)
{
return ascendingToast;
}
else
{
return descendingToast;
}
}
public boolean isDefaultAscending()
{
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
// Key is accountUuid:folderName , value is a long of the highest message UID ever emptied from Trash
private ConcurrentHashMap<String, Long> expungedUid = new ConcurrentHashMap<String, Long>();
private String createMessageKey(Account account, String folder, Message message)
{
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid)
{
return account.getUuid() + ":" + folder + ":" + uid;
}
private String createFolderKey(Account account, String folder)
{
return account.getUuid() + ":" + folder;
}
private void suppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
String messKey = createMessageKey(account, folder, message);
// Log.d(K9.LOG_TAG, "Suppressing message with key " + messKey);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
unsuppressMessage(account, folder, message.getUid());
}
private void unsuppressMessage(Account account, String folder, String uid)
{
if (account == null || folder == null || uid == null)
{
return;
}
String messKey = createMessageKey(account, folder, uid);
//Log.d(K9.LOG_TAG, "Unsuppressing message with key " + messKey);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return false;
}
String messKey = createMessageKey(account, folder, message);
//Log.d(K9.LOG_TAG, "Checking suppression of message with key " + messKey);
if (deletedUids.containsKey(messKey))
{
//Log.d(K9.LOG_TAG, "Message with key " + messKey + " is suppressed");
return true;
}
Long expungedUidL = expungedUid.get(createFolderKey(account, folder));
if (expungedUidL != null)
{
long expungedUid = expungedUidL;
String messageUidS = message.getUid();
try
{
long messageUid = Long.parseLong(messageUidS);
if (messageUid <= expungedUid)
{
return false;
}
}
catch (NumberFormatException nfe)
{
// Nothing to do
}
}
return false;
}
private MessagingController(Application application)
{
mApplication = application;
mThread = new Thread(this);
mThread.start();
if (memorizingListener != null)
{
addListener(memorizingListener);
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application)
{
if (inst == null)
{
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy()
{
return mBusy;
}
public void run()
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true)
{
String commandDescription = null;
try
{
Command command = mCommands.take();
if (command != null)
{
commandDescription = command.description;
String ground = (command.isForeground ? "Foreground" : "Background");
Log.i(K9.LOG_TAG, "Running " + ground + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
command.runnable.run();
Log.i(K9.LOG_TAG, ground + " Command '" + command.description + "' completed");
for (MessagingListener l : getListeners())
{
l.controllerCommandCompleted(mCommands.size() > 0);
}
if (command.listener != null && !getListeners().contains(command.listener))
{
command.listener.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground)
{
int retries = 10;
Exception e = null;
while (retries
{
try
{
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
}
catch (InterruptedException ie)
{
try
{
Thread.sleep(200);
}
catch (InterruptedException ne)
{
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener)
{
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener)
{
if (memorizingListener != null && listener != null)
{
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener)
{
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners()
{
return mListeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
for (MessagingListener l : getListeners())
{
l.listFoldersStarted(account);
}
if (listener != null)
{
listener.listFoldersStarted(account);
}
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder[] localFolders = localStore.getPersonalNamespaces();
if (refreshRemote || localFolders == null || localFolders.length == 0)
{
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners())
{
l.listFolders(account, localFolders);
}
if (listener != null)
{
listener.listFolders(account, localFolders);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, e.getMessage());
}
if (listener != null)
{
listener.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, e);
return;
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
if (listener != null)
{
listener.listFoldersFinished(account);
}
}
});
}
private void doRefreshRemote(final Account account, MessagingListener listener)
{
put("doRefreshRemote", listener, new Runnable()
{
public void run()
{
try
{
Store store = Store.getInstance(account.getStoreUri(), mApplication);
Folder[] remoteFolders = store.getPersonalNamespaces();
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.length; i < count; i++)
{
LocalFolder localFolder = localStore.getFolder(remoteFolders[i].getName());
if (!localFolder.exists())
{
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders[i].getName());
}
Folder[] localFolders = localStore.getPersonalNamespaces();
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders)
{
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(K9.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName()))
{
continue;
}
if (!remoteFolderNames.contains(localFolder.getName()))
{
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces();
for (MessagingListener l : getListeners())
{
l.listFolders(account, localFolders);
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, "");
}
addErrorMessage(account, e);
}
}
});
}
/**
* List the messages in the local message store for the given folder asynchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
listLocalMessagesSynchronous(account, folder, listener);
}
});
}
/**
* List the messages in the local message store for the given folder synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesStarted(account, folder);
}
Folder localFolder = null;
MessageRetrievalListener retrievalListener =
new MessageRetrievalListener()
{
List<Message> pendingMessages = new ArrayList<Message>();
int totalDone = 0;
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(account, folder, message) == false)
{
pendingMessages.add(message);
totalDone++;
if (pendingMessages.size() > 10)
{
addPendingMessages();
}
}
else
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesRemoveMessage(account, folder, message);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesRemoveMessage(account, folder, message);
}
}
}
public void messagesFinished(int number)
{
addPendingMessages();
}
private void addPendingMessages()
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
pendingMessages.clear();
}
};
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
localFolder.getMessages(
retrievalListener,
false // Skip deleted messages
);
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished");
}
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFinished(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener)
{
try
{
LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
synchronizeMailbox(account, folder, listener);
}
catch (MessagingException me)
{
addErrorMessage(account, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts)
{
for (Account account : accounts)
{
try
{
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e)
{
addErrorMessage(account, e);
Log.e(K9.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener)
{
putBackground("synchronizeMailbox", listener, new Runnable()
{
public void run()
{
synchronizeMailboxSynchronous(account, folder, listener);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
*/
public void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener)
{
/*
* We don't ever sync the Outbox.
*/
if (folder.equals(account.getOutboxFolderName()))
{
return;
}
if (account.getErrorFolderName().equals(folder))
{
return;
}
String debugLine = "Synchronizing folder " + account.getDescription() + ":" + folder;
Log.i(K9.LOG_TAG, debugLine);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxStarted(account, folder);
}
LocalFolder tLocalFolder = null;
Exception commandException = null;
try
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " +
account.getDescription());
}
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
}
final LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
tLocalFolder = (LocalFolder) localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages)
{
localUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: About to get remote store for " + folder);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
}
Folder remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName()))
{
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
}
remoteFolder.open(OpenMode.READ_WRITE);
if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy()))
{
Log.i(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
// final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " +
remoteMessageCount);
}
if (remoteMessageCount > 0)
{
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message thisMess : remoteMessageArray)
{
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
}
remoteMessageArray = null;
}
else if (remoteMessageCount < 0)
{
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store.
*/
for (Message localMessage : localMessages)
{
if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.X_DESTROYED, true);
// Log.d(K9.LOG_TAG, "Destroying message " + localMessage.getUid() + " which isn't in the most recent group on server");
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages);
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
remoteFolder.close();
localFolder.close();
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages + " new messages");
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
tLocalFolder.close();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
}
private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException
{
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount != -1)
{
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
return remoteUnreadMessageCount;
}
else
{
return localFolder.getMessageCount();
}
}
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded at all");
}
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is already locally present");
}
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
}
unsyncedMessages.add(message);
}
else
{
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
Log.i(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: About to sync " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
}
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (!message.isSet(Flag.SEEN))
{
if (account.isNotifySelfNewMail() || account.isAnIdentity(message.getFrom()) == false)
{
newMessages.incrementAndGet();
}
}
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE))
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
Log.i(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
Log.i(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
Log.i(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
}
progress.incrementAndGet();
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
Log.i(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
Log.i(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE)
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
}
// Update the listener with what we've found
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
Message localMessage = localFolder.getMessage(message.getUid());
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}//for large messsages
Log.i(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags())
{
Log.i(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(syncFlagMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (isMessageSuppressed(account, folder, localMessage) == false)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
if (localMessage.isSet(Flag.DELETED))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
Log.i(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException
{
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED))
{
return false;
}
if (remoteMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED })
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag))
{
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
}
while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command)
{
try
{
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localStore.addPendingCommand(command);
}
catch (Exception e)
{
addErrorMessage(account, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account)
{
putBackground("processPendingCommands", null, new Runnable()
{
public void run()
{
try
{
processPendingCommandsSynchronous(account);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException
{
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0)
{
return;
}
for (MessagingListener l : getListeners())
{
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands)
{
processingCommand = command;
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
}
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners())
{
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command))
{
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command))
{
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command))
{
processPendingSetFlagOld(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command))
{
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command))
{
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command))
{
processPendingMoveOrCopyOld(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command))
{
processPendingEmptyTrash(command, account);
}
else if (PENDING_COMMAND_EXPUNGE.equals(command.command))
{
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
}
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
addErrorMessage(account, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
finally
{
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
finally
{
for (MessagingListener l : getListeners())
{
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null)
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null)
{
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
localMessage
}
, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else
{
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate.compareTo(localDate) > 0)
{
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.DELETED, true);
}
else
{
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
remoteMessage.setFlag(Flag.DELETED, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[])
{
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
try
{
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
remoteSrcFolder = remoteStore.getFolder(srcFolder);
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteSrcFolder.getMessage(uid));
}
}
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
}
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
}
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName))
{
destFolderName = null;
}
remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName);
}
else
{
remoteDestFolder = remoteStore.getFolder(destFolder);
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy)
{
remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
}
if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
}
finally
{
if (remoteSrcFolder != null)
{
remoteSrcFolder.close();
}
if (remoteDestFolder != null)
{
remoteDestFolder.close();
}
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids)
{
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.size() == 0)
{
return;
}
remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
}
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null)
{
return;
}
remoteMessage.setFlag(flag, newState);
}
private void queueExpunge(final Account account, final String folderName)
{
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder );
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder );
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException
{
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null)
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
}
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
}
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy)
{
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException
{
String folder = command.arguments[0];
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners())
{
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, 0);
}
try
{
if (account.getErrorFolderName().equals(folder))
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true);
remoteFolder.close();
}
catch (UnsupportedOperationException uoe)
{
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally
{
localFolder.close();
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, Throwable t)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
String rootCauseMessage = getRootCauseMessage(t);
Log.e(K9.LOG_TAG, "Error " + "'" + rootCauseMessage + "'", t);
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
message.setBody(new TextBody(baos.toString()));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(rootCauseMessage);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, localFolder.getName(), localFolder.getUnreadMessageCount());
}
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(
final Account account,
final String folderName,
final Message[] messages,
final Flag flag,
final boolean newState)
{
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++)
{
uids[i] = messages[i].getUid();
}
setFlag(account, folderName, uids, flag, newState);
}
public void setFlag(
final Account account,
final String folderName,
final String[] uids,
final Flag flag,
final boolean newState)
{
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
Folder localFolder = null;
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = new Message[uids.length];
for (int i = 0; i < uids.length; i++)
{
String uid = uids[i];
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folderName))
{
sendCount.remove(uid);
}
messages[i] = localFolder.getMessage(uid);
}
localFolder.setFlags(messages, new Flag[] {flag}, newState);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount());
}
if (account.getErrorFolderName().equals(folderName))
{
return;
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, me);
throw new RuntimeException(me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}//setMesssageFlag
public void clearAllPending(final Account account)
{
try
{
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, me);
}
}
private void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener)
{
put("loadMessageForViewRemote", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
}
else
{
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// This is a view message request, so mark it read
if (!message.isSet(Flag.SEEN))
{
setFlag(account, localFolder.getName(), new Message[] { message }, Flag.SEEN, true);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, e);
}
finally
{
if (remoteFolder!=null)
{
remoteFolder.close();
}
if (localFolder!=null)
{
localFolder.close();
}
}//finally
}//run
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewStarted(account, folder, uid);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable()
{
public void run()
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
LocalMessage message = (LocalMessage)localFolder.getMessage(uid);
if (message==null
|| message.getId()==0)
{
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
loadMessageForViewRemote(account, folder, uid, listener);
localFolder.close();
return;
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
message
}, fp, null);
localFolder.close();
if (!message.isSet(Flag.SEEN))
{
setFlag(account, localFolder.getName(), new Message[] { message }, Flag.SEEN, true);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, e);
}
}
});
}
// public void loadMessageForViewSynchronous(final Account account, final String folder, final String uid,
// MessagingListener listener) {
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewStarted(account, folder, uid);
// LocalFolder localFolder = null;
// Folder remoteFolder = null;
// try {
// Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
// localFolder = (LocalFolder) localStore.getFolder(folder);
// localFolder.open(OpenMode.READ_WRITE);
// Message message = localFolder.getMessage(uid);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
// if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
// Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
// remoteFolder = remoteStore.getFolder(folder);
// remoteFolder.open(OpenMode.READ_WRITE);
// // Get the remote message and fully download it
// Message remoteMessage = remoteFolder.getMessage(uid);
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.BODY);
// remoteFolder.fetch(new Message[]{remoteMessage}, fp, null);
// // Store the message locally and load the stored message into memory
// localFolder.appendMessages(new Message[]{remoteMessage});
// message = localFolder.getMessage(uid);
// localFolder.fetch(new Message[]{message}, fp, null);
// // Mark that this message is now fully synched
// message.setFlag(Flag.X_DOWNLOADED_FULL, true);
// else {
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.ENVELOPE);
// fp.add(FetchProfile.Item.BODY);
// localFolder.fetch(new Message[]{
// message
// }, fp, null);
// if (!message.isSet(Flag.SEEN)) {
// markMessageRead(account, localFolder, message, true);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewBodyAvailable(account, folder, uid, message);
// if (listener != null) {
// listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewFinished(account, folder, uid, message);
// if (listener != null) {
// listener.loadMessageForViewFinished(account, folder, uid, message);
// catch (Exception e) {
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewFailed(account, folder, uid, e.getMessage());
// addErrorMessage(account, e);
// finally {
// if (localFolder!=null) {
// try {
// localFolder.close(false);
// catch (MessagingException e) {
// Log.w(K9.LOG_TAG, null, e);
// if (remoteFolder!=null) {
// try {
// remoteFolder.close(false);
// catch (MessagingException e) {
// Log.w(K9.LOG_TAG, null, e);
// }//loadMessageForViewSynchronous
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener)
{
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try
{
if (part.getBody() != null)
{
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, false);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me)
{
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, true);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
put("loadAttachment", listener, new Runnable()
{
public void run()
{
try
{
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments)
{
attachment.setBody(null);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(message.getFolder().getName());
Folder remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
FetchProfile fp = new FetchProfile();
fp.add(part);
remoteFolder.fetch(new Message[] { message }, fp, null);
localFolder.updateMessage((LocalMessage)message);
localFolder.close();
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me)
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "", me);
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
if (listener != null)
{
listener.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, me);
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener)
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, null);
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
// TODO general failed
}
addErrorMessage(account, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener)
{
putBackground("sendPendingMessages", listener, new Runnable()
{
public void run()
{
sendPendingMessagesSynchronous(account);
}
});
}
public boolean messagesPendingSend(final Account account)
{
try
{
Folder localFolder = null;
Store localStore = Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return false;
}
localFolder.open(OpenMode.READ_WRITE);
int localMessages = localFolder.getMessageCount();
localFolder.close();
if (localMessages > 0)
{
return true;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return;
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
int progress = 0;
int todo = localMessages.length;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account.getTransportUri());
for (Message message : localMessages)
{
if (message.isSet(Flag.DELETED))
{
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED))
{
Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try
{
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS)
{
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try
{
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
localSentFolder.getName(),
message.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e)
{
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
if (localFolder.getMessageCount() == 0)
{
localFolder.delete(false);
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent i = FolderList.actionHandleAccountIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void getAccountUnreadCount(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
int unreadMessageCount = 0;
try
{
unreadMessageCount = account.getUnreadMessageCount(context, mApplication);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
l.accountStatusChanged(account, unreadMessageCount);
}
};
put("getAccountUnread:" + account.getDescription(), l, unreadRunnable);
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
int unreadMessageCount = 0;
try
{
Folder localFolder = (Folder) Store.getInstance(account.getLocalStoreUri(), mApplication).getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public int moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
int messagesMoved = 0;
for (Message message : messages)
{
if (moveMessage(account, srcFolder, message, destFolder, listener))
{
messagesMoved++;
}
}
return messagesMoved;
}
public boolean moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
suppressMessage(account, srcFolder, message);
putBackground("moveMessage", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, false, listener);
}
});
return true;
}
else
{
return false;
}
}
public boolean isMoveCapable(Message message)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
return true;
}
else
{
return false;
}
}
public boolean isCopyCapable(Message message)
{
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public int copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
int messagesCopied = 0;
for (Message message : messages)
{
if (copyMessage(account, srcFolder, message, destFolder, listener))
{
messagesCopied++;
}
}
return messagesCopied;
}
public boolean copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
putBackground("copyMessage", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, true, listener);
}
});
return true;
}
else
{
return false;
}
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message message,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false))
{
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false))
{
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
Message lMessage = localSrcFolder.getMessage(message.getUid());
String origUid = message.getUid();
if (lMessage != null)
{
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", uid = " + origUid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy)
{
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(new Message[] { message }, fp, null);
localSrcFolder.copyMessages(new Message[] { message }, localDestFolder);
}
else
{
localSrcFolder.moveMessages(new Message[] { message }, localDestFolder);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, new String[] { origUid });
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener)
{
putBackground("expunge", null, new Runnable()
{
public void run()
{
queueExpunge(account, folder);
}
});
}
public void deleteMessages(final Account account, final String folder, final Message[] messages,
final MessagingListener listener)
{
for (Message message : messages)
{
suppressMessage(account, folder, message);
}
putBackground("deleteMessages", null, new Runnable()
{
public void run()
{
deleteMessagesSynchronous(account, folder, messages, listener);
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages,
MessagingListener listener)
{
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try
{
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages)
{
unsuppressMessage(account, folder, message);
if (listener != null)
{
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners())
{
l.messageDeleted(account, folder, message);
}
}
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = localStore.getFolder(folder);
if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
}
localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
else
{
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (localTrashFolder.exists() == false)
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists() == true)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
}
localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, account.getTrashFolderName(), localFolder.getUnreadMessageCount());
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
}
if (folder.equals(account.getOutboxFolderName()))
{
for (Message message : messages)
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
}
else
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (localTrashFolder != null)
{
localTrashFolder.close();
}
}
}
private String[] getUidsFromMessages(Message[] messages)
{
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++)
{
uids[i] = messages[i].getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException
{
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try
{
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
public void emptyTrash(final Account account, MessagingListener listener)
{
putBackground("emptyTrash", listener, new Runnable()
{
public void run()
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
localFolder.close();
for (MessagingListener l : getListeners())
{
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, e);
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
}
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
}
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null)
{
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null)
{
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener)
{
WakeLock twakeLock = null;
if (useManualWakeLock)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final WakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners())
{
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable()
{
public void run()
{
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null)
{
accounts = new Account[]
{
account
};
}
else
{
accounts = prefs.getAccounts();
}
for (final Account account : accounts)
{
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
continue;
}
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
putBackground("sendPending " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (messagesPendingSend(account))
{
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent intent = FolderList.actionHandleAccountIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
for (final Folder folder : localStore.getPersonalNamespaces())
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never sync a folder that isn't displayed
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
}
continue;
}
if (modeMismatch(aSyncMode, fSyncClass))
{
// Do not sync folders in the wrong class
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
}
continue;
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
}
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable()
{
public void run()
{
try
{
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder tLocalFolder = (LocalFolder) localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
return;
}
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent intent = FolderList.actionHandleAccountIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName(), listener);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, e);
}
}
}
);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, e);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, e);
}
putBackground("finalize sync", null, new Runnable()
{
public void run()
{
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null)
{
wakeLock.release();
}
for (MessagingListener l : getListeners())
{
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void notifyAccount(Context context, Account thisAccount, int newMailCount)
{
int unreadMessageCount = 0;
try
{
unreadMessageCount = thisAccount.getUnreadMessageCount(context, mApplication);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to get unread message count", e);
}
Log.i(K9.LOG_TAG, "notifyAccount Account " + thisAccount.getDescription() + ", newMailCount = " + newMailCount);
boolean isNotifyAccount = thisAccount.isNotifyNewMail();
if (isNotifyAccount)
{
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
if (newMailCount > 0 && unreadMessageCount > 0)
{
String notice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount,
thisAccount.getDescription());
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
context.getString(R.string.notification_new_title), System.currentTimeMillis());
notif.number = unreadMessageCount;
Intent i = FolderList.actionHandleAccountIntent(context, thisAccount);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_new_title), notice, pi);
String ringtone = thisAccount.getRingtone();
notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
if (thisAccount.isVibrate())
{
notif.defaults |= Notification.DEFAULT_VIBRATE;
}
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
notifMgr.notify(thisAccount.getAccountNumber(), notif);
}
else if (unreadMessageCount == 0)
{
notifMgr.cancel(thisAccount.getAccountNumber());
}
}
for (MessagingListener l : getListeners())
{
l.accountStatusChanged(thisAccount, unreadMessageCount);
}
}
public void saveDraft(final Account account, final Message message)
{
try
{
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[]
{
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, e);
}
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode)
{
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS))
{
return true;
}
else
{
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
class Command implements Comparable
{
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
public int compareTo(Object arg0)
{
if (arg0 instanceof Command)
{
Command other = (Command)arg0;
if (other.isForeground == true && isForeground == false)
{
return 1;
}
else if (other.isForeground == false && isForeground == true)
{
return -1;
}
else
{
return (sequence - other.sequence);
}
}
return 0;
}
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
public Collection<Pusher> getPushers()
{
return pushers.values();
}
public boolean setupPushing(final Account account)
{
try
{
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null)
{
previousPusher.stop();
}
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
for (final Folder folder : localStore.getPersonalNamespaces())
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never push a folder that isn't displayed
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
}
continue;
}
if (modeMismatch(aPushMode, fPushClass))
{
// Do not push folders in the wrong class
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
}
continue;
}
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (names.size() > 0)
{
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders)
{
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try
{
Store store = Store.getInstance(account.getStoreUri(), mApplication);
if (store.isPushCapable() == false)
{
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
Pusher oldPusher = null;
if (pusher != null)
{
oldPusher = pushers.putIfAbsent(account, pusher);
}
if (oldPusher != null)
{
pusher = oldPusher;
}
else
{
pusher.start(names);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
}
else
{
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing()
{
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext())
{
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly)
{
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder= (LocalFolder) localStore.getFolder(remoteFolder.getName());
localFolder.open(OpenMode.READ_WRITE);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size());
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount);
notifyAccount(mApplication, account, newCount);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
}
catch (Exception e)
{
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try
{
localFolder.setStatus(errorMessage);
}
catch (Exception se)
{
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to close localFolder", e);
}
}
latch.countDown();
}
}
});
try
{
latch.await();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
enum MemorizingState { STARTED, FINISHED, FAILED };
class Memory
{
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName)
{
account = nAccount;
folderName = nFolderName;
}
String getKey()
{
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName)
{
return taccount.getDescription() + ":" + tfolderName;
}
class MemorizingListener extends MessagingListener
{
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName)
{
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null)
{
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
public synchronized void synchronizeMailboxStarted(Account account, String folder)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other)
{
if (other != null)
{
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values())
{
if (memory.syncingState != null)
{
switch (memory.syncingState)
{
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null)
{
switch (memory.sendingState)
{
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null)
{
switch (memory.pushingState)
{
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
}
}
if (memory.processingState != null)
{
switch (memory.processingState)
{
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null)
{
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null)
{
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null)
{
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null)
{
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
}
else
{
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0)
{
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active)
{
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
public synchronized void sendPendingMessagesStarted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
public synchronized void sendPendingMessagesCompleted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
public synchronized void sendPendingMessagesFailed(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
public void synchronizeMailboxProgress(Account account, String folderName, int completed, int total)
{
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
public void pendingCommandsProcessing(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
public void pendingCommandsFinished(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
public void pendingCommandStarted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
public void pendingCommandCompleted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
}
|
package com.fsck.k9.preferences;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.fsck.k9.K9;
import com.fsck.k9.helper.Utility;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class Storage implements SharedPreferences {
private static ConcurrentHashMap<Context, Storage> storages =
new ConcurrentHashMap<Context, Storage>();
private volatile ConcurrentHashMap<String, String> storage = new ConcurrentHashMap<String, String>();
private CopyOnWriteArrayList<OnSharedPreferenceChangeListener> listeners =
new CopyOnWriteArrayList<OnSharedPreferenceChangeListener>();
private int DB_VERSION = 2;
private String DB_NAME = "preferences_storage";
private ThreadLocal<ConcurrentHashMap<String, String>> workingStorage
= new ThreadLocal<ConcurrentHashMap<String, String>>();
private ThreadLocal<SQLiteDatabase> workingDB =
new ThreadLocal<SQLiteDatabase>();
private ThreadLocal<ArrayList<String>> workingChangedKeys = new ThreadLocal<ArrayList<String>>();
private Context context = null;
private SQLiteDatabase openDB() {
SQLiteDatabase mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
if (mDb.getVersion() == 1) {
Log.i(K9.LOG_TAG, "Updating preferences to urlencoded username/password");
String accountUuids = readValue(mDb, "accountUuids");
if (accountUuids != null && accountUuids.length() != 0) {
String[] uuids = accountUuids.split(",");
for (String uuid : uuids) {
try {
String storeUriStr = Utility.base64Decode(readValue(mDb, uuid + ".storeUri"));
String transportUriStr = Utility.base64Decode(readValue(mDb, uuid + ".transportUri"));
URI uri = new URI(transportUriStr);
String newUserInfo = null;
if (transportUriStr != null) {
String[] userInfoParts = uri.getUserInfo().split(":");
String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8");
String passwordEnc = "";
String authType = "";
if (userInfoParts.length > 1) {
passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8");
}
if (userInfoParts.length > 2) {
authType = ":" + userInfoParts[2];
}
newUserInfo = usernameEnc + passwordEnc + authType;
}
if (newUserInfo != null) {
URI newUri = new URI(uri.getScheme(), newUserInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
String newTransportUriStr = Utility.base64Encode(newUri.toString());
writeValue(mDb, uuid + ".transportUri", newTransportUriStr);
}
uri = new URI(storeUriStr);
newUserInfo = null;
if (storeUriStr.startsWith("imap")) {
String[] userInfoParts = uri.getUserInfo().split(":");
if (userInfoParts.length == 2) {
String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8");
String passwordEnc = URLEncoder.encode(userInfoParts[1], "UTF-8");
newUserInfo = usernameEnc + ":" + passwordEnc;
} else {
String authType = userInfoParts[0];
String usernameEnc = URLEncoder.encode(userInfoParts[1], "UTF-8");
String passwordEnc = URLEncoder.encode(userInfoParts[2], "UTF-8");
newUserInfo = authType + ":" + usernameEnc + ":" + passwordEnc;
}
} else if (storeUriStr.startsWith("pop3")) {
String[] userInfoParts = uri.getUserInfo().split(":", 2);
String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8");
String passwordEnc = "";
if (userInfoParts.length > 1) {
passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8");
}
newUserInfo = usernameEnc + passwordEnc;
} else if (storeUriStr.startsWith("webdav")) {
String[] userInfoParts = uri.getUserInfo().split(":", 2);
String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8");
String passwordEnc = "";
if (userInfoParts.length > 1) {
passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8");
}
newUserInfo = usernameEnc + passwordEnc;
}
if (newUserInfo != null) {
URI newUri = new URI(uri.getScheme(), newUserInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
String newStoreUriStr = Utility.base64Encode(newUri.toString());
writeValue(mDb, uuid + ".storeUri", newStoreUriStr);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "ooops", e);
}
}
}
mDb.setVersion(DB_VERSION);
}
if (mDb.getVersion() != DB_VERSION) {
Log.i(K9.LOG_TAG, "Creating Storage database");
mDb.execSQL("DROP TABLE IF EXISTS preferences_storage");
mDb.execSQL("CREATE TABLE preferences_storage " +
"(primkey TEXT PRIMARY KEY ON CONFLICT REPLACE, value TEXT)");
mDb.setVersion(DB_VERSION);
}
return mDb;
}
public static Storage getStorage(Context context) {
Storage tmpStorage = storages.get(context);
if (tmpStorage != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Returning already existing Storage");
}
return tmpStorage;
} else {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Creating provisional storage");
}
tmpStorage = new Storage(context);
Storage oldStorage = storages.putIfAbsent(context, tmpStorage);
if (oldStorage != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Another thread beat us to creating the Storage, returning that one");
}
return oldStorage;
} else {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Returning the Storage we created");
}
return tmpStorage;
}
}
}
private void loadValues() {
long startTime = System.currentTimeMillis();
Log.i(K9.LOG_TAG, "Loading preferences from DB into Storage");
Cursor cursor = null;
SQLiteDatabase mDb = null;
try {
mDb = openDB();
cursor = mDb.rawQuery("SELECT primkey, value FROM preferences_storage", null);
while (cursor.moveToNext()) {
String key = cursor.getString(0);
String value = cursor.getString(1);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'");
}
storage.put(key, value);
}
} finally {
Utility.closeQuietly(cursor);
if (mDb != null) {
mDb.close();
}
long endTime = System.currentTimeMillis();
Log.i(K9.LOG_TAG, "Preferences load took " + (endTime - startTime) + "ms");
}
}
private Storage(Context context) {
this.context = context;
loadValues();
}
private void keyChange(String key) {
ArrayList<String> changedKeys = workingChangedKeys.get();
if (!changedKeys.contains(key)) {
changedKeys.add(key);
}
}
protected void put(String key, String value) {
ContentValues cv = generateCV(key, value);
workingDB.get().insert("preferences_storage", "primkey", cv);
liveUpdate(key, value);
}
protected void put(Map<String, String> insertables) {
String sql = "INSERT INTO preferences_storage (primkey, value) VALUES (?, ?)";
SQLiteStatement stmt = workingDB.get().compileStatement(sql);
for (Map.Entry<String, String> entry : insertables.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
stmt.bindString(1, key);
stmt.bindString(2, value);
stmt.execute();
stmt.clearBindings();
liveUpdate(key, value);
}
stmt.close();
}
private ContentValues generateCV(String key, String value) {
ContentValues cv = new ContentValues();
cv.put("primkey", key);
cv.put("value", value);
return cv;
}
private void liveUpdate(String key, String value) {
workingStorage.get().put(key, value);
keyChange(key);
}
protected void remove(String key) {
workingDB.get().delete("preferences_storage", "primkey = ?", new String[] { key });
workingStorage.get().remove(key);
keyChange(key);
}
protected void removeAll() {
for (String key : workingStorage.get().keySet()) {
keyChange(key);
}
workingDB.get().execSQL("DELETE FROM preferences_storage");
workingStorage.get().clear();
}
protected void doInTransaction(Runnable dbWork) {
ConcurrentHashMap<String, String> newStorage = new ConcurrentHashMap<String, String>();
newStorage.putAll(storage);
workingStorage.set(newStorage);
SQLiteDatabase mDb = openDB();
workingDB.set(mDb);
ArrayList<String> changedKeys = new ArrayList<String>();
workingChangedKeys.set(changedKeys);
mDb.beginTransaction();
try {
dbWork.run();
mDb.setTransactionSuccessful();
storage = newStorage;
for (String changedKey : changedKeys) {
for (OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(this, changedKey);
}
}
} finally {
workingDB.remove();
workingStorage.remove();
workingChangedKeys.remove();
mDb.endTransaction();
mDb.close();
}
}
public long size() {
return storage.size();
}
//@Override
public boolean contains(String key) {
return storage.contains(key);
}
//@Override
public com.fsck.k9.preferences.Editor edit() {
return new com.fsck.k9.preferences.Editor(this);
}
//@Override
public Map<String, String> getAll() {
return storage;
}
//@Override
public boolean getBoolean(String key, boolean defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
return Boolean.parseBoolean(val);
}
//@Override
public float getFloat(String key, float defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
try {
return Float.parseFloat(val);
} catch (NumberFormatException nfe) {
Log.e(K9.LOG_TAG, "Could not parse float", nfe);
return defValue;
}
}
//@Override
public int getInt(String key, int defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
try {
return Integer.parseInt(val);
} catch (NumberFormatException nfe) {
Log.e(K9.LOG_TAG, "Could not parse int", nfe);
return defValue;
}
}
//@Override
public long getLong(String key, long defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
try {
return Long.parseLong(val);
} catch (NumberFormatException nfe) {
Log.e(K9.LOG_TAG, "Could not parse long", nfe);
return defValue;
}
}
//@Override
public String getString(String key, String defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
return val;
}
//@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
listeners.addIfAbsent(listener);
}
//@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
listeners.remove(listener);
}
private String readValue(SQLiteDatabase mDb, String key) {
Cursor cursor = null;
String value = null;
try {
cursor = mDb.query(
"preferences_storage",
new String[] {"value"},
"primkey = ?",
new String[] {key},
null,
null,
null);
if (cursor.moveToNext()) {
value = cursor.getString(0);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'");
}
}
} finally {
Utility.closeQuietly(cursor);
}
return value;
}
private void writeValue(SQLiteDatabase mDb, String key, String value) {
ContentValues cv = new ContentValues();
cv.put("primkey", key);
cv.put("value", value);
long result = mDb.insert("preferences_storage", "primkey", cv);
if (result == -1) {
Log.e(K9.LOG_TAG, "Error writing key '" + key + "', value = '" + value + "'");
}
}
@Override
public Set<String> getStringSet(String arg0, Set<String> arg1) {
throw new RuntimeException("Not implemented");
}
}
|
package com.soundcloud.api;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CloudAPIIntegrationTest implements Params.Track, Endpoints {
static final String CLIENT_ID = "yH1Jv2C5fhIbZfGTpKtujQ";
static final String CLIENT_SECRET = "C6o8jc517b6PIw0RKtcfQsbOK3BjGpxWFLg977UiguY";
CloudAPI api;
/*
To get full HTTP logging, add the following system properties:
-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG
-Dorg.apache.commons.logging.simplelog.log.org.apache.http.wire=ERROR
*/
@Before
public void setUp() throws Exception {
api = new ApiWrapper(
CLIENT_ID,
CLIENT_SECRET,
null,
null,
Env.SANDBOX);
}
private Token login() throws IOException {
return login(null);
}
private Token login(String scope) throws IOException {
return api.login("api-testing", "testing", scope);
}
@Test
public void shouldUploadASimpleAudioFile() throws Exception {
login();
HttpResponse resp = api.post(Request.to(TRACKS).with(
TITLE, "Hello Android",
POST_TO_EMPTY, "")
.withFile(ASSET_DATA, new File(getClass().getResource("hello.aiff").getFile())));
int status = resp.getStatusLine().getStatusCode();
assertThat(status, is(201));
}
@Test
public void shouldUploadASimpleAudioFileBytes() throws Exception {
login();
File f = new File(getClass().getResource("hello.aiff").getFile());
ByteBuffer bb = ByteBuffer.allocate((int) f.length());
FileInputStream fis = new FileInputStream(f);
for (;;) if (fis.getChannel().read(bb) <= 0) break;
HttpResponse resp = api.post(Request.to(TRACKS).with(
TITLE, "Hello Android",
POST_TO_EMPTY, "")
.withFile(ASSET_DATA, bb, "hello.aiff"));
int status = resp.getStatusLine().getStatusCode();
assertThat(status, is(201));
}
@Test(expected = IOException.class)
public void shouldNotGetASignupTokenWhenInofficialApp() throws Exception {
login();
api.clientCredentials();
}
@Test
public void shouldReturn401WithInvalidToken() throws Exception {
login();
api.setToken(new Token("invalid", "invalid"));
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(401));
}
@Test
public void shouldRefreshAutomaticallyWhenTokenExpired() throws Exception {
login();
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(200));
final Token oldToken = api.getToken();
assertThat(api.invalidateToken(), is(nullValue()));
resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(200));
// make sure we've got a new token
assertThat(oldToken, not(equalTo(api.getToken())));
}
@Test
public void shouldResolveUrls() throws Exception {
login();
long id = api.resolve("http://sandbox-soundcloud.com/api-testing");
assertThat(id, is(1862213L));
}
@Test
public void shouldResolveStreamUrls() throws Exception {
login();
String resolved = api.resolveStreamUrl("https://api.sandbox-soundcloud.com/tracks/2100832/stream");
assertThat(resolved, not(nullValue()));
assertThat(resolved, containsString("http://ak-media.soundcloud.com/"));
}
@Test
public void shouldSupportRangeRequest() throws Exception {
login();
String resolved = api.resolveStreamUrl("https://api.sandbox-soundcloud.com/tracks/2100832/stream");
assertThat(resolved, not(nullValue()));
HttpResponse resp = api
.getHttpClient()
.execute(Request.to(resolved).range(50, 100).buildRequest(HttpGet.class));
assertThat(resp.getStatusLine().toString(), resp.getStatusLine().getStatusCode(), is(206));
Header range = resp.getFirstHeader("Content-Range");
assertThat(range, notNullValue());
assertThat(range.getValue(), equalTo("bytes 50-100/19643"));
assertThat(resp.getEntity().getContentLength(), is(51L));
}
@Test
public void readMyDetails() throws Exception {
login();
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(200));
assertThat(
resp.getFirstHeader("Content-Type").getValue(),
containsString("application/json"));
JSONObject me = Http.getJSON(resp);
assertThat(me.getString("username"), equalTo("api-testing"));
// writeResponse(resp, "me.json");
}
@Test
public void shouldLoginWithNonExpiringScope() throws Exception {
Token token = login(Token.SCOPE_NON_EXPIRING);
assertThat(token.scoped(Token.SCOPE_NON_EXPIRING), is(true));
assertThat(token.refresh, is(nullValue()));
assertThat(token.getExpiresIn(), is(nullValue()));
assertThat(token.valid(), is(true));
// make sure we can issue a request with this token
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(200));
}
@Test
public void shouldNotRefreshWithNonExpiringScope() throws Exception {
Token token = login(Token.SCOPE_NON_EXPIRING);
assertThat(token.scoped(Token.SCOPE_NON_EXPIRING), is(true));
assertThat(api.invalidateToken(), is(nullValue()));
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(401));
}
@Test
public void shouldChangeContentType() throws Exception {
login();
api.setDefaultContentType("application/xml");
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(
resp.getFirstHeader("Content-Type").getValue(),
containsString("application/xml"));
}
@Test
public void shouldSupportConditionalGets() throws Exception {
login();
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
assertThat(resp.getStatusLine().getStatusCode(), is(200) );
String etag = Http.etag(resp);
assertNotNull(etag);
resp = api.get(Request.to(Endpoints.MY_DETAILS).ifNoneMatch(etag));
assertThat(resp.getStatusLine().getStatusCode(), is(304) /* not-modified */);
}
@Test @Ignore
public void shouldSupportConcurrentConnectionsToApiHost() throws Exception {
login();
int num = 20;
final CyclicBarrier start = new CyclicBarrier(num, new Runnable() {
@Override
public void run() {
System.err.println("starting...");
}
});
final CyclicBarrier end = new CyclicBarrier(num);
while (num
new Thread("t-"+num) {
@Override public void run() {
try {
start.await();
System.err.println("running: "+toString());
try {
HttpResponse resp = api.get(Request.to(Endpoints.MY_DETAILS));
resp.getEntity().consumeContent();
assertThat(resp.getStatusLine().getStatusCode(), is(200));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
System.err.println("finished: "+toString());
end.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
}.start();
}
start.await();
end.await();
System.err.println("all threads finished");
}
@Test @Ignore
public void updateMyDetails() throws Exception {
Request updateMe = Request.to(MY_DETAILS).with(
Params.User.WEBSITE, "http://mywebsite.com")
.withFile(Params.User.AVATAR, new File(getClass().getResource("cat.jpg").getFile()));
HttpResponse resp = api.put(updateMe);
assertThat(resp.getStatusLine().getStatusCode(), is(200));
}
@SuppressWarnings({"UnusedDeclaration"})
private void writeResponse(HttpResponse resp, String file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
InputStream is = resp.getEntity().getContent();
byte[] b = new byte[8192];
int n;
while ((n = is.read(b)) >= 0) fos.write(b, 0, n);
is.close();
fos.close();
}
}
|
package com.googlecode.ant_deb_task;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.Tar;
import org.apache.tools.ant.types.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.security.MessageDigest;
/**
* Task that creates a Debian package.
*
* @antTaskName deb
*/
public class Deb extends Task
{
private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+");
public static class Description extends ProjectComponent
{
private String _synopsis;
private String _extended = "";
public String getSynopsis ()
{
return _synopsis;
}
public void setSynopsis (String synopsis)
{
_synopsis = synopsis.trim ();
}
public void addText (String text)
{
_extended += getProject ().replaceProperties (text);
}
public String getExtended ()
{
return _extended;
}
public String getExtendedFormatted ()
{
StringBuffer buffer = new StringBuffer (_extended.length ());
String lines[] = _extended.split ("\n");
int start = 0;
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
start++;
}
int end = lines.length;
for (int i = lines.length - 1; i >= 0; i
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
end
}
for (int i = start; i < end; i++)
{
String line = lines[i].trim ();
buffer.append (' ');
buffer.append (line.length () == 0 ? "." : line);
buffer.append ('\n');
}
buffer.deleteCharAt (buffer.length () - 1);
return buffer.toString ();
}
}
public static class Version extends ProjectComponent
{
private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9+\\-.:]*");
private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+\\-]+");
private int _epoch = 0;
private String _upstream;
private String _debian = "1";
public void setEpoch(int epoch)
{
_epoch = epoch;
}
public void setUpstream(String upstream)
{
_upstream = upstream.trim ();
if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ())
throw new BuildException("Invalid upstream version number!");
}
public void setDebian(String debian)
{
_debian = debian.trim ();
if (!DEBIAN_VERSION_PATTERN.matcher (_debian).matches ())
throw new BuildException("Invalid debian version number!");
}
public String toString()
{
StringBuffer version = new StringBuffer();
if (_epoch > 0)
{
version.append(_epoch);
version.append(':');
}
else if (_upstream.indexOf(':') > -1)
throw new BuildException("Upstream version can contain colons only if epoch is specified!");
version.append(_upstream);
if (_debian.length() > 0)
{
version.append('-');
version.append(_debian);
}
else if (_upstream.indexOf('-') > -1)
throw new BuildException("Upstream version can contain hyphens only if debian version is specified!");
return version.toString();
}
}
public static class Maintainer extends ProjectComponent
{
private String _name;
private String _email;
public void setName (String name)
{
_name = name.trim ();
}
public void setEmail (String email)
{
_email = email.trim ();
}
public String toString()
{
if (_name == null || _name.length () == 0)
return _email;
StringBuffer buffer = new StringBuffer (_name);
buffer.append (" <");
buffer.append (_email);
buffer.append (">");
return buffer.toString ();
}
}
public static class Section extends EnumeratedAttribute
{
private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"};
private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"};
private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length);
public Section ()
{
for (int i = 0; i < PREFIXES.length; i++)
{
String prefix = PREFIXES[i];
for (int j = 0; j < BASIC_SECTIONS.length; j++)
{
String basicSection = BASIC_SECTIONS[j];
sections.add (prefix + basicSection);
}
}
}
public String[] getValues ()
{
return (String[]) sections.toArray (new String[]{});
}
}
public static class Priority extends EnumeratedAttribute
{
public String[] getValues ()
{
return new String[] {"required", "important", "standard", "optional", "extra"};
}
}
private File _toDir;
private String _package;
private String _version;
private Deb.Version _versionObj;
private String _section;
private String _priority = "extra";
private String _architecture = "all";
private String _depends;
private String _preDepends;
private String _recommends;
private String _suggests;
private String _enhances;
private String _conflicts;
private String _maintainer;
private Deb.Maintainer _maintainerObj;
private Deb.Description _description;
private Set _conffiles = new HashSet ();
private List _data = new ArrayList();
private File _preinst;
private File _postinst;
private File _prerm;
private File _postrm;
private File _config;
private File _templates;
private File _tempFolder;
private long _installedSize = 0;
private SortedSet _dataFolders;
private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod ();
private static final Tar.TarLongFileMode GNU_LONGFILE_MODE = new Tar.TarLongFileMode ();
static
{
GZIP_COMPRESSION_METHOD.setValue ("gzip");
GNU_LONGFILE_MODE.setValue(Tar.TarLongFileMode.GNU);
}
public void setToDir (File toDir)
{
_toDir = toDir;
}
public void setPackage (String packageName)
{
if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches())
throw new BuildException("Invalid package name!");
_package = packageName;
}
public void setVersion (String version)
{
_version = version;
}
public void setSection (Section section)
{
_section = section.getValue();
}
public void setPriority (Priority priority)
{
_priority = priority.getValue();
}
public void setArchitecture (String architecture)
{
_architecture = architecture;
}
public void setDepends (String depends)
{
_depends = depends;
}
public void setPreDepends (String preDepends)
{
_preDepends = preDepends;
}
public void setRecommends (String recommends)
{
_recommends = recommends;
}
public void setSuggests (String suggests)
{
_suggests = suggests;
}
public void setEnhances (String enhances)
{
_enhances = enhances;
}
public void setConflicts (String conflicts)
{
_conflicts = conflicts;
}
public void setMaintainer (String maintainer)
{
_maintainer = maintainer;
}
public void setPreinst (File preinst)
{
_preinst = preinst;
}
public void setPostinst (File postinst)
{
_postinst = postinst;
}
public void setPrerm (File prerm)
{
_prerm = prerm;
}
public void setPostrm (File postrm)
{
_postrm = postrm;
}
public void setConfig (File config)
{
_config = config;
}
public void setTemplates (File templates)
{
_templates = templates;
}
public void addConfFiles (TarFileSet conffiles)
{
_conffiles.add (conffiles);
_data.add (conffiles);
}
public void addDescription (Deb.Description description)
{
_description = description;
}
public void add (TarFileSet resourceCollection)
{
_data.add(resourceCollection);
}
public void addVersion(Deb.Version version)
{
_versionObj = version;
}
public void addMaintainer(Deb.Maintainer maintainer)
{
_maintainerObj = maintainer;
}
private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException
{
log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE);
PrintWriter control = new UnixPrintWriter (controlFile);
control.print ("Package: ");
control.println (_package);
control.print ("Version: ");
control.println (_version);
if (_section != null)
{
control.print ("Section: ");
control.println (_section);
}
if (_priority != null)
{
control.print ("Priority: ");
control.println (_priority);
}
control.print ("Architecture: ");
control.println (_architecture);
if (_depends != null)
{
control.print ("Depends: ");
control.println (_depends);
}
if (_preDepends != null)
{
control.print ("Pre-Depends: ");
control.println (_preDepends);
}
if (_recommends != null)
{
control.print ("Recommends: ");
control.println (_recommends);
}
if (_suggests != null)
{
control.print ("Suggests: ");
control.println (_suggests);
}
if (_enhances != null)
{
control.print ("Enhances: ");
control.println (_enhances);
}
if (_conflicts != null)
{
control.print ("Conflicts: ");
control.println (_conflicts);
}
if (installedSize > 0)
{
control.print ("Installed-Size: ");
control.println (installedSize / 1024L);
}
control.print ("Maintainer: ");
control.println (_maintainer);
control.print ("Description: ");
control.println (_description.getSynopsis ());
control.println (_description.getExtendedFormatted ());
control.close ();
}
private File createMasterControlFile () throws IOException
{
File controlFile = new File (_tempFolder, "control");
writeControlFile (controlFile, _installedSize);
File md5sumsFile = new File (_tempFolder, "md5sums");
File conffilesFile = new File (_tempFolder, "conffiles");
File masterControlFile = new File (_tempFolder, "control.tar.gz");
Tar controlTar = new Tar ();
controlTar.setProject (getProject ());
controlTar.setTaskName (getTaskName ());
controlTar.setDestFile (masterControlFile);
controlTar.setCompression (GZIP_COMPRESSION_METHOD);
addFileToTar (controlTar, controlFile, "control", "644");
addFileToTar (controlTar, md5sumsFile, "md5sums", "644");
if (conffilesFile.length () > 0)
addFileToTar (controlTar, conffilesFile, "conffiles", "644");
if (_preinst != null)
addFileToTar (controlTar, _preinst, "preinst", "755");
if (_postinst != null)
addFileToTar (controlTar, _postinst, "postinst", "755");
if (_prerm != null)
addFileToTar (controlTar, _prerm, "prerm", "755");
if (_postrm != null)
addFileToTar (controlTar, _postrm, "postrm", "755");
if (_config != null)
addFileToTar (controlTar, _config, "config", "755");
if (_templates != null)
addFileToTar (controlTar, _templates, "templates", "644");
controlTar.perform ();
controlFile.delete ();
return masterControlFile;
}
private void addFileToTar(Tar tar, File file, String fullpath, String fileMode)
{
TarFileSet controlFileSet = tar.createTarFileSet ();
controlFileSet.setFile (file);
controlFileSet.setFullpath (fullpath);
controlFileSet.setFileMode (fileMode);
controlFileSet.setUserName ("root");
controlFileSet.setGroup ("root");
}
public void execute () throws BuildException
{
try
{
if (_versionObj != null)
_version = _versionObj.toString ();
if (_maintainerObj != null)
_maintainer = _maintainerObj.toString ();
_tempFolder = createTempFolder();
scanData ();
File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb");
File dataFile = createDataFile ();
File masterControlFile = createMasterControlFile ();
log ("Writing deb file to: " + debFile.getAbsolutePath());
BuildDeb.buildDeb (debFile, masterControlFile, dataFile);
masterControlFile.delete ();
dataFile.delete ();
}
catch (IOException e)
{
throw new BuildException (e);
}
}
private File createDataFile () throws IOException
{
File dataFile = new File (_tempFolder, "data.tar.gz");
Tar dataTar = new Tar ();
dataTar.setProject (getProject ());
dataTar.setTaskName (getTaskName ());
dataTar.setDestFile (dataFile);
dataTar.setCompression (GZIP_COMPRESSION_METHOD);
dataTar.setLongfile(GNU_LONGFILE_MODE);
// add folders
for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();)
{
String targetFolder = (String) dataFoldersIter.next ();
TarFileSet targetFolderSet = dataTar.createTarFileSet ();
targetFolderSet.setFile (_tempFolder);
targetFolderSet.setFullpath (targetFolder);
targetFolderSet.setUserName ("root");
targetFolderSet.setGroup ("root");
}
// add actual data
for (int i = 0; i < _data.size (); i++) {
TarFileSet data = (TarFileSet) _data.get (i);
data.setUserName ("root");
data.setGroup ("root");
dataTar.add (data);
}
dataTar.execute ();
return dataFile;
}
private File createTempFolder() throws IOException
{
File tempFile = File.createTempFile ("deb", ".dir");
String tempFolderName = tempFile.getAbsolutePath ();
tempFile.delete ();
tempFile = new File (tempFolderName, "removeme");
tempFile.mkdirs ();
tempFile.delete ();
log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE);
return new File (tempFolderName);
}
private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums"));
PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles"));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (prefix.length () > 0 && !prefix.endsWith ("/"))
prefix += '/';
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.replace (File.separatorChar, '/'));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile () ;
while (parentFolder != null)
{
String parentFolderPath = parentFolder.getPath ().replace(File.separatorChar, '/');
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
// write conffiles
if (_conffiles.contains (fileset))
conffiles.println (targetName);
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
conffiles.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
private String[] getFileNames(FileSet fs)
{
DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
String[] directories = ds.getIncludedDirectories();
String[] filesPerSe = ds.getIncludedFiles();
String[] files = new String [directories.length + filesPerSe.length];
System.arraycopy(directories, 0, files, 0, directories.length);
System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length);
return files;
}
private String getFileMd5(File file)
{
try
{
MessageDigest md5 = MessageDigest.getInstance ("MD5");
FileInputStream inputStream = new FileInputStream (file);
byte[] buffer = new byte[1024];
while (true)
{
int read = inputStream.read (buffer);
if (read == -1)
break;
md5.update (buffer, 0, read);
}
byte[] md5Bytes = md5.digest ();
StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2);
for (int i = 0; i < md5Bytes.length; i++)
{
String hex = Integer.toHexString (md5Bytes[i] & 0x00ff);
if (hex.length () == 1)
md5Buffer.append ('0');
md5Buffer.append (hex);
}
return md5Buffer.toString ();
}
catch (Exception e)
{
throw new BuildException(e);
}
}
}
|
package de.micromata.jira.rest;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import org.junit.*;
import de.micromata.jira.rest.domain.TransitionBean;
import de.micromata.jira.rest.util.RestException;
@Ignore
public class TestIssueTransition {
private static JiraRestClient jiraRestClient;
private static RestWrapper restWrapper;
private static final String ISSUE_KEY = "DEMO-1";
private static Map<Integer, TransitionBean> currentIssueTransitions;
public static void main(String[] args) throws URISyntaxException, RestException {
URI uri = new URI("http://localhost:2990/jira");
String username = "admin";
String password = "admin";
jiraRestClient = new JiraRestClient(uri, username, password);
restWrapper = new RestWrapperImpl();
initAvailableTransitionStates();
testTransitionCloseToReopen();
// testTransitionOpenToClose();
// testTransitionOpenToStart();
// testTransitionStartToStop();
// testTransitionOpenToResolve();
// testTransitionResolveToClose();
showAvailableTransitionStates();
}
public static void initAvailableTransitionStates() throws RestException {
currentIssueTransitions = restWrapper.getIssueTransitionsByKey(jiraRestClient, ISSUE_KEY);
System.out.println("
System.out.println("Mögliche Transitions für das Issue: " + ISSUE_KEY);
System.out.println("
System.out.println("
for (int id : currentIssueTransitions.keySet()) {
TransitionBean tb = currentIssueTransitions.get(id);
System.out.println("Transition ID: " + id + " Name: " + tb.getName() + " Assignee: " + tb.isAssigneeRequired());
}
System.out.println("
}
public static void showAvailableTransitionStates() throws RestException {
currentIssueTransitions = restWrapper.getIssueTransitionsByKey(jiraRestClient, ISSUE_KEY);
System.out.println("
System.out.println("Mögliche Transitions für den nächsten Test:\n");
for (int id : currentIssueTransitions.keySet()) {
TransitionBean tb = currentIssueTransitions.get(id);
System.out.println("Transition ID: " + id + " Name: " + tb.getName() + " Assignee: " + tb.isAssigneeRequired());
}
System.out.println("
}
public static void testTransitionCloseToReopen() throws RestException {
int transitionId = 3;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") reopened: " + update);
}
public static void testTransitionOpenToClose() throws RestException {
int transitionId = 2;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") closed: " + update);
}
public static void testTransitionOpenToStart() throws RestException {
int transitionId = 4;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") started: " + update);
}
public static void testTransitionStartToStop() throws RestException {
int transitionId = 301;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") stoped: " + update);
}
public static void testTransitionOpenToResolve() throws RestException {
int transitionId = 5;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") resolved: " + update);
}
public static void testTransitionResolveToClose() throws RestException {
int transitionId = 701;
boolean update = restWrapper.updateIssueTransitionByKey(jiraRestClient, ISSUE_KEY, transitionId);
assertTrue(update);
System.out.println("Transition (ID=" + transitionId + ") closed: " + update);
}
}
|
package ch.uzh.csg.reimbursement.service;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import ch.uzh.csg.reimbursement.dto.ExpenseDto;
import ch.uzh.csg.reimbursement.model.Expense;
import ch.uzh.csg.reimbursement.model.User;
import ch.uzh.csg.reimbursement.repository.ExpenseRepositoryProvider;
@RunWith(MockitoJUnitRunner.class)
public class ExpenseServiceTest {
@InjectMocks
private ExpenseService service;
@Mock
private ExpenseRepositoryProvider repository;
@Mock
private UserService userService;
@Captor
private ArgumentCaptor<Expense> argumentCaptorExpense;
@Test
public void testCreateExpense() {
// given
ExpenseDto dto = mock(ExpenseDto.class);
given(dto.getBookingText()).willReturn("Booking Text");
User user = mock(User.class);
given(userService.getLoggedInUser()).willReturn(user);
// when
service.create(dto);
// then
verify(repository).create(argumentCaptorExpense.capture());
Expense expense = argumentCaptorExpense.getValue();
assertThat(expense.getBookingText(), is(equalTo(dto.getBookingText())));
assertThat(expense.getUser(), is(equalTo(user)));
}
@Test
public void testFindAllByUser() {
// given
String uid = "user-uid";
Set<Expense> expenseSet = new HashSet<Expense>();
given(repository.findAllByUser(uid)).willReturn(expenseSet);
// when
Set<Expense> returningExpenseSet = repository.findAllByUser(uid);
// then
verify(repository).findAllByUser(uid);
assertThat(returningExpenseSet, is(equalTo(expenseSet)));
}
@Test
public void testFindByUid() {
// given
String uid = "expense-uid";
Expense expense = mock(Expense.class);
given(repository.findByUid(uid)).willReturn(expense);
// when
Expense returningExpense = service.findByUid(uid);
// then
verify(repository).findByUid(uid);
assertThat(returningExpense, is(equalTo(expense)));
}
}
|
package com.icecondor.eaglet.api;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import org.json.JSONObject;
import android.os.Handler;
import android.util.Log;
import com.icecondor.eaglet.Constants;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpGet;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.http.WebSocket;
public class Client implements ConnectCallbacks {
private final URI apiUrl;
private final AsyncHttpClient client;
private final ClientActions actions;
private boolean reconnect = true;
private static final int RECONNECT_WAIT_MS = 5000;
private int reconnects = 0;
private final Handler handler;
private boolean connecting; // Connected / Connecting
private Future<WebSocket> websocketFuture;
private WebSocket websocket;
public Client(String serverURL, ClientActions actions) throws URISyntaxException {
this.apiUrl = new URI(serverURL);
this.actions = actions;
handler = new Handler();
this.client = AsyncHttpClient.getDefaultInstance();
KoushiSocket.disableSSLCheck(client);
}
public void connect() {
if(connecting == false) {
connecting = true;
actions.onConnecting(apiUrl);
// AndroidSync quirk, uses http urls
String httpQuirkUrl = apiUrl.toString().replace("ws:
AsyncHttpRequest get = new AsyncHttpGet(httpQuirkUrl);
get.setTimeout(2500);
websocketFuture = client.websocket(get, null, new KoushiSocket(this));
} else {
Log.d(Constants.APP_TAG, "client: ignoring connect(). connecting in progress.");
}
}
public void startPersistentConnect() {
reconnect = true;
doConnect();
}
public boolean getConnecting() {
return connecting;
}
@Override
public void onTimeout() {
connecting = false;
actions.onTimeout();
if(reconnect) {
reconnects += 1;
long waitMillis = exponentialBackoffTime(reconnects);
Log.d(Constants.APP_TAG, "api.Client connect: onTimeout. reconnects = "+reconnects+". next try "+(waitMillis/1000)+"s.");
handler.postDelayed(new Runnable() {
@Override
public void run() {
doConnect();
}
}, waitMillis);
}
}
private long exponentialBackoffTime(int reconnects) {
return (long)Math.pow(RECONNECT_WAIT_MS/1000,reconnects);
}
private void doConnect() {
connect();
}
/* ConnectCallbacks */
@Override
public void onMessage(JSONObject msg) {
Log.d(Constants.APP_TAG, "Client onMessage: "+msg);
}
@Override
public void onConnected() {
Log.d(Constants.APP_TAG, "Client onConnected.");
try {
websocket = websocketFuture.get();
connecting = false;
reconnects = 0;
actions.onConnected();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@Override
public void onDisconnected() {
Log.d(Constants.APP_TAG, "Client onDisconnected.");
connecting = false;
reconnects = 0;
actions.onDisconnected();
doConnect();
}
/* API Calls */
public void accountCheck(String email) {
websocket.send("{1:2}");
}
}
|
package com.cloudmine.api.integration;
import com.cloudmine.api.CMFile;
import com.cloudmine.api.rest.CMFileMetaData;
import com.cloudmine.api.rest.CMStore;
import com.cloudmine.api.rest.callbacks.CMObjectResponseCallback;
import com.cloudmine.api.rest.callbacks.FileCreationResponseCallback;
import com.cloudmine.api.rest.response.CMObjectResponse;
import com.cloudmine.api.rest.response.FileCreationResponse;
import com.cloudmine.test.ServiceTestBase;
import org.junit.Ignore;
import org.junit.Test;
import static com.cloudmine.test.AsyncTestResultsCoordinator.waitThenAssertTestResults;
import static com.cloudmine.test.TestServiceCallback.testCallback;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class CMFileIntegrationTest extends ServiceTestBase {
@Test
@Ignore //this should be updated to not use the store, but no one uses file metadata anyway
public void testLoadFileMetaData() {
final CMFile file = new CMFile(getObjectInputStream(), "application/oop");
file.save(testCallback(new FileCreationResponseCallback() {
public void onCompletion(FileCreationResponse response) {
assertTrue(response.wasSuccess());
}
}));
waitThenAssertTestResults();
assertEquals(0, CMStore.getStore().getStoredObjects().size());
CMStore.getStore().loadApplicationFileMetaData(file.getFileId(),
testCallback(new CMObjectResponseCallback() {
public void onCompletion(CMObjectResponse response) {
assertTrue(response.wasSuccess());
int returned = 0;
for(CMFileMetaData data : response.getObjects(CMFileMetaData.class)) {
assertEquals("application/oop", data.getContentType());
assertEquals(file.getFileId(), data.getFilename());
returned++;
}
assertEquals(1, returned);
}
}));
waitThenAssertTestResults();
assertEquals(1, CMStore.getStore().getStoredObjects().size());
}
}
|
package fr.ens.transcriptome.nividic.om;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.List;
import junit.framework.TestCase;
import fr.ens.transcriptome.nividic.om.design.Design;
import fr.ens.transcriptome.nividic.om.design.DesignFactory;
import fr.ens.transcriptome.nividic.om.design.Slide;
import fr.ens.transcriptome.nividic.om.design.SlideDescription;
import fr.ens.transcriptome.nividic.om.design.io.DesignWriter;
import fr.ens.transcriptome.nividic.om.design.io.GoulpharDesignReader;
import fr.ens.transcriptome.nividic.om.design.io.LimmaDesignReader;
import fr.ens.transcriptome.nividic.om.design.io.LimmaDesignWriter;
import fr.ens.transcriptome.nividic.om.io.NividicIOException;
import fr.ens.transcriptome.nividic.om.samples.Samples;
public class DesignTest extends TestCase {
private Design createDesign() {
return DesignFactory.create2ColorsDesign();
}
public void testRead1() throws NividicIOException {
InputStream is =
this.getClass().getResourceAsStream("/files/SwirlSample.txt");
LimmaDesignReader ldr = new LimmaDesignReader(is);
Design d = ldr.read();
Slide s = d.getSlide(0);
// System.out.println("id: " + s.getName());
// System.out.println("s/n: "+s.getDescription().getSerialNumber());
ByteArrayOutputStream os = new ByteArrayOutputStream();
DesignWriter dw = new LimmaDesignWriter(os);
dw.write(d);
// System.out.println(os.toString());
}
public void testRead2() throws NividicIOException {
InputStream is =
this.getClass().getResourceAsStream("/files/ApoAITargets.txt");
LimmaDesignReader ldr = new LimmaDesignReader(is);
Design d = ldr.read();
Slide s = d.getSlide(0);
// System.out.println("id: " + s.getName());
// System.out.println("s/n: " + s.getDescription().getSerialNumber());
ByteArrayOutputStream os = new ByteArrayOutputStream();
DesignWriter dw = new LimmaDesignWriter(os);
dw.write(d);
// System.out.println(os.toString());
}
public void testGlobal() throws ParseException, NividicIOException {
Design d = createDesign();
Samples samples = d.getSamples();
samples.addSample("WT");
samples.addSample("Swirl");
d.addSlide("81");
d.addSlide("82");
d.addSlide("93");
d.addSlide("94");
d.setDescription("81", SlideDescription.SLIDE_NUMBER_FIELD, "l81");
d.setDescription("82", SlideDescription.SLIDE_NUMBER_FIELD, "l82");
d.setDescription("93", SlideDescription.SLIDE_NUMBER_FIELD, "l93");
d.setDescription("94", SlideDescription.SLIDE_NUMBER_FIELD, "l94");
d.setTarget("81", PhysicalConstants.GREEN_FIELD, "Swirl");
d.setTarget("81", PhysicalConstants.RED_FIELD, "WT");
d.setSource("81", "swirl.spot1");
d.getSlideDescription("81").setDate("20/09/2001");
d.setTarget("82", PhysicalConstants.GREEN_FIELD, "WT");
d.setTarget("82", PhysicalConstants.RED_FIELD, "Swirl");
d.setSource("82", "swirl.spot2");
d.getSlideDescription("82").setDate("20/09/2001");
d.setTarget("93", PhysicalConstants.GREEN_FIELD, "Swirl");
d.setTarget("93", PhysicalConstants.RED_FIELD, "WT");
d.setSource("93", "swirl.spot3");
d.getSlideDescription("93").setDate("8/11/2001");
d.setTarget("94", PhysicalConstants.GREEN_FIELD, "WT");
d.setTarget("94", PhysicalConstants.RED_FIELD, "Swirl");
d.setSource("94", "swirl.spot4");
d.getSlideDescription("94").setDate("8/11/2001");
ByteArrayOutputStream os = new ByteArrayOutputStream();
DesignWriter dw = new LimmaDesignWriter(os);
dw.write(d);
// System.out.println(os.toString());
}
public void testGoulpharAroma() throws NividicIOException {
InputStream is = this.getClass().getResourceAsStream("/files/param.dat");
GoulpharDesignReader ldr = new GoulpharDesignReader(is);
ldr.setDataSourceNormalized(false);
Design d = ldr.read();
ByteArrayOutputStream os = new ByteArrayOutputStream();
DesignWriter dw = new LimmaDesignWriter(os);
dw.write(d);
// System.out.println(os.toString());
}
public void testGoulpha() throws NividicIOException {
InputStream is =
this.getClass().getResourceAsStream("/files/param_goulphar.dat");
GoulpharDesignReader ldr = new GoulpharDesignReader(is);
ldr.setDataSourceNormalized(false);
Design d = ldr.read();
ByteArrayOutputStream os = new ByteArrayOutputStream();
DesignWriter dw = new LimmaDesignWriter(os);
dw.write(d);
// System.out.println(os.toString());
}
public void testGetSamples() {
Design d = createDesign();
Samples samples = d.getSamples();
assertNotNull(samples);
samples.addSample("WT");
samples.addSample("Mutant");
assertEquals(2, samples.getSamplesCount());
}
public void testIsLabel() {
Design d = createDesign();
assertTrue(d.isLabel(PhysicalConstants.GREEN_FIELD));
assertTrue(d.isLabel(PhysicalConstants.RED_FIELD));
assertFalse(d.isLabel("Target"));
}
public void testGetLabelCount() {
Design d = createDesign();
assertEquals(2, d.getLabelCount());
}
public void testAddLabel() {
Design d = createDesign();
assertEquals(2, d.getLabelCount());
d.addLabel("Cy9");
assertEquals(3, d.getLabelCount());
assertTrue(d.isLabel("Cy9"));
}
public void testRenameLabel() {
// fail("Not yet implemented");
}
public void testGetLabelsNames() {
Design d = createDesign();
List<String> labels = d.getLabelsNames();
for (String l : labels)
assertTrue(d.isLabel(l));
}
public void testRemoveLabel() {
// fail("Not yet implemented");
}
public void testIsSlide() {
// fail("Not yet implemented");
}
public void testAddSlide() {
// fail("Not yet implemented");
}
public void testGetSlideCount() {
// fail("Not yet implemented");
}
public void testRenameSlide() {
// fail("Not yet implemented");
}
public void testGetSlides() {
// fail("Not yet implemented");
}
public void testRemoveSlide() {
// fail("Not yet implemented");
}
public void testSetTarget() {
// fail("Not yet implemented");
}
public void testGetTarget() {
// fail("Not yet implemented");
}
public void testGetSlideDescription() {
// fail("Not yet implemented");
}
public void testSetSourceStringDataSource() {
// fail("Not yet implemented");
}
public void testSetSourceStringString() {
// fail("Not yet implemented");
}
public void testSetSourceFormatStringBioAssayFormat() {
// fail("Not yet implemented");
}
public void testSetSourceFormatStringString() {
// fail("Not yet implemented");
}
public void testGetSource() {
// fail("Not yet implemented");
}
public void testGetSourceInfo() {
// fail("Not yet implemented");
}
public void testGetFormat() {
// fail("Not yet implemented");
}
}
|
package com.lesfurets.maven.partial.core;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.Guice;
import com.lesfurets.maven.partial.mocks.*;
@RunWith(MockitoJUnitRunner.class)
public class DifferentFilesTest extends RepoTest {
private static final String REFS_HEADS_FEATURE_2 = "refs/heads/feature/2";
private static final String HEAD = "HEAD";
private static final String FETCH_FILE = "fetch-file";
private static final String DEVELOP = "refs/heads/develop";
private static final String REMOTE_DEVELOP = "refs/remotes/origin/develop";
@Before
public void before() throws Exception {
super.init();
localRepoMock = new LocalRepoMock(true);
}
@Test
public void listIncludingOnlyUncommited() throws Exception {
LOCAL_DIR.resolve("file5").toFile().createNewFile();
ModuleMock.module().provideGit().add().addFilepattern(".").call();
Property.untracked.setValue(Boolean.FALSE.toString());
Property.uncommited.setValue(Boolean.TRUE.toString());
assertTrue(getInstance().get().stream().anyMatch(p -> p.toString().contains("file5")));
}
@Test
public void listIncludingOnlyUntracked() throws Exception {
LOCAL_DIR.resolve("file5").toFile().createNewFile();
Property.uncommited.setValue(Boolean.FALSE.toString());
Property.untracked.setValue(Boolean.TRUE.toString());
assertTrue(getInstance().get().stream().anyMatch(p -> p.toString().contains("file5")));
}
@Test
public void listWithCheckout() throws Exception {
getLocalRepoMock().getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
Property.baseBranch.setValue("refs/heads/feature/2");
getInstance().get();
assertTrue(consoleOut.toString().contains("Checking out base branch refs/heads/feature/2"));
}
@Test
public void list() throws Exception {
final DifferentFiles differentFiles = getInstance();
final Set<Path> expected = new HashSet<>(Arrays.asList(
Paths.get(LOCAL_DIR + "/child2/subchild2/src/resources/file2"),
Paths.get(LOCAL_DIR + "/child2/subchild2/src/resources/file22"),
Paths.get(LOCAL_DIR + "/child3/src/resources/file1"),
Paths.get(LOCAL_DIR + "/child4/pom.xml")
));
assertEquals(expected, differentFiles.get());
}
@Test
public void listInSubdir() throws Exception {
Path workDir = LOCAL_DIR.resolve("child2");
final DifferentFiles differentFiles = getInstance();
final Set<Path> expected = new HashSet<>(Arrays.asList(
workDir.resolve("subchild2/src/resources/file2"),
workDir.resolve("subchild2/src/resources/file22"),
workDir.resolve("../child3/src/resources/file1").normalize(),
workDir.resolve("../child4/pom.xml").normalize()
));
assertEquals(expected, differentFiles.get());
}
@Test
public void listComparedToMergeBase() throws Exception {
getLocalRepoMock().getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
getLocalRepoMock().getGit().checkout().setName(REFS_HEADS_FEATURE_2).call();
getLocalRepoMock().getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
Property.baseBranch.setValue(REFS_HEADS_FEATURE_2);
Property.compareToMergeBase.setValue("true");
assertTrue(getInstance().get().stream().collect(toSet()).contains(LOCAL_DIR.resolve("feature2-only-file.txt")));
assertTrue(consoleOut.toString().contains("ee64b9b863d3d30b429459cb3ccfaeac67e4efa1"));
}
@Test
public void fetch() throws Exception {
Git remoteGit = localRepoMock.getRemoteRepo().getGit();
remoteGit.reset().setMode(ResetCommand.ResetType.HARD).call();
remoteGit.checkout().setName(DEVELOP).call();
remoteGit.getRepository().getDirectory().toPath().resolve(FETCH_FILE).toFile().createNewFile();
remoteGit.add().addFilepattern(".").call();
remoteGit.commit().setMessage(FETCH_FILE).call();
assertEquals(FETCH_FILE, remoteGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
Property.fetchReferenceBranch.setValue(Boolean.TRUE.toString());
Property.referenceBranch.setValue(REMOTE_DEVELOP);
getInstance().get();
Git localGit = localRepoMock.getGit();
localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
localGit.checkout().setName(REMOTE_DEVELOP).call();
assertEquals(FETCH_FILE, localGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
}
@Test
public void fetchNonExistent() throws Exception {
Git remoteGit = localRepoMock.getRemoteRepo().getGit();
remoteGit.reset().setMode(ResetCommand.ResetType.HARD).call();
remoteGit.checkout().setName(DEVELOP).call();
remoteGit.getRepository().getDirectory().toPath().resolve(FETCH_FILE).toFile().createNewFile();
remoteGit.add().addFilepattern(".").call();
remoteGit.commit().setMessage(FETCH_FILE).call();
Git localGit = localRepoMock.getGit();
localGit.branchDelete().setBranchNames(DEVELOP).call();
localGit.branchDelete().setBranchNames(REMOTE_DEVELOP).call();
assertEquals(FETCH_FILE, remoteGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
Property.fetchReferenceBranch.setValue(Boolean.TRUE.toString());
Property.referenceBranch.setValue(REMOTE_DEVELOP);
getInstance().get();
localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
localGit.checkout().setName(REMOTE_DEVELOP).call();
assertEquals(FETCH_FILE, localGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
}
private boolean filterIgnored(Path p) {
return !p.toString().contains("target") && !p.toString().contains(".iml");
}
private DifferentFiles getInstance() throws Exception {
return Guice.createInjector(ModuleMock.module()).getInstance(DifferentFiles.class);
}
}
|
package gov.usgs.cida.wqp.service;
import static gov.usgs.cida.wqp.exception.WqpExceptionId.METHOD_PARAM_EMPTY;
import static gov.usgs.cida.wqp.exception.WqpExceptionId.METHOD_PARAM_NULL;
import static gov.usgs.cida.wqp.exception.WqpExceptionId.URL_PARSING_EXCEPTION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URL;
import org.junit.Test;
import gov.usgs.cida.wqp.BaseSpringTest;
import gov.usgs.cida.wqp.exception.WqpException;
import gov.usgs.cida.wqp.parameter.Parameters;
public class CodesServiceTest extends BaseSpringTest {
@Test
public void testMakeUrl_nullParam() throws Exception {
try {
new CodesService(null, null, 0).makeCodesUrl(null, "provider");
fail("should have thrown exception on null parameter");
} catch (WqpException e) {
assertEquals("Expect param exception", METHOD_PARAM_NULL, e.getExceptionid());
}
}
@Test
public void testMakeUrl_nullCode() throws Exception {
try {
new CodesService(null, null, 0).makeCodesUrl(Parameters.PROVIDERS, null);
fail("should have thrown exception on null code");
} catch (WqpException e) {
assertEquals("Expect param exception", METHOD_PARAM_NULL, e.getExceptionid());
}
}
@Test
public void testMakeUrl_emptyCode() throws Exception {
try {
new CodesService(null, null, 0).makeCodesUrl(Parameters.PROVIDERS, "");
fail("should have thrown exception on empty string");
} catch (WqpException e) {
assertEquals("Expect param exception", METHOD_PARAM_EMPTY, e.getExceptionid());
}
}
@Test
public void testMakeUrl_default() throws Exception {
String baseUrl = "https://wqp.codes.usgs.gov/codes/";
URL actualUrl = new CodesService(baseUrl, JSON, 0).makeCodesUrl(Parameters.PROVIDERS, "pro/vider");
String expectedUrl = baseUrl +"/"+ Parameters.PROVIDERS +"/pro%2Fvider?mimeType=json";
assertEquals(expectedUrl, actualUrl.toString());
}
@Test
public void testMakeUrl_customMimeType() throws Exception {
String baseUrl = "https://wqp.codes.usgs.gov/codes/";
String mimeType = XML;
URL actualUrl = new CodesService(baseUrl, mimeType, 0).makeCodesUrl(Parameters.PROVIDERS, "provider");
String expectedUrl = baseUrl +"/"+ Parameters.PROVIDERS +"/provider?mimeType="+mimeType;
assertEquals(expectedUrl, actualUrl.toString());
}
@Test
public void testMakeUrl_badURL() throws Exception {
String baseUrl = "ht//tps://wqp.codes.usgs.gov/bad/URL/";
try {
URL actualUrl = new CodesService(baseUrl, null, 0).makeCodesUrl(Parameters.PROVIDERS, "provider");
System.out.println(actualUrl.toString());
fail("should have thrown exception on bad URL");
} catch (WqpException e) {
assertEquals("Expect URL exception", URL_PARSING_EXCEPTION, e.getExceptionid());
}
}
@Test
public void testValidation_nullParam() throws Exception {
try {
new CodesService(null, null, 0).validate(null, "provider");
fail("should have thrown exception on null parameter");
} catch (WqpException e) {
assertTrue("Expect param exception", e.getExceptionid() == METHOD_PARAM_NULL);
}
}
@Test
public void testValidation_nullCode() throws Exception {
try {
new CodesService(null, null, 0).validate(Parameters.PROVIDERS, null);
fail("should have thrown exception on null code");
} catch (WqpException e) {
assertEquals("Expect param exception", METHOD_PARAM_NULL, e.getExceptionid());
}
}
@Test
public void testValidation_emptyCode() throws Exception {
boolean actual = new CodesService(null, null, 0).validate(Parameters.PROVIDERS, "");
assertFalse("Empty string code is always invalid", actual);
}
}
|
package hdm.pk070.jscheme.environment;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.obj.SchemeObject;
import hdm.pk070.jscheme.obj.type.SchemeInteger;
import hdm.pk070.jscheme.obj.type.SchemeSymbol;
import hdm.pk070.jscheme.util.ReflectionUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
public class GlobalEnvironmentTest {
private GlobalEnvironment globalEnvironment;
@Before
public void setUp() {
globalEnvironment = GlobalEnvironment.getInstance();
}
@Test
public void testPutEntryIntoEnvironment() throws SchemeError {
SchemeSymbol testSymbol = new SchemeSymbol("foo");
globalEnvironment.put(testSymbol, new SchemeInteger(42));
assertThat(ReflectionUtils.getAttributeVal(globalEnvironment, "currentFillSize"), equalTo(1));
assertThat(globalEnvironmentContains(EnvironmentEntry.create(testSymbol, new SchemeInteger(42))),
equalTo(true));
}
@Test
public void testGetEntryFromEnvironment() throws SchemeError {
SchemeSymbol keySymbol = new SchemeSymbol("foo");
globalEnvironment.put(keySymbol, new SchemeInteger(42));
SchemeObject result = globalEnvironment.get(keySymbol);
assertThat("result must not be null!", result, notNullValue());
assertThat("result must be of type SchemeInteger!", result.typeOf(SchemeInteger.class), equalTo(true));
assertThat("result does not match expected value!", result, equalTo(new SchemeInteger(42)));
}
@Test
public void testGetReturnsNullOnMissingEntry() {
SchemeObject result = globalEnvironment.get(new SchemeSymbol("bar"));
assertThat(result, nullValue());
}
@Test
public void testRehash() {
ReflectionUtils.invokeMethod(globalEnvironment, "startRehash");
EnvironmentEntry[] environmentEntries = (EnvironmentEntry[]) ReflectionUtils.getAttributeVal
(globalEnvironment, "currentGlobalEnvironmentEntries");
assertThat(environmentEntries.length, equalTo((511 + 1) * 2 - 1));
}
@After
public void tearDown() {
// reset environment for each test since it is a singleton
EnvironmentEntry[] environmentEntries = (EnvironmentEntry[]) ReflectionUtils.getAttributeVal
(globalEnvironment, "currentGlobalEnvironmentEntries");
environmentEntries = new EnvironmentEntry[511];
}
private boolean globalEnvironmentContains(EnvironmentEntry expectedEntry) {
EnvironmentEntry[] currentGlobalEnvironmentEntries = (EnvironmentEntry[]) ReflectionUtils.getAttributeVal
(globalEnvironment,
"currentGlobalEnvironmentEntries");
Optional<EnvironmentEntry> entryOptional = Arrays.asList(currentGlobalEnvironmentEntries).stream()
.filter(entry -> Objects.nonNull(entry))
.filter(envEntry -> envEntry.equals(expectedEntry))
.findAny();
return entryOptional.isPresent();
}
}
|
package mkl.testarea.pdfbox2.content;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBoolean;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDFormContentStream;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.function.PDFunctionType2;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup;
import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroupAttributes;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType2;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.ByteStreams;
/**
* @author mkl
*/
public class AddDropShadow {
final static File RESULT_FOLDER = new File("target/test-outputs", "content");
@BeforeClass
public static void setUpBeforeClass() throws Exception {
RESULT_FOLDER.mkdirs();
}
@Test
public void testRectangleWithDropShadow() throws IOException {
PDDocument doc = new PDDocument();
PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(getClass().getResourceAsStream("Willi-1.jpg")), "Willi-1.jpg");
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
int left = -60;
int top = 96;
int width = 471;
int height = 365;
contentStream.setStrokingColor(1, 0, 0);
contentStream.setLineWidth(4);
int imageOriginalWidth = 633;
int imageOriginalHeight = 422;
float scaleX = 0.99f;
float scaleY = 0.99f;
float imageWidth = imageOriginalWidth*scaleX;
float imageHeight = imageOriginalHeight*scaleY;
float imageY = page.getMediaBox().getHeight() - (top + imageHeight-58);
float imageX = -104;
PDExtendedGraphicsState extGS = new PDExtendedGraphicsState();
extGS.setNonStrokingAlphaConstant(.2f);
contentStream.saveGraphicsState();
contentStream.setGraphicsStateParameters(extGS);
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.addRect(left + 5, page.getMediaBox().getHeight() - top - height - 5, width, height);
contentStream.fill();
contentStream.restoreGraphicsState();
contentStream.addRect(left, page.getMediaBox().getHeight() - top - height, width, height);
contentStream.clip();
contentStream.drawImage(pdImage, imageX, imageY, imageWidth, imageHeight);
contentStream.close();
doc.save(new File(RESULT_FOLDER, "RectangleWithDropShadow.pdf"));
doc.close();
}
@Test
public void testRectangleWithDropShadowFade() throws IOException {
PDDocument doc = new PDDocument();
PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(getClass().getResourceAsStream("Willi-1.jpg")), "Willi-1.jpg");
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
int left = -60;
int top = 96;
int width = 471;
int height = 365;
contentStream.setStrokingColor(1, 0, 0);
contentStream.setLineWidth(4);
int imageOriginalWidth = 633;
int imageOriginalHeight = 422;
float scaleX = 0.99f;
float scaleY = 0.99f;
float imageWidth = imageOriginalWidth*scaleX;
float imageHeight = imageOriginalHeight*scaleY;
float imageY = page.getMediaBox().getHeight() - (top + imageHeight-58);
float imageX = -104;
PDExtendedGraphicsState extGS = createStateWithSMask(doc, left, page.getMediaBox().getHeight() - top - height, width, height);
contentStream.saveGraphicsState();
contentStream.setGraphicsStateParameters(extGS);
contentStream.setNonStrokingColor(Color.BLACK);
PDRectangle cropBox = page.getCropBox();
contentStream.addRect(cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), cropBox.getWidth(), cropBox.getHeight());
contentStream.fill();
contentStream.restoreGraphicsState();
contentStream.addRect(left, page.getMediaBox().getHeight() - top - height, width, height);
contentStream.clip();
contentStream.drawImage(pdImage, imageX, imageY, imageWidth, imageHeight);
contentStream.close();
doc.save(new File(RESULT_FOLDER, "RectangleWithDropShadowFade.pdf"));
doc.close();
}
/**
* Creates a {@link PDExtendedGraphicsState} with a soft mask for a fading drop shadow.
*
* @see #testRectangleWithDropShadowFade()
* @see UseSoftMask#testSoftMaskedImageAndRectangle()
*/
PDExtendedGraphicsState createStateWithSMask(PDDocument document, float x, float y, float width, float height) throws IOException {
float offset = 15;
float fade = 15;
float opacityFrom = .2f;
float opacityTo = 0f;
x += offset;
y -= offset;
float xCenter = x + width/2;
float yCenter = y + height/2;
float innerWidth = width - 2*fade;
float innerHeight = height - 2*fade;
PDFunctionType2 func = createFadingFunction(opacityFrom, opacityTo);
PDShading axialShading = createShading(-fade, 0);
axialShading.setFunction(func);
PDTransparencyGroupAttributes transparencyGroupAttributes = new PDTransparencyGroupAttributes();
transparencyGroupAttributes.getCOSObject().setItem(COSName.CS, COSName.DEVICEGRAY);
PDTransparencyGroup transparencyGroup = new PDTransparencyGroup(document);
transparencyGroup.setBBox(PDRectangle.A4);
transparencyGroup.setResources(new PDResources());
transparencyGroup.getCOSObject().setItem(COSName.GROUP, transparencyGroupAttributes);
try ( PDFormContentStream canvas = new PDFormContentStream(transparencyGroup) ) {
canvas.saveGraphicsState();
clip(canvas, xCenter, yCenter, innerWidth, innerHeight, innerWidth, -innerHeight);
canvas.transform(Matrix.getTranslateInstance(x + width, 0));
canvas.shadingFill(axialShading);
canvas.restoreGraphicsState();
canvas.saveGraphicsState();
clip(canvas, xCenter, yCenter, -innerWidth, innerHeight, innerWidth, innerHeight);
canvas.transform(Matrix.getRotateInstance((float)Math.PI / 2, 0, y + height));
canvas.shadingFill(axialShading);
canvas.restoreGraphicsState();
canvas.saveGraphicsState();
clip(canvas, xCenter, yCenter, -innerWidth, innerHeight, -innerWidth, -innerHeight);
canvas.transform(Matrix.getRotateInstance((float)Math.PI, x, 0));
canvas.shadingFill(axialShading);
canvas.restoreGraphicsState();
canvas.saveGraphicsState();
clip(canvas, xCenter, yCenter, innerWidth, -innerHeight, -innerWidth, -innerHeight);
canvas.transform(Matrix.getRotateInstance(-(float)Math.PI / 2, 0, y));
canvas.shadingFill(axialShading);
canvas.restoreGraphicsState();
}
COSDictionary softMaskDictionary = new COSDictionary();
softMaskDictionary.setItem(COSName.TYPE, COSName.MASK);
softMaskDictionary.setItem(COSName.S, COSName.LUMINOSITY);
softMaskDictionary.setItem(COSName.G, transparencyGroup);
PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
extendedGraphicsState.getCOSObject().setItem(COSName.SMASK, softMaskDictionary);
return extendedGraphicsState;
}
/**
* @see #testRectangleWithDropShadowFade()
* @see #createStateWithSMask(PDDocument, float, float, float, float)
*/
PDFunctionType2 createFadingFunction(float opacityFrom, float opacityTo) {
COSDictionary function = new COSDictionary();
function.setInt(COSName.FUNCTION_TYPE, 2);
COSArray domain = new COSArray();
domain.add(COSInteger.get(0));
domain.add(COSInteger.get(1));
COSArray c0 = new COSArray();
c0.add(new COSFloat(opacityFrom));
COSArray c1 = new COSArray();
c1.add(new COSFloat(opacityTo));
function.setItem(COSName.DOMAIN, domain);
function.setItem(COSName.C0, c0);
function.setItem(COSName.C1, c1);
function.setInt(COSName.N, 1);
return new PDFunctionType2(function);
}
/**
* @see #testRectangleWithDropShadowFade()
* @see #createStateWithSMask(PDDocument, float, float, float, float)
*/
PDShading createShading(float xFrom, float xTo) {
PDShadingType2 axialShading = new PDShadingType2(new COSDictionary());
axialShading.setColorSpace(PDDeviceGray.INSTANCE);
axialShading.setShadingType(PDShading.SHADING_TYPE2);
COSArray coords = new COSArray();
coords.add(new COSFloat(xFrom));
coords.add(new COSFloat(0));
coords.add(new COSFloat(xTo));
coords.add(new COSFloat(0));
axialShading.setCoords(coords);
COSArray extend = new COSArray();
extend.add(COSBoolean.TRUE);
extend.add(COSBoolean.TRUE);
axialShading.setExtend(extend);
return axialShading;
}
/**
* @see #testRectangleWithDropShadowFade()
* @see #createStateWithSMask(PDDocument, float, float, float, float)
*/
void clip(PDFormContentStream canvas, float x0, float y0, float deltaX1, float deltaY1, float deltaX2, float deltaY2) throws IOException {
canvas.moveTo(x0, y0);
canvas.lineTo(x0 + deltaX1, y0 + deltaY1);
canvas.lineTo(x0 + deltaX2, y0 + deltaY2);
canvas.close();
canvas.clip();
}
}
|
package kuleuven.group2.data.updating;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import kuleuven.group2.data.TestDatabase;
import kuleuven.group2.data.updating.TestResultUpdater;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
public class TestResultUpdaterTest {
private TestDatabase database;
private TestResultUpdater updater;
private static Description suiteDescription;
private static Description method1Description;
private static Description method2Description;
private static Failure method2Failure;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
suiteDescription = Description.createSuiteDescription(TestClass.class);
method1Description = Description.createTestDescription(TestClass.class, "testMethod1S");
method2Description = Description.createTestDescription(TestClass.class, "testMethod2F");
method2Failure = new Failure(method2Description, null);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
database = new TestDatabase();
updater = new TestResultUpdater(database);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSucceedTests() throws Exception {
updater.testRunStarted(suiteDescription);
updater.testStarted(method1Description);
updater.testFinished(method1Description);
// one successful run was added
assertEquals(1, database.getAllTestRuns().size());
updater.testStarted(method2Description);
updater.testAssumptionFailure(method2Failure);
updater.testRunFinished(null);
// there are now two runs in the database: one failed and one succeeded
assertEquals(2, database.getAllTestRuns().size());
}
private class TestClass {
private TestedClass subject;
@Before
public void setUp() {
subject = new TestedClass();
}
@Test
public void testMethod1S() {
assertTrue(subject.getTrue());
}
@Test
public void testMethod2F() {
assertTrue(subject.getFalse());
}
}
private class TestedClass {
public TestedClass() {
// do nothing
}
public boolean getFalse() {
return false;
}
public boolean getTrue() {
return true;
}
}
}
|
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
import java.time.*;
import java.util.UUID;
import static net.openhft.chronicle.bytes.NativeBytes.nativeBytes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BinaryWire2Test {
@NotNull
Bytes bytes = nativeBytes();
StringBuilder csp = new StringBuilder();
StringBuilder key1 = new StringBuilder();
StringBuilder key2 = new StringBuilder();
StringBuilder value1 = new StringBuilder();
StringBuilder value2 = new StringBuilder();
long tid;
@NotNull
private BinaryWire createWire() {
bytes.clear();
return new BinaryWire(bytes);
}
@Test
public void testBool() {
Wire wire = createWire();
wire.write().bool(false)
.write().bool(true)
.write().bool(null);
wire.read().bool("error", Assert::assertFalse)
.read().bool("error", Assert::assertTrue)
.read().bool("error", Assert::assertNull);
}
@Test
public void testBytesStore() {
Wire wire = createWire();
wire.write().object(Bytes.from("Hello"));
Bytes b = Bytes.elasticByteBuffer();
wire.read().object(b, Object.class);
assertEquals("Hello", b.toString());
}
@Test
public void testFloat32() {
Wire wire = createWire();
wire.write().float32(0.0F)
.write().float32(Float.NaN)
.write().float32(Float.POSITIVE_INFINITY);
wire.read().float32(this, (o, t) -> assertEquals(0.0F, t, 0.0F))
.read().float32(this, (o, t) -> assertTrue(Float.isNaN(t)))
.read().float32(this, (o, t) -> assertEquals(Float.POSITIVE_INFINITY, t, 0.0F));
}
@Test
public void testTime() {
Wire wire = createWire();
LocalTime now = LocalTime.now();
wire.write().time(now)
.write().time(LocalTime.MAX)
.write().time(LocalTime.MIN);
wire.read().time(now, Assert::assertEquals)
.read().time(LocalTime.MAX, Assert::assertEquals)
.read().time(LocalTime.MIN, Assert::assertEquals);
}
@Test
public void testZonedDateTime() {
Wire wire = createWire();
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime max = ZonedDateTime.of(LocalDateTime.MAX, ZoneId.systemDefault());
ZonedDateTime min = ZonedDateTime.of(LocalDateTime.MIN, ZoneId.systemDefault());
wire.write().zonedDateTime(now)
.write().zonedDateTime(max)
.write().zonedDateTime(min);
wire.read().zonedDateTime(now, Assert::assertEquals)
.read().zonedDateTime(max, Assert::assertEquals)
.read().zonedDateTime(min, Assert::assertEquals);
}
@Test
public void testDate() {
Wire wire = createWire();
LocalDate now = LocalDate.now();
wire.write().date(now)
.write().date(LocalDate.MAX)
.write().date(LocalDate.MIN);
wire.read().date(this, (o, t) -> assertEquals(now, t))
.read().date(this, (o, t) -> assertEquals(LocalDate.MAX, t))
.read().date(this, (o, t) -> assertEquals(LocalDate.MIN, t));
}
@Test
public void testUuid() {
Wire wire = createWire();
UUID uuid = UUID.randomUUID();
wire.write().uuid(uuid)
.write().uuid(new UUID(0, 0))
.write().uuid(new UUID(Long.MAX_VALUE, Long.MAX_VALUE));
wire.read().uuid(this, (o, t) -> assertEquals(uuid, t))
.read().uuid(this, (o, t) -> assertEquals(new UUID(0, 0), t))
.read().uuid(this, (o, t) -> assertEquals(new UUID(Long.MAX_VALUE, Long.MAX_VALUE), t));
}
@Test
public void testSequence() {
Wire wire = createWire();
writeMessage(wire);
System.out.println(wire.bytes().toHexString());
Wire twire = new TextWire(Bytes.elasticByteBuffer());
writeMessage(twire);
System.out.println(Wires.fromSizePrefixedBlobs(twire.bytes()));
}
private void writeMessage(@NotNull WireOut wire) {
wire.writeDocument(true, w -> w
.write(() -> "csp").text("//path/service")
.write(() -> "tid").int64(123456789));
wire.writeDocument(false, w -> w
.write(() -> "entrySet").sequence(s -> {
s.marshallable(m -> m
.write(() -> "key").text("key-1")
.write(() -> "value").text("value-1"));
s.marshallable(m -> m
.write(() -> "key").text("key-2")
.write(() -> "value").text("value-2"));
}));
}
@Test
public void testEnum() {
Wire wire = createWire();
wire.write().object(WireType.BINARY)
.write().object(WireType.TEXT)
.write().object(WireType.RAW);
assertEquals(WireType.BINARY, wire.read().object(Object.class));
assertEquals(WireType.TEXT, wire.read().object(Object.class));
assertEquals(WireType.RAW, wire.read().object(Object.class));
}
@Test
public void fieldAfterText() {
Wire wire = createWire();
wire.writeDocument(false, w -> w.write(() -> "data").typePrefix("!UpdateEvent").marshallable(
v -> v.write(() -> "assetName").text("/name")
.write(() -> "key").object("test")
.write(() -> "oldValue").object("world1")
.write(() -> "value").object("world2")));
assertEquals("--- !!data #binary\n" +
"data: !!UpdateEvent {\n" +
" assetName: /name,\n" +
" key: test,\n" +
" oldValue: world1,\n" +
" value: world2\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
wire.readDocument(null, w -> w.read(() -> "data").typePrefix(this, (o, t) -> assertEquals("!UpdateEvent", t.toString())).marshallable(
m -> m.read(() -> "assetName").object(String.class, "/name", Assert::assertEquals)
.read(() -> "key").object(String.class, "test", Assert::assertEquals)
.read(() -> "oldValue").object(String.class, "world1", Assert::assertEquals)
.read(() -> "value").object(String.class, "world2", Assert::assertEquals)));
}
@Test
public void fieldAfterNull() {
Wire wire = createWire();
wire.writeDocument(false, w -> w.write(() -> "data").typedMarshallable("!UpdateEvent",
v -> v.write(() -> "assetName").text("/name")
.write(() -> "key").object("test")
.write(() -> "oldValue").object(null)
.write(() -> "value").object("world2")));
assertEquals("--- !!data #binary\n" +
"data: !!UpdateEvent {\n" +
" assetName: /name,\n" +
" key: test,\n" +
" oldValue: !!null \"\",\n" +
" value: world2\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
wire.readDocument(null, w -> w.read(() -> "data").typePrefix(this, (o, t) -> assertEquals("!UpdateEvent", t.toString())).marshallable(
m -> m.read(() -> "assetName").object(String.class, "/name", Assert::assertEquals)
.read(() -> "key").object(String.class, "test", Assert::assertEquals)
.read(() -> "oldValue").object(String.class, "error", Assert::assertNull)
.read(() -> "value").object(String.class, "world2", Assert::assertEquals)));
}
}
|
package nl.thehyve.ocdu.validators;
import nl.thehyve.ocdu.TestUtils;
import nl.thehyve.ocdu.models.OCEntities.Subject;
import nl.thehyve.ocdu.models.OcDefinitions.MetaData;
import nl.thehyve.ocdu.models.OcDefinitions.SiteDefinition;
import nl.thehyve.ocdu.models.errors.ValidationErrorMessage;
import nl.thehyve.ocdu.soap.ResponseHandlers.GetStudyMetadataResponseHandler;
import nl.thehyve.ocdu.validators.patientDataChecks.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openclinica.ws.beans.StudySubjectWithEventsType;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
public class PatientDataOcChecksTests {
private static MetaData metadata;
private static List<StudySubjectWithEventsType> testSubjectWithEventsTypeList;
private static Set<String> presentInData;
@BeforeClass
public static void setup() {
try {
testSubjectWithEventsTypeList = TestUtils.createStudySubjectWithEventList();
MessageFactory messageFactory = MessageFactory.newInstance();
File testFile = new File("docs/responseExamples/Sjogren_STUDY1.xml");
FileInputStream in = new FileInputStream(testFile);
SOAPMessage mockedResponseGetMetadata = messageFactory.createMessage(null, in);
metadata = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
presentInData = new HashSet<>();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSuccess() {
List<Subject> subjects = new ArrayList<>();
PatientDataOcChecks ocChecks = new PatientDataOcChecks(metadata, subjects, testSubjectWithEventsTypeList, presentInData);
List<ValidationErrorMessage> errors = ocChecks.getErrors();
assertThat(errors, empty());
}
@Test
public void testGenderFormat() {
Subject subject = new Subject();
subject.setSsid("1234");
subject.setGender("wrongGenderFormat");
GenderPatientDataCheck check = new GenderPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Gender"));
}
@Test
public void testBirthdateFormatYearOnly() {
Subject subject = new Subject();
subject.setSsid("1234");
//invalid format
subject.setDateOfBirth("198x");
DateOfBirthPatientDataCheck check = new DateOfBirthPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("invalid"));
}
@Test
public void testBirthdateFormatFullDate() {
Subject subject = new Subject();
subject.setSsid("1234");
metadata.setBirthdateRequired(1);
//future birthday
subject.setDateOfBirth("01-06-3012");
DateOfBirthPatientDataCheck check = new DateOfBirthPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("past"));
subject.setDateOfBirth(null);
error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Date of birth is missing"));
}
@Test
public void testDateOfEnrollmentEmpty() {
Subject subject = new Subject();
subject.setSsid("1234");
//empty date of enrollment, today's date is used
subject.setDateOfEnrollment("");
DateOfEnrollmentPatientDataCheck check = new DateOfEnrollmentPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Today"));
}
@Test
public void testDateOfEnrollmentFuture() {
Subject subject = new Subject();
subject.setSsid("1234");
//date of enrollment should be in the past
subject.setDateOfEnrollment("01-06-3012");
DateOfEnrollmentPatientDataCheck check = new DateOfEnrollmentPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("past"));
}
@Test
public void testDateOfEnrollmentInvalidFormat() {
Subject subject = new Subject();
subject.setSsid("1234");
//invalid date format
subject.setDateOfEnrollment("01-JU");
DateOfEnrollmentPatientDataCheck check = new DateOfEnrollmentPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("invalid"));
}
@Test
public void testPersonIdProvided() {
Subject subject = new Subject();
subject.setSsid("1234");
//person id is provided
subject.setPersonId("1357");
PersonIdPatientDataCheck check = new PersonIdPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Person"));
}
@Test
public void testSecondaryIdTooLong() {
Subject subject = new Subject();
subject.setSsid("1234");
//secondary id is provided, but too long
subject.setSecondaryId("1111112222222222333333333444444444445555555555666666666667777777777888888");
SecondaryIdPatientDataCheck check = new SecondaryIdPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("length"));
}
@Test
public void testStudyNotProvided() {
Subject subject = new Subject();
subject.setSsid("1234");
//study is not provided
subject.setStudy("");
StudyPatientDataCheck check = new StudyPatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Study should"));
}
@Test
public void testSitesNotExist() {
Subject subject = new Subject();
subject.setSsid("1234");
//sites do not exist
subject.setStudy("S_STUDY1");
subject.setSite("myownsitethatdoesnotexist");
SitePatientDataCheck check = new SitePatientDataCheck();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("exist"));
}
@Test
public void testSiteExistSuccess() {
Subject subject = new Subject();
subject.setSsid("1234");
//sites do not exist
subject.setStudy("S_STUDY1");
subject.setSite("SjogrenSjogren");
SitePatientDataCheck check = new SitePatientDataCheck();
List<SiteDefinition> siteDefs = new ArrayList<>();
SiteDefinition sjogrenSite = new SiteDefinition();
sjogrenSite.setSiteOID("SjogrenSjogren");
siteDefs.add(sjogrenSite);
metadata.setSiteDefinitions(siteDefs);
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertNull(error);
}
@Test
public void bannedGenderTest() throws Exception {
MetaData metaData = new MetaData();
metaData.setGenderRequired(false);
Subject subjectWithGender = new Subject();
subjectWithGender.setGender("m");
GenderPatientDataCheck check = new GenderPatientDataCheck();
int bogusLineNumber = 1;
ValidationErrorMessage error = check.getCorrespondingError(bogusLineNumber, subjectWithGender, metaData,
testSubjectWithEventsTypeList, presentInData);
assertThat(error, is(notNullValue()));
assertThat(error.getMessage(), containsString("It is not allowed to upload gender by the study protocol"));
}
@Test
public void bannedDobTest() throws Exception {
MetaData metaData = new MetaData();
int notRequired = 3;
metaData.setBirthdateRequired(notRequired);
Subject subjectWithDOB = new Subject();
Subject subjectWithDOBFull = new Subject();
subjectWithDOBFull.setDateOfBirth("01-JUN-2000");
subjectWithDOB.setDateOfBirth("1997");
DateOfBirthPatientDataCheck check = new DateOfBirthPatientDataCheck();
int bogusLineNumber = 1;
ValidationErrorMessage error = check.getCorrespondingError(bogusLineNumber, subjectWithDOB, metaData, testSubjectWithEventsTypeList, presentInData);
ValidationErrorMessage errorFullYear = check.getCorrespondingError(bogusLineNumber, subjectWithDOBFull, metaData, testSubjectWithEventsTypeList, presentInData);
assertThat(error, is(notNullValue()));
assertThat(error.getMessage(), containsString("Date of birth submission is not allowed by the study protocol"));
assertThat(errorFullYear.getMessage(), is(notNullValue()));
assertThat(errorFullYear.getMessage(), containsString("Date of birth submission is not allowed by the study protocol"));
}
@Test
public void subjectAlreadyRegisteredTest() throws Exception {
Subject subject = new Subject();
subject.setSsid("EV-00002");
SubjectNotRegistered check = new SubjectNotRegistered();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("already registered"));
}
@Test
public void subjectPresentInTheData() throws Exception {
Subject subject = new Subject();
String s1 = "EV-00002";
subject.setSsid(s1);
PresentInData check = new PresentInData();
ValidationErrorMessage error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat(error.getMessage(), containsString("Absent in the data file"));
presentInData.add(s1);
error = check.getCorrespondingError(0, subject, metadata, testSubjectWithEventsTypeList, presentInData);
assertThat("Returns null for subject present in the data-file", error, nullValue());
}
}
|
package com.qozix.layouts;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import com.qozix.animation.Tween;
import com.qozix.animation.TweenListener;
import com.qozix.animation.easing.Strong;
import com.qozix.widgets.Scroller;
/**
* ZoomPanLayout extends ViewGroup to provide support for scrolling and zooming. Fling, drag, pinch and
* double-tap events are supported natively.
*
* ZoomPanLayout does not support direct insertion of child Views, and manages positioning through an intermediary View.
* the addChild method provides an interface to add layouts to that intermediary view. Each of these children are provided
* with LayoutParams of MATCH_PARENT for both axes, and will always be positioned at 0,0, so should generally be ViewGroups
* themselves (RelativeLayouts or FrameLayouts are generally appropriate).
*/
public class ZoomPanLayout extends ViewGroup {
private static final int MINIMUM_VELOCITY = 50;
private static final int ZOOM_ANIMATION_DURATION = 500;
private static final int SLIDE_DURATION = 500;
private static final int VELOCITY_UNITS = 1000;
private static final int DOUBLE_TAP_TIME_THRESHOLD = 250;
private static final int SINGLE_TAP_DISTANCE_THRESHOLD = 50;
private static final double MINIMUM_PINCH_SCALE = 0.0;
private static final float FRICTION = 0.99f;
private int baseWidth;
private int baseHeight;
private int scaledWidth;
private int scaledHeight;
private double scale = 1;
private double historicalScale = 1;
private double minScale = 0;
private double maxScale = 1;
private boolean scaleToFit = true;
private Point pinchStartScroll = new Point();
private Point pinchStartOffset = new Point();
private double pinchStartDistance;
private Point doubleTapStartScroll = new Point();
private Point doubleTapStartOffset = new Point();
private double doubleTapDestinationScale;
private Point firstFinger = new Point();
private Point secondFinger = new Point();
private Point lastFirstFinger = new Point();
private Point lastSecondFinger = new Point();
private Point scrollPosition = new Point();
private Point singleTapHistory = new Point();
private Point doubleTapHistory = new Point();
private Point firstFingerLastDown = new Point();
private Point secondFingerLastDown = new Point();
private Point actualPoint = new Point();
private Point destinationScroll = new Point();
private boolean secondFingerIsDown = false;
private boolean firstFingerIsDown = false;
private boolean isTapInterrupted = false;
private boolean isBeingFlung = false;
private boolean isDragging = false;
private boolean isPinching = false;
private int dragStartThreshold = 30;
private int pinchStartThreshold = 30;
private long lastTouchedAt;
private ScrollActionHandler scrollActionHandler;
private Scroller scroller;
private VelocityTracker velocity;
private HashSet<GestureListener> gestureListeners = new HashSet<GestureListener>();
private HashSet<ZoomPanListener> zoomPanListeners = new HashSet<ZoomPanListener>();
private StaticLayout clip;
private TweenListener tweenListener = new TweenListener() {
@Override
public void onTweenComplete() {
isTweening = false;
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onZoomComplete( scale );
listener.onZoomPanEvent();
}
}
@Override
public void onTweenProgress( double progress, double eased ) {
double originalChange = doubleTapDestinationScale - historicalScale;
double updatedChange = originalChange * eased;
double currentScale = historicalScale + updatedChange;
setScale( currentScale );
maintainScrollDuringScaleTween();
}
@Override
public void onTweenStart() {
saveHistoricalScale();
isTweening = true;
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onZoomStart( scale );
listener.onZoomPanEvent();
}
}
};
private boolean isTweening;
private Tween tween = new Tween();
{
tween.setAnimationEase( Strong.EaseOut );
tween.addTweenListener( tweenListener );
}
/**
* Constructor to use when creating a ZoomPanLayout from code. Inflating from XML is not currently supported.
* @param context (Context) The Context the ZoomPanLayout is running in, through which it can access the current theme, resources, etc.
*/
public ZoomPanLayout( Context context ) {
super( context );
setWillNotDraw( false );
scrollActionHandler = new ScrollActionHandler( this );
scroller = new Scroller( context );
scroller.setFriction( FRICTION );
clip = new StaticLayout( context );
super.addView( clip, -1, new LayoutParams( -1, -1 ) );
updateClip();
}
// PUBLIC API
/**
* Determines whether the ZoomPanLayout should limit it's minimum scale to no less than what would be required to fill it's container
* @param shouldScaleToFit (boolean) True to limit minimum scale, false to allow arbitrary minimum scale (see {@link setScaleLimits})
*/
public void setScaleToFit( boolean shouldScaleToFit ) {
scaleToFit = shouldScaleToFit;
calculateMinimumScaleToFit();
}
/**
* Set minimum and maximum scale values for this ZoomPanLayout.
* Note that if {@link shouldScaleToFit} is set to true, the minimum value set here will be ignored
* Default values are 0 and 1.
* @param min
* @param max
*/
public void setScaleLimits( double min, double max ) {
// if scaleToFit is set, don't allow overwrite
if ( !scaleToFit ) {
minScale = min;
}
maxScale = max;
setScale( scale );
}
/**
* Sets the size (width and height) of the ZoomPanLayout as it should be rendered at a scale of 1f (100%)
* @param wide width
* @param tall height
*/
public void setSize( int wide, int tall ) {
baseWidth = wide;
baseHeight = tall;
scaledWidth = (int) ( baseWidth * scale );
scaledHeight = (int) ( baseHeight * scale );
updateClip();
}
/**
* Returns the base (un-scaled) width
* @return (int) base width
*/
public int getBaseWidth() {
return baseWidth;
}
/**
* Returns the base (un-scaled) height
* @return (int) base height
*/
public int getBaseHeight() {
return baseHeight;
}
/**
* Returns the scaled width
* @return (int) scaled width
*/
public int getScaledWidth() {
return scaledWidth;
}
/**
* Returns the scaled height
* @return (int) scaled height
*/
public int getScaledHeight() {
return scaledHeight;
}
/**
* Sets the scale (0-1) of the ZoomPanLayout
* @param scale (double) The new value of the ZoomPanLayout scale
*/
public void setScale( double d ) {
d = Math.max( d, minScale );
d = Math.min( d, maxScale );
if ( scale != d ) {
scale = d;
scaledWidth = (int) ( baseWidth * scale );
scaledHeight = (int) ( baseHeight * scale );
updateClip();
postInvalidate();
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onScaleChanged( scale );
listener.onZoomPanEvent();
}
}
}
/**
* Requests a redraw
*/
public void redraw() {
updateClip();
postInvalidate();
}
/**
* Retrieves the current scale of the ZoomPanLayout
* @return (double) the current scale of the ZoomPanLayout
*/
public double getScale() {
return scale;
}
/**
* Returns whether the ZoomPanLayout is currently being flung
* @return (boolean) true if the ZoomPanLayout is currently flinging, false otherwise
*/
public boolean isFlinging() {
return isBeingFlung;
}
/**
* Returns the single child of the ZoomPanLayout, a ViewGroup that serves as an intermediary container
* @return (View) The child view of the ZoomPanLayout that manages all contained views
*/
public View getClip() {
return clip;
}
/**
* Returns the Scroller instance used to manage dragging and flinging.
* @return (Scroller) The Scroller instance use to manage dragging and flinging.
*/
public Scroller getScroller(){
return scroller;
}
/**
* Returns the minimum distance required to start a drag operation, in pixels.
* @return (int) Pixel threshold required to start a drag.
*/
public int getDragStartThreshold(){
return dragStartThreshold;
}
/**
* Returns the minimum distance required to start a drag operation, in pixels.
* @param threshold (int) Pixel threshold required to start a drag.
*/
public void setDragStartThreshold( int threshold ){
dragStartThreshold = threshold;
}
/**
* Returns the minimum distance required to start a pinch operation, in pixels.
* @return (int) Pixel threshold required to start a pinch.
*/
public int getPinchStartThreshold(){
return pinchStartThreshold;
}
/**
* Returns the minimum distance required to start a pinch operation, in pixels.
* @param threshold (int) Pixel threshold required to start a pinch.
*/
public void setPinchStartThreshold( int threshold ){
pinchStartThreshold = threshold;
}
/**
* Adds a GestureListener to the ZoomPanLayout, which will receive gesture events
* @param listener (GestureListener) Listener to add
* @return (boolean) true when the listener set did not already contain the Listener, false otherwise
*/
public boolean addGestureListener( GestureListener listener ) {
return gestureListeners.add( listener );
}
/**
* Removes a GestureListener from the ZoomPanLayout
* @param listener (GestureListener) Listener to remove
* @return (boolean) if the Listener was removed, false otherwise
*/
public boolean removeGestureListener( GestureListener listener ) {
return gestureListeners.remove( listener );
}
/**
* Adds a ZoomPanListener to the ZoomPanLayout, which will receive events relating to zoom and pan actions
* @param listener (ZoomPanListener) Listener to add
* @return (boolean) true when the listener set did not already contain the Listener, false otherwise
*/
public boolean addZoomPanListener( ZoomPanListener listener ) {
return zoomPanListeners.add( listener );
}
/**
* Removes a ZoomPanListener from the ZoomPanLayout
* @param listener (ZoomPanListener) Listener to remove
* @return (boolean) if the Listener was removed, false otherwise
*/
public boolean removeZoomPanListener( ZoomPanListener listener ) {
return zoomPanListeners.remove( listener );
}
/**
* Scrolls the ZoomPanLayout to the x and y values specified by {@param point} Point
* @param point (Point) Point instance containing the destination x and y values
*/
public void scrollToPoint( Point point ) {
constrainPoint( point );
int ox = getScrollX();
int oy = getScrollY();
int nx = (int) point.x;
int ny = (int) point.y;
scrollTo( nx, ny );
if ( ox != nx || oy != ny ) {
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onScrollChanged( nx, ny );
listener.onZoomPanEvent();
}
}
}
/**
* Scrolls and centers the ZoomPanLayout to the x and y values specified by {@param point} Point
* @param point (Point) Point instance containing the destination x and y values
*/
public void scrollToAndCenter( Point point ) { // TODO:
int x = (int) -( getWidth() * 0.5 );
int y = (int) -( getHeight() * 0.5 );
point.offset( x, y );
scrollToPoint( point );
}
/**
* Scrolls the ZoomPanLayout to the x and y values specified by {@param point} Point using scrolling animation
* @param point (Point) Point instance containing the destination x and y values
*/
public void slideToPoint( Point point ) { // TODO:
constrainPoint( point );
int startX = getScrollX();
int startY = getScrollY();
int dx = point.x - startX;
int dy = point.y - startY;
scroller.startScroll( startX, startY, dx, dy, SLIDE_DURATION );
invalidate(); // we're posting invalidate in computeScroll, yet both are required
}
/**
* Scrolls and centers the ZoomPanLayout to the x and y values specified by {@param point} Point using scrolling animation
* @param point (Point) Point instance containing the destination x and y values
*/
public void slideToAndCenter( Point point ) { // TODO:
int x = (int) -( getWidth() * 0.5 );
int y = (int) -( getHeight() * 0.5 );
point.offset( x, y );
slideToPoint( point );
}
/**
* <i>This method is experimental</i>
* Scroll and scale to match passed Rect as closely as possible.
* The widget will attempt to frame the Rectangle, so that it's contained
* within the viewport, if possible.
* @param rect (Rect) rectangle to frame
*/
public void frameViewport( Rect rect ) {
// position it
scrollToPoint( new Point( rect.left, rect.top ) ); // TODO: center the axis that's smaller?
// scale it
double scaleX = getWidth() / (double) rect.width();
double scaleY = getHeight() / (double) rect.height();
double minimumScale = Math.min( scaleX, scaleY );
smoothScaleTo( minimumScale, SLIDE_DURATION );
}
/**
* Set the scale of the ZoomPanLayout while maintaining the current center point
* @param scale (double) The new value of the ZoomPanLayout scale
*/
public void setScaleFromCenter( double s ) {
s = Math.max( s, minScale );
s = Math.min( s, maxScale );
if ( s == scale )
return;
int centerOffsetX = (int) ( getWidth() * 0.5f );
int centerOffsetY = (int) ( getHeight() * 0.5f );
Point offset = new Point( centerOffsetX, centerOffsetY );
Point scroll = new Point( getScrollX(), getScrollY() );
scroll.offset( offset.x, offset.y );
double deltaScale = s / getScale();
int x = (int) ( scroll.x * deltaScale ) - offset.x;
int y = (int) ( scroll.y * deltaScale ) - offset.y;
Point destination = new Point( x, y );
setScale( s );
scrollToPoint( destination );
}
/**
* Adds a View to the intermediary ViewGroup that manages layout for the ZoomPanLayout.
* This View will be laid out at the width and height specified by {@setSize} at 0, 0
* All ViewGroup.addView signatures are routed through this signature, so the only parameters
* considered are child and index.
* @param child (View) The View to be added to the ZoomPanLayout view tree
* @param index (int) The position at which to add the child View
*/
@Override
public void addView( View child, int index, LayoutParams params ) {
LayoutParams lp = new LayoutParams( scaledWidth, scaledHeight );
clip.addView( child, index, lp );
}
@Override
public void removeAllViews() {
clip.removeAllViews();
}
@Override
public void removeViewAt( int index ) {
clip.removeViewAt( index );
}
@Override
public void removeViews( int start, int count ) {
clip.removeViews( start, count );
}
/**
* Scales the ZoomPanLayout with animated progress
* @param destination (double) The final scale to animate to
* @param duration (int) The duration (in milliseconds) of the animation
*/
public void smoothScaleTo( double destination, int duration ) {
if ( isTweening ) {
return;
}
saveHistoricalScale();
int x = (int) ( ( getWidth() * 0.5 ) + 0.5 );
int y = (int) ( ( getHeight() * 0.5 ) + 0.5 );
doubleTapStartOffset.set( x, y );
doubleTapStartScroll.set( getScrollX(), getScrollY() );
doubleTapStartScroll.offset( x, y );
startSmoothScaleTo( destination, duration );
}
// PRIVATE/PROTECTED
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
measureChildren( widthMeasureSpec, heightMeasureSpec );
int w = clip.getMeasuredWidth();
int h = clip.getMeasuredHeight();
w = Math.max( w, getSuggestedMinimumWidth() );
h = Math.max( h, getSuggestedMinimumHeight() );
w = resolveSize( w, widthMeasureSpec );
h = resolveSize( h, heightMeasureSpec );
setMeasuredDimension( w, h );
}
@Override
protected void onLayout( boolean changed, int l, int t, int r, int b ) {
clip.layout( 0, 0, clip.getMeasuredWidth(), clip.getMeasuredHeight() );
constrainScroll();
if ( changed ) {
calculateMinimumScaleToFit();
}
}
private void calculateMinimumScaleToFit() {
if ( scaleToFit ) {
double minimumScaleX = getWidth() / (double) baseWidth;
double minimumScaleY = getHeight() / (double) baseHeight;
double recalculatedMinScale = Math.max( minimumScaleX, minimumScaleY );
if ( recalculatedMinScale != minScale ) {
minScale = recalculatedMinScale;
setScale( scale );
}
}
}
private void updateClip() {
updateViewClip( clip );
for ( int i = 0; i < clip.getChildCount(); i++ ) {
View child = clip.getChildAt( i );
updateViewClip( child );
}
constrainScroll();
}
private void updateViewClip( View v ) {
LayoutParams lp = v.getLayoutParams();
lp.width = scaledWidth;
lp.height = scaledHeight;
v.setLayoutParams( lp );
}
@Override
public void computeScroll() {
if ( scroller.computeScrollOffset() ) {
Point destination = new Point( scroller.getCurrX(), scroller.getCurrY() );
scrollToPoint( destination );
dispatchScrollActionNotification();
postInvalidate(); // should not be necessary but is...
}
}
private void dispatchScrollActionNotification() {
if ( scrollActionHandler.hasMessages( 0 ) ) {
scrollActionHandler.removeMessages( 0 );
}
scrollActionHandler.sendEmptyMessageDelayed( 0, 100 );
}
private void handleScrollerAction() {
Point point = new Point();
point.x = getScrollX();
point.y = getScrollY();
for ( GestureListener listener : gestureListeners ) {
listener.onScrollComplete( point );
}
if ( isBeingFlung ) {
isBeingFlung = false;
for ( GestureListener listener : gestureListeners ) {
listener.onFlingComplete( point );
}
}
}
private void constrainPoint( Point point ) {
int x = point.x;
int y = point.y;
int mx = Math.max( 0, Math.min( x, getLimitX() ) );
int my = Math.max( 0, Math.min( y, getLimitY() ) );
if ( x != mx || y != my ) {
point.set( mx, my );
}
}
private void constrainScroll() { // TODO:
Point currentScroll = new Point( getScrollX(), getScrollY() );
Point limitScroll = new Point( currentScroll );
constrainPoint( limitScroll );
if ( !currentScroll.equals( limitScroll ) ) {
scrollToPoint( limitScroll );
}
}
private int getLimitX() {
return scaledWidth - getWidth();
}
private int getLimitY() {
return scaledHeight - getHeight();
}
private void saveHistoricalScale() {
historicalScale = scale;
}
private void savePinchHistory() {
int x = (int) ( ( firstFinger.x + secondFinger.x ) * 0.5 );
int y = (int) ( ( firstFinger.y + secondFinger.y ) * 0.5 );
pinchStartOffset.set( x, y );
pinchStartScroll.set( getScrollX(), getScrollY() );
pinchStartScroll.offset( x, y );
}
private void maintainScrollDuringPinchOperation() {
double deltaScale = scale / historicalScale;
int x = (int) ( pinchStartScroll.x * deltaScale ) - pinchStartOffset.x;
int y = (int) ( pinchStartScroll.y * deltaScale ) - pinchStartOffset.y;
destinationScroll.set( x, y );
scrollToPoint( destinationScroll );
}
private void saveDoubleTapHistory() {
doubleTapStartOffset.set( firstFinger.x, firstFinger.y );
doubleTapStartScroll.set( getScrollX(), getScrollY() );
doubleTapStartScroll.offset( doubleTapStartOffset.x, doubleTapStartOffset.y );
}
private void maintainScrollDuringScaleTween() {
double deltaScale = scale / historicalScale;
int x = (int) ( doubleTapStartScroll.x * deltaScale ) - doubleTapStartOffset.x;
int y = (int) ( doubleTapStartScroll.y * deltaScale ) - doubleTapStartOffset.y;
destinationScroll.set( x, y );
scrollToPoint( destinationScroll );
}
private void saveHistoricalPinchDistance() {
int dx = firstFinger.x - secondFinger.x;
int dy = firstFinger.y - secondFinger.y;
pinchStartDistance = Math.sqrt( dx * dx + dy * dy );
}
private void setScaleFromPinch() {
int dx = firstFinger.x - secondFinger.x;
int dy = firstFinger.y - secondFinger.y;
double pinchCurrentDistance = Math.sqrt( dx * dx + dy * dy );
double currentScale = pinchCurrentDistance / pinchStartDistance;
currentScale = Math.max( currentScale, MINIMUM_PINCH_SCALE );
currentScale = historicalScale * currentScale;
setScale( currentScale );
}
private void performDrag() {
Point delta = new Point();
if ( secondFingerIsDown && !firstFingerIsDown ) {
delta.set( lastSecondFinger.x, lastSecondFinger.y );
delta.offset( -secondFinger.x, -secondFinger.y );
} else {
delta.set( lastFirstFinger.x, lastFirstFinger.y );
delta.offset( -firstFinger.x, -firstFinger.y );
}
scrollPosition.offset( delta.x, delta.y );
scrollToPoint( scrollPosition );
}
private boolean performFling() {
if ( secondFingerIsDown ) {
return false;
}
velocity.computeCurrentVelocity( VELOCITY_UNITS );
double xv = velocity.getXVelocity();
double yv = velocity.getYVelocity();
double totalVelocity = Math.abs( xv ) + Math.abs( yv );
if ( totalVelocity > MINIMUM_VELOCITY ) {
scroller.fling( getScrollX(), getScrollY(), (int) -xv, (int) -yv, 0, getLimitX(), 0, getLimitY() );
postInvalidate();
return true;
}
return false;
}
// if the taps occurred within threshold, it's a double tap
private boolean determineIfQualifiedDoubleTap() {
long now = System.currentTimeMillis();
long ellapsed = now - lastTouchedAt;
lastTouchedAt = now;
return ( ellapsed <= DOUBLE_TAP_TIME_THRESHOLD ) && ( Math.abs( firstFinger.x - doubleTapHistory.x ) <= SINGLE_TAP_DISTANCE_THRESHOLD )
&& ( Math.abs( firstFinger.y - doubleTapHistory.y ) <= SINGLE_TAP_DISTANCE_THRESHOLD );
}
private void saveTapActionOrigination() {
singleTapHistory.set( firstFinger.x, firstFinger.y );
}
private void saveDoubleTapOrigination() {
doubleTapHistory.set( firstFinger.x, firstFinger.y );
}
private void saveFirstFingerDown() {
firstFingerLastDown.set ( firstFinger.x, firstFinger.y );
}
private void saveSecondFingerDown() {
secondFingerLastDown.set ( secondFinger.x, secondFinger.y );
}
private void setTapInterrupted( boolean v ) {
isTapInterrupted = v;
}
// if the touch event has traveled past threshold since the finger first when down, it's not a tap
private boolean determineIfQualifiedSingleTap() {
return !isTapInterrupted && ( Math.abs( firstFinger.x - singleTapHistory.x ) <= SINGLE_TAP_DISTANCE_THRESHOLD )
&& ( Math.abs( firstFinger.y - singleTapHistory.y ) <= SINGLE_TAP_DISTANCE_THRESHOLD );
}
private void startSmoothScaleTo( double destination, int duration ){
if ( isTweening ) {
return;
}
doubleTapDestinationScale = destination;
tween.setDuration( duration );
tween.start();
}
private void processEvent( MotionEvent event ) {
// copy for history
lastFirstFinger.set( firstFinger.x, firstFinger.y );
lastSecondFinger.set( secondFinger.x, secondFinger.y );
// set false for now
firstFingerIsDown = false;
secondFingerIsDown = false;
// determine which finger is down and populate the appropriate points
for ( int i = 0; i < event.getPointerCount(); i++ ) {
int id = event.getPointerId( i );
int x = (int) event.getX( i );
int y = (int) event.getY( i );
switch ( id ) {
case 0:
firstFingerIsDown = true;
firstFinger.set( x, y );
actualPoint.set( x, y );
break;
case 1:
secondFingerIsDown = true;
secondFinger.set( x, y );
actualPoint.set( x, y );
break;
}
}
// record scroll position and adjust finger point to account for scroll offset
scrollPosition.set( getScrollX(), getScrollY() );
actualPoint.offset( scrollPosition.x, scrollPosition.y );
// update velocity for flinging
// TODO: this can probably be moved to the ACTION_MOVE switch
if ( velocity == null ) {
velocity = VelocityTracker.obtain();
}
velocity.addMovement( event );
}
@Override
public boolean onTouchEvent( MotionEvent event ) {
// update positions
processEvent( event );
// get the type of action
final int action = event.getAction() & MotionEvent.ACTION_MASK;
// react based on nature of touch event
switch ( action ) {
// first finger goes down
case MotionEvent.ACTION_DOWN:
if ( !scroller.isFinished() ) {
scroller.abortAnimation();
}
isBeingFlung = false;
isDragging = false;
setTapInterrupted( false );
saveFirstFingerDown();
saveTapActionOrigination();
for ( GestureListener listener : gestureListeners ) {
listener.onFingerDown( actualPoint );
}
break;
// second finger goes down
case MotionEvent.ACTION_POINTER_DOWN:
isPinching = false;
saveSecondFingerDown();
setTapInterrupted( true );
for ( GestureListener listener : gestureListeners ) {
listener.onFingerDown( actualPoint );
}
break;
// either finger moves
case MotionEvent.ACTION_MOVE:
// if both fingers are down, that means it's a pinch
if ( firstFingerIsDown && secondFingerIsDown ) {
if ( !isPinching ) {
double firstFingerDistance = getDistance( firstFinger, firstFingerLastDown );
double secondFingerDistance = getDistance( secondFinger, secondFingerLastDown );
double distance = ( firstFingerDistance + secondFingerDistance ) * 0.5;
isPinching = distance >= pinchStartThreshold;
// are we starting a pinch action?
if ( isPinching ) {
saveHistoricalPinchDistance();
saveHistoricalScale();
savePinchHistory();
for ( GestureListener listener : gestureListeners ) {
listener.onPinchStart( pinchStartOffset );
}
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onZoomStart( scale );
listener.onZoomPanEvent();
}
}
}
if ( isPinching ) {
setScaleFromPinch();
maintainScrollDuringPinchOperation();
for ( GestureListener listener : gestureListeners ) {
listener.onPinch( pinchStartOffset );
}
}
// otherwise it's a drag
} else {
if ( !isDragging ) {
double distance = getDistance( firstFinger, firstFingerLastDown );
isDragging = distance >= dragStartThreshold;
}
if ( isDragging ) {
performDrag();
for ( GestureListener listener : gestureListeners ) {
listener.onDrag( actualPoint );
}
}
}
break;
// first finger goes up
case MotionEvent.ACTION_UP:
if ( performFling() ) {
isBeingFlung = true;
Point startPoint = new Point( getScrollX(), getScrollY() );
Point finalPoint = new Point( scroller.getFinalX(), scroller.getFinalY() );
for ( GestureListener listener : gestureListeners ) {
listener.onFling( startPoint, finalPoint );
}
}
if ( velocity != null ) {
velocity.recycle();
velocity = null;
}
// could be a single tap...
if ( determineIfQualifiedSingleTap() ) {
for ( GestureListener listener : gestureListeners ) {
listener.onTap( actualPoint );
}
}
// or a double tap
if ( determineIfQualifiedDoubleTap() ) {
scroller.forceFinished( true );
saveHistoricalScale();
saveDoubleTapHistory();
double destination;
if ( scale >= maxScale ) {
destination = minScale;
} else {
destination = Math.min( maxScale, scale * 2 );
}
startSmoothScaleTo( destination, ZOOM_ANIMATION_DURATION );
for ( GestureListener listener : gestureListeners ) {
listener.onDoubleTap( actualPoint );
}
}
// either way it's a finger up event
for ( GestureListener listener : gestureListeners ) {
listener.onFingerUp( actualPoint );
}
// save coordinates to measure against the next double tap
saveDoubleTapOrigination();
isDragging = false;
isPinching = false;
break;
// second finger goes up
case MotionEvent.ACTION_POINTER_UP:
isPinching = false;
setTapInterrupted( true );
for ( GestureListener listener : gestureListeners ) {
listener.onFingerUp( actualPoint );
}
for ( GestureListener listener : gestureListeners ) {
listener.onPinchComplete( pinchStartOffset );
}
for ( ZoomPanListener listener : zoomPanListeners ) {
listener.onZoomComplete( scale );
listener.onZoomPanEvent();
}
break;
}
return true;
}
// sugar to calculate distance between 2 Points, because android.graphics.Point is horrible
private static double getDistance( Point p1, Point p2 ) {
int x = p1.x - p2.x;
int y = p1.y - p2.y;
return Math.sqrt( x * x + y * y );
}
private static class ScrollActionHandler extends Handler {
private final WeakReference<ZoomPanLayout> reference;
public ScrollActionHandler( ZoomPanLayout zoomPanLayout ) {
super();
reference = new WeakReference<ZoomPanLayout>( zoomPanLayout );
}
@Override
public void handleMessage( Message msg ) {
ZoomPanLayout zoomPanLayout = reference.get();
if ( zoomPanLayout != null ) {
zoomPanLayout.handleScrollerAction();
}
}
}
// Public static interfaces and classes
public static interface ZoomPanListener {
public void onScaleChanged( double scale );
public void onScrollChanged( int x, int y );
public void onZoomStart( double scale );
public void onZoomComplete( double scale );
public void onZoomPanEvent();
}
public static interface GestureListener {
public void onFingerDown( Point point );
public void onScrollComplete( Point point );
public void onFingerUp( Point point );
public void onDrag( Point point );
public void onDoubleTap( Point point );
public void onTap( Point point );
public void onPinch( Point point );
public void onPinchStart( Point point );
public void onPinchComplete( Point point );
public void onFling( Point startPoint, Point finalPoint );
public void onFlingComplete( Point point );
}
}
|
package org.fiware.apps.marketplace.it;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.fiware.apps.marketplace.model.Categories;
import org.fiware.apps.marketplace.model.Category;
import org.fiware.apps.marketplace.model.Description;
import org.fiware.apps.marketplace.model.Descriptions;
import org.fiware.apps.marketplace.model.ErrorType;
import org.fiware.apps.marketplace.model.Offering;
import org.fiware.apps.marketplace.model.Offerings;
import org.fiware.apps.marketplace.model.Review;
import org.fiware.apps.marketplace.model.Reviews;
import org.fiware.apps.marketplace.model.Service;
import org.fiware.apps.marketplace.model.Store;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DescriptionServiceIT extends AbstractIT {
private final static String USER_NAME = "marketplace";
private final static String PASSWORD = "password1!a";
private final static String EMAIL = "example@example.com";
private final static String FIRST_STORE_NAME = "wstore";
private final static String FIRST_STORE_URL = "http://store.lab.fiware.org";
private final static String SECOND_STORE_NAME = "wstore-testbed";
private final static String SECOND_STORE_URL = "http://store.testbed.fiware.org";
private final static String MESSAGE_NAME_IN_USE = "This name is already in use in this Store.";
private final static String MESSAGE_URL_IN_USE = "This URL is already in use in this Store.";
private final static String MESSAGE_INVALID_RDF = "Your RDF could not be parsed.";
private final static String MESSAGE_DESCRIPTION_NOT_FOUND = "Description %s not found in Store %s";
@Before
public void setUp() {
createUser(USER_NAME, EMAIL, PASSWORD);
createStore(USER_NAME, PASSWORD, FIRST_STORE_NAME, FIRST_STORE_URL);
startMockServer();
}
@After
public void stopMockServer() {
wireMock.stop();
}
/////////////////////////////////////// AUXILIAR //////////////////////////////////////
private Response getDescription(String userName, String password, String storeName, String descriptionName) {
Client client = ClientBuilder.newClient();
return client.target(endPoint + "/api/v2/store/" + storeName + "/description/" + descriptionName)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
/**
* This method retrieves an offering from the list of obtained offerings and check if its
* price plans, services and categories are OK
* @param offerings The list of offerings that the service has returned
* @param storeName The name of the store where the offering is registered
* @param descriptionName The of the the description that contains the offering
* @param offering The offering to be checked. This instance contains the expected values.
*/
private void checkOfferingInternalState(List<Offering> offerings, String storeName, String descriptionName,
Offering offering) {
// Required for indexOf to work
Store store = new Store();
store.setName(storeName);
Description description = new Description();
description.setName(descriptionName);
description.setStore(store);
offering.setDescribedIn(description);
// Get offering from the list
int index = offerings.indexOf(offering);
Offering receivedOffering = offerings.get(index);
assertThat(receivedOffering.getPricePlans()).isEqualTo(offering.getPricePlans());
assertThat(offerings.get(index).getCategories()).isEqualTo(offering.getCategories());
// Services should be manually compared, since the URI is not sent to the final user and is the only
// field used in equals...
assertThat(receivedOffering.getServices().size()).isEqualTo(offering.getServices().size());
for (Service service: offering.getServices()) {
boolean found = false;
Iterator<Service> servicesIterator = receivedOffering.getServices().iterator();
while(servicesIterator.hasNext() && !found) {
Service receivedService = servicesIterator.next();
if (service.getDisplayName().equals(receivedService.getDisplayName()) &&
service.getComment().equals(receivedService.getComment())) {
found = true;
}
}
// When the loop ends, the service should have been found
assertThat(found).isTrue();
}
}
private void checkOfferingInList(String storeName, String descriptionName,
String offeringUri, List<Offering> offeringsList) {
// We must set the description into the offering in order to make "isIn" work appropriately
// "isIn" is based on "equals" and it depends on the URL of the offering and its description
Offering offering = new Offering();
offering.setUri(offeringUri);
// A description is managed by one store
Store store = new Store();
store.setName(storeName);
// Description.equals depends on the name and its store
Description description = new Description();
description.setName(descriptionName);
description.setStore(store);
offering.setDescribedIn(description);
// Check that the offering is contained in the list of offerings returned by WMarket
assertThat(offering).isIn(offeringsList);
}
private void checkDescription(String userName, String password, String storeName,
String descriptionName, String displayName, String url, String comment) {
Description retrievedDescription = getDescription(userName, password, storeName, descriptionName)
.readEntity(Description.class);
assertThat(retrievedDescription.getName()).isEqualTo(descriptionName);
assertThat(retrievedDescription.getDisplayName()).isEqualTo(displayName);
assertThat(retrievedDescription.getUrl()).isEqualTo(url);
assertThat(retrievedDescription.getComment()).isEqualTo(comment);
// Check offerings
List<Offering> expectedOfferings = DESCRIPTIONS_OFFERINGS.get(url);
List<Offering> descriptionOfferings = retrievedDescription.getOfferings();
assertThat(descriptionOfferings.size()).isEqualTo(expectedOfferings.size());
for (Offering expectedOffering: expectedOfferings) {
checkOfferingInList(storeName, descriptionName, expectedOffering.getUri(), descriptionOfferings);
// Check internal state (services, categories, price plans,...)
checkOfferingInternalState(descriptionOfferings, storeName, descriptionName, expectedOffering);
}
}
private Response createOrUpdateDescription(String userName, String password, String storeName,
String descriptionName, String displayName, String url, String comment) {
Description description = new Description();
description.setDisplayName(displayName);
description.setUrl(url);
description.setComment(comment);
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + storeName + "/description/" + descriptionName)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password))
.post(Entity.entity(description, MediaType.APPLICATION_JSON));
return response;
}
//////////////////////////////////////// CREATE ///////////////////////////////////////
private Response createDescription(String userName, String password, String storeName, String displayName,
String url, String comment) {
return createOrUpdateDescription(userName, password, storeName, "", displayName, url, comment);
}
private void testCreation(String url) {
String displayName = "Description 1";
String descriptionName = "description-1";
String descriptionComment = "Example Comment";
Response response = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName, url,
descriptionComment);
assertThat(response.getStatus()).isEqualTo(201);
assertThat(response.getHeaderString("Location")).isEqualTo(endPoint + "/api/v2/store/" + FIRST_STORE_NAME +
"/description/" + descriptionName);
// Check that the description actually exists
checkDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, descriptionName, displayName, url,
descriptionComment);
}
@Test
public void testCreationDefaultUSDL() {
testCreation(defaultUSDLPath);
}
@Test
public void testCreationSecondaryUSDL() {
testCreation(secondaryUSDLPath);
}
private void testCreationInvalidField(String displayName, String url, String comment, String invalidField,
String message) {
Response response = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName, url, comment);
checkAPIError(response, 400, invalidField, message, ErrorType.VALIDATION_ERROR);
}
@Test
public void testCreationDisplayNameInvalid() {
testCreationInvalidField("Description!", defaultUSDLPath, "", "displayName",
MESSAGE_INVALID_DISPLAY_NAME);
}
@Test
public void testCreationDisplayNameTooShort() {
testCreationInvalidField("a", defaultUSDLPath, "", "displayName",
String.format(MESSAGE_TOO_SHORT, 3));
}
@Test
public void testCreationDisplayNameTooLong() {
testCreationInvalidField("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
+ "abcdefghijklmnopqrstuvw", defaultUSDLPath, "", "displayName",
String.format(MESSAGE_TOO_LONG, 100));
}
@Test
public void testCreationURLInvalid() {
testCreationInvalidField("Description", "https:/127.0.0.1:" + wireMock.port(), "", "url",
MESSAGE_INVALID_URL);
}
@Test
public void testCreationRDFInvalid() {
testCreationInvalidField("Description", serverUrl, "", "url", MESSAGE_INVALID_RDF);
}
@Test
public void testCreationCommentTooLong() {
testCreationInvalidField("Description", defaultUSDLPath, "12345678901234567890123456789012345678901234567890"
+ "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
+ "7890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
"comment", String.format(MESSAGE_TOO_LONG, 200));
}
private void testCreationFieldAlreadyExists(String displayName1, String displayName2, String url1, String url2,
String field, String expectedMessage) {
createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName1, url1, "");
Response response = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName2, url2, "");
checkAPIError(response, 400, field, expectedMessage, ErrorType.VALIDATION_ERROR);
}
@Test
public void testCreationDisplayNameAlreadyExists() {
String displayName = "Description 1";
// name is based on display name and name is checked before display name...
testCreationFieldAlreadyExists(displayName, displayName, defaultUSDLPath, defaultUSDLPath + "a", "displayName",
MESSAGE_NAME_IN_USE);
}
@Test
public void testCreationURLAlreadyExists() {
testCreationFieldAlreadyExists("offering-1", "offering-2", defaultUSDLPath, defaultUSDLPath, "url",
MESSAGE_URL_IN_USE);
}
@Test
public void testCreationNameAndUrlAlreadyExistsInAnotherStore() {
// Create another Store
String descriptionName = "description-1";
createStore(USER_NAME, PASSWORD, SECOND_STORE_NAME, SECOND_STORE_URL);
Response createResponse1 = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionName, defaultUSDLPath, "");
Response createResponse2 = createDescription(USER_NAME, PASSWORD, SECOND_STORE_NAME,
descriptionName, defaultUSDLPath, "");
// Both offerings can be created
assertThat(createResponse1.getStatus()).isEqualTo(201);
assertThat(createResponse2.getStatus()).isEqualTo(201);
}
@Test
public void testDeleteUserWithDescription() {
String name = "description-1";
Response createStoreResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name,
defaultUSDLPath, "");
assertThat(createStoreResponse.getStatus()).isEqualTo(201);
checkDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name, name, defaultUSDLPath, "");
// Delete user
Response deleteUserResponse = deleteUser(USER_NAME, PASSWORD, USER_NAME);
assertThat(deleteUserResponse.getStatus()).isEqualTo(204);
// Create another user to be able to check the store
String newUserName = USER_NAME + "a";
String email = "new_email__@example.com";
Response createUserResponse = createUser(newUserName, email, PASSWORD);
assertThat(createUserResponse.getStatus()).isEqualTo(201);
// Check that the Store does not exist anymore
Response getStoreResponse = getDescription(newUserName, PASSWORD, FIRST_STORE_NAME, name);
checkAPIError(getStoreResponse, 404, null, String.format(MESSAGE_STORE_NOT_FOUND, FIRST_STORE_NAME),
ErrorType.NOT_FOUND);
}
//////////////////////////////////////// UPDATE ///////////////////////////////////////
private Response updateDescription(String userName, String password, String storeName,
String descriptionName, String displayName, String url, String comment) {
return createOrUpdateDescription(userName, password, storeName, descriptionName, displayName, url, comment);
}
private void testUpdate(String newDisplayName, String newUrl, String newComment) {
// Create Description
String name = "description-1";
String displayName = "Description-1";
String comment = "commnet1";
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName,
defaultUSDLPath, comment);
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Update the description
Response updateDescriptionResponse = updateDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name,
newDisplayName, newUrl, newComment);
assertThat(updateDescriptionResponse.getStatus()).isEqualTo(200);
// Check that the description has been updated
String expectedDisplayName = newDisplayName == null ? displayName : newDisplayName;
String expectedUrl = newUrl == null ? defaultUSDLPath : newUrl;
String expectedComment = newComment == null ? comment : newComment;
checkDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name, expectedDisplayName,
expectedUrl, expectedComment);
}
@Test
public void testUpdateNameAndDescription() {
testUpdate("Description 2", null, "comment-2");
}
@Test
public void tesUpdateUrlSameUrl() {
testUpdate(null, defaultUSDLPath, null);
}
@Test
public void testUpdateUrlDifferentUrl() {
testUpdate(null, secondaryUSDLPath, null);
}
private void testUpdateInvalidField(String newDisplayName, String newUrl, String newComment,
String invalidField, String message) {
String name = "offering";
String displayName = "Offering";
String comment = "";
Response createResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName,
defaultUSDLPath, comment);
assertThat(createResponse.getStatus()).isEqualTo(201);
Response updateResponse = updateDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name, newDisplayName,
newUrl, newComment);
checkAPIError(updateResponse, 400, invalidField, message, ErrorType.VALIDATION_ERROR);
}
@Test
public void testUpdateDisplayNameInvalid() {
testUpdateInvalidField("Description!", defaultUSDLPath, "", "displayName",
MESSAGE_INVALID_DISPLAY_NAME);
}
@Test
public void testUpdateDisplayNameTooShort() {
testUpdateInvalidField("a", defaultUSDLPath, "", "displayName",
String.format(MESSAGE_TOO_SHORT, 3));
}
@Test
public void testUpdateDisplayNameTooLong() {
testUpdateInvalidField("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
+ "abcdefghijklmnopqrstuvw", defaultUSDLPath, "", "displayName",
String.format(MESSAGE_TOO_LONG, 100));
}
@Test
public void testUpdateURLInvalid() {
testUpdateInvalidField("Description", "https:/store.lab.fiware.org/offering1.rdf", "", "url",
MESSAGE_INVALID_URL);
}
@Test
public void testUpdateRDFInvalid() {
testUpdateInvalidField("Description", serverUrl, "", "url", MESSAGE_INVALID_RDF);
}
@Test
public void testUpdateCommentTooLong() {
testUpdateInvalidField("Offering", serverUrl, "12345678901234567890123456789012345678901234567890"
+ "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
+ "7890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
"comment", String.format(MESSAGE_TOO_LONG, 200));
}
/**
* This methods creates two descriptions, based on the different parameters and tries to updates the second
* description based on updatedDisplayName and updatedURL. However, it's expected that one of these parameters
* has been used to create the first description, so an error should arise. Error details should be contained in
* field an expectedMessage.
* @param nameDescription1 The name of the first description
* @param urlDescription1 The URL of the first description
* @param nameDescription2 The name of the second description (the one to be updated). This name is used to modify
* the description so this is not a displayName but the name (the one without spaces, ...)
* @param urlDescription2 The URL of the second description (the one to be updated)
* @param updatedDisplayName The new display name to be set in the second description
* @param updatedURL The new URL to be set in the second description
* @param field The field that is repeated
* @param expectedMessage Expected error message
*/
private void testUpdateFieldAlreayExists(
String nameDescription1, String urlDescription1,
String nameDescription2, String urlDescription2,
String updatedDisplayName, String updatedURL,
String field, String expectedMessage) {
Response createStore1Response = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, nameDescription1,
urlDescription1, "");
Response createStore2Response = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, nameDescription2,
urlDescription2, "");
assertThat(createStore1Response.getStatus()).isEqualTo(201);
assertThat(createStore2Response.getStatus()).isEqualTo(201);
Response updateResponse = updateDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, nameDescription2,
updatedDisplayName, updatedURL, null);
checkAPIError(updateResponse, 400, field, expectedMessage, ErrorType.VALIDATION_ERROR);
}
@Test
public void testUpdateDisplayNameAlreadyExists() {
String displayName = "description";
testUpdateFieldAlreayExists(
displayName, defaultUSDLPath,
"descritpion-2", secondaryUSDLPath,
displayName, null,
"displayName", MESSAGE_NAME_IN_USE);
}
@Test
public void testUpdateURLAlreadyExists() {
testUpdateFieldAlreayExists(
"description", defaultUSDLPath,
"description-2", secondaryUSDLPath,
"description-2", defaultUSDLPath,
"url", MESSAGE_URL_IN_USE);
}
@Test
public void testUpdateNonExisting() {
String displayName = "offering-1";
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName,
defaultUSDLPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Update non-existing description
String descriptionToBeUpdated = displayName + "a"; //This ID is supposed not to exist
Response updateDescriptionResponse = updateDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionToBeUpdated, "new display", null, null);
checkAPIError(updateDescriptionResponse, 404, null,
String.format(MESSAGE_DESCRIPTION_NOT_FOUND, descriptionToBeUpdated,
FIRST_STORE_NAME), ErrorType.NOT_FOUND);
}
@Test
public void testUpdateWithAnotherUser() {
String displayName = "offering-1";
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, displayName,
defaultUSDLPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Create another user
String newUserName = USER_NAME + "a";
String email = "new_email__@example.com";
createUser(newUserName, email, PASSWORD);
// Update description with the new user
Response updateDescriptionResponse = updateDescription(newUserName, PASSWORD, FIRST_STORE_NAME, displayName,
"new display name", null, null);
checkAPIError(updateDescriptionResponse, 403, null,
String.format(MESSAGE_NOT_AUTHORIZED, "update description"), ErrorType.FORBIDDEN);
}
//////////////////////////////////////// DELETE ///////////////////////////////////////
private Response deleteDescription(String authUserName, String authPassword, String storeName,
String descriptionName) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + storeName + "/description/" + descriptionName)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(authUserName, authPassword))
.delete();
return response;
}
@Test
public void testDelete() {
String name = "description-1";
// Create the description
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name,
defaultUSDLPath, null);
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Delete the description
Response deleteDescriptionResponse = deleteDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name);
assertThat(deleteDescriptionResponse.getStatus()).isEqualTo(204);
}
@Test
public void testDeleteNonExisting() {
String name = "description-1";
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name,
defaultUSDLPath, null);
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Delete non-existing description
String descriptionToBeDeleted = name + "a"; //This ID is supposed not to exist
Response deleteStoreResponse = deleteDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionToBeDeleted);
checkAPIError(deleteStoreResponse, 404, null,
String.format(MESSAGE_DESCRIPTION_NOT_FOUND, descriptionToBeDeleted,
FIRST_STORE_NAME), ErrorType.NOT_FOUND);
}
@Test
public void testDeleteWithAnotherUser() {
String name = "description-1";
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, name,
defaultUSDLPath, null);
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Create another user
String newUserName = USER_NAME + "a";
String email = "new_email__@example.com";
createUser(newUserName, email, PASSWORD);
//Delete user
Response deleteStoreResponse = deleteDescription(newUserName, PASSWORD, FIRST_STORE_NAME, name);
checkAPIError(deleteStoreResponse, 403, null, String.format(MESSAGE_NOT_AUTHORIZED, "delete description"),
ErrorType.FORBIDDEN);
}
////////////////////////////////// LIST DESCRIPTIONS //////////////////////////////////
@Test
public void testListAllDescriptionsInStore() {
int DESCRIPTIONS_CREATED = 6;
// Create some descriptions
String displayNamePattern = "Store %d";
String urlPattern = serverUrl + "/default%d.rdf";
for (int i = 0; i < DESCRIPTIONS_CREATED; i++) {
createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, String.format(displayNamePattern, i),
String.format(urlPattern, i), "");
}
// Get all descriptions
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + FIRST_STORE_NAME + "/description")
.request(MediaType.APPLICATION_JSON).header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
// Check the response
assertThat(response.getStatus()).isEqualTo(200);
Descriptions descriptions = response.readEntity(Descriptions.class);
assertThat(descriptions.getDescriptions().size()).isEqualTo(DESCRIPTIONS_CREATED);
// Users are supposed to be returned in order
for (int i = 0; i < DESCRIPTIONS_CREATED; i++) {
Description description = descriptions.getDescriptions().get(i);
assertThat(description.getDisplayName()).isEqualTo(String.format(displayNamePattern, i));
assertThat(description.getUrl()).isEqualTo(String.format(urlPattern, i));
}
}
private void testListSomeDescriptionsInStore(int offset, int max) {
int DESCRIPTIONS_CREATED = 10;
// Create some descriptions
String displayNamePattern = "Store %d";
String urlPattern = serverUrl + "/default%d.rdf";
for (int i = 0; i < DESCRIPTIONS_CREATED; i++) {
createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, String.format(displayNamePattern, i),
String.format(urlPattern, i), "");
}
// Get required descriptions
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + FIRST_STORE_NAME + "/description")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
// Check the response
int expectedElements = (offset + max) > DESCRIPTIONS_CREATED ? DESCRIPTIONS_CREATED - offset : max;
assertThat(response.getStatus()).isEqualTo(200);
Descriptions descriptions = response.readEntity(Descriptions.class);
assertThat(descriptions.getDescriptions().size()).isEqualTo(expectedElements);
// Users are supposed to be returned in order
for (int i = offset; i < offset + expectedElements; i++) {
Description description = descriptions.getDescriptions().get(i - offset);
assertThat(description.getDisplayName()).isEqualTo(String.format(displayNamePattern, i));
assertThat(description.getUrl()).isEqualTo(String.format(urlPattern, i));
}
}
@Test
public void testListSomeDescriptionsMaxInRange() {
testListSomeDescriptionsInStore(3, 4);
}
@Test
public void testListSomeDescriptionsMaxNotInRange() {
testListSomeDescriptionsInStore(5, 7);
}
private void testListDescriptionsInStoreInvalidParams(int offset, int max) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + FIRST_STORE_NAME + "/description")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, MESSAGE_INVALID_OFFSET_MAX, ErrorType.BAD_REQUEST);
}
@Test
public void testListDescriptionsInStoreInvalidOffset() {
testListDescriptionsInStoreInvalidParams(-1, 2);
}
@Test
public void testListDescriptionsInStoreInvalidMax() {
testListDescriptionsInStoreInvalidParams(1, 0);
}
////////////////////////////////// ALL DESCRIPTIONS //////////////////////////////////
private void testListDescriptions(int offset, int max) {
// Create an additional Store
Response createStoreResponse = createStore(USER_NAME, PASSWORD, SECOND_STORE_NAME, SECOND_STORE_URL);
assertThat(createStoreResponse.getStatus()).isEqualTo(201);
// Create descriptions (2)
Description[] originalDescriptions = new Description[2];
Description description0 = new Description();
description0.setName("default");
description0.setUrl(defaultUSDLPath);
Description description1 = new Description();
description1.setName("secondary");
description1.setUrl(secondaryUSDLPath);
originalDescriptions[0] = description0;
originalDescriptions[1] = description1;
// Insert descriptions (2) into the Stores (2). Total: 4 descriptions
String[] stores = new String[]{FIRST_STORE_NAME, SECOND_STORE_NAME};
for (String store: stores) {
for (Description description: originalDescriptions) {
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, store,
description.getName(), description.getUrl(), "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
}
}
// Get all descriptions
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/description")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
// Check that the right number of descriptions has been returned...
Descriptions retrievedDescriptions = response.readEntity(Descriptions.class);
int descriptionsCreated = stores.length * originalDescriptions.length; // 4 descriptions
int expectedElements = offset + max > descriptionsCreated ? descriptionsCreated - offset : max;
assertThat(retrievedDescriptions.getDescriptions().size()).isEqualTo(expectedElements);
// Check descriptions
for (int i = 0; i < retrievedDescriptions.getDescriptions().size(); i++) {
Description description = retrievedDescriptions.getDescriptions().get(i);
int indexInGeneralArray = offset + i;
// Check that store name is correct
// Store 0: [DESC0, DESC1], Store 1: [DESC2, DESC3], ...
int storeIndex = indexInGeneralArray / originalDescriptions.length;
assertThat(description.getStore().getName()).isEqualTo(stores[storeIndex]);
// Check that the description is correct
// Even -> Description 1 (description1Name, defaultUSDLPath)
// Odd -> Description 2 (description2Name, secondaryUSDLPath)
int descriptionIndex = indexInGeneralArray % originalDescriptions.length;
assertThat(description.getName()).isEqualTo(originalDescriptions[descriptionIndex].getName());
assertThat(description.getUrl()).isEqualTo(originalDescriptions[descriptionIndex].getUrl());
}
}
@Test
public void testListAllDescriptions() {
testListDescriptions(0, 100);
}
@Test
public void testListSomeDescriptions() {
testListDescriptions(1, 3);
}
private void testListDescriptionsInvalidParams(int offset, int max) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/description")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, MESSAGE_INVALID_OFFSET_MAX, ErrorType.BAD_REQUEST);
}
@Test
public void testListDescriptionsInvalidOffset() {
testListDescriptionsInvalidParams(-1, 2);
}
@Test
public void testListDescriptionsInvalidMax() {
testListDescriptionsInvalidParams(1, 0);
}
/////////////////////////////////// STORE OFFERINGS ///////////////////////////////////
private Response getStoreOfferings(String userName, String password, String storeName) {
Client client = ClientBuilder.newClient();
return client.target(endPoint + "/api/v2/store/" + storeName + "/offering/")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
private Response getStoreOfferings(String userName, String password, String storeName, int offset, int max) {
Client client = ClientBuilder.newClient();
return client.target(endPoint + "/api/v2/store/" + storeName + "/offering/")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
@Test
public void testStoreOfferings() {
final String NAME = "store";
final String USDL = "usdl";
String description1Name = "displayname";
String description2Name = "secondary";
Map<String, Map<String, String>> storeDescriptions = new HashMap<>();
Map<String, String> firstStoreDescription = new HashMap<>();
firstStoreDescription.put(NAME, description1Name);
firstStoreDescription.put(USDL, defaultUSDLPath);
storeDescriptions.put(FIRST_STORE_NAME, firstStoreDescription);
Map<String, String> secondStoreDescription = new HashMap<>();
secondStoreDescription.put(NAME, description2Name);
secondStoreDescription.put(USDL, secondaryUSDLPath);
storeDescriptions.put(SECOND_STORE_NAME, secondStoreDescription);
// Create an additional Store
Response createStoreResponse = createStore(USER_NAME, PASSWORD, SECOND_STORE_NAME, SECOND_STORE_URL);
assertThat(createStoreResponse.getStatus()).isEqualTo(201);
// Push each description in a different store
for (String storeName: storeDescriptions.keySet()) {
String descriptionName = storeDescriptions.get(storeName).get(NAME);
String usdl = storeDescriptions.get(storeName).get(USDL);
Response createDescRes = createDescription(USER_NAME, PASSWORD, storeName, descriptionName, usdl, "");
assertThat(createDescRes.getStatus()).isEqualTo(201);
}
// Get stores offerings
for (String storeName: storeDescriptions.keySet()) {
Response storeOfferingResponse = getStoreOfferings(USER_NAME, PASSWORD, storeName);
assertThat(storeOfferingResponse.getStatus()).isEqualTo(200);
Offerings offerings = storeOfferingResponse.readEntity(Offerings.class);
String descriptionName = storeDescriptions.get(storeName).get(NAME);
String descriptionUSDLPath = storeDescriptions.get(storeName).get(USDL);
List<Offering> expectedStoreOfferings = DESCRIPTIONS_OFFERINGS.get(descriptionUSDLPath);
List<Offering> actualStoreOfferings = offerings.getOfferings();
assertThat(actualStoreOfferings.size()).isEqualTo(expectedStoreOfferings.size());
// Check that all the expected offerings are in the list of offerings contained in the store
for (Offering offering: expectedStoreOfferings) {
checkOfferingInList(storeName, descriptionName, offering.getUri(), offerings.getOfferings());
checkOfferingInternalState(offerings.getOfferings(), storeName, descriptionName, offering);
}
}
}
private void testGetSomeStoreOfferings(int offset, int max) {
int OFFERINGS_IN_DESCRIPTION = 2;
// We are using the description that contains two offerings
// and checking if offset and max works in an appropriate way
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD,
FIRST_STORE_NAME, "displayName", secondaryUSDLPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Check that the number of returned offerings is correct
Response storeOfferingResponse = getStoreOfferings(USER_NAME, PASSWORD, FIRST_STORE_NAME, offset, max);
Offerings offerings = storeOfferingResponse.readEntity(Offerings.class);
int expectedElements = offset + max > OFFERINGS_IN_DESCRIPTION ? OFFERINGS_IN_DESCRIPTION - offset : max;
assertThat(offerings.getOfferings().size()).isEqualTo(expectedElements);
}
@Test
public void testGetFirstStoreOffering() {
testGetSomeStoreOfferings(0, 1);
}
@Test
public void tesGetSecondStoreOffering() {
testGetSomeStoreOfferings(1, 1);
}
@Test
public void tesGetAllStoreOffering() {
testGetSomeStoreOfferings(0, 2);
}
private void testListOfferingsInStoreInvalidParams(int offset, int max, String orderBy, String expectedMessage) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + FIRST_STORE_NAME + "/offering")
.queryParam("offset", offset)
.queryParam("max", max)
.queryParam("orderBy", orderBy)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, expectedMessage, ErrorType.BAD_REQUEST);
}
@Test
public void testListOfferingsInStoreInvalidOffset() {
testListOfferingsInStoreInvalidParams(-1, 2, "id", MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListOfferingsInStoreInvalidMax() {
testListOfferingsInStoreInvalidParams(1, 0, "id", MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListOfferingsInStoreInvalidOrderBy() {
String orderBy = "namea";
testListOfferingsInStoreInvalidParams(1, 1, orderBy, "Offerings cannot be ordered by " + orderBy + ".");
}
//////////////////////////////////// ALL OFFERINGS ////////////////////////////////////
private void intializeStoresWithOfferings(Map<String, String> descriptions) {
// Create an additional Store
Response createStoreResponse = createStore(USER_NAME, PASSWORD, SECOND_STORE_NAME, SECOND_STORE_URL);
assertThat(createStoreResponse.getStatus()).isEqualTo(201);
// Push both descriptions in both stores
String[] stores = new String[]{FIRST_STORE_NAME, SECOND_STORE_NAME};
for (String store: stores) {
for (Entry<String, String> description: descriptions.entrySet()) {
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, store,
description.getKey(), description.getValue(), "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
}
}
}
@Test
public void testGetAllOfferings() {
final int TOTAL_OFFERINGS = 6; // 6 offerings: 3 in each store.
Map<String, String> descriptions = new HashMap<>();
descriptions.put("default", defaultUSDLPath);
descriptions.put("secondary", secondaryUSDLPath);
intializeStoresWithOfferings(descriptions);
// Get all the offerings
Client client = ClientBuilder.newClient();
Response allOfferingsResponse = client.target(endPoint + "/api/v2/offering")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
assertThat(allOfferingsResponse.getStatus()).isEqualTo(200);
Offerings offerings = allOfferingsResponse.readEntity(Offerings.class);
assertThat(offerings.getOfferings().size()).isEqualTo(TOTAL_OFFERINGS);
}
private void testGetSomeOfferings(int offset, int max) {
final int TOTAL_OFFERINGS = 6;
Map<String, String> descriptions = new HashMap<>();
descriptions.put("default", defaultUSDLPath);
descriptions.put("secondary", secondaryUSDLPath);
intializeStoresWithOfferings(descriptions);
// Get all the offerings
Client client = ClientBuilder.newClient();
Response allOfferingsResponse = client.target(endPoint + "/api/v2/offering")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
assertThat(allOfferingsResponse.getStatus()).isEqualTo(200);
Offerings offerings = allOfferingsResponse.readEntity(Offerings.class);
int expectedElements = offset + max > TOTAL_OFFERINGS ? TOTAL_OFFERINGS - offset : max;
assertThat(offerings.getOfferings().size()).isEqualTo(expectedElements);
}
@Test
public void testGetFirstTwoElements() {
testGetSomeOfferings(0, 2);
}
@Test
public void testGetMoreElementsThanExisting() {
testGetSomeOfferings(3, 9);
}
private void testListOfferingsInvalidParams(int offset, int max, String orderBy, String expectedMessage) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/offering")
.queryParam("offset", offset)
.queryParam("max", max)
.queryParam("orderBy", orderBy)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, expectedMessage, ErrorType.BAD_REQUEST);
}
@Test
public void testListOfferingsInvalidOffset() {
testListOfferingsInvalidParams(-1, 2, "id", MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListOfferingsInvalidMax() {
testListOfferingsInvalidParams(1, 0, "id", MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListOfferingsInvalidOrderBy() {
String orderBy = "namea";
testListOfferingsInvalidParams(1, 1, orderBy, "Offerings cannot be ordered by " + orderBy + ".");
}
////////////////////////////////////// BOOKMARKS //////////////////////////////////////
private Response getBookmarkedOfferings() {
// Get all the offerings
Client client = ClientBuilder.newClient();
Response allOfferingsResponse = client.target(endPoint + "/api/v2/offering/bookmark")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
return allOfferingsResponse;
}
/**
* This method bookmarks or unbookmarks an offering depending on its previous state
* @param userName User that will bookmark the offering
* @param password user's password
* @param storeName The name of the store where the offering to be bookmarked is contained
* @param descriptionName The name of the descritpion where the offering to be bookmarked is described
* @param offeringName The name of the offering to be bookmarked
* @return The response from the server
*/
private Response bookmarkOrUnbookmarkOffering(String userName, String password,String storeName,
String descriptionName, String offeringName) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/store/" + storeName + "/description/" +
descriptionName + "/offering/" + offeringName + "/bookmark")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password))
.post(null);
return response;
}
@Test
public void testBookmarkAndUnbookmarkOffering() {
String firstDescriptionName = "default";
String secondDescriptionName = "secondary";
Map<String, String> descriptions = new HashMap<>();
descriptions.put(firstDescriptionName, defaultUSDLPath);
descriptions.put(secondDescriptionName, secondaryUSDLPath);
intializeStoresWithOfferings(descriptions);
// Select one offering
String descriptionWithOfferingToBookmark = firstDescriptionName;
Offering bookmarkedOffering = DESCRIPTIONS_OFFERINGS.get(
descriptions.get(descriptionWithOfferingToBookmark)).get(0);
// Bookmark one offering
Response bookmarkResponse = bookmarkOrUnbookmarkOffering(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionWithOfferingToBookmark, bookmarkedOffering.getName());
assertThat(bookmarkResponse.getStatus()).isEqualTo(204);
// Set store and description for offering. Otherwise, test will fail since offering.equals is based
// on these fields
Store store = new Store();
store.setName(FIRST_STORE_NAME);
Description description = new Description();
description.setName(descriptionWithOfferingToBookmark);
description.setStore(store);
bookmarkedOffering.setDescribedIn(description);
// Check that bookmarked offerings contains the bookmarked offering
Response bookmarkedOfferingsResponse = getBookmarkedOfferings();
assertThat(bookmarkedOfferingsResponse.getStatus()).isEqualTo(200);
List<Offering> bookmarkedOfferings = bookmarkedOfferingsResponse.readEntity(Offerings.class).getOfferings();
assertThat(bookmarkedOfferings.size()).isEqualTo(1);
// bookmarkedOffering parameters MUST be properly initialized
assertThat(bookmarkedOfferings.get(0)).isEqualTo(bookmarkedOffering);
assertThat(bookmarkedOfferings.get(0).getDescribedIn().getName()).isEqualTo(descriptionWithOfferingToBookmark);
assertThat(bookmarkedOfferings.get(0).getDescribedIn().getStore().getName()).isEqualTo(FIRST_STORE_NAME);
// Unbookmark the offering
Response unbookmarkResponse = bookmarkOrUnbookmarkOffering(USER_NAME, PASSWORD,FIRST_STORE_NAME,
descriptionWithOfferingToBookmark, bookmarkedOffering.getName());
assertThat(unbookmarkResponse.getStatus()).isEqualTo(204);
// Check that bookmarked offerings is empty
bookmarkedOfferingsResponse = getBookmarkedOfferings();
assertThat(bookmarkedOfferingsResponse.getStatus()).isEqualTo(200);
bookmarkedOfferings = bookmarkedOfferingsResponse.readEntity(Offerings.class).getOfferings();
assertThat(bookmarkedOfferings).isEmpty();
}
@Test
public void testBookmarkTwoOfferings() {
String firstDescriptionName = "default";
String secondDescriptionName = "secondary";
Map<String, String> descriptions = new HashMap<>();
descriptions.put(firstDescriptionName, defaultUSDLPath);
descriptions.put(secondDescriptionName, secondaryUSDLPath);
intializeStoresWithOfferings(descriptions);
// Select one offering
String descriptionWithOfferingToBookmark = firstDescriptionName;
Offering bookmarkedOffering = DESCRIPTIONS_OFFERINGS.get(descriptions.get(firstDescriptionName)).get(0);
// Bookmark the offerings from different stores (same offering in different stores)
String[] stores = {FIRST_STORE_NAME, SECOND_STORE_NAME};
for (String storeName: stores) {
Response bookmarkResponse = bookmarkOrUnbookmarkOffering(USER_NAME, PASSWORD, storeName,
descriptionWithOfferingToBookmark, bookmarkedOffering.getName());
assertThat(bookmarkResponse.getStatus()).isEqualTo(204);
}
// Check that bookmarked offerings contains both offerings
Response bookmarkedOfferingsResponse = getBookmarkedOfferings();
assertThat(bookmarkedOfferingsResponse.getStatus()).isEqualTo(200);
List<Offering> bookmarkedOfferings = bookmarkedOfferingsResponse.readEntity(Offerings.class).getOfferings();
assertThat(bookmarkedOfferings.size()).isEqualTo(stores.length);
for (int i = 0; i < bookmarkedOfferings.size(); i++) {
checkOfferingInList(stores[i], descriptionWithOfferingToBookmark, bookmarkedOffering.getUri(),
bookmarkedOfferings);
}
}
/**
* Test for a know bug (fixed): When an user tries to remove an offering that has been
* bookmarked, the system throws an exception
*/
@Test
public void testRemoveBookmarkedOffering() {
String usdlPath = defaultUSDLPath;
String descriptionName = "description";
Response createDescRes = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionName, usdlPath, "");
assertThat(createDescRes.getStatus()).isEqualTo(201);
// Bookmark the offering
Response bookmarkRes = bookmarkOrUnbookmarkOffering(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionName, DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName());
assertThat(bookmarkRes.getStatus()).isEqualTo(204);
// Delete the offering
Response deleteRes = deleteDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME, descriptionName);
assertThat(deleteRes.getStatus()).isEqualTo(204);
}
/**
* Test for a know bug (fixed): When a user bookmarks an offering, the system throws an
* exception when this user tries to remove their own account.
*/
@Test
public void testRemoveUserWithBookmarkedOfferings() {
String usdlPath = defaultUSDLPath;
// Create an offering
String descriptionName = "description";
Response createDescRes = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionName, usdlPath, "");
assertThat(createDescRes.getStatus()).isEqualTo(201);
// Create another user
String userName = USER_NAME + "A";
String email = "example3@example.com";
Response createUserRes = createUser(userName, email, PASSWORD);
assertThat(createUserRes.getStatus()).isEqualTo(201);
// Bookmark the offering with the new user
Response bookmarkRes = bookmarkOrUnbookmarkOffering(userName, PASSWORD, FIRST_STORE_NAME,
descriptionName, DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName());
assertThat(bookmarkRes.getStatus()).isEqualTo(204);
// Delete the user
Response deleteUserRes = deleteUser(userName, PASSWORD, userName);
assertThat(deleteUserRes.getStatus()).isEqualTo(204);
// Check that the offering has not been deleted
Response getOffRes = getOffering(USER_NAME, PASSWORD, FIRST_STORE_NAME,
descriptionName, DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName());
assertThat(getOffRes.getStatus()).isEqualTo(200);
}
/////////////////////////////////////// REVIEWS ///////////////////////////////////////
private Response getOffering(String userName, String password, String storeName, String descriptionName,
String offeringName) {
Client client = ClientBuilder.newClient();
return client.target(endPoint + "/api/v2/store/" + storeName + "/description/" + descriptionName +
"/offering/" + offeringName)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
private int createOfferingAndReview(String storeName, String descriptionName, String usdlPath,
String offeringName, int score, String comment) {
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, storeName,
descriptionName, usdlPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
Response res = createOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName,
offeringName, score, comment);
assertThat(res.getStatus()).isEqualTo(201);
// Get offering and its average score
Offering reviewdOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewdOffering.getAverageScore()).isEqualTo(score);
// Get review ID
String[] urlParts = res.getLocation().getPath().split("/");
int reviewId = Integer.parseInt(urlParts[urlParts.length - 1]);
assertThat(res.getLocation().getPath()).endsWith("/api/v2/store/" + storeName + "/description/" +
descriptionName + "/offering/" + offeringName + "/review/" + reviewId);
return reviewId;
}
@Test
public void testReviewOffering() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String comment = "Basic comment";
int reviewId = createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, comment);
checkOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
reviewId, score, comment);
}
@Test
public void testUserCannotReviewOneStoreTwice() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String comment = "Basic comment";
createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, comment);
// Create another review for the same offering with the same user
Response res = createOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName,
offeringName, score, comment);
checkAPIError(res, 403, null, "You are not authorized to review Offering. An entity can only be reviewed once",
ErrorType.FORBIDDEN);
}
@Test
public void testUpdateReview() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String comment = "Basic comment";
int reviewId = createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, comment);
// Update review
int newScore = 3;
String newComment = "This is a new comment";
Response updateRes = updateOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
reviewId, newScore, newComment);
assertThat(updateRes.getStatus()).isEqualTo(200);
// Check updated review
checkOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
reviewId, newScore, newComment);
// Check that average score has been properly updated
Offering reviewOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewOffering.getAverageScore()).isEqualTo(newScore);
}
@Test
public void testDeleteReview() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String comment = "Basic comment";
int reviewId = createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, comment);
Response deleteResponse = deleteOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName,
offeringName, reviewId);
assertThat(deleteResponse.getStatus()).isEqualTo(204);
// Get review should return 404
Response getResponse = getOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName,
offeringName, reviewId);
assertThat(getResponse.getStatus()).isEqualTo(404);
// Average score should be zero when the last review is deleted
Offering reviewedOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewedOffering.getAverageScore()).isEqualTo(0);
}
private String getCommentFromBase(String baseComment, int score) {
return baseComment + " " + score;
}
private double createNReviews(String storeName, String descriptionName, String offeringName, String baseComment,
int nReviews, int initialScore) {
double totalScore = 0;
String alphabet = "abcdefghijklmonpqrstuvwxyz";
for (int score = initialScore; score < nReviews + initialScore; score++) {
// Create user for review
char userSuffix = alphabet.charAt(score % alphabet.length());
String userName = "userforrating" + userSuffix;
String email = "rating" + userSuffix + "@example.com";
Response createUserRes = createUser(userName, email, PASSWORD);
assertThat(createUserRes.getStatus()).isEqualTo(201);
// Review the offering with the new user (one user can only review one offering once)
String comment = getCommentFromBase(baseComment, score);
Response res = createOfferingReview(userName, PASSWORD, storeName, descriptionName, offeringName,
score, comment);
assertThat(res.getStatus()).isEqualTo(201);
totalScore += score;
}
return totalScore;
}
@Test
public void testCreateNReviews() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
String baseComment = "Basic comment";
// Create offering
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, storeName,
descriptionName, usdlPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Create reviews
int reviewsNumber = 4;
int initialScore = 1;
double totalScore = createNReviews(storeName, descriptionName, offeringName, baseComment,
reviewsNumber, initialScore);
// Get average score
double average = totalScore / ((double) reviewsNumber);
Offering reviewdOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewdOffering.getAverageScore()).isEqualTo(average);
// Get reviews list and check values
Reviews reviews = getOfferingReviews(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
0, 100, "id", false).readEntity(Reviews.class);
List<Review> reviewsList = reviews.getReviews();
assertThat(reviews.getReviews()).hasSize((int) reviewsNumber);
for (int i = 0; i < reviewsList.size(); i++) {
Review review = reviewsList.get(i);
int score = i + initialScore;
// Comment is based on the score
assertThat(review.getComment()).isEqualTo(getCommentFromBase(baseComment, score));
assertThat(review.getScore()).isEqualTo(score);
}
// Get two reviews: ordered by score DESC, offset is 1
int max = 2;
int secondBestScore = initialScore + reviewsNumber - 2;
reviews = getOfferingReviews(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
1, 2, "score", true).readEntity(Reviews.class);
reviewsList = reviews.getReviews();
assertThat(reviewsList).hasSize(max);
for (int i = 0; i < reviewsList.size(); i++) {
Review review = reviewsList.get(i);
int score = secondBestScore - i;
// Comment is based on the score
assertThat(review.getComment()).isEqualTo(getCommentFromBase(baseComment, score));
assertThat(review.getScore()).isEqualTo(score);
}
}
@Test
public void testUpdateReviewComplex() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String baseComment = "Basic comment";
int reviewId = createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, baseComment);
// Create additional reviews
int reviewsNumber = 2;
double totalScore = createNReviews(storeName, descriptionName, offeringName, baseComment, reviewsNumber, 1);
// Update initial review
int newScore = 3;
String newComment = "This is a new comment";
Response updateRes = updateOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
reviewId, newScore, newComment);
assertThat(updateRes.getStatus()).isEqualTo(200);
// Check that the review has been properly updated
checkOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName, offeringName,
reviewId, newScore, newComment);
// Get average score
double average = (totalScore + newScore) / ((double) (reviewsNumber + 1));
Offering reviewedOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewedOffering.getAverageScore()).isEqualTo(average);
}
@Test
public void testDeleteReviewComplex() {
String usdlPath = defaultUSDLPath;
String storeName = FIRST_STORE_NAME;
String descriptionName = "default";
String offeringName = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0).getName();
int score = 5;
String baseComment = "Basic comment";
int reviewId = createOfferingAndReview(storeName, descriptionName, usdlPath, offeringName,
score, baseComment);
// Create additional reviews
int reviewsNumber = 2;
double totalScore = createNReviews(storeName, descriptionName, offeringName, baseComment, reviewsNumber, 1);
// Delete initial review
Response deleteRes = deleteOfferingReview(USER_NAME, PASSWORD, storeName, descriptionName,
offeringName, reviewId);
assertThat(deleteRes.getStatus()).isEqualTo(204);
// Get average score
double average = totalScore / reviewsNumber;
Offering reviewdOffering = getOffering(USER_NAME, PASSWORD, storeName, descriptionName, offeringName)
.readEntity(Offering.class);
assertThat(reviewdOffering.getAverageScore()).isEqualTo(average);
}
///////////////////////////////////// CATEGORIES //////////////////////////////////////
private Response getCategories(String userName, String password) {
Client client = ClientBuilder.newClient();
return client.target(endPoint + "/api/v2/category/")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
private Response getCategoryRecommendations(String userName, String password, String category, String orderBy) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(endPoint + "/api/v2/category/" + category + "/offering");
// Include order when parameter is not null. BY default, offerings are ordered by score
if (orderBy != null) {
target = target.queryParam("orderBy", orderBy);
}
return target.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(userName, password)).get();
}
@Test
public void testGetCategories() {
String usdlPath = defaultUSDLPath;
Offering offering = DESCRIPTIONS_OFFERINGS.get(usdlPath).get(0);
// Create one offering. This offering is contained in two categories
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
"description", usdlPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Get categories
Response getCategoriesResponse = getCategories(USER_NAME, PASSWORD);
assertThat(getCategoriesResponse.getStatus()).isEqualTo(200);
// Check that all the categories are included
Categories categories = getCategoriesResponse.readEntity(Categories.class);
List<Category> categoriesList = categories.getCategories();
assertThat(categoriesList).containsAll(offering.getCategories());
}
@Test
public void testGetCategoryRecommendations() {
String storeName = FIRST_STORE_NAME;
String descriptionName = "description";
String usdlPath = secondaryUSDLPath;
// Create two offerings
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, storeName,
descriptionName, usdlPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Review both offerings. First one with 1 starts and second one with 5 starts
List<Offering> descriptionOfferings = DESCRIPTIONS_OFFERINGS.get(usdlPath);
assertThat(descriptionOfferings.size()).isEqualTo(2); // Two offerings expected in this Description
Offering highScoredOffering = descriptionOfferings.get(1);
Offering lowScoredOffering = descriptionOfferings.get(0);
Response createRating1Response = createOfferingReview(USER_NAME, PASSWORD, storeName,
descriptionName, lowScoredOffering.getName(), 1, "");
assertThat(createRating1Response.getStatus()).isEqualTo(201);
Response createRating2Response = createOfferingReview(USER_NAME, PASSWORD, storeName,
descriptionName, highScoredOffering.getName(), 5, "");
assertThat(createRating2Response.getStatus()).isEqualTo(201);
// Get the category in common between the two offerings
Set<Category> commonCategories = new HashSet<>(descriptionOfferings.get(0).getCategories());
commonCategories.retainAll(descriptionOfferings.get(1).getCategories());
String categoryName = commonCategories.iterator().next().getName();
// Get category recommendations (offerings should be ordered by score: second offering
// should be the first one in the list)
Response getRecommendationsResponse = getCategoryRecommendations(USER_NAME, PASSWORD, categoryName, null);
assertThat(getRecommendationsResponse.getStatus()).isEqualTo(200);
Offerings recommendations = getRecommendationsResponse.readEntity(Offerings.class);
List<Offering> offeringsList = recommendations.getOfferings();
// Set offerings description since offering.equals depends on it
Store store = new Store();
store.setName(storeName);
Description description = new Description();
description.setName(descriptionName);
description.setStore(store);
descriptionOfferings.get(0).setDescribedIn(description);
descriptionOfferings.get(1).setDescribedIn(description);
// Check that offerings has been returned in the correct order
assertThat(offeringsList.get(0)).isEqualTo(highScoredOffering);
assertThat(offeringsList.get(1)).isEqualTo(lowScoredOffering);
}
@Test
public void testGetCategoriesInvalidOrder() {
String usdlPath = defaultUSDLPath;
Offering offering = DESCRIPTIONS_OFFERINGS.get(defaultUSDLPath).get(0);
// Create one offering.
Response createDescriptionResponse = createDescription(USER_NAME, PASSWORD, FIRST_STORE_NAME,
"description", usdlPath, "");
assertThat(createDescriptionResponse.getStatus()).isEqualTo(201);
// Get offerings for one category with invalid order
String categoryName = offering.getCategories().iterator().next().getName();
String orderBy = "namea";
Response getRecommendationsResponse = getCategoryRecommendations(USER_NAME, PASSWORD, categoryName, orderBy);
assertThat(getRecommendationsResponse.getStatus()).isEqualTo(400);
checkAPIError(getRecommendationsResponse, 400, null,
"Offerings cannot be ordered by " + orderBy + ".", ErrorType.BAD_REQUEST);
}
//////////////////////////////// LAST VIEWED OFFERINGS ////////////////////////////////
private Response getLastViewedOfferings() {
// Get all the offerings
Client client = ClientBuilder.newClient();
Response allOfferingsResponse = client.target(endPoint + "/api/v2/offering/lastViewed")
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
return allOfferingsResponse;
}
private void testListViewedOfferingsInvalidParams(int offset, int max, String expectedMessage) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/offering/lastViewed")
.queryParam("offset", offset)
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, expectedMessage, ErrorType.BAD_REQUEST);
}
@Test
public void testListViewedOfferingsInvalidOffset() {
testListViewedOfferingsInvalidParams(-1, 2, MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListViewedOfferingsInvalidMax() {
testListViewedOfferingsInvalidParams(1, 0, MESSAGE_INVALID_OFFSET_MAX);
}
@Test
public void testListViewedOfferings() {
// Initialization
String firstDescriptionName = "default";
String secondDescriptionName = "secondary";
Map<String, String> descriptions = new HashMap<>();
descriptions.put(firstDescriptionName, defaultUSDLPath);
descriptions.put(secondDescriptionName, secondaryUSDLPath);
intializeStoresWithOfferings(descriptions);
// Select one offering
String descriptionWithOfferingToView = firstDescriptionName;
Offering viewedOffering = DESCRIPTIONS_OFFERINGS.get(descriptions.get(firstDescriptionName)).get(0);
// View the offerings in different stores (same offering in different stores)
String[] stores = {FIRST_STORE_NAME, SECOND_STORE_NAME};
for (String storeName: stores) {
Response viewResponse = getOffering(USER_NAME, PASSWORD, storeName,
descriptionWithOfferingToView, viewedOffering.getName());
assertThat(viewResponse.getStatus()).isEqualTo(200);
}
// Check that viewed offerings contains both offerings
Response viewedOfferingsResponse = getLastViewedOfferings();
assertThat(viewedOfferingsResponse.getStatus()).isEqualTo(200);
List<Offering> viewedOfferings = viewedOfferingsResponse.readEntity(Offerings.class).getOfferings();
assertThat(viewedOfferings.size()).isEqualTo(stores.length);
for (int i = 0; i < viewedOfferings.size(); i++) {
checkOfferingInList(stores[i], descriptionWithOfferingToView, viewedOffering.getUri(), viewedOfferings);
}
}
///////////////////////////// OFFERINGS VIEWED BY OTHERS //////////////////////////////
private void testOfferingsViewedByOthersInvalidParams(int max, String expectedMessage) {
Client client = ClientBuilder.newClient();
Response response = client.target(endPoint + "/api/v2/offering/viewedByOthers")
.queryParam("max", max)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", getAuthorization(USER_NAME, PASSWORD))
.get();
checkAPIError(response, 400, null, expectedMessage, ErrorType.BAD_REQUEST);
}
@Test
public void testOfferingsViewedByOthersZeroIsNotAValidMax() {
testOfferingsViewedByOthersInvalidParams(0, "max is not valid");
}
@Test
public void testOfferingsViewedByOthersMaxIsToHigh() {
testOfferingsViewedByOthersInvalidParams(21, "max cannot be higher than 20.");
}
// Core functionality is check in SeleniumIT...
// TODO: Add extra test to check that max works as expected
}
|
package org.influxdb.querybuilder;
import static org.influxdb.querybuilder.BuiltQuery.QueryBuilder.*;
import static org.influxdb.querybuilder.time.DurationLiteral.HOUR;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.influxdb.dto.Query;
import org.junit.jupiter.api.Test;
public class SelectionSubQueryImplTest {
private static final String DATABASE = "testdb";
@Test
public void testSubQuery() {
Query query =
new Query(
"SELECT column1,column2 FROM (SELECT * FROM foobar) WHERE column1=1 GROUP BY time;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE, "foobar")
.close()
.where(eq("column1", 1))
.groupBy("time");
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
@Test
public void testSubQueryColumns() {
Query query =
new Query(
"SELECT column1,column2 FROM (SELECT column1,column2 FROM foobar) WHERE column1=1 GROUP BY time;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.column("column1")
.column("column2")
.from("foobar")
.close()
.where(eq("column1", 1))
.groupBy("time");
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
/*test * */
@Test
public void testSubQueryWithSubQueries() {
Query query =
new Query(
"SELECT column1,column2 FROM ("
+ "SELECT MAX(column1),MAX(column2) FROM ("
+ "SELECT * FROM ("
+ "SELECT MAX(column1),MEAN(column2) FROM ("
+ "SELECT DISTINCT test1 FROM foobar WHERE column1>3 GROUP BY column2"
+ ")"
+ ") WHERE column1=5 GROUP BY column2 LIMIT 50 OFFSET 10"
+ ") WHERE column1=4"
+ ") WHERE column3=5 LIMIT 5 OFFSET 10;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.max("column1")
.max("column2")
.fromSubQuery()
.all()
.fromSubQuery()
.max("column1")
.mean("column2")
.fromSubQuery()
.column("test1")
.distinct()
.from("foobar")
.where(gt("column1", 3))
.groupBy("column2")
.close()
.close()
.where(eq("column1", 5))
.groupBy("column2")
.limit(50, 10)
.close()
.where(eq("column1", 4))
.close()
.where(eq("column3", 5))
.limit(5, 10);
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
@Test
public void testSubQueryWithLimitAndSOffSET() {
Query query =
new Query(
"SELECT column1,column2 FROM ("
+ "SELECT MAX(column1),MAX(column2) FROM ("
+ "SELECT * FROM ("
+ "SELECT MAX(column1),MEAN(column2) FROM ("
+ "SELECT DISTINCT test1 FROM foobar WHERE column1>3 GROUP BY column2 LIMIT 1 OFFSET 20 SLIMIT 2 SOFFSET 10"
+ ")"
+ ") WHERE column1=5 GROUP BY column2 ORDER BY time DESC LIMIT 50 OFFSET 10"
+ ") WHERE column1=4 OR column1=7 GROUP BY time(4h) ORDER BY time ASC SLIMIT 3"
+ ") WHERE column3=5 LIMIT 5 OFFSET 10;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.max("column1")
.max("column2")
.fromSubQuery()
.all()
.fromSubQuery()
.max("column1")
.mean("column2")
.fromSubQuery()
.column("test1")
.distinct()
.from("foobar")
.where(gt("column1", 3))
.groupBy("column2")
.limit(1, 20)
.sLimit(2, 10)
.close()
.close()
.where(eq("column1", 5))
.groupBy("column2")
.limit(50, 10)
.orderBy(desc())
.close()
.where(eq("column1", 4))
.or(eq("column1",7))
.sLimit(3)
.orderBy(asc())
.groupBy(time(4l,HOUR))
.close()
.where(eq("column3", 5))
.limit(5, 10);
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
@Test
public void testSubQueryTimeZoneColumns() {
Query query =
new Query(
"SELECT column1,column2 FROM (SELECT column1,column2 FROM foobar tz('America/Chicago')) WHERE column1=1 GROUP BY time;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.column("column1")
.column("column2")
.from("foobar")
.tz("America/Chicago")
.close()
.where(eq("column1", 1))
.groupBy("time");
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
@Test
public void testSubQuerySelectRegexColumns() {
Query query =
new Query(
"SELECT column1,column2 FROM (SELECT /k/ FROM foobar tz('America/Chicago')) WHERE column1=1 GROUP BY time;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.regex("k")
.from("foobar")
.tz("America/Chicago")
.close()
.where(eq("column1", 1))
.groupBy("time");
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
@Test
public void testSubQueryNested() {
Query query =
new Query(
"SELECT column1,column2 FROM (SELECT /k/ FROM foobar WHERE (column1=2 OR column1=3) OR (column2=5 AND column2=7) tz('America/Chicago')) WHERE column1=1 GROUP BY time;",
DATABASE);
Query select =
select()
.requiresPost()
.column("column1")
.column("column2")
.fromSubQuery(DATABASE)
.regex("k")
.from("foobar")
.where()
.andNested()
.and(eq("column1",2))
.or(eq("column1",3))
.close()
.orNested()
.and(eq("column2",5))
.and(eq("column2",7))
.close()
.tz("America/Chicago")
.close()
.where(eq("column1", 1))
.groupBy("time");
assertEquals(query.getCommand(), select.getCommand());
assertEquals(query.getDatabase(), select.getDatabase());
}
}
|
package org.csveed.bean.conversion;
import org.csveed.bean.BeanInstructions;
import org.csveed.bean.BeanParser;
import org.csveed.bean.BeanProperties;
import org.csveed.common.Column;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Currency;
import java.util.TimeZone;
import java.util.regex.Pattern;
public class BeanWrapperTest {
private BeanProperties properties = deriveProperties();
private Bean bean;
private DefaultConverters defaultConverters = new DefaultConverters();
private BeanWrapper beanWrapper;
@Before
public void init() {
bean = new Bean();
beanWrapper = new BeanWrapper(defaultConverters, bean);
}
@Test
public void hitAllProperties() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("charset")),null);
beanWrapper.setProperty(properties.fromName(new Column("charset")),"");
beanWrapper.setProperty(properties.fromName(new Column("chars")),null);
beanWrapper.setProperty(properties.fromName(new Column("bytes")),null);
beanWrapper.setProperty(properties.fromName(new Column("booleanObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("byteObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("shortObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("intObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("longObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("floatObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("doubleObject")),"");
beanWrapper.setProperty(properties.fromName(new Column("bigDecimal")),"");
beanWrapper.setProperty(properties.fromName(new Column("bigInteger")),"");
}
@Test
public void getCharset() throws Exception {
bean.setCharset(Charset.forName("US-ASCII"));
assertEquals("US-ASCII", beanWrapper.getProperty(properties.fromName(new Column("charset"))));
}
@Test
public void setCharset() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("charset")),"US-ASCII");
assertEquals("US-ASCII", bean.getCharset().displayName());
}
@Test
public void getCurrency() throws Exception {
bean.setCurrency(Currency.getInstance("USD"));
assertEquals("USD", beanWrapper.getProperty(properties.fromName(new Column("currency"))));
}
@Test
public void setCurrency() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("currency")),"USD");
assertEquals("USD", bean.getCurrency().getCurrencyCode());
}
@Test
public void getPattern() throws Exception {
bean.setPattern(Pattern.compile("[0-9]"));
assertEquals("[0-9]", beanWrapper.getProperty(properties.fromName(new Column("pattern"))));
}
@Test
public void setPattern() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("pattern")),"[0-9]");
assertEquals("[0-9]", bean.getPattern().pattern());
}
@Test
public void getTimeZone() throws Exception {
bean.setTimeZone(TimeZone.getTimeZone("GMT-8"));
assertEquals("GMT-08:00", beanWrapper.getProperty(properties.fromName(new Column("timeZone"))));
}
@Test
public void setTimeZone() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("timeZone")),"GMT-8");
assertEquals("GMT-08:00", bean.getTimeZone().getDisplayName());
}
@Test
public void getBytes() throws Exception {
bean.setBytes(new byte[]{65, 66, 67});
assertEquals("ABC", beanWrapper.getProperty(properties.fromName(new Column("bytes"))));
}
@Test
public void setBytes() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("bytes")),"ABC");
assertTrue(Arrays.equals(new byte[]{65, 66, 67}, bean.getBytes()));
}
@Test
public void getChars() throws Exception {
bean.setChars(new char[]{'A', 'B', 'C'});
assertEquals("ABC", beanWrapper.getProperty(properties.fromName(new Column("chars"))));
}
@Test
public void setChars() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("chars")),"ABC");
assertTrue(Arrays.equals(new char[] { 'A', 'B', 'C' } , bean.getChars()));
}
@Test
public void getCharPrimitive() throws Exception {
bean.setCharPrimitive('ü');
assertEquals("ü", beanWrapper.getProperty(properties.fromName(new Column("charPrimitive"))));
}
@Test
public void setCharPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("charPrimitive")),"ü");
assertEquals('ü', bean.getCharPrimitive());
}
@Test
public void getCharacter() throws Exception {
bean.setCharacter('ü');
assertEquals("ü", beanWrapper.getProperty(properties.fromName(new Column("character"))));
}
@Test
public void setCharacter() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("character")),"ü");
assertEquals('ü', (char)bean.getCharacter());
}
@Test
public void getBooleanPrimitive() throws Exception {
bean.setBooleanPrimitive(true);
assertEquals("true", beanWrapper.getProperty(properties.fromName(new Column("booleanPrimitive"))));
}
@Test
public void setBooleanPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("booleanPrimitive")),"on");
assertEquals(true, bean.isBooleanPrimitive());
}
@Test
public void getBooleanObject() throws Exception {
bean.setBooleanObject(Boolean.TRUE);
assertEquals("true", beanWrapper.getProperty(properties.fromName(new Column("booleanObject"))));
}
@Test
public void setBooleanObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("booleanObject")),"on");
assertEquals(Boolean.TRUE, bean.getBooleanObject());
}
@Test
public void getBytePrimitive() throws Exception {
bean.setBytePrimitive((byte) 17);
assertEquals("17", beanWrapper.getProperty(properties.fromName(new Column("bytePrimitive"))));
}
@Test
public void setBytePrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("bytePrimitive")),"17");
assertEquals(17, bean.getBytePrimitive());
}
@Test
public void getByteObject() throws Exception {
bean.setByteObject(Byte.valueOf("17"));
assertEquals("17", beanWrapper.getProperty(properties.fromName(new Column("byteObject"))));
}
@Test
public void setByteObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("byteObject")),"17");
assertEquals(Byte.valueOf("17"),bean.getByteObject());
}
@Test
public void getShortPrimitive() throws Exception {
bean.setShortPrimitive((short) 17);
assertEquals("17", beanWrapper.getProperty(properties.fromName(new Column("shortPrimitive"))));
}
@Test
public void setShortPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("shortPrimitive")),"17");
assertEquals(17, bean.getShortPrimitive());
}
@Test
public void getShortObject() throws Exception {
bean.setShortObject(Short.valueOf("17"));
assertEquals("17", beanWrapper.getProperty(properties.fromName(new Column("shortObject"))));
}
@Test
public void setShortObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("shortObject")),"17");
assertEquals(Short.valueOf("17"),bean.getShortObject());
}
@Test
public void getIntPrimitive() throws Exception {
bean.setIntPrimitive(989);
assertEquals("989", beanWrapper.getProperty(properties.fromName(new Column("intPrimitive"))));
}
@Test
public void setIntPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("intPrimitive")),"1989");
assertEquals(1989, bean.getIntPrimitive());
}
@Test
public void getIntObject() throws Exception {
bean.setIntObject(989);
assertEquals("989", beanWrapper.getProperty(properties.fromName(new Column("intObject"))));
}
@Test
public void setIntObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("intObject")),"1989");
assertEquals((Integer)1989, bean.getIntObject());
}
@Test
public void getLongPrimitive() throws Exception {
bean.setLongPrimitive(989);
assertEquals("989", beanWrapper.getProperty(properties.fromName(new Column("longPrimitive"))));
}
@Test
public void setLongPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("longPrimitive")),"1989");
assertEquals(1989, bean.getLongPrimitive());
}
@Test
public void getLongObject() throws Exception {
bean.setLongObject(989L);
assertEquals("989", beanWrapper.getProperty(properties.fromName(new Column("longObject"))));
}
@Test
public void setLongObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("longObject")),"1989");
assertEquals((Long)1989L, bean.getLongObject());
}
@Test
public void getFloatPrimitive() throws Exception {
bean.setFloatPrimitive((float)42.42);
assertEquals("42.42", beanWrapper.getProperty(properties.fromName(new Column("floatPrimitive"))));
}
@Test
public void setFloatPrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("floatPrimitive")),"42.42");
assertEquals((float)42.42, bean.getFloatPrimitive(), 1);
}
@Test
public void getFloatObject() throws Exception {
bean.setFloatObject(Float.valueOf("42.42"));
assertEquals("42.42", beanWrapper.getProperty(properties.fromName(new Column("floatObject"))));
}
@Test
public void setFloatObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("floatObject")),"42.42");
assertEquals(Float.valueOf("42.42"),bean.getFloatObject());
}
@Test
public void getDoublePrimitive() throws Exception {
bean.setDoublePrimitive(42.42);
assertEquals("42.42", beanWrapper.getProperty(properties.fromName(new Column("doublePrimitive"))));
}
@Test
public void setDoublePrimitive() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("doublePrimitive")),"42.42");
assertEquals(42.42, bean.getDoublePrimitive(), 1);
}
@Test
public void getDoubleObject() throws Exception {
bean.setDoubleObject(Double.valueOf("42.42"));
assertEquals("42.42", beanWrapper.getProperty(properties.fromName(new Column("doubleObject"))));
}
@Test
public void setDoubleObject() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("doubleObject")),"42.42");
assertEquals(Double.valueOf("42.42"),bean.getDoubleObject());
}
@Test
public void getBigDecimal() throws Exception {
bean.setBigDecimal(new BigDecimal("42.123"));
assertEquals("42.123", beanWrapper.getProperty(properties.fromName(new Column("bigDecimal"))));
}
@Test
public void setBigDecimal() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("bigDecimal")),"42.12345678901234567890");
assertEquals(new BigDecimal("42.12345678901234567890"),bean.getBigDecimal());
}
@Test
public void getBigInteger() throws Exception {
bean.setBigInteger(new BigInteger("4212345678901234567890"));
assertEquals("4212345678901234567890", beanWrapper.getProperty(properties.fromName(new Column("bigInteger"))));
}
@Test
public void setBigInteger() throws Exception {
beanWrapper.setProperty(properties.fromName(new Column("bigInteger")),"4212345678901234567890");
assertEquals(new BigInteger("4212345678901234567890"),bean.getBigInteger());
}
protected BeanProperties deriveProperties() {
BeanInstructions instructions = new BeanParser().getBeanInstructions(Bean.class);
return instructions.getProperties();
}
}
|
package org.nextrtc.server.dao.provider;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.nextrtc.server.dao.Members;
import org.nextrtc.server.domain.Member;
import org.nextrtc.server.domain.provider.DefaultMember;
import org.nextrtc.server.factory.MemberFactory;
import org.nextrtc.server.factory.provider.DefaultMemberFactory;
import com.google.common.base.Optional;
public class InMemoryMembersTest {
private Members container;
private MemberFactory factory = new DefaultMemberFactory();
@Before
public void setupContainer() {
container = new InMemboryMembers();
}
@Test
public void shouldCreateMember() {
// given
// when
Member newOne = factory.create();
// then
assertNotNull(newOne);
assertNotNull(newOne.getId());
}
@Test
public void shouldFindCreatedMember() {
// given
Member member = factory.create();
container.save(member);
// when
Optional<Member> found = container.findBy(member.getId());
// then
assertTrue(found.isPresent());
assertThat(found.get(), is(member));
}
@Test
public void shouldRemoveMember() {
// given
Member member = factory.create();
container.save(member);
// when
container.remove(member);
// then
assertFalse(container.findBy(member.getId()).isPresent());
}
@Test
public void shouldUpdateMemberNick() {
// given
Member member = factory.create();
container.save(member);
assertThat(member.getName(), isEmptyOrNullString());
// when
container.update(new DefaultMember(member.getId(), "Stefan"));
// then
Optional<Member> found = container.findBy(member.getId());
assertTrue(found.isPresent());
assertThat(member.getId(), is(found.get().getId()));
assertThat("Stefan", is(found.get().getName()));
}
}
|
package org.grouplens.grapht.util;
import javax.inject.Provider;
/**
* A class with several inner classes implementing Provider for testing
* purposes.
*/
public class TestingProviders {
public static class Target implements Cloneable{}
public static class GenericTarget<T>{}
/*
* The simplest form of provider. This has no generics or anything else sophisticated.
*/
public static class SimpleProvider implements Provider<Target>{
public Target get(){
return null;
}
}
/*
* Creates the situation that TypedProviders are most needed.
*
* The Provider is parametrized over a type variable which is subject to type erasure
*/
public static abstract class AbstractProvider<T> implements Provider<T>{
public T get(){
return null;
}
}
public static abstract class AbstractProvider2<T> extends AbstractProvider<T>{}
public static class SubtypedProvider extends AbstractProvider<Target>{}
public static class SubtypedProvider2 extends AbstractProvider2<Target>{}
/*
* Same as the above, instead of abstract classes, provider is found up the interface hierarchy.
*/
public static interface InterfaceProvider<T> extends Provider<T>{}
public static interface InterfaceProvider2<T> extends InterfaceProvider<T>{}
public static class ImplementedProvider implements InterfaceProvider<Target>{
public Target get(){
return null;
}
}
public static class ImplementedProvider2 implements InterfaceProvider2<Target>{
public Target get(){
return null;
}
}
/*
* These are Providers with unbound type variables. These are **not** supported.
*/
public static class BoundedProvider<T extends Target> implements Provider<T>{
public T get(){
return null;
}
}
public static class UnboundedProvider<T> implements Provider<T>{
public T get(){
return null;
}
}
public static class MultiBoundProvider<T extends Target & Cloneable> implements Provider<T>{
public T get(){
return null;
}
}
}
|
package org.iiitb.os.os_proj;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.iiitb.os.os_proj.db.MongoConnectivity;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import junit.framework.TestCase;
public class TestMongoConnectivity {
public static String TESTDB = "testDB";
public static String TESTCOLLECTION = "testCollection";
public static MongoConnectivity testMongo;
public static DBCollection res;
@BeforeClass
public static void setupDB(){
testMongo = new MongoConnectivity();
res = testMongo.openConnection(TESTCOLLECTION);
//res.drop();
}
@Before
public void addSampleFile() {
Date date = new Date();
UserFile testFile = new UserFile();
testFile.setData("This is test data");
testFile.setDate_created(date);
testFile.setDate_updated(date);
testFile.setFile_size(1234);
testFile.setId(1234);
testFile.setFiletypeId(1);
testFile.setId(1234);
testFile.setName("Kanchu17");
testFile.setPath("/home/kanchan");
testFile.setTimestamp(date);
testFile.setUser_created(1);
testFile.setUser_updated(2);
WriteResult result = testMongo.createFile(testFile);
}
@After
public void clearDatabase(){
BasicDBObject dbo=new BasicDBObject();
//dbo.put("name","Kanchu17");
res.findAndRemove(dbo);
}
@Test
public void testOpenConnection() {
MongoConnectivity testMongo = new MongoConnectivity();
res = testMongo.openConnection(TESTCOLLECTION);
assertEquals(TESTCOLLECTION, res.getName());
}
@Test
public void testAddFile() {
UserFile u = getTestFile();
WriteResult result = testMongo.createFile(u);
assertNull(result.getError());
}
public void addTestFile() {
UserFile u = getTestFile();
WriteResult result = testMongo.createFile(u);
assertNull(result.getError());
}
public UserFile getTestFile() {
Date date = new Date();
UserFile testFile = new UserFile();
testFile.setData("This is test data");
testFile.setDate_created(date);
testFile.setDate_updated(date);
testFile.setFile_size(1234);
testFile.setId(1234);
testFile.setFiletypeId(1);
testFile.setId(1234);
testFile.setName("Kanchu17");
testFile.setPath("/home/kanchan");
testFile.setTimestamp(date);
testFile.setUser_created(1);
testFile.setUser_updated(2);
return testFile;
}
@Test
public void testDeletefile() {
UserFile u = getTestFile();
String fname = u.getName();
/*DBObject result = testMongo.deleteFile(fname);
String str = (String) result.get("name");
assertEquals(str, fname);
*/
}
@Test
public void testUpdatefile() {
UserFile u = getTestFile();
WriteResult result = testMongo.updateCommon(u);
assertNull(result.getError());
}
@Test
public void testDisplayFile() {
Map<String, String> constraints = new HashMap<String, String>();
constraints.put("name", "Kanchu17");
UserFile u = getTestFile();
String file_name = u.getName();
ArrayList<UserFile> files = testMongo.getFiles(constraints);
for (int i = 0; i < files.size(); i++) {
System.out.println(files.get(i).getName());
}
}
}
|
package org.numenta.nupic.unit.encoders;
import org.junit.Test;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.encoders.CategoryEncoder;
import org.numenta.nupic.encoders.DecodeResult;
import org.numenta.nupic.encoders.EncoderResult;
import org.numenta.nupic.encoders.RangeList;
import org.numenta.nupic.util.ArrayUtils;
import org.numenta.nupic.util.Condition;
import org.numenta.nupic.util.MinMax;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CategoryEncoderTest {
private CategoryEncoder ce;
private Parameters parameters;
private void setUp() {
parameters = Parameters.getDefaultParameters();
parameters.setParameterByKey(KEY.W, 3);
parameters.setParameterByKey(KEY.MINVAL, 0.0);
parameters.setParameterByKey(KEY.MAXVAL, 8.0);
parameters.setParameterByKey(KEY.PERIODIC, false);
parameters.setParameterByKey(KEY.FORCED, true);
}
private void initCE() {
ce = new CategoryEncoder();
Parameters.apply(ce, parameters);
ce.init();
}
@Test
public void testCategoryEncoder() {
String[] categories = new String[] { "ES", "GB", "US" };
setUp();
parameters.setParameterByKey(KEY.RADIUS, 1.0);
parameters.setParameterByKey(KEY.CATEGORY_LIST, Arrays.<String>asList(categories));
initCE();
System.out.println("Testing CategoryEncoder...");
// forced: is not recommended, but is used here for readability. see scalar.py
int[] output = ce.encode("US");
assertTrue(Arrays.equals(new int[] { 0,0,0,0,0,0,0,0,0,1,1,1 }, output));
// Test reverse lookup
DecodeResult decoded = ce.decode(output, "");
assertEquals(decoded.getFields().size(), 1, 0);
List<RangeList> rangeList = new ArrayList<RangeList>(decoded.getFields().values());
assertEquals(1, rangeList.get(0).size(), 0);
MinMax minMax = rangeList.get(0).getRanges().get(0);
assertEquals(minMax.min(), minMax.max(), 0);
assertTrue(minMax.min() == 3 && minMax.max() == 3);
System.out.println("decodedToStr of " + minMax + "=>" + ce.decodedToStr(decoded));
// Test topdown compute
for(String v : categories) {
output = ce.encode(v);
EncoderResult topDown = ce.topDownCompute(output).get(0);
assertEquals(v, topDown.getValue());
assertEquals((int)ce.getScalars(v).get(0), (int)topDown.getScalar().doubleValue());
int[] bucketIndices = ce.getBucketIndices(v);
System.out.println("bucket index => " + bucketIndices[0]);
topDown = ce.getBucketInfo(bucketIndices).get(0);
assertEquals(v, topDown.getValue());
assertEquals((int)ce.getScalars(v).get(0), (int)topDown.getScalar().doubleValue());
assertEquals(topDown.getEncoding(), Arrays.toString(output));
assertEquals(topDown.getValue(), ce.getBucketValues(String.class).get(bucketIndices[0]));
}
// unknown category
output = ce.encode("NA");
assertTrue(Arrays.equals(new int[] { 1,1,1,0,0,0,0,0,0,0,0,0 }, output));
// Test reverse lookup
decoded = ce.decode(output, "");
assertEquals(decoded.getFields().size(), 1, 0);
rangeList = new ArrayList<RangeList>(decoded.getFields().values());
assertEquals(1, rangeList.get(0).size(), 0);
minMax = rangeList.get(0).getRanges().get(0);
assertEquals(minMax.min(), minMax.max(), 0);
assertTrue(minMax.min() == 0 && minMax.max() == 0);
System.out.println("decodedToStr of " + minMax + "=>" + ce.decodedToStr(decoded));
EncoderResult topDown = ce.topDownCompute(output).get(0);
assertEquals(topDown.getValue(), "<UNKNOWN>");
assertEquals(topDown.getScalar(), 0);
output = ce.encode("ES");
assertTrue(Arrays.equals( new int[] {0,0,0,1,1,1,0,0,0,0,0,0 }, output));
// MISSING VALUE
int[] outputForMissing = ce.encode(null);
assertTrue(Arrays.equals( new int[] {0,0,0,0,0,0,0,0,0,0,0,0 }, outputForMissing));
// Test reverse lookup
decoded = ce.decode(output, "");
assertEquals(decoded.getFields().size(), 1, 0);
rangeList = new ArrayList<RangeList>(decoded.getFields().values());
assertEquals(1, rangeList.get(0).size(), 0);
minMax = rangeList.get(0).getRanges().get(0);
assertEquals(minMax.min(), minMax.max(), 0);
assertTrue(minMax.min() == 1 && minMax.max() == 1);
System.out.println("decodedToStr of " + minMax + "=>" + ce.decodedToStr(decoded));
// Test topdown compute
topDown = ce.topDownCompute(output).get(0);
assertEquals(topDown.getValue(), "ES");
assertEquals(topDown.getScalar(), (int)ce.getScalars("ES").get(0));
// Multiple categories
Arrays.fill(output, 1);
// Test reverse lookup
decoded = ce.decode(output, "");
assertEquals(decoded.getFields().size(), 1, 0);
rangeList = new ArrayList<RangeList>(decoded.getFields().values());
assertEquals(1, rangeList.get(0).size(), 0);
minMax = rangeList.get(0).getRanges().get(0);
assertTrue(minMax.min() != minMax.max());
assertTrue(minMax.min() == 0 && minMax.max() == 3);
System.out.println("decodedToStr of " + minMax + "=>" + ce.decodedToStr(decoded));
// Test with width = 1
categories = new String[] { "cat1", "cat2", "cat3", "cat4", "cat5" };
setUp();
parameters.setParameterByKey(KEY.RADIUS, 1.0);
parameters.setParameterByKey(KEY.CATEGORY_LIST, Arrays.<String>asList(categories));
initCE();
for(String cat : categories) {
output = ce.encode(cat);
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println(cat + "->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
}
// Test with width = 9, removing some bits in the encoded output
categories = new String[9];
for(int i = 0;i < 9;i++) categories[i] = String.format("cat%d", i + 1);
//forced: is not recommended, but is used here for readability.
setUp();
parameters.setRadius(1);
parameters.setW(9);
parameters.setForced(true);
parameters.setCategoryList(Arrays.<String>asList(categories));
initCE();
for(String cat : categories) {
output = ce.encode(cat);
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println(cat + "->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
// Get rid of 1 bit on the left
int[] outputNZs = ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
});
// int[] outputPreserve = Arrays.copyOf(output, output.length);
output[outputNZs[0]] = 0;
// System.out.println("output = " + Arrays.toString(outputPreserve));
// System.out.println("outputNZs = " + Arrays.toString(outputNZs));
// System.out.println("outputDelta = " + Arrays.toString(output));
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println("missing 1 bit on left: ->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
// Get rid of 1 bit on the right
output[outputNZs[0]] = 1;
output[outputNZs[outputNZs.length - 1]] = 0;
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println("missing 1 bit on right: ->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
// Get rid of 4 bits on the left
Arrays.fill(output, 0);
int[] indexes = ArrayUtils.range(outputNZs[outputNZs.length - 5], outputNZs[outputNZs.length - 1] + 1);
for(int i = 0;i < indexes.length;i++) output[indexes[i]] = 1;
System.out.println(Arrays.toString(output));
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println("missing 4 bits on left: ->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
// Get rid of 4 bits on the right
Arrays.fill(output, 0);
indexes = ArrayUtils.range(outputNZs[0], outputNZs[5]);
for(int i = 0;i < indexes.length;i++) output[indexes[i]] = 1;
System.out.println(Arrays.toString(output));
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println("missing 4 bits on left: ->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertEquals(topDown.getValue(), cat);
assertEquals(topDown.getScalar(), (int)ce.getScalars(cat).get(0));
}
int[] output1 = ce.encode("cat1");
int[] output2 = ce.encode("cat9");
output = ArrayUtils.or(output1, output2);
topDown = ce.topDownCompute(output).get(0);
if(ce.getVerbosity() >= 1) {
System.out.println("cat1 + cat9 ->" + Arrays.toString(output) +
" " + ArrayUtils.where(output, new Condition.Adapter<Integer>() {
public boolean eval(int i) { return i == 1; }
}));
System.out.println(" scalarTopDown: " + ce.topDownCompute(output));
System.out.println(" topDown " + topDown);
}
assertTrue(topDown.getScalar().equals((int)ce.getScalars("cat1").get(0)) ||
topDown.getScalar().equals((int)ce.getScalars("cat9").get(0)));
System.out.println("passed"); //Just because they did it in the Python version :-)
}
}
|
package org.red5.client.net.rtmp;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.apache.commons.codec.binary.Hex;
import org.apache.mina.core.buffer.IoBuffer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.red5.io.utils.IOUtils;
import org.red5.server.net.rtmp.RTMPConnection;
import org.red5.server.net.rtmp.RTMPHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RTMPHandshakeTest {
private Logger log = LoggerFactory.getLogger(RTMPHandshakeTest.class);
private IoBuffer clientC0C1;
private IoBuffer clientC2;
private IoBuffer serverS0S1S2part1;
private IoBuffer serverS0S1S2part2;
private String youtubeC0C1 = "000000000a002d0235c46e929009dde8c80b089c3026c0938c1fa6415bff483969db1468d34f1c884457b87da48b1f17d2e39645da5a9c16af84ada92e69c5c4074e17098ff957ac1a1cf790ef1791055d45fb21c0c07c070cbc32cf0335a45c61a2034fd6c26207cf2cb43ae3dded6af8df61562548e7162f543174d6921349c7be44e484384aa181215342a64ce1c3d43a0114200a80f0e7b59ada97b9b85e6db722338d49b3f0d14c3a4a94d582aa4885f73c1d0fceecc6a8753dab512608eb26ddfe75f5944c630816d3bb7eb8364ef7e10b5c656263a4e7b9a76cafc5eebe1688c7d64a2a40621189025e45695003c2cf2571875b491cc559fea4ddbc90c4776df8deb5b5f2f9f4dba77350a94f2a907210c2127f8d0de02b8f16789b78c42af556ce9eefaddb8c7df925f349e2aa96aea00dce63d01ae8a63af555d8dae49855267c583a4fbb8b664e527f77f10c35ec97dfff65ac2b72a15a6b046a1431dc8efad25ef518d519b2a60de84e2dfe25cd501d1560beeadc87dc141104e51b7872434de589ea6481fd2e1d3495f7d23f270e7f9761054745baa18024c346f5a1b92e7eb50a5f29eb600a7dc0faa1ffc466391074defcf58a041db4ec517479196c9e8c5d81b3eb2a1397da5294579f44ba9fb091100aea646250a9d7d00543911997b1ae429ff19b0a1218fc7394f00aaa8792b78572e38581c2cc9d0a0c51a7a7b7b9dc8354004bf4c42857297d0270fa807af3e24b9621d232352a3c3514434f1de607af2385bfe0b3c54d446650e10dfb9031ad9b9d9d433e900012723382dd7f8ed3a226b96e10667ce670641010f07737f0cf79290d5c0acfc05c267bb843015bfe6e6f7f71f4f9a7eb8bdee2930a4d378988b84d6ef7717568ff54f05053a80a02f0ce32e432d7ab9b64bb36b20698e79643aa18b28585b4b1e88708c28c9acd22122eb6e5287624dfa835a5e03639f48ae71d5cf03c2630f0e9e89a10bab5691d31ffefe36e7a60dbf4886725d78eddc4f0e531fc4587824b1d3562b804f9b8254f0145f8e9d7e2545299db07c90674f889757208377bb7c9e88f8024b0c62935bdda2654fc40dfe151650311ade463e4da983e5c8ee3cf29689ef9b77a183ba90e6a84bda69cc4ec272e05dc7bb4a55807fb78171fdc3e8e47e33566e73e053272ed531bad8bae867784abb60004088d98414807a2c86df7588a7fdbf1c9b110ca490c121014f009b5d3e4d1d727b2c74a02998adc3e3a8e6eb28935efc7fda51dcc2db06d62918c4a994102d202995379bd98860fe474be43cbe54b9d9db9503eb9b72a1b31cb22e82f7810e00009c7a2543b6ba0b860217fcc8c88a2584b9cb9e0afa909cd8df1a9fae599e7b8229abf29b8472ef9373817e25b5000842ebf72319d24c8e0fa10fec6048123f3580d653109ef84b0a5f6a3a992fb39346e697dff104f3426e83e746ff8edf123f15feec66f2c20524c1d6743535e32372de313441795acdf6261e12408df31c58a5626ffec0731393f64154929e10112227bc2a1c927d58127d980461c49925a93112b8bc71a57b48775aa337e2947bd15452260bf19424728a4fd5c44c87457ce3386fa0cf47f5aa2b7d1d82352b4de6428bde3958b987f0e508d9f31e0458fd458b3500a8d9ec1fee7ad6fccb3da94823ef55f6ce8f84bb1bc8665bacc6c5390db8e6fd3cd2c54838509fc913d77c8728109a26b32c422a2ae1e0a59e234e4c2ec66cdbf21a9ee060b3a166f5dc15c50ca91dd395f0ee5a2313413ac7e52647df9a84ae91b8222d7f93fc5c5787e86c81f0c5485c44f8829cb56dff488e510a96165c0b02b227834b4ed87d8f4db079d54558a7f942757e07c70ba99821b1a827e230e38610dced3271fb94fcf510d24f626805c6a41942797bdfba427d31a17f9bf02e74143ff5c484c32b7c60feec68af406d5e6afda905bfcba439fe3d7cc704f79e8ac564fed59006f0013b7208220c2e6a85c4eef626ffebd483ce9a1d8713f68abcfedb6940b007bfead624b682bcef8168dfbd6171e067babcdb96ec8bb2f6e632a9c0fd86128a4e92b40741fb428c16474bfedde6b996f047fe281fad73d9d86a4484a31715040dd233bfe60d691595a262e6b19f8b4961149d1452300bde251b1914f8be8b7d6";
private String youtubeS1 = "000000000400000126b33989118ea1422bc3c3317eb7a6774d6c0f5dafc8ea157885c76344adfe087437e66f8ce198081e6c6cc3a340c17a7ad8483a62534ed21f2894f4f6189787be97d83cffd2e98ebf787313885757746896d4cd1aefee23b32ccf7d36036ecf913dfa49930d69a725992ba9a5790254fcd7affbe902689ce7c94b5033f313090d30a78f79860e7bcf5882e52cd70d486d4f19cae1b56bdc8693d80c5b6e413fa8965b76b5acfaafe926c6ec2b95fbb5f4e680a883251a5bfe40fe47900be1929c4617803522fa2dcc349e9ea4d35f8d37222a0831ecde078854e5a8237ff2ee67b7a6326985e241de02fd1829c1dd3572af76d1df23ef4519a8463d4e69759ae1a350602c89473f3ace601da88174f92c3e267c7f84b82acee80df6d660dccff6fd4aa9c02ee28bc1df77566d93a1651fcf6c89bc5c9d1dc0b0e2cdaafe0a028b6f5a825a3751d596ef413abf198f9959869b4d906a70eb660e977e62e2b6519b28ca9431780875b6f5354d0adc0ac21eb9e2197433af49ac7cbb6b20eb5c21a2eb3c72159b4cdea534f324ecee0aec977aea152b043eaa1e5c03a147ac1cee8fa17e0536351d2e9e20c1c6f1bfa4d7aca02ef01a01aa5f68e82667646d074817a5b884a0021e0d54d8ea88fb6bcc618e1bff170fed08844cdc21dc077383d137b31a0a502313404423f4d1a39d29e0706e0e1d36c3a3eb10bddbf7cc1ec19d73bf7df5c8e310d06966465fb1a1c61e7fa476ec5615a75597f8c397443401bf82849af05ac48dd11d959a9708512827293f8d404913e779e31197c2f1e927dbc5f6585ba06297d975f4c2e0d5102430340de92d86a707fb096ba2d9bf2b02f4d5023f010be0b718b88b462af971ca7d0c59c0f5098e08ae6967bb169a5365a6be5a2974d43a287fcdff34bbb54471a8914d63cbb763d3ccf7a63974dc30affd3d10e1fc7ded4b138ab0ed8c539c2182d7f950c793be8150229e1a96803459bdaaad254179f361a407e10cb4a2fd2fcbd628ae363cbba7b27da583e95cc5e0b4d493f8b17258351adde40d2e8fce8cd0454ad49e3a128cc689f45ba714903f49733b7ead91a965a3ba65b4914139de79d29afb60fe97426c315d7fde490783e2922e3c20af94d7f2bd1e3403436d564462d8c3295e1e9db3972c574a0669312cad2576d37be5bfcf5ca9ae618c7f45fb78771e773f3c68afbd3f013356c6389f38c75f28d244c0431bc93ecd1ced40ceb880ddea7d93ac5efbad9ab2df10313343bee0523108f52c97180b64c73257868a6968859bac5326aa54d2f85ecac814102f3f3fac8b953752163a3097b8e7912c1f56359d3149d6722d59fa2dfe54a8fd0dc6752750824a1f43cf03e30343b1ef0e63d35191b05eec3655e9a60dfed78e1827d7b15f458865eacced082dbfb3355b3390d4a9ff8f25f8cb61e4844a23f102bc17d4bf5308f0264524f0cfd0a5eaa42b5fbafd9736efe8ea5907d22f293a4ddadfb9dac8d522c7a09adb6f38d0c294f54d043d053b428e5c9d73d85b966a61639a60a6a164d50fa4bc510caab2ddd75266cd41e16fdd61f96dc54d243395f1a2bdc00c532ea179fc78d29f91eaf678235b498244d2323e83227cfd3977d4b28c689a769a268240d5c9b337858bcce23d66d0aa85da16a0dc017871bcc90494489db1682f88296278b32e829d5673e0d54310eed45be4fd3e9d732843b55c6b902c57a65ff5735331be1e62005cbaa4acf27ca208c6daff6a6b6dc7e25d88ef43f469435b78ffeb243c7cfc1c0483b0e47e11586c533c5c74f662cf7a1e0d037aa7d722fb348d9fff88b2244f44b7bab8ee3cf5425fdf6bc6f6b6395cdd4dd0fda76c89aed47aca19298118ab55b1c2bcf54dfb91c4f42a66aa808d68780f49b20adef3de077b38a9701e2d2fa0f8d5c42413da26b0c0480c6824dd019924c4a1ab3edeb38d43fd8cd17fc1898c777826a20710f1b973f72532156abb8e72285516a372f1821e0f016b08a0844bd8f10e9163913e9fb570aea5499123c0b7e3549ca99b5aa2f784a6cf2e49d7bc192b40e0a8af31ed9296280c12a9131e70eb7e8aa6530879e06c87ad52e0ef1206d643be317c72bc1a4cb1cd28f5c2a57ccde6fd8591ee4b18c18af86e04b9cd3df18e0ae2af4185000000000a002d0235c46e929009dde8c80b089c3026c0938c1fa6415bff483969db1468d34f1c884457b87da48b1f17d2e39645da5a9c16af84ada92e69c5c4074e17098ff957ac1a1cf790ef1791055d45fb21c0c07c070cbc32cf0335a45c61a2034fd6c26207cf2cb43ae3dded6af8df61562548e7162f543174d6921349c7be44e484384aa181215342a64ce1c3d43a0114200a80f0e7b59ada97b9b85e6db722338d49b3f0d14c3a4a94d582aa4885f73c1d0fceecc6a8753dab512608eb26ddfe75f5944c630816d3bb7eb8364ef7e10b5c656263a4e7b9a76cafc5eebe1688c7d64a2a40621189025e45695003c2cf2571875b491cc559fea4ddbc90c4776df8deb5b5f2f9f4dba77350a94f2a907210c2127f8d0de02b8f16789b78c42af556ce9eefaddb8c7df925f349e2aa96aea00dce63d01ae8a63af555d8dae49855267c583a4fbb8b664e527f77f10c35ec97dfff65ac2b72a15a6b046a1431dc8efad25ef518d519b2a60de84e2dfe25cd501d1560beeadc87dc141104e51b7872434de589ea6481fd2e1d3495f7d23f270e7f9761054745baa18024c346f5a1b92e7eb50a5f29eb600a7dc0faa1ffc466391074defcf58a041db4ec517479196c9e8c5d81b3eb2a1397da5294579f44ba9fb091100aea646250a9d7d00543911997b1ae429ff19b0a1218fc7394f00aaa8792b78572e38581c2cc9d0a0c51a7a7b7b9dc8354004bf4c42857297d0270fa807af3e24b9621d232352a3c3514434f1de607af2385bfe0b3c54d446650e10dfb9031ad9b9d9d433e900012723382dd7f8ed3a226b96e10667ce670641010f07737f0cf79290d5c0acfc05c267bb843015bfe6e6f7f71f4f9a7eb8bdee2930a4d378988b84d6ef7717568ff54f05053a80a02f0ce32e432d7ab9b64bb36b20698e79643aa18b28585b4b1e88708c28c9acd22122eb6e5287624dfa835a5e03639f48ae71d5cf03c2630f0e9e89a10bab5691d31ffefe36e7a60dbf4886725d78eddc4f0e531fc4587824b1d3562b804f9b8254f0145f8e9d7e2545299db07c90674f889757208377bb7c9e88f8024b0c62935bdda2654fc40dfe151650311ade463e4da983e5c8ee3cf29689ef9b77a183ba90e6a84bda69cc4ec272e05dc7bb4a55807fb78171fdc3e8e47e33566e73e053272ed531bad8bae867784abb60004088d98414807a2c86df7588a7fdbf1c9b110ca490c121014f009b5d3e4d1d727b2c74a02998adc3e3a8e6eb28935efc7fda51dcc2db06d62918c4a994102d202995379bd98860fe474be43cbe54b9d9db9503eb9b72a1b31cb22e82f7810e00009c7a2543b6ba0b860217fcc8c88a2584b9cb9e0afa909cd8df1a9fae599e7b8229abf29b8472ef9373817e25b5000842ebf72319d24c8e0fa10fec6048123f3580d653109ef84b0a5f6a3a992fb39346e697dff104f3426e83e746ff8edf123f15feec66f2c20524c1d6743535e32372de313441795acdf6261e12408df31c58a5626ffec0731393f64154929e10112227bc2a1c927d58127d980461c49925a93112b8bc71a57b48775aa337e2947bd15452260bf19424728a4fd5c44c87457ce3386fa0cf47f5aa2b7d1d82352b4de6428bde3958b987f0e508d9f31e0458fd458b3500a8d9ec1fee7ad6fccb3da94823ef55f6ce8f84bb1bc8665bacc6c5390db8e6fd3cd2c54838509fc913d77c8728109a26b32c422a2ae1e0a59e234e4c2ec66cdbf21a9ee060b3a166f5dc15c50ca91dd395f0ee5a2313413ac7e52647df9a84ae91b8222d7f93fc5c5787e86c81f0c5485c44f8829cb56dff488e510a96165c0b02b227834b4ed87d8f4db079d54558a7f942757e07c70ba99821b1a827e230e38610dced3271fb94fcf510d24f626805c6a41942797bdfba427d31a17f9bf02e74143ff5c484c32b7c60feec68af406d5e6afda905bfcba439fe3d7cc704f79e8ac564fed59006f0013b7208220c2e6a85c4eef626ffebd483ce9a1d8713f68abcfedb6940b007bfead624b682bcef8168dfbd6171e067babcdb96ec8bb2f6e632a9c0fd86128a4e92b40741fb428c16474bfedde6b996f047fe281fad73d9d86a4484a31715040dd233bfe60d691595a262e6b19f8b4961149d1452300bde251b1914f8be8b7d6";
@Before
public void setUp() throws Exception {
clientC0C1 = IoBuffer.allocate(1537);
// put the handshake type in the first position
clientC0C1.put(RTMPConnection.RTMP_NON_ENCRYPTED);
fillBuffer(clientC0C1, "RTMP-C0C1.dat");
clientC2 = IoBuffer.allocate(1536);
fillBuffer(clientC2, "RTMP-C2.dat");
serverS0S1S2part1 = IoBuffer.allocate(1537);
// put the handshake type in the first position
serverS0S1S2part1.put(RTMPConnection.RTMP_NON_ENCRYPTED);
fillBuffer(serverS0S1S2part1, "RTMP-S0S1S2-01.dat");
serverS0S1S2part2 = IoBuffer.allocate(1536);
fillBuffer(serverS0S1S2part2, "RTMP-S0S1S2-02.dat");
}
private void fillBuffer(IoBuffer buf, String byteDumpFile) throws Exception {
File f = new File(String.format("%s/target/test-classes/%s", System.getProperty("user.dir"), byteDumpFile));
FileInputStream fis = new FileInputStream(f);
ByteBuffer bb = ByteBuffer.allocate((int) f.length());
fis.getChannel().read(bb);
bb.flip();
buf.put(bb);
buf.flip();
log.debug("Filled buffer: {}", buf);
fis.close();
}
@After
public void tearDown() throws Exception {
clientC0C1.free();
clientC2.free();
serverS0S1S2part1.free();
serverS0S1S2part2.free();
}
@Test
public void testClientDigest() throws InterruptedException {
log.info("\ntestClientDigest");
OutboundHandshake out = new OutboundHandshake();
int algorithm = 0;
byte[] handshakeBytes = out.generateClientRequest1().array();
// get the handshake digest
int digestPos = out.getDigestOffset(algorithm, handshakeBytes, 0);
log.debug("Digest position offset: {}", digestPos);
out.calculateDigest(digestPos, handshakeBytes, 0, RTMPHandshake.GENUINE_FP_KEY, 30, handshakeBytes, digestPos);
log.debug("Calculated digest: {}", Hex.encodeHexString(Arrays.copyOfRange(handshakeBytes, digestPos, digestPos + 32)));
Assert.assertTrue(out.verifyDigest(digestPos, handshakeBytes, RTMPHandshake.GENUINE_FP_KEY, 30));
}
/** Clientside test */
@Test
public void testOutboundHandshake() {
log.info("\ntestOutboundHandshake");
OutboundHandshake out = new OutboundHandshake();
// set the handshake type
out.setHandshakeType(RTMPConnection.RTMP_NON_ENCRYPTED);
// called initially with null input which triggers creation of C1
//IoBuffer C1 = hs.doHandshake(null);
//log.debug("C1: {}", C1);
//log.debug("C0C1 bytes: {}", new String(clientC0C1.array()));
// strip 03 byte
serverS0S1S2part1.get();
// send in the first part of server handshake
IoBuffer C2 = out.decodeServerResponse1(serverS0S1S2part1);
Assert.assertNotNull(C2);
log.debug("S1 (first): {}", C2);
// send in the second part of server handshake, this creates C2
boolean res = out.decodeServerResponse2(serverS0S1S2part2);
Assert.assertTrue(res);
log.debug("S2 (second): {}", res);
//log.debug("Server bytes1: {}", new String(serverS0S1S2part1.array()));
//log.debug("Server bytes2: {}", new String(serverS0S1S2part2.array()));
// put parts 1 and 2 together
IoBuffer S0S1S2 = IoBuffer.allocate(3073);
S0S1S2.put(serverS0S1S2part1);
S0S1S2.put(serverS0S1S2part2);
S0S1S2.flip();
// strip the 03 byte
S0S1S2.get();
// send in the combined server handshake, this creates C2
C2 = out.decodeServerResponse1(S0S1S2);
log.debug("C2 (third): {}", C2);
}
@Test
public void testValidate() {
log.info("\ntestValidate");
// client side handshake handler
OutboundHandshake out = new OutboundHandshake();
// set the handshake type
out.setHandshakeType(RTMPConnection.RTMP_NON_ENCRYPTED);
// try SO12
IoBuffer S0S1S2 = IoBuffer.allocate(3073);
S0S1S2.put(serverS0S1S2part1);
S0S1S2.put(serverS0S1S2part2);
S0S1S2.flip();
// strip the 03 type byte
S0S1S2.get();
log.debug("Validate server: {}", S0S1S2);
boolean server = out.validate(S0S1S2.array());
log.debug("Handshake is valid: {}", server);
// XXX S0S1S2 data needs to be regenerated, what we have is corrupt
//Assert.assertTrue(server);
}
@Test
public void testValidateFromYouTube() {
log.info("\ntestValidateFromYouTube");
// client side handshake handler
OutboundHandshake out = new OutboundHandshake();
// server response
IoBuffer y = IoBuffer.allocate(0);
y.setAutoExpand(true);
y.put(IOUtils.hexStringToByteArray(youtubeS1));
y.flip();
log.debug("Validate youtube: {}", y);
boolean youtube = out.validate(y.array());
//boolean decoded = out.decodeServerResponse1(y);
//Assert.assertTrue(youtube && decoded);
}
}
|
// OO jDREW - An Object Oriented extension of the Java Deductive Reasoning Engine for the Web
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
package org.ruleml.oojdrew.tests;
import java.util.prefs.PreferenceChangeListener;
import org.ruleml.oojdrew.Configuration;
public class MockConfiguration implements Configuration {
private boolean ruleMLCompatibilityModeEnabled;
public boolean getValidateRuleMLEnabled() {
return ruleMLCompatibilityModeEnabled;
}
public void setValidateRuleMLEnabled(boolean enabled) {
ruleMLCompatibilityModeEnabled = enabled;
}
public int getTextFontSize() {
throw new UnsupportedOperationException();
}
public void setTextFontSize(int newSize) {
throw new UnsupportedOperationException();
}
public void addPreferenceChangeListener(PreferenceChangeListener listener) {
throw new UnsupportedOperationException();
}
}
|
package org.apache.commons.collections;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit Tests for <code>MultiHashMap</code>.
*
*/
public class TestMultiHashMap extends TestMap
{
public TestMultiHashMap(String testName)
{
super(testName);
}
public static Test suite()
{
return new TestSuite(TestMultiHashMap.class);
}
public static void main(String args[])
{
String[] testCaseName = { TestMultiHashMap.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// MutltiHashMap was introduced in Collections 2.x
public int getCompatibilityVersion() {
return 2;
}
public Map makeEmptyMap() {
return new MultiHashMap();
}
// Tests
public void testPutNGet()
{
MultiHashMap map = new MultiHashMap();
loadMap( map );
checkMap( map );
assertTrue( map.get(new Integer(99)) == null );
map.clear();
assertTrue( map.size() == 0 );
}
public void testContainsValue()
{
MultiHashMap map = new MultiHashMap();
loadMap( map );
assertTrue( map.containsValue( "uno" ) );
assertTrue( map.containsValue( "quatro" ) );
assertTrue( map.containsValue( "two" ) );
assertTrue( ! map.containsValue( "uggaBugga" ) );
map.clear();
}
public void testValues()
{
MultiHashMap map = new MultiHashMap();
loadMap( map );
Collection vals = map.values();
assertTrue( vals.size() == getFullSize() );
map.clear();
}
static private class MapPair
{
MapPair( int key, String val )
{
mKey = new Integer( key );
mValue = val;
}
Integer mKey = null;
String mValue = null;
}
static private MapPair[][] sMapPairs =
{
{new MapPair(0,"zero")},
{new MapPair(1,"one"), new MapPair(1,"ONE"), new MapPair(1,"uno")},
{new MapPair(2,"two"), new MapPair(2,"two") },
{new MapPair(3,"three"), new MapPair(3,"THREE"), new MapPair(3,"tres")},
{new MapPair(4,"four"), new MapPair(4,"quatro")}
};
private void loadMap( MultiHashMap map )
{
// Set up so that we load the keys "randomly"
// (i.e. we don't want to load int row-order, so that all like keys
// load together. We want to mix it up...)
int numRows = sMapPairs.length;
int maxCols = 0;
for( int ii=0; ii < sMapPairs.length; ii++ ){
if ( sMapPairs[ii].length > maxCols )
maxCols = sMapPairs[ii].length;
}
for( int ii=0; ii < maxCols; ii++ ){
for( int jj=0; jj < numRows; jj++ ){
if ( ii < sMapPairs[jj].length ) {
map.put( sMapPairs[jj][ii].mKey, sMapPairs[jj][ii].mValue);
}
}
}
assertTrue( map.size() == sMapPairs.length );
}
private void checkMap( MultiHashMap map )
{
for( int ii=0; ii < sMapPairs.length; ii++ ){
checkKeyList( map, ii );
}
}
private void checkKeyList( MultiHashMap map, int index )
{
assertTrue( index < sMapPairs.length );
Integer key = sMapPairs[index][0].mKey ;
Object obj = map.get( key );
assertTrue( obj != null );
assertTrue( obj instanceof Collection );
Collection keyList = (Collection)obj;
assertTrue( keyList.size() == sMapPairs[index].length );
Iterator iter = keyList.iterator();
while ( iter.hasNext() ) {
Object oval = iter.next();
assertTrue( oval != null );
assertTrue( oval instanceof String );
String val = (String)oval;
boolean foundIt = false;
for( int ii=0; ii < sMapPairs[index].length; ii++ ){
if( val.equals( sMapPairs[index][ii].mValue ) )
foundIt = true;
}
assertTrue( foundIt );
}
}
public int getFullSize()
{
int len = 0;
for( int ii=0; ii < sMapPairs.length; ii++ ){
len += sMapPairs[ii].length;
}
return len;
}
public void testEntrySetIterator() {
}
public void testEntrySetContainsProperMappings() {
}
public void testEntrySetIteratorHasProperMappings() {
// override and ignore test -- it will fail when verifying the iterator for
// the set contains the right value -- we're not returning the value, we're
// returning a collection.
// TODO: re-implement this test to ensure the values of the iterator match
// the proper collection rather than the value the superclass is checking
// for.
return;
}
}
|
package org.smoothbuild.fs.mem;
import javax.inject.Singleton;
import org.smoothbuild.fs.base.FileSystem;
import com.google.inject.AbstractModule;
public class InMemoryFileSystemModule extends AbstractModule {
@Override
protected void configure() {
bind(InMemoryFileSystem.class).in(Singleton.class);
bind(FileSystem.class).to(InMemoryFileSystem.class);
}
}
|
package org.perl6.nqp.sixmodel.reprs;
import java.math.BigInteger;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.perl6.nqp.runtime.ThreadContext;
import org.perl6.nqp.sixmodel.REPR;
import org.perl6.nqp.sixmodel.STable;
import org.perl6.nqp.sixmodel.SerializationReader;
import org.perl6.nqp.sixmodel.SerializationWriter;
import org.perl6.nqp.sixmodel.SixModelObject;
import org.perl6.nqp.sixmodel.StorageSpec;
import org.perl6.nqp.sixmodel.TypeObject;
public class P6bigint extends REPR {
public SixModelObject type_object_for(ThreadContext tc, SixModelObject HOW) {
STable st = new STable(this, HOW);
SixModelObject obj = new TypeObject();
obj.st = st;
st.WHAT = obj;
return st.WHAT;
}
public SixModelObject allocate(ThreadContext tc, STable st) {
P6bigintInstance obj = new P6bigintInstance();
obj.st = st;
return obj;
}
public StorageSpec get_storage_spec(ThreadContext tc, STable st) {
StorageSpec ss = new StorageSpec();
ss.inlineable = StorageSpec.INLINED;
ss.boxed_primitive = StorageSpec.BP_INT;
ss.bits = 64;
ss.can_box = StorageSpec.CAN_BOX_INT;
return ss;
}
public void inlineStorage(ThreadContext tc, STable st, ClassWriter cw, String prefix) {
cw.visitField(Opcodes.ACC_PUBLIC, prefix, Type.getType(BigInteger.class).getDescriptor(), null, null);
}
public void inlineBind(ThreadContext tc, STable st, MethodVisitor mv, String className, String prefix) {
String bigIntegerType = Type.getType(BigInteger.class).getDescriptor();
String bigIntegerIN = Type.getType(BigInteger.class).getInternalName();
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitInsn(Opcodes.ICONST_0 + ThreadContext.NATIVE_JVM_OBJ);
mv.visitFieldInsn(Opcodes.PUTFIELD, "org/perl6/nqp/runtime/ThreadContext", "native_type", "I");
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitFieldInsn(Opcodes.GETFIELD, "org/perl6/nqp/runtime/ThreadContext", "native_j",
Type.getType(Object.class).getDescriptor());
mv.visitTypeInsn(Opcodes.CHECKCAST, bigIntegerIN);
mv.visitFieldInsn(Opcodes.PUTFIELD, className, prefix, bigIntegerType);
mv.visitInsn(Opcodes.RETURN);
}
public void inlineGet(ThreadContext tc, STable st, MethodVisitor mv, String className, String prefix) {
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitInsn(Opcodes.DUP);
mv.visitInsn(Opcodes.ICONST_0 + ThreadContext.NATIVE_JVM_OBJ);
mv.visitFieldInsn(Opcodes.PUTFIELD, "org/perl6/nqp/runtime/ThreadContext", "native_type", "I");
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(Opcodes.GETFIELD, className, prefix,
Type.getType(BigInteger.class).getDescriptor());
mv.visitFieldInsn(Opcodes.PUTFIELD, "org/perl6/nqp/runtime/ThreadContext", "native_j",
Type.getType(Object.class).getDescriptor());
mv.visitInsn(Opcodes.RETURN);
}
public void generateBoxingMethods(ThreadContext tc, STable st, ClassWriter cw, String className, String prefix) {
String bigIntegerType = Type.getType(BigInteger.class).getDescriptor();
String bigIntegerIN = Type.getType(BigInteger.class).getInternalName();
String getDesc = "(Lorg/perl6/nqp/runtime/ThreadContext;)J";
MethodVisitor getMeth = cw.visitMethod(Opcodes.ACC_PUBLIC, "get_int", getDesc, null, null);
getMeth.visitVarInsn(Opcodes.ALOAD, 0);
getMeth.visitFieldInsn(Opcodes.GETFIELD, className, prefix, bigIntegerType);
getMeth.visitMethodInsn(Opcodes.INVOKEVIRTUAL, bigIntegerIN, "longValue", "()J");
getMeth.visitInsn(Opcodes.LRETURN);
getMeth.visitMaxs(0, 0);
String setDesc = "(Lorg/perl6/nqp/runtime/ThreadContext;J)V";
MethodVisitor setMeth = cw.visitMethod(Opcodes.ACC_PUBLIC, "set_int", setDesc, null, null);
setMeth.visitVarInsn(Opcodes.ALOAD, 0);
setMeth.visitVarInsn(Opcodes.LLOAD, 2);
setMeth.visitMethodInsn(Opcodes.INVOKESTATIC, bigIntegerIN, "valueOf",
Type.getMethodDescriptor(Type.getType(BigInteger.class), new Type[] { Type.LONG_TYPE }));
setMeth.visitFieldInsn(Opcodes.PUTFIELD, className, prefix, bigIntegerType);
setMeth.visitInsn(Opcodes.RETURN);
setMeth.visitMaxs(0, 0);
}
public SixModelObject deserialize_stub(ThreadContext tc, STable st) {
throw new RuntimeException("Deserialization NYI for P6bigint");
}
public void deserialize_finish(ThreadContext tc, STable st,
SerializationReader reader, SixModelObject obj) {
throw new RuntimeException("Deserialization NYI for P6bigint");
}
public void deserialize_inlined(ThreadContext tc, STable st, SerializationReader reader,
String prefix, SixModelObject obj) {
try {
obj.getClass().getField(prefix).set(obj, new BigInteger(reader.readStr()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void serialize_inlined(ThreadContext tc, STable st, SerializationWriter writer,
String prefix, SixModelObject obj) {
try {
writer.writeStr(obj.getClass().getField(prefix).get(obj).toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package com.thoughtworks.acceptance;
import java.math.BigDecimal;
import java.math.BigInteger;
public class BasicTypesTest extends AbstractAcceptanceTest {
public void testPrimitiveNumbers() {
assertBothWays(new Integer(99), "<int>99</int>");
assertBothWays(new Integer(-99), "<int>-99</int>");
assertBothWays(new Integer(0), "<int>0</int>");
assertBothWays(new Float(-123.45f), "<float>-123.45</float>");
assertBothWays(new Double(-1234567890.12345), "<double>-1.23456789012345E9</double>");
assertBothWays(new Long(123456789123456L), "<long>123456789123456</long>");
assertBothWays(new Short((short) 123), "<short>123</short>");
}
public void testDifferentBaseIntegers() {
assertEquals(new Integer(255), xstream.fromXML("<int>0xFF</int>"));
assertEquals(new Integer(8), xstream.fromXML("<int>010</int>"));
}
public void testNegativeIntegersInHex() {
assertEquals(new Byte((byte)-1), xstream.fromXML("<byte>0xFF</byte>"));
assertEquals(new Short((short)-1), xstream.fromXML("<short>0xFFFF</short>"));
assertEquals(new Integer(-1), xstream.fromXML("<int>0xFFFFFFFF</int>"));
assertEquals(new Long(Long.MAX_VALUE), xstream.fromXML("<long>0x7FFFFFFFFFFFFFFF</long>"));
}
public void testNegativeIntegersInOctal() {
assertEquals(new Byte((byte)-1), xstream.fromXML("<byte>0377</byte>"));
assertEquals(new Short((short)-1), xstream.fromXML("<short>0177777</short>"));
assertEquals(new Integer(-1), xstream.fromXML("<int>037777777777</int>"));
assertEquals(new Long(Long.MAX_VALUE), xstream.fromXML("<long>0777777777777777777777</long>"));
}
public void testOtherPrimitives() {
assertBothWays(new Character('z'), "<char>z</char>");
assertBothWays(Boolean.TRUE, "<boolean>true</boolean>");
assertBothWays(Boolean.FALSE, "<boolean>false</boolean>");
assertBothWays(new Byte((byte) 44), "<byte>44</byte>");
}
public void testNullCharacter() {
assertEquals(new Character('\0'), xstream.fromXML("<char null=\"true\"/>")); // pre XStream 1.3
assertBothWays(new Character('\0'), "<char></char>");
}
public void testNonUnicodeCharacter() {
assertBothWays(new Character('\uffff'), "<char></char>");
}
public void testStrings() {
assertBothWays("hello world", "<string>hello world</string>");
}
public void testStringsWithISOControlCharacter() {
assertBothWays("hello\u0004world", "<string>helloworld</string>");
assertBothWays("hello\u0096world", "<string>hello–world</string>");
}
public void testStringBuffer() {
StringBuffer buffer = new StringBuffer();
buffer.append("woo");
String xml = xstream.toXML(buffer);
assertEquals(xml, "<string-buffer>woo</string-buffer>");
StringBuffer out = (StringBuffer) xstream.fromXML(xml);
assertEquals("woo", out.toString());
}
public void testBigInteger() {
BigInteger bigInteger = new BigInteger("1234567890123456");
assertBothWays(bigInteger, "<big-int>1234567890123456</big-int>");
}
public void testBigDecimal() {
BigDecimal bigDecimal = new BigDecimal("1234567890123456.987654321");
assertBothWays(bigDecimal, "<big-decimal>1234567890123456.987654321</big-decimal>");
}
public void testNull() {
assertBothWays(null, "<null/>");
}
public void testNumberFormats() {
assertEquals(1.0, ((Double)xstream.fromXML("<double>1</double>")).doubleValue(), 0.001);
assertEquals(1.0f, ((Float)xstream.fromXML("<float>1</float>")).floatValue(), 0.001);
}
}
|
package bot;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Server {
// Fields
private static SSLSocketFactory sslfact;
public static Scanner in;
public static PrintStream out;
private static Socket socket;
private static SSLSocket sslsocket;
private static boolean isConnected;
private static String address;
private static int port;
private static boolean useSSL;
private static boolean reading = false;
private static ArrayDeque<String> toserver;
private static ArrayDeque<String> toserverlesspriority;
static Thread thread;
public static void connectTo(String address, int port, boolean useSSL){
Server.address = address;
Server.port = port;
Server.useSSL = useSSL;
try{
toserver = new ArrayDeque<String>();
toserverlesspriority = new ArrayDeque<String>();
if(socket != null)socket.close();
if(sslsocket != null)sslsocket.close();
if(out != null) out.close();
if(in != null) in.close();
if(useSSL){
System.setProperty("javax.net.ssl.trustStore", Config.getPathToKeystore());
try {
X509TrustManager[] tm = new X509TrustManager[] { new X509TrustManager(){
public void checkClientTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public void checkServerTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers (){
return null;
}
}};
SSLContext context = SSLContext.getInstance ("SSL");
context.init( new KeyManager[0], tm, new SecureRandom( ) );
sslfact = (SSLSocketFactory) context.getSocketFactory ();
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException e) {
}
sslsocket = (SSLSocket)sslfact.createSocket(address, port);
sslsocket.startHandshake();
in = new Scanner(sslsocket.getInputStream());
out = new PrintStream(sslsocket.getOutputStream());
}
else{
socket = new Socket(address, port);
in = new Scanner(socket.getInputStream());
out = new PrintStream(socket.getOutputStream());
}
readToServerStream();
isConnected = true;
}
catch(Exception e){
IrcBot.out.println("Could not connect: " + e.toString());
IrcBot.out.println("Retrying in 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
if(!isConnected){
connectTo(address,port,useSSL);
}
}
public static void send(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
if(message.startsWith("PRIVMSG") || message.startsWith("NOTICE ")){
String[] split = message.split(" ");
String tosend = "";
System.out.println();
System.out.println("MESSAGE " + message);
System.out.println();
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserver.add(tosend.substring(0, tosend.length()-1));
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
send(next.substring(0, next.length()-1));
break;
}
}
if(!hitLimit)toserver.add(tosend.substring(0, tosend.length()-1));
}
else{
toserver.addFirst(message);
}
}
public static void pm(String target, String message){
send(String.format("PRIVMSG %s :%s", target, message));
}
public static void notice(String target, String message){
send(String.format("NOTICE %s :%s", target, message));
}
public static void lessPrioritySend(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
if(message.startsWith("PRIVMSG") || message.startsWith("NOTICE ")){
String[] split = message.split(" ");
String tosend = "";
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserverlesspriority.add(tosend.substring(0, tosend.length()-1));
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
lessPrioritySend(next.substring(0, next.length()-1));
break;
}
}
if(!hitLimit)toserverlesspriority.add(tosend.substring(0, tosend.length()-1));
}
else{
toserver.addFirst(message);
}
}
public static void lessPriorityPm(String target, String message){
lessPrioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void lessPriorityNotice(String target, String message){
lessPrioritySend(String.format("NOTICE %s :%s", target, message));
}
public static void prioritySend(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
if(message.startsWith("PRIVMSG") || message.startsWith("NOTICE ")){
String[] split = message.split(" ");
String tosend = "";
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserver.addFirst(tosend.substring(0, tosend.length()-1));
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
prioritySend(next.substring(0, next.length()-1));
break;
}
}
if(!hitLimit)toserver.addFirst(tosend.substring(0, tosend.length()-1));
}
else{
toserver.addFirst(message);
}
}
public static void priorityPm(String target, String message){
prioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void priorityNotice(String target, String message){
prioritySend(String.format("NOTICE %s :%s", target, message));
}
/**
* PRIVMSG for room
* NOTICE for user
*/
public static void say(String target, String message){
if(target.startsWith("#")) Server.pm(target, message);
else Server.notice(target, message);
}
public static void say(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.pm(target, messagearray[i]);
else Server.notice(target, messagearray[i]);
}
}
/**
* Priority
*/
public static void prioritySay(String target, String message){
if(target.startsWith("#")) Server.priorityPm(target, message);
else Server.priorityNotice(target, message);
}
public static void prioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.priorityPm(target, messagearray[i]);
else Server.priorityNotice(target, messagearray[i]);
}
}
/**
* Less Priority say
*/
public static void lessPrioritySay(String target, String message){
if(target.startsWith("#")) Server.lessPriorityPm(target, message);
else Server.lessPriorityNotice(target, message);
}
public static void lessPrioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.lessPriorityPm(target, messagearray[i]);
else Server.lessPriorityNotice(target, messagearray[i]);
}
}
public static boolean isConnected(){
return isConnected;
}
public static void resetConnection(String reason){
IrcBot.out.println("Resetting connection: " + reason);
isConnected = false;
IrcBot.stop();
try {
connectTo(address,port,useSSL);
Thread.sleep(2000);
if(IrcBot.attemptLogin()){
IrcBot.sendOnLogin();
isConnected = true;
IrcBot.listenToServer();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void disconnect(){
prioritySend("QUIT :Shutting down!");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(1);
//Runtime.getRuntime().exit(1);
}
private static void readToServerStream(){
if(reading)return;
reading = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
if(toserver.size() != 0){
String tosend = toserver.poll().replaceAll("\r", "").replaceAll("\n", "");;
System.out.println(tosend);
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
else if(toserverlesspriority.size() != 0){
String tosend = toserverlesspriority.poll().replaceAll("\r", "").replaceAll("\n", "");;
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
});
thread.start();
}
}
|
package nars.logic.nal7;
import com.google.common.collect.Lists;
import nars.core.Memory;
import nars.core.Parameters;
import nars.io.Symbols;
import nars.logic.*;
import nars.logic.entity.*;
import nars.logic.nal1.Inheritance;
import nars.logic.nal2.Similarity;
import nars.logic.nal4.Product;
import nars.logic.nal5.Conjunction;
import nars.logic.nal5.Equivalence;
import nars.logic.nal5.Implication;
import nars.logic.nal8.Operation;
import java.util.*;
/**
*
* @author peiwang
*/
public class TemporalRules {
public static final int ORDER_NONE = 2;
public static final int ORDER_FORWARD = 1;
public static final int ORDER_CONCURRENT = 0;
public static final int ORDER_BACKWARD = -1;
public static final int ORDER_INVALID = -2;
public final static int reverseOrder(final int order) {
if (order == ORDER_INVALID) {
throw new RuntimeException("ORDER_INVALID not handled here");
}
if (order == ORDER_NONE) {
return ORDER_NONE;
} else {
return -order;
}
}
public final static boolean matchingOrder(final Sentence a, final Sentence b) {
return matchingOrder(a.getTemporalOrder(), b.getTemporalOrder());
}
public final static boolean matchingOrder(final int order1, final int order2) {
return (order1 == order2) || (order1 == ORDER_NONE) || (order2 == ORDER_NONE);
}
public final static int dedExeOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if ((order1 == order2) || (order2 == TemporalRules.ORDER_NONE)) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = order2;
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = order1;
}
return order;
}
public final static int abdIndComOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if (order2 == TemporalRules.ORDER_NONE) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = reverseOrder(order2);
} else if ((order2 == TemporalRules.ORDER_CONCURRENT) || (order1 == -order2)) {
order = order1;
}
return order;
}
public final static int analogyOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
if ((order2 == TemporalRules.ORDER_NONE) || (order2 == TemporalRules.ORDER_CONCURRENT)) {
order = order1;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure < 20) ? order2 : reverseOrder(order2);
} else if (order1 == order2) {
if ((figure == 12) || (figure == 21)) {
order = order1;
}
} else if ((order1 == -order2)) {
if ((figure == 11) || (figure == 22)) {
order = order1;
}
}
return order;
}
public static final int resemblanceOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
int order1Reverse = reverseOrder(order1);
if ((order2 == TemporalRules.ORDER_NONE)) {
order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure % 10 == 1) ? order2 : reverseOrder(order2); // switch when 12 or 22
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12
} else if (order1 == order2) {
order = (figure == 21) ? order1 : -order1;
}
return order;
}
public static final int composeOrder(final int order1, final int order2) {
int order = ORDER_INVALID;
if (order2 == TemporalRules.ORDER_NONE) {
order = order1;
} else if (order1 == TemporalRules.ORDER_NONE) {
order = order2;
} else if (order1 == order2) {
order = order1;
}
return order;
}
/** whether temporal induction can generate a task by avoiding producing wrong terms; only one temporal operator is allowed */
public final static boolean tooMuchTemporalStatements(final Term t, int maxTemporalRelations) {
return (t == null) || (t.containedTemporalRelations() > maxTemporalRelations);
}
// { A =/> B, B =/> C } |- (&/,A,B) =/> C
// { A =/> B, (&/,B,...) =/> C } |- (&/,A,B,...) =/> C
public static boolean temporalInductionChain(final Sentence s1, final Sentence s2, final NAL nal) {
//prevent trying question sentences, causes NPE
if ((s1.truth == null) || (s2.truth == null))
return false;
//try if B1 unifies with B2, if yes, create new judgement
Implication S1=(Implication) s1.term;
Implication S2=(Implication) s2.term;
Term A=S1.getSubject();
Term B1=S1.getPredicate();
Term B2=S2.getSubject();
Term C=S2.getPredicate();
ArrayList<Term> args=null;
int beginoffset=0;
if(B2 instanceof Conjunction) {
Conjunction CB2=((Conjunction)B2);
if(CB2.getTemporalOrder()==TemporalRules.ORDER_FORWARD) {
if(A instanceof Conjunction && A.getTemporalOrder()==TemporalRules.ORDER_FORWARD) {
Conjunction ConjA=(Conjunction) A;
args=new ArrayList(CB2.term.length+ConjA.term.length);
beginoffset=ConjA.size();
Collections.addAll(args, ConjA.term);
} else {
args = new ArrayList(CB2.term.length + 1);
args.add(A);
beginoffset=1;
}
Collections.addAll(args, CB2.term);
}
}
else {
args=Lists.newArrayList(A, B1);
}
if(args==null)
return false;
//ok we have our B2, no matter if packed as first argument of &/ or directly, lets see if it unifies
Term[] term = args.toArray(new Term[args.size()]);
Term realB2 = term[beginoffset];
Map<Term, Term> res1 = Parameters.newHashMap();
Map<Term, Term> res2 = Parameters.newHashMap();
if(Variables.findSubstitute(Symbols.VAR_INDEPENDENT, B1, realB2, res1,res2)) {
//ok it unifies, so lets create a &/ term
for(int i=0;i<term.length;i++) {
final Term ti = term[i];
if (ti instanceof CompoundTerm) {
Term ts = ((CompoundTerm)ti).applySubstitute(res1);
if(ts!=null)
term[i] = ts;
}
else {
term[i] = res1.getOrDefault(ti,ti);
}
}
int order1=s1.getTemporalOrder();
int order2=s2.getTemporalOrder();
//check if term has a element which is equal to C
for(Term t : term) {
if(Terms.equalSubTermsInRespectToImageAndProduct(t, C)) {
return false;
}
for(Term u : term) {
if(u!=t) { //important: checking reference here is as it should be!
if(Terms.equalSubTermsInRespectToImageAndProduct(t, u)) {
return false;
}
}
}
}
Term S = Conjunction.make(term,order1);
Implication whole=Implication.make(S, C,order2);
if(whole!=null) {
TruthValue truth = TruthFunctions.deduction(s1.truth, s2.truth);
BudgetValue budget = BudgetFunctions.forward(truth, nal);
budget.setPriority((float) Math.min(0.99, budget.getPriority()));
return nal.doublePremiseTask(whole, truth, budget, true)!=null;
}
}
return false;
}
/** whether a term can be used in temoralInduction(,,) */
protected static boolean termForTemporalInduction(final Term t) {
/*
//if(t1 instanceof Operation && t2 instanceof Operation) {
// return; //maybe too restrictive
//}
if(((t1 instanceof Implication || t1 instanceof Equivalence) && t1.getTemporalOrder()!=TemporalRules.ORDER_NONE) ||
((t2 instanceof Implication || t2 instanceof Equivalence) && t2.getTemporalOrder()!=TemporalRules.ORDER_NONE)) {
return; //better, if this is fullfilled, there would be more than one temporal operator in the statement, return
}
*/
return (t instanceof Inheritance) || (t instanceof Similarity);
}
public static void applyExpectationOffset(Memory memory, Term temporalStatement, Stamp stamp) {
if(temporalStatement!=null && temporalStatement instanceof Implication) {
Implication imp=(Implication) temporalStatement;
if(imp.getSubject() instanceof Conjunction && imp.getTemporalOrder()==TemporalRules.ORDER_FORWARD) {
Conjunction conj=(Conjunction) imp.getSubject();
if(conj.term[conj.term.length-1] instanceof Interval) {
Interval intv=(Interval) conj.term[conj.term.length-1];
long time_offset=intv.durationCycles(memory);
stamp.setOccurrenceTime(stamp.getOccurrenceTime()+time_offset);
}
}
}
}
static final Variable var1 = new Variable("$0");
static final Variable var2 = var1;
public static void temporalInduction(final Sentence s1, final Sentence s2, final NAL nal, Collection<Task> success) {
if ((s1.truth==null) || (s2.truth==null))
return;
Term t1 = s1.term;
Term t2 = s2.term;
if (Statement.invalidStatement(t1, t2))
return;
Term t11=null;
Term t22=null;
//since induction shouldnt miss something trivial random is not good here
///ex: *Memory.randomNumber.nextDouble()>0.5 &&*/
if (termForTemporalInduction(t1) && termForTemporalInduction(t2)) {
Statement ss1 = (Statement) t1;
Statement ss2 = (Statement) t2;
if (ss1.getSubject().equals(ss2.getSubject())) {
t11 = Statement.make(ss1, var1, ss1.getPredicate());
t22 = Statement.make(ss2, var2, ss2.getPredicate());
} else if (ss1.getPredicate().equals(ss2.getPredicate())) {
t11 = Statement.make(ss1, ss1.getSubject(), var1);
t22 = Statement.make(ss2, ss2.getSubject(), var2);
}
//allow also temporal induction on operator arguments:
if(ss2 instanceof Operation ^ ss1 instanceof Operation) {
if(ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp=ss1.getSubject();
Term ss2_term = ss2.getSubject();
boolean applicableVariableType = !(comp instanceof Variable && comp.hasVarIndep());
if(ss2_term instanceof Product) {
Product ss2_prod=(Product) ss2_term;
if(applicableVariableType && Terms.contains(ss2_prod.term, comp)) { //only if there is one and it isnt a variable already
Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1);
t11 = Statement.make(ss1, var1, ss1.getPredicate());
Operation op=(Operation) Operation.make(
new Product(ars),
ss2.getPredicate()
);
t22 = op;
}
}
}
if(ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp=ss2.getSubject();
Term ss1_term = ss1.getSubject();
boolean applicableVariableType = !(comp instanceof Variable && comp.hasVarIndep());
if(ss1_term instanceof Product) {
Product ss1_prod=(Product) ss1_term;
if(applicableVariableType && Terms.contains(ss1_prod.term, comp)) { //only if there is one and it isnt a variable already
Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1);
t22 = Statement.make(ss2, var1, ss2.getPredicate());
Operation op=(Operation) Operation.make(
new Product(ars),
ss1.getPredicate()
);
t11 = op;
}
}
}
}
}
final Interval.AtomicDuration duration = nal.memory.param.duration;
int durationCycles = duration.get();
long time1 = s1.getOccurenceTime();
long time2 = s2.getOccurenceTime();
long timeDiff = time2 - time1;
List<Interval> interval;
if (!concurrent(time1, time2, durationCycles)) {
interval = Interval.intervalSequence(Math.abs(timeDiff), Parameters.TEMPORAL_INTERVAL_PRECISION, nal.mem());
if (timeDiff > 0) {
t1 = Conjunction.make(t1, interval, ORDER_FORWARD);
if(t11!=null) {
t11 = Conjunction.make(t11, interval, ORDER_FORWARD);
}
} else {
t2 = Conjunction.make(t2, interval, ORDER_FORWARD);
if(t22!=null) {
t22 = Conjunction.make(t22, interval, ORDER_FORWARD);
}
}
}
int order = order(timeDiff, durationCycles);
TruthValue givenTruth1 = s1.truth;
TruthValue givenTruth2 = s2.truth;
TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2);
TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1);
TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2);
BudgetValue budget1 = BudgetFunctions.forward(truth1, nal);
BudgetValue budget2 = BudgetFunctions.forward(truth2, nal);
BudgetValue budget3 = BudgetFunctions.forward(truth3, nal);
Statement statement1 = Implication.make(t1, t2, order);
Statement statement2 = Implication.make(t2, t1, reverseOrder(order));
Statement statement3 = Equivalence.make(t1, t2, order);
final int inductionLimit = nal.param.temporalRelationsMax.get();
if(t11!=null && t22!=null) {
Statement statement11 = Implication.make(t11, t22, order);
Statement statement22 = Implication.make(t22, t11, reverseOrder(order));
Statement statement33 = Equivalence.make(t11, t22, order);
if(!tooMuchTemporalStatements(statement11,inductionLimit)) {
Task t=nal.doublePremiseTask(statement11, truth1, budget1,true);
if(t!=null) {
success.add(t);
}
}
if(!tooMuchTemporalStatements(statement22,inductionLimit)) {
Task t=nal.doublePremiseTask(statement22, truth2, budget2,true);
if(t!=null) {
success.add(t);
}
}
if(!tooMuchTemporalStatements(statement33,inductionLimit)) {
Task t=nal.doublePremiseTask(statement33, truth3, budget3,true);
if(t!=null) {
success.add(t);
}
}
}
if(!tooMuchTemporalStatements(statement1,inductionLimit)) {
Task t=nal.doublePremiseTask(statement1, truth1, budget1,true);
if(t!=null) {
success.add(t);
}
}
if(!tooMuchTemporalStatements(statement2,inductionLimit)) {
Task t=nal.doublePremiseTask(statement2, truth2, budget2,true); //=/> only to keep graph simple for now
if(t!=null) {
success.add(t);
}
}
if(!tooMuchTemporalStatements(statement3,inductionLimit)) {
Task t=nal.doublePremiseTask(statement3, truth3, budget3,true);
if(t!=null) {
success.add(t);
}
}
}
/**
* Evaluate the quality of the judgment as a solution to a problem
*
* @param problem A goal or question
* @param solution The solution to be evaluated
* @return The quality of the judgment as the solution
*/
public static float solutionQuality(final Sentence problem, final Sentence solution, Memory memory) {
if (!matchingOrder(problem, solution)) {
return 0.0F;
}
long ptime = problem.getOccurenceTime();
TruthValue truth;
if (ptime!=solution.getOccurenceTime())
truth = solution.projectionTruth(ptime, memory.time());
else
truth = solution.truth;
if (problem.hasQueryVar()) {
return truth.getExpectation() / solution.term.getComplexity();
} else {
return truth.getConfidence();
}
}
/**
* Evaluate the quality of a belief as a solution to a problem, then reward
* the belief and de-prioritize the problem
*
* @param problem The problem (question or goal) to be solved
* @param solution The belief as solution
* @param task The task to be immediately processed, or null for continued
* process
* @return The budget for the new task which is the belief activated, if
* necessary
*/
public static BudgetValue solutionEval(final Sentence problem, final Sentence solution, Task task, final NAL nal) {
BudgetValue budget = null;
boolean feedbackToLinks = false;
if (task == null) {
task = nal.getCurrentTask();
feedbackToLinks = true;
}
boolean judgmentTask = task.sentence.isJudgment();
final float quality = TemporalRules.solutionQuality(problem, solution, nal.mem());
if (judgmentTask) {
task.incPriority(quality);
} else {
float taskPriority = task.getPriority();
budget = new BudgetValue(UtilityFunctions.or(taskPriority, quality), task.getDurability(), BudgetFunctions.truthToQuality(solution.truth));
task.setPriority(Math.min(1 - quality, taskPriority));
}
if (feedbackToLinks) {
TaskLink tLink = nal.getCurrentTaskLink();
tLink.setPriority(Math.min(1 - quality, tLink.getPriority()));
TermLink bLink = nal.getCurrentBeliefLink();
bLink.incPriority(quality);
}
return budget;
}
public static int order(final long timeDiff, final int durationCycles) {
final int halfDuration = durationCycles/2;
if (timeDiff >= halfDuration) {
return ORDER_FORWARD;
} else if (timeDiff <= -halfDuration) {
return ORDER_BACKWARD;
} else {
return ORDER_CONCURRENT;
}
}
/** if (relative) event B after (stationary) event A then order=forward;
* event B before then order=backward
* occur at the same time, relative to duration: order = concurrent
*/
public static int order(final long a, final long b, final int durationCycles) {
if ((a == Stamp.ETERNAL) || (b == Stamp.ETERNAL))
throw new RuntimeException("order() does not compare ETERNAL times");
return order(b - a, durationCycles);
}
public static boolean concurrent(Sentence a, Sentence b, final int durationCycles) {
return concurrent(a.getOccurenceTime(), b.getOccurenceTime(), durationCycles);
}
/** whether two times are concurrent with respect ao a specific duration ("present moment") # of cycles */
public static boolean concurrent(final long a, final long b, final int durationCycles) {
//since Stamp.ETERNAL is Integer.MIN_VALUE,
//avoid any overflow errors by checking eternal first
if (a == Stamp.ETERNAL) {
//if both are eternal, consider concurrent. this is consistent with the original
//method of calculation which compared equivalent integer values only
return (b == Stamp.ETERNAL);
}
else if (b == Stamp.ETERNAL) {
return false; //a==b was compared above
}
else {
return order(a, b, durationCycles) == ORDER_CONCURRENT;
}
}
}
|
package nl.esciencecenter.ncradar;
public class ParameterValues {
private final int AREACELL;
private final double AZIMMAX;
private final double AZIMMIN;
private final double CLUTPERCCELL;
private final double DBZCELL;
private final double DBZCLUTTER;
private final double DBZFACTOR;
private final double DBZMAX;
private final double DBZMIN;
private final double DBZNOISE;
private final double DBZRAIN;
private final double EMASKMAX;
private final double HLAYER;
private final int NDATA;
private final int NDBZMIN;
private final int NEIGHBOURS;
private final int NGAPBIN;
private final int NGAPMIN;
private final int NLAYER;
private final int NTEXBINAZIM;
private final int NTEXBINRANG;
private final int NTEXMIN;
private final double RANGMAX;
private final double RANGMAXSTDEV;
private final double RANGMIN;
private final double RANGMINSTDEV;
private final double SIGMABIRD;
private final double STDEVBIRD;
private final double STDEVCELL;
private final double STDEVSCALE;
private final double VDIFMAX;
private final double VMASKMAX;
private final double VRADMIN;
public ParameterValues() {
// FIXME still have to rename properties to more meaningful names;
// FIXME also make compliant with naming convention
this.HLAYER = 0.200; // p. 84
this.NLAYER = 30;
this.NDATA = 4;
this.RANGMIN = 5.0 * 1000; // p. 84 says 10.0 // FIXME original value was in km
this.RANGMINSTDEV = 5.0; // equivalent of RANGMINSTDEV, but for VRAD
// instead of DBZ?
this.RANGMAXSTDEV = 25.0;
this.RANGMAX = (25.0 + 5.0) * 1000; // p.84 // FIXME original value was in km
this.AZIMMIN = 0.0;
this.AZIMMAX = 360.0;
this.VRADMIN = 1.0; // p. 74
this.NGAPBIN = 8;
this.NGAPMIN = 5;
this.NDBZMIN = 25;
this.VDIFMAX = 10.0;
this.VMASKMAX = 0.0;
this.EMASKMAX = 500.0; // original value was 5, but that does nothing. In any case, must be same units as rangeScale
this.DBZMIN = -100.0;
this.DBZMAX = 20.0;
this.DBZNOISE = -40.0;
this.DBZRAIN = 0.0; // p.75
this.DBZCELL = 15.0; // p. 78
this.STDEVCELL = 5.0; // p. 78
this.AREACELL = 4;
this.CLUTPERCCELL = 0.5; // p. 78
this.NEIGHBOURS = 5;
this.STDEVSCALE = 0.1;
this.NTEXBINAZIM = 3;
this.NTEXBINRANG = 3;
this.NTEXMIN = 4;
this.DBZCLUTTER = -10.0;
this.DBZFACTOR = 360.7; // eq. 7.13 p. 89
this.SIGMABIRD = 11.0; // p.89
this.STDEVBIRD = 2.0; // p. 86
}
public int getAREACELL() {
return AREACELL;
}
public double getAZIMMAX() {
return AZIMMAX;
}
public double getAZIMMIN() {
return AZIMMIN;
}
public double getCLUTPERCCELL() {
return CLUTPERCCELL;
}
public double getDBZCELL() {
return DBZCELL;
}
public double getDBZCLUTTER() {
return DBZCLUTTER;
}
public double getDBZFACTOR() {
return DBZFACTOR;
}
public double getDBZMAX() {
return DBZMAX;
}
public double getDBZMIN() {
return DBZMIN;
}
public double getDBZNOISE() {
return DBZNOISE;
}
public double getDBZRAIN() {
return DBZRAIN;
}
public double getEMASKMAX() {
return EMASKMAX;
}
public double getHLAYER() {
return HLAYER;
}
public int getNDATA() {
return NDATA;
}
public int getNDBZMIN() {
return NDBZMIN;
}
public int getNEIGHBOURS() {
return NEIGHBOURS;
}
public int getNGAPBIN() {
return NGAPBIN;
}
public int getNGAPMIN() {
return NGAPMIN;
}
public int getNLAYER() {
return NLAYER;
}
public int getNTEXBINAZIM() {
return NTEXBINAZIM;
}
public int getNTEXBINRANG() {
return NTEXBINRANG;
}
public int getNTEXMIN() {
return NTEXMIN;
}
public double getRANGMAX() {
return RANGMAX;
}
public double getRANGMAXSTDEV() {
return RANGMAXSTDEV;
}
public double getRANGMIN() {
return RANGMIN;
}
public double getRANGMINSTDEV() {
return RANGMINSTDEV;
}
public double getSIGMABIRD() {
return SIGMABIRD;
}
public double getSTDEVBIRD() {
return STDEVBIRD;
}
public double getSTDEVCELL() {
return STDEVCELL;
}
public double getSTDEVSCALE() {
return STDEVSCALE;
}
public double getVDIFMAX() {
return VDIFMAX;
}
public double getVMASKMAX() {
return VMASKMAX;
}
public double getVRADMIN() {
return VRADMIN;
}
}
|
package org.wyona.yanel.servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamSource;
import org.wyona.neutron.XMLExceptionV1;
import org.wyona.yanel.core.ResourceTypeIdentifier;
import org.wyona.yanel.core.StateOfView;
import org.wyona.yanel.core.Environment;
import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.ResourceConfiguration;
import org.wyona.yanel.core.ResourceTypeRegistry;
import org.wyona.yanel.core.Yanel;
import org.wyona.yanel.core.api.attributes.IntrospectableV1;
import org.wyona.yanel.core.api.attributes.ModifiableV1;
import org.wyona.yanel.core.api.attributes.ModifiableV2;
import org.wyona.yanel.core.api.attributes.TranslatableV1;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.api.attributes.ViewableV1;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.api.attributes.WorkflowableV1;
import org.wyona.yanel.core.api.security.WebAuthenticator;
import org.wyona.yanel.core.attributes.versionable.RevisionInformation;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.wyona.yanel.core.serialization.SerializerFactory;
import org.wyona.yanel.core.source.SourceResolver;
import org.wyona.yanel.core.source.YanelStreamSource;
import org.wyona.yanel.core.transformation.I18nTransformer2;
import org.wyona.yanel.core.util.DateUtil;
import org.wyona.yanel.core.util.HttpServletRequestHelper;
import org.wyona.yanel.core.workflow.Workflow;
import org.wyona.yanel.core.workflow.WorkflowException;
import org.wyona.yanel.core.workflow.WorkflowHelper;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.wyona.yanel.servlet.IdentityMap;
import org.wyona.yanel.servlet.communication.HttpRequest;
import org.wyona.yanel.servlet.communication.HttpResponse;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.Usecase;
import org.wyona.security.core.api.User;
import org.apache.log4j.Category;
import org.apache.xalan.transformer.TransformerIdentityImpl;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.apache.xml.serializer.Serializer;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Main entry of Yanel webapp
*/
public class YanelServlet extends HttpServlet {
private static Category log = Category.getInstance(YanelServlet.class);
private Map map;
private Yanel yanelInstance;
private Sitetree sitetree;
private File xsltInfoAndException;
private String xsltLoginScreenDefault;
private boolean displayMostRecentVersion = true;
public static final String IDENTITY_MAP_KEY = "identity-map";
private static final String TOOLBAR_USECASE = "toolbar"; //TODO is this the same as YanelAuthoringUI.TOOLBAR_KEY?
public static final String NAMESPACE = "http:
private static final String METHOD_PROPFIND = "PROPFIND";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_DELETE = "DELETE";
private static final String HTTP_REFERRER = "Referer";
private String sslPort = null;
private String toolbarMasterSwitch = "off";
private String reservedPrefix;
private String servletContextRealPath;
private int cacheExpires = 0;
private YanelHTMLUI yanelUI;
private boolean logBrowserHistory = false;
public static final String DEFAULT_ENCODING = "UTF-8";
public static final String YANEL_ACCESS_POLICY_USECASE = "yanel.policy";
public static final String YANEL_USECASE = "yanel.usecase";
public static final String YANEL_RESOURCE = "yanel.resource";
public static final String YANEL_RESOURCE_USECASE = YANEL_RESOURCE + ".usecase";
public static final String YANEL_RESOURCE_REVN = YANEL_RESOURCE + ".revision";
public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION = YANEL_RESOURCE + ".workflow.transition";
public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT = YANEL_RESOURCE_WORKFLOW_TRANSITION + ".output";
public static final String VIEW_ID_PARAM_NAME = "yanel.resource.viewid";
public static final String RESOURCE_META_ID_PARAM_NAME = "yanel.resource.meta";
public static final String RELEASE_LOCK = "release-lock";
private static final String CONTENT_TYPE_XHTML = "xhtml";
@Override
public void init(ServletConfig config) throws ServletException {
servletContextRealPath = config.getServletContext().getRealPath("/");
xsltInfoAndException = org.wyona.commons.io.FileUtil.file(servletContextRealPath, config.getInitParameter("exception-and-info-screen-xslt"));
xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt");
displayMostRecentVersion = new Boolean(config.getInitParameter("workflow.not-live.most-recent-version")).booleanValue();
try {
yanelInstance = Yanel.getInstance();
yanelInstance.init();
map = yanelInstance.getMapImpl("map");
sitetree = yanelInstance.getSitetreeImpl("repo-navigation");
sslPort = config.getInitParameter("ssl-port");
toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch");
reservedPrefix = yanelInstance.getReservedPrefix();
String expires = config.getInitParameter("static-content-cache-expires");
if (expires != null) {
this.cacheExpires = Integer.parseInt(expires);
}
yanelUI = new YanelHTMLUI(map, reservedPrefix);
// TODO: Make this value configurable (also per realm or per individual user!)
logBrowserHistory = false;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
* Dispatch requests
*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// do not add code here outside the try-catch block, it's our..
try { // ..last chance to log all Yanel servlet thread exceptions
String httpAcceptMediaTypes = request.getHeader("Accept");
String httpAcceptLanguage = request.getHeader("Accept-Language");
String yanelUsecase = request.getParameter(YANEL_USECASE);
if(yanelUsecase != null && yanelUsecase.equals("logout")) {
// Logout from Yanel
if(doLogout(request, response) != null) return;
} else if(yanelUsecase != null && yanelUsecase.equals("create")) {
// Create a new resource
if(doCreate(request, response) != null) return;
}
// Check authorization and if authorization failed, then try to authenticate
if(doAccessControl(request, response) != null) {
// Either redirect (after successful authentication) or access denied (and response will send the login screen)
return;
} else {
if (log.isDebugEnabled()) log.debug("Access granted: " + request.getServletPath());
}
// TODO: Only HTML pages and PDFs etc. should be logged, but no images, CSS, etc.
if(logBrowserHistory) logBrowserHistoryOfUser(request);
// Check for requests re policies
String policyRequestPara = request.getParameter(YANEL_ACCESS_POLICY_USECASE);
if (policyRequestPara != null) {
doAccessPolicyRequest(request, response, policyRequestPara);
return;
}
// Check for requests for global data
Resource resource = getResource(request, response);
String path = resource.getPath();
if (path.indexOf("/" + reservedPrefix + "/") == 0) {
getGlobalData(request, response);
return;
}
String value = request.getParameter(YANEL_RESOURCE_USECASE);
// Delete node
if (value != null && value.equals("delete")) {
handleDeleteUsecase(request, response);
return;
}
// Delegate ...
String method = request.getMethod();
if (method.equals(METHOD_PROPFIND)) {
doPropfind(request, response);
} else if (method.equals(METHOD_GET)) {
doGet(request, response);
} else if (method.equals(METHOD_POST)) {
doPost(request, response);
} else if (method.equals(METHOD_PUT)) {
doPut(request, response);
} else if (method.equals(METHOD_DELETE)) {
doDelete(request, response);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(request, response);
} else {
log.error("No such method implemented: " + method);
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
} catch (ServletException e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new IOException(e.getMessage());
}// this was our last chance to log all Yanel servlet thread exceptions so..
// do not add code here outside the try-catch block
}
/**
* HTTP GET implementation.
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
Resource resource = getResource(request, response);
// Enable or disable toolbar
yanelUI.switchToolbar(request);
String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION);
if (transition != null) {
executeWorkflowTransition(request,
response,
request.getParameter(YANEL_RESOURCE_REVN),
transition);
return;
}
// Check for requests refered by WebDAV
String yanelWebDAV = request.getParameter("yanel.webdav");
if(yanelWebDAV != null && yanelWebDAV.equals("propfind1")) {
log.info("WebDAV client (" + request.getHeader("User-Agent") + ") requests to \"edit\" a resource: " + resource.getRealm() + ", " + resource.getPath());
//return;
}
String value = request.getParameter(YANEL_RESOURCE_USECASE);
try {
if (value != null && value.equals(RELEASE_LOCK)) {
log.warn("Try to release lock ...");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
VersionableV2 versionable = (VersionableV2)resource;
String checkoutUserID = versionable.getCheckoutUserID();
String userID = getEnvironment(request, response).getIdentity().getUsername();
if (checkoutUserID.equals(userID)) {
try {
versionable.cancelCheckout();
log.warn("DEBUG: Lock has been released.");
} catch (Exception e) {
throw new ServletException("Releasing the lock of <" + resource.getPath() + "> failed because of: " + e.getMessage(), e);
}
} else {
String eMessage = "Releasing the lock of '" + resource.getPath() + "' failed because checkout user '" + checkoutUserID + "' and session user '" + userID + "' are not the same!";
log.warn(eMessage);
throw new ServletException(eMessage);
}
}
return;
} else if (value != null && value.equals("roll-back")) {
log.debug("Roll back ...");
org.wyona.yanel.core.util.VersioningUtil.rollBack(resource, request.getParameter(YANEL_RESOURCE_REVN), getIdentity(request, map).getUsername());
// TODO: Send confirmation screen
getContent(request, response);
return;
} else {
getContent(request, response);
return;
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
/**
* Returns the mime-type according to the given file extension.
* Default is application/octet-stream.
* @param extension
* @return
*/
private static String guessMimeType(String extension) {
String ext = extension.toLowerCase();
if (ext.equals("html") || ext.equals("htm")) return "text/html";
if (ext.equals("css")) return "text/css";
if (ext.equals("txt")) return "text/plain";
if (ext.equals("js")) return "application/x-javascript";
if (ext.equals("jpg") || ext.equals("jpg")) return "image/jpeg";
if (ext.equals("gif")) return "image/gif";
if (ext.equals("pdf")) return "application/pdf";
if (ext.equals("zip")) return "application/zip";
if (ext.equals("htc")) return "text/x-component";
// TODO: add more mime types
// TODO: and move to MimeTypeUtil
return "application/octet-stream"; // default
}
/**
* Get view of resource
*/
private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
View view = null;
org.w3c.dom.Document doc = null;
try {
doc = getDocument(NAMESPACE, "yanel");
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
Element rootElement = doc.getDocumentElement();
rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);
Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request"));
requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI());
requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath());
HttpSession session = request.getSession(true);
Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
sessionElement.setAttribute("id", session.getId());
Enumeration<?> attrNames = session.getAttributeNames();
if (!attrNames.hasMoreElements()) {
Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes"));
}
while (attrNames.hasMoreElements()) {
String name = (String)attrNames.nextElement();
String value = session.getAttribute(name).toString();
Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
sessionAttributeElement.setAttribute("name", name);
sessionAttributeElement.appendChild(doc.createTextNode(value));
}
String usecase = request.getParameter(YANEL_RESOURCE_USECASE);
Resource res = null;
long lastModified = -1;
long size = -1;
// START first try
try {
Environment environment = getEnvironment(request, response);
res = getResource(request, response);
if (res != null) {
Element resourceElement = getResourceMetaData(res, doc, rootElement);
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
if (log.isDebugEnabled()) log.debug("Resource is viewable V1");
viewElement.setAttributeNS(NAMESPACE, "version", "1");
appendViewDescriptors(doc, viewElement, ((ViewableV1) res).getViewDescriptors());
String viewId = request.getParameter(VIEW_ID_PARAM_NAME);
try {
view = ((ViewableV1) res).getView(request, viewId);
} catch (org.wyona.yarep.core.NoSuchNodeException e) {
String message = e.getMessage();
log.error(message, e);
do404(request, response, doc, message);
return;
} catch (Exception e) {
String message = e.getMessage();
log.error(message, e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttributeNS(NAMESPACE, "status", "500");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
return;
}
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
if (log.isDebugEnabled()) log.debug("Resource is viewable V2");
viewElement.setAttributeNS(NAMESPACE, "version", "2");
appendViewDescriptors(doc, viewElement, ((ViewableV2) res).getViewDescriptors());
if (!((ViewableV2) res).exists()) {
log.warn("No such ViewableV2 resource: " + res.getPath());
log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!");
//do404(request, response, doc, res.getPath());
//return;
}
size = ((ViewableV2) res).getSize();
Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
String viewId = request.getParameter(VIEW_ID_PARAM_NAME);
try {
String revisionName = request.getParameter(YANEL_RESOURCE_REVN);
// NOTE: Check also if usecase is not roll-back, because roll-back is also using the yanel.resource.revision
if (revisionName != null && ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2") && !isRollBack(request)) {
view = ((VersionableV2) res).getView(viewId, revisionName);
} else if (environment.getStateOfView().equals(StateOfView.LIVE) && ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && WorkflowHelper.getWorkflow(res) != null) {
// TODO: Check if resource actually exists (see the exist problem above), because even it doesn't exist, the workflowable interfaces can return something although it doesn't really make sense. For example if a resource type is workflowable, but it has no workflow associated with it, then WorkflowHelper.isLive will nevertheless return true, whereas WorkflowHelper.getLiveView will throw an exception!
if (!((ViewableV2) res).exists()) {
log.warn("No such ViewableV2 resource: " + res.getPath());
log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!");
do404(request, response, doc, res.getPath());
return;
}
WorkflowableV1 workflowable = (WorkflowableV1)res;
if (workflowable.isLive()) {
view = workflowable.getLiveView(viewId);
} else {
String message = "The viewable (V2) resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet.";
log.warn(message);
// TODO: Make this configurable per realm
if (displayMostRecentVersion) {
log.warn("Instead the live version, the most recent version will be displayed!");
view = ((ViewableV2) res).getView(viewId);
} else {
log.warn("Instead the live version, a 404 will be displayed!");
// TODO: Instead a 404 one might want to show a different kind of screen
do404(request, response, doc, message);
return;
}
}
} else {
view = ((ViewableV2) res).getView(viewId);
}
} catch (org.wyona.yarep.core.NoSuchNodeException e) {
String message = e.getMessage();
log.warn(message, e);
do404(request, response, doc, message);
return;
} catch (org.wyona.yanel.core.ResourceNotFoundException e) {
String message = e.getMessage();
log.warn(message, e);
do404(request, response, doc, message);
return;
}
} else { // NO Viewable interface implemented!
String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")";
log.error(message);
Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable"));
noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttributeNS(NAMESPACE, "status", "501");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED);
setYanelOutput(request, response, doc);
return;
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
lastModified = ((ModifiableV2) res).getLastModified();
Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified"));
lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString()));
} else {
Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified"));
}
// START Versionable (and Workflowable)
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
// retrieve the revisions, but only in the meta usecase (for performance reasons):
if (request.getParameter(RESOURCE_META_ID_PARAM_NAME) != null) {
RevisionInformation[] revisionsInfo = ((VersionableV2)res).getRevisions();
Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions"));
WorkflowableV1 workflowableResource = null;
Workflow workflow = null;
String liveRevisionName = null;
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1")) {
workflowableResource = (WorkflowableV1)res;
workflow = WorkflowHelper.getWorkflow(res);
liveRevisionName = WorkflowHelper.getLiveRevision(res);
}
if (revisionsInfo != null && revisionsInfo.length > 0) {
for (int i = revisionsInfo.length - 1; i >= 0; i
Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision"));
Element revisionNameElement = (Element) revisionElement.appendChild(doc.createElement("name"));
revisionNameElement.appendChild(doc.createTextNode(revisionsInfo[i].getName()));
Element revisionDateElement = (Element) revisionElement.appendChild(doc.createElement("date"));
revisionDateElement.appendChild(doc.createTextNode(DateUtil.format(revisionsInfo[i].getDate())));
Element revisionUserElement = (Element) revisionElement.appendChild(doc.createElement("user"));
revisionUserElement.appendChild(doc.createTextNode(revisionsInfo[i].getUser()));
Element revisionCommentElement = (Element) revisionElement.appendChild(doc.createElement("comment"));
revisionCommentElement.appendChild(doc.createTextNode(revisionsInfo[i].getComment()));
// Add workflow info
if (workflowableResource != null && workflow != null) {
Element revisionWorkflowElement = (Element) revisionElement.appendChild(doc.createElement("workflow-state"));
String wfState = workflowableResource.getWorkflowState(revisionsInfo[i].getName());
if (wfState == null) {
wfState = workflow.getInitialState();
}
if (liveRevisionName != null && revisionsInfo[i].getName().equals(liveRevisionName)) {
revisionWorkflowElement.appendChild(doc.createTextNode(wfState + " (LIVE)"));
} else {
revisionWorkflowElement.appendChild(doc.createTextNode(wfState));
}
}
}
} else {
Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet"));
}
}
} else {
Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable"));
}
// END Versionable (and Workflowable)
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) {
TranslatableV1 translatable = ((TranslatableV1) res);
Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations"));
String[] languages = translatable.getLanguages();
for (int i=0; i<languages.length; i++) {
Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation"));
translationElement.setAttribute("language", languages[i]);
String path = translatable.getTranslation(languages[i]).getPath();
translationElement.setAttribute("path", path);
}
}
if (usecase != null && usecase.equals("checkout")) {
if(log.isDebugEnabled()) log.debug("Checkout data ...");
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
// NOTE: The code below will throw an exception if the document is checked out already by another user.
String userID = environment.getIdentity().getUsername();
VersionableV2 versionable = (VersionableV2)res;
if (versionable.isCheckedOut()) {
String checkoutUserID = versionable.getCheckoutUserID();
if (checkoutUserID.equals(userID)) {
log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID);
} else {
if (isClientSupportingNeutron(request)) {
String eMessage = "Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID;
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// TODO: Checkout date and break-lock (optional)
response.getWriter().print(XMLExceptionV1.getCheckoutException(eMessage, res.getPath(), checkoutUserID, null));
return;
} else {
throw new Exception("Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID);
}
}
} else {
versionable.checkout(userID);
}
} else {
log.warn("Acquire lock has not been implemented yet ...!");
// acquireLock();
}
}
} else {
Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null"));
}
} catch (org.wyona.yarep.core.NoSuchNodeException e) {
String message = e.getMessage();
log.warn(message, e);
do404(request, response, doc, message);
return;
} catch (org.wyona.yanel.core.ResourceNotFoundException e) {
String message = e.getMessage();
log.warn(message, e);
do404(request, response, doc, message);
return;
} catch (Exception e) {
log.error(e.getMessage(), e);
String message = e.toString() + "\n\n" + getStackTrace(e);
//String message = e.toString();
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
return;
}
// END first try
// START introspection generation
if (usecase != null && usecase.equals("introspection")) {
sendIntrospectionAsResponse(res, doc, rootElement, request, response);
return;
}
// END introspection generation
String meta = request.getParameter(RESOURCE_META_ID_PARAM_NAME);
if (meta != null) {
if (meta.length() > 0) {
log.warn("TODO: meta: " + meta);
} else {
log.debug("Show all meta");
}
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
setYanelOutput(request, response, doc);
return;
}
if (view != null) {
if (generateResponse(view, res, request, response, doc, size, lastModified) != null) return;
} else {
String message = "View is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
return;
}
/**
* HTTP POST implementation.
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION);
if (transition != null) {
executeWorkflowTransition(request,
response,
request.getParameter(YANEL_RESOURCE_REVN),
transition);
return;
}
String value = request.getParameter(YANEL_RESOURCE_USECASE);
if (value != null && value.equals("save")) {
log.debug("Save data ...");
save(request, response, false);
return;
} else if (value != null && value.equals("checkin")) {
log.debug("Checkin data ...");
save(request, response, true);
log.warn("Release lock has not been implemented yet ...");
// releaseLock();
return;
} else {
log.info("No parameter " + YANEL_RESOURCE_USECASE + "!");
String contentType = request.getContentType();
// TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16)
if (contentType.indexOf("application/atom+xml") >= 0) {
InputStream in = intercept(request.getInputStream());
// Create new Atom entry
try {
String atomEntryUniversalName = "<{http:
Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
String newEntryPath = yanelInstance.getMap().getPath(realm, request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml");
log.debug("Realm and Path of new Atom entry: " + realm + " " + newEntryPath);
Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null));
((ModifiableV2)atomEntryResource).write(in);
byte buffer[] = new byte[8192];
int bytesRead;
InputStream resourceIn = ((ModifiableV2)atomEntryResource).getInputStream();
OutputStream responseOut = response.getOutputStream();
while ((bytesRead = resourceIn.read(buffer)) != -1) {
responseOut.write(buffer, 0, bytesRead);
}
resourceIn.close();
//responseOut.close();
// TODO: Fix Location ...
response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED);
return;
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
// Enable or disable toolbar
yanelUI.switchToolbar(request);
getContent(request, response);
}
}
/**
* Perform the given transition on the indicated revision.
* @param request
* @param response
* @param transition
* @throws ServletException
* @throws IOException
*/
private void executeWorkflowTransition(HttpServletRequest request,
HttpServletResponse response,
String revision,
String transition)
throws ServletException, IOException {
Resource resource = getResource(request, response);
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Workflowable", "1")) {
WorkflowableV1 workflowable = (WorkflowableV1)resource;
try {
String outputFormat = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT);
StringBuilder sb = null;
workflowable.doTransition(transition, revision);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
if (outputFormat != null && CONTENT_TYPE_XHTML.equals(outputFormat.toLowerCase())) {
response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
sb = new StringBuilder("<html xmlns=\"http:
+ " has been performed.</p><p>Return to <a href=\""
+ request.getHeader(HTTP_REFERRER)
+ "\">the page</a>.</p></body></html>");
} else {
log.warn("No output format query string parameter '" + YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT + "' has been specified.");
response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append(workflowable.getWorkflowIntrospection());
}
PrintWriter w = response.getWriter();
w.print(sb);
} catch (WorkflowException e) {
// TODO: Implement response if transition has failed ...
throw new ServletException(e.getMessage(), e);
}
} else {
log.warn("Resource not workflowable: " + resource.getPath());
}
}
/**
* HTTP PUT implementation.
*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO: Reuse code doPost resp. share code with doPut
String value = request.getParameter(YANEL_RESOURCE_USECASE);
if (value != null && value.equals("save")) {
log.debug("Save data ...");
save(request, response, false);
return;
} else if (value != null && value.equals("checkin")) {
log.debug("Checkin data ...");
save(request, response, true);
log.warn("Release lock has not been implemented yet ...!");
// releaseLock();
return;
} else {
log.warn("No parameter " + YANEL_RESOURCE_USECASE + "!");
String contentType = request.getContentType();
if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) {
InputStream in = intercept(request.getInputStream());
// Overwrite existing atom entry
try {
String atomEntryUniversalName = "<{http:
Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
String entryPath = yanelInstance.getMap().getPath(realm, request.getServletPath());
log.debug("Realm and Path of new Atom entry: " + realm + " " + entryPath);
Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, entryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null));
// TODO: There seems to be a problem ...
((ModifiableV2)atomEntryResource).write(in);
// NOTE: This method does not update updated date
/*
OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath);
byte buffer[] = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
*/
log.info("Atom entry has been saved: " + entryPath);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
return;
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
} else {
Resource resource = getResource(request, response);
log.warn("Client (" + request.getHeader("User-Agent") + ") requests to save a resource: " + resource.getRealm() + ", " + resource.getPath());
save(request, response, false);
return;
}
}
}
/**
* HTTP DELETE implementation.
*/
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Resource res = getResource(request, response);
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
if (((ModifiableV2) res).delete()) {
// TODO: Also delete resource config! What about access policies?!
log.debug("Resource has been deleted: " + res);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html" + "; charset=" + "UTF-8");
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(res.getPath());
StringBuffer sb = new StringBuffer("<html xmlns=\"http:
PrintWriter w = response.getWriter();
w.print(sb);
return;
} else {
log.warn("Resource could not be deleted: " + res);
response.setStatus(response.SC_FORBIDDEN);
return;
}
} else {
log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." );
response.sendError(response.SC_NOT_IMPLEMENTED);
return;
}
} catch (Exception e) {
throw new ServletException("Could not delete resource with URL <" + request.getRequestURL() + ">: " + e.getMessage(), e);
}
}
/**
* Resolve resource for a specific request
*/
private Resource getResource(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
HttpRequest httpRequest = (HttpRequest)request;
HttpResponse httpResponse = new HttpResponse(response);
Resource res = yanelInstance.getResourceManager().getResource(getEnvironment(httpRequest, httpResponse), realm, path);
return res;
} catch (Exception e) {
throw new ServletException("Could not get resource for request <" + request.getServletPath() + ">: " + e.getMessage(), e);
}
}
/**
* Get environment containing identity , client request, etc.
*/
private Environment getEnvironment(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Identity identity;
try {
identity = getIdentity(request, map);
Realm realm = map.getRealm(request.getServletPath());
String stateOfView = StateOfView.AUTHORING;
if (yanelUI.isToolbarEnabled(request)) {
stateOfView = StateOfView.AUTHORING;
} else {
stateOfView = StateOfView.LIVE;
}
//log.debug("State of view: " + stateOfView);
Environment environment = new Environment(request, response, identity, stateOfView, null);
return environment;
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
/**
* Save data
*/
private void save(HttpServletRequest request, HttpServletResponse response, boolean doCheckin) throws ServletException, IOException {
log.debug("Save data ...");
Resource resource = getResource(request, response);
/* NOTE: Commented because the current default repo implementation does not support versioning yet.
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
try {
// check the resource state:
Identity identity = getIdentity(request);
String userID = identity.getUser().getID();
VersionableV2 versionable = (VersionableV2)resource;
if (versionable.isCheckedOut()) {
String checkoutUserID = versionable.getCheckoutUserID();
if (!checkoutUserID.equals(userID)) {
throw new Exception("Resource is checked out by another user: " + checkoutUserID);
}
} else {
throw new Exception("Resource is not checked out.");
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
*/
InputStream in = request.getInputStream();
// Check on well-formedness ...
String contentType = request.getContentType();
log.debug("Content-Type: " + contentType);
if (contentType != null && (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0)) {
try {
in = isWellFormed(in);
} catch(Exception e) {
log.error(e, e);
response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter w = response.getWriter();
w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.DATA_NOT_WELL_FORMED, e.getMessage()));
return;
}
} else {
log.info("No well-formedness check required for content type: " + contentType);
}
// IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write ....
OutputStream out = null;
Resource res = getResource(request, response);
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) {
out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath()));
write(in, out, request, response);
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
try {
out = ((ModifiableV2) res).getOutputStream();
if (out != null) {
write(in, out, request, response);
} else {
log.warn("getOutputStream() returned null, hence fallback to write()");
((ModifiableV2) res).write(in);
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
} else {
String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!";
log.warn(message);
// TODO: Differentiate between Neutron based and other clients ... (Use method isClientSupportingNeutron())
response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter w = response.getWriter();
// TODO: This is not really a 'checkin' problem, but rather a general 'save-data' problem, but the Neutron spec does not support such a type: http://neutron.wyona.org/draft-neutron-protocol-v0.html#rfc.section.8
w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.CHECKIN, message));
}
if (doCheckin) {
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
VersionableV2 versionable = (VersionableV2)resource;
try {
versionable.checkin("updated");
} catch (Exception e) {
throw new ServletException("Could not check in resource <" + resource.getPath() + ">: " + e.getMessage(), e);
}
}
}
}
/**
* Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication
*/
private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get usecase
Usecase usecase = getUsecase(request);
// Get identity, realm, path
Identity identity;
Realm realm;
String path;
try {
identity = getIdentity(request, map);
realm = map.getRealm(request.getServletPath());
path = map.getPath(realm, request.getServletPath());
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
// Check Authorization
boolean authorized = false;
try {
if (log.isDebugEnabled()) log.debug("Check authorization: realm: " + realm + ", path: " + path + ", identity: " + identity + ", Usecase: " + usecase.getName());
authorized = realm.getPolicyManager().authorize(path, identity, usecase);
if (log.isDebugEnabled()) log.debug("Check authorization result: " + authorized);
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
if(!authorized) {
// TODO: Implement HTTP BASIC/DIGEST response (see above)
log.info("Access denied: " + getRequestURLQS(request, null, false));
if(!request.isSecure()) {
if(sslPort != null) {
log.info("Redirect to SSL ...");
try {
URL url = new URL(getRequestURLQS(request, null, false).toString());
url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile());
if (realm.isProxySet()) {
if (realm.getProxySSLPort() >= 0) {
log.debug("Use configured port: " + realm.getProxySSLPort());
url = new URL(url.getProtocol(), url.getHost(), new Integer(realm.getProxySSLPort()).intValue(), url.getFile());
} else {
log.debug("Use default port: " + url.getDefaultPort());
// NOTE: getDefaultPort depends on the Protocol (e.g. https is 443)
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
}
log.info("Redirect to SSL: " + url);
response.setHeader("Location", url.toString());
// TODO: Yulup has a bug re TEMPORARY_REDIRECT
//response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY);
return response;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
log.warn("SSL does not seem to be configured!");
}
}
if(doAuthenticate(request, response) != null) {
log.info("Return response of web authenticator.");
/*
NOTE: Such a response can have different reasons:
- Either no credentials provided yet and web authenticator is generating a response to fetch credentials
- Or authentication failed and web authenticator is resending response to fetch again credentials");
- Or authentication was successful and web authenticator sends a redirect
*/
return response;
} else {
try {
log.warn("Authentication was successful for user: " + getIdentity(request, map).getUsername());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
URL url = new URL(getRequestURLQS(request, null, false).toString());
if (sslPort != null) {
url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile());
}
log.warn("Redirect to original request: " + url);
//response.sendRedirect(url.toString()); // 302
// TODO: Yulup has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!)
response.setHeader("Location", url.toString());
response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
//response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302
return response;
}
} else {
log.info("Access granted: " + getRequestURLQS(request, null, false));
return null;
}
}
/**
* Patch request with proxy settings re realm configuration
*/
private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) {
try {
Realm realm = map.getRealm(request.getServletPath());
// TODO: Handle this exception more gracefully!
if (realm == null) log.error("No realm found for path " +request.getServletPath());
String proxyHostName = realm.getProxyHostName();
int proxyPort = realm.getProxyPort();
String proxyPrefix = realm.getProxyPrefix();
URL url = null;
url = new URL(request.getRequestURL().toString());
//if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) {
if(realm.isProxySet()) {
if (proxyHostName != null) {
url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
}
if (proxyPort >= 0) {
url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile());
} else {
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
if (proxyPrefix != null) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length()));
}
//log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url);
} else {
//log.debug("No proxy set for this realm resp. request: " + realm + ", " + url);
}
String urlQS = url.toString();
if (request.getQueryString() != null) {
urlQS = urlQS + "?" + request.getQueryString();
if (addQS != null) urlQS = urlQS + "&" + addQS;
} else {
if (addQS != null) urlQS = urlQS + "?" + addQS;
}
if (xml) urlQS = urlQS.replaceAll("&", "&");
if(log.isDebugEnabled()) log.debug("Request: " + urlQS);
return urlQS;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
private void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Resource resource = getResource(request, response);
//Node node = resource.getRealm().getSitetree().getNode(resource.getPath());
Node node = sitetree.getNode(resource.getRealm(),resource.getPath());
String depth = request.getHeader("Depth");
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append("<multistatus xmlns=\"DAV:\">");
if (depth.equals("0")) {
if (node.isCollection()) {
sb.append(" <response>");
sb.append(" <href>"+request.getRequestURI()+"</href>");
sb.append(" <propstat>");
sb.append(" <prop>");
sb.append(" <resourcetype><collection/></resourcetype>");
sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>");
sb.append(" </prop>");
sb.append(" <status>HTTP/1.1 200 OK</status>");
sb.append(" </propstat>");
sb.append(" </response>");
} else if (node.isResource()) {
sb.append(" <response>");
sb.append(" <href>"+request.getRequestURI()+"</href>");
sb.append(" <propstat>");
sb.append(" <prop>");
sb.append(" <resourcetype/>");
// TODO: Set mime type of node!
sb.append(" <getcontenttype>application/octet-stream</getcontenttype>");
// TODO: Set content length and last modified!
sb.append(" <getcontentlength>0</getcontentlength>");
sb.append(" <getlastmodified>1969.02.16</getlastmodified>");
// See http://www.webdav.org/specs/rfc2518.html
sb.append(" <source>\n");
sb.append(" <link>\n");
sb.append(" <src>" + request.getRequestURI() + "</src>\n");
sb.append(" <dst>" + request.getRequestURI() + "?yanel.resource.modifiable.source</dst>\n");
sb.append(" </link>\n");
sb.append(" </source>\n");
sb.append(" </prop>");
sb.append(" <status>HTTP/1.1 200 OK</status>");
sb.append(" </propstat>");
sb.append(" </response>");
} else {
log.error("Neither collection nor resource!");
}
} else if (depth.equals("1")) {
// TODO: Shouldn't one check with isCollection() first?!
Node[] children = node.getChildren();
if (children != null) {
for (int i = 0; i < children.length; i++) {
if (children[i].isCollection()) {
sb.append(" <response>\n");
sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "/</href>\n");
sb.append(" <propstat>\n");
sb.append(" <prop>\n");
sb.append(" <displayname>" + children[i].getName() + "</displayname>\n");
sb.append(" <resourcetype><collection/></resourcetype>\n");
sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>\n");
sb.append(" </prop>\n");
sb.append(" <status>HTTP/1.1 200 OK</status>\n");
sb.append(" </propstat>\n");
sb.append(" </response>\n");
} else if(children[i].isResource()) {
sb.append(" <response>\n");
sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.webdav=propfind1</href>\n");
sb.append(" <propstat>\n");
sb.append(" <prop>\n");
sb.append(" <displayname>" + children[i].getName() + "</displayname>\n");
sb.append(" <resourcetype/>\n");
// TODO: Set mime type of node!
sb.append(" <getcontenttype>application/octet-stream</getcontenttype>\n");
// TODO: Set content length and last modified!
sb.append(" <getcontentlength>0</getcontentlength>");
sb.append(" <getlastmodified>1969.02.16</getlastmodified>");
// See http://www.webdav.org/specs/rfc2518.html
sb.append(" <source>\n");
sb.append(" <link>\n");
sb.append(" <src>" + request.getRequestURI() + "/" + children[i].getName() + "</src>\n");
sb.append(" <dst>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.resource.modifiable.source</dst>\n");
sb.append(" </link>\n");
sb.append(" </source>\n");
sb.append(" </prop>\n");
sb.append(" <status>HTTP/1.1 200 OK</status>\n");
sb.append(" </propstat>\n");
sb.append(" </response>\n");
} else {
log.error("Neither collection nor resource: " + children[i].getPath());
}
}
} else {
log.warn("No children!");
}
} else if (depth.equals("infinity")) {
log.warn("TODO: List children and their children and their children ...");
} else {
log.error("No such depth: " + depth);
}
sb.append("</multistatus>");
//response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS);
response.setStatus(207, "Multi-Status");
PrintWriter w = response.getWriter();
w.print(sb);
}
/**
* HTTP OPTIONS implementation.
*/
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("DAV", "1");
// TODO: Is there anything else to do?!
}
/**
* Authentication
* @return null when authentication successful or has already been authenticated, otherwise return response generated by web authenticator
*/
private HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// TODO/TBD: In the case of HTTP-BASIC/DIGEST one needs to check authentication with every request
// TODO: enhance API with flag, e.g. session-based="true/false"
// WARNING: One needs to separate doAuthenticate from the login screen generation!
//if (getIdentity(request) != null) return null;
WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator();
return wa.doAuthenticate(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort);
} catch (Exception e) {
log.error(e.getMessage(), e);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return response;
}
}
/**
* Escapes all reserved xml characters (& < > ' ") in a string.
* @param s input string
* @return string with escaped characters
*/
public static String encodeXML(String s) {
s = s.replaceAll("&", "&");
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("'", "'");
s = s.replaceAll("\"", """);
return s;
}
/**
* Do logout
* @return null for a regular logout and a Neutron response if auth scheme is Neutron
*/
private HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (yanelUI.isToolbarEnabled(request)) {
// TODO: Check if WORLD has access to the toolbar
//if (getRealm().getPolicyManager().authorize(path, new Identity(), new Usecase(TOOLBAR_USECASE))) {
yanelUI.disableToolbar(request);
}
HttpSession session = request.getSession(true);
// TODO: should we logout only from the current realm, or from all realms?
// -> logout only from the current realm
Realm realm = map.getRealm(request.getServletPath());
IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY);
if (identityMap != null && identityMap.containsKey(realm.getID())) {
log.info("Logout from realm: " + realm.getID());
identityMap.remove(realm.getID());
}
String clientSupportedAuthScheme = getClientAuthenticationScheme(request);
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
String neutronVersions = getClientSupportedNeutronVersions(request);
// TODO: Reply according to which neutron versions the client supports
// TODO: send some XML content, e.g. <logout-successful/>
response.setContentType("text/plain; charset=" + DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
PrintWriter writer = response.getWriter();
writer.print("Neutron Logout Successful!");
return response;
}
if (log.isDebugEnabled()) log.debug("Regular Logout Successful!");
//return null;
URL url = new URL(getRequestURLQS(request, null, false).toString());
String urlWithoutLogoutQS = url.toString().substring(0, url.toString().lastIndexOf("?"));
log.warn("Redirect to original request: " + urlWithoutLogoutQS);
//response.sendRedirect(url.toString()); // 302
response.setHeader("Location", urlWithoutLogoutQS.toString());
//response.setHeader("Location", url.toString());
response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
//response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302
return response;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
* Do create a new resource
*/
private HttpServletResponse doCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.error("Not implemented yet!");
return null;
}
static public String patchMimeType(String mimeType, HttpServletRequest request) throws ServletException, IOException {
String httpAcceptMediaTypes = request.getHeader("Accept");
if (mimeType != null && mimeType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) {
log.info("Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml");
return "text/html";
}
return mimeType;
}
/**
* Intercept InputStream and log content ...
*/
private InputStream intercept(InputStream in) throws IOException {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int bytesR;
while ((bytesR = in.read(buf)) != -1) {
baos.write(buf, 0, bytesR);
}
// Buffer within memory (TODO: Maybe replace with File-buffering ...)
byte[] memBuffer = baos.toByteArray();
log.debug("InputStream: " + baos);
return new java.io.ByteArrayInputStream(memBuffer);
}
/**
* Generate a "Yanel" response (page information, 404, internal server error, ...)
*/
private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException {
String path = getResource(request, response).getPath();
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(path);
try {
String yanelFormat = request.getParameter("yanel.format");
if(yanelFormat != null && yanelFormat.equals("xml")) {
response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
org.wyona.commons.xml.XMLHelper.writeDocument(doc, response.getOutputStream());
/*
OutputStream out = response.getOutputStream();
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out));
out.close();
*/
} else {
String mimeType = patchMimeType("application/xhtml+xml", request);
response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING);
// create identity transformer which serves as a dom-to-sax transformer
TransformerIdentityImpl transformer = new TransformerIdentityImpl();
// create xslt transformer:
SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
TransformerHandler xsltTransformer = saxTransformerFactory.newTransformerHandler(new StreamSource(xsltInfoAndException));
xsltTransformer.getTransformer().setParameter("yanel.back2realm", backToRealm);
xsltTransformer.getTransformer().setParameter("yanel.reservedPrefix", reservedPrefix);
// create i18n transformer:
I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getLanguage(request), yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage());
CatalogResolver catalogResolver = new CatalogResolver();
i18nTransformer.setEntityResolver(new CatalogResolver());
// create serializer:
Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT);
// chain everything together (create a pipeline):
xsltTransformer.setResult(new SAXResult(i18nTransformer));
i18nTransformer.setResult(new SAXResult(serializer.asContentHandler()));
serializer.setOutputStream(response.getOutputStream());
// execute pipeline:
transformer.transform(new DOMSource(doc), new SAXResult(xsltTransformer));
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
/**
* Get language with the following priorization: 1) yanel.meta.language query string parameter, 2) Accept-Language header, 3) Default en
*/
private String getLanguage(HttpServletRequest request) throws Exception {
// TODO: Shouldn't this be replaced by Resource.getRequestedLanguage() or Resource.getContentLanguage() ?!
String language = request.getParameter("yanel.meta.language");
if (language == null) {
language = request.getHeader("Accept-Language");
if (language != null) {
int commaIndex = language.indexOf(",");
if (commaIndex > 0) {
language = language.substring(0, commaIndex);
}
int dashIndex = language.indexOf("-");
if (dashIndex > 0) {
language = language.substring(0, dashIndex);
}
}
}
if(language != null && language.length() > 0) return language;
return yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage();
}
/**
* Write to output stream of modifiable resource
*/
private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (out != null) {
log.debug("Content-Type: " + request.getContentType());
// TODO: Compare mime-type from response with mime-type of resource
//if (contentType.equals("text/xml")) { ... }
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html>");
sb.append("<body>");
sb.append("<p>Data has been saved ...</p>");
sb.append("</body>");
sb.append("</html>");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING);
PrintWriter w = response.getWriter();
w.print(sb);
log.info("Data has been saved ...");
return;
} else {
log.error("OutputStream is null!");
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html>");
sb.append("<body>");
sb.append("<p>Exception: OutputStream is null!</p>");
sb.append("</body>");
sb.append("</html>");
PrintWriter w = response.getWriter();
w.print(sb);
response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
/**
* Gets the identity from the session associated with the given request or via the 'Authorization' HTTP header in the case of BASIC or DIGEST
* @param request Client/Servlet request
* @param map
* @return Identity if one exist, or otherwise an empty identity
*/
static Identity getIdentity(HttpServletRequest request, Map map) throws Exception {
Realm realm = map.getRealm(request.getServletPath());
HttpSession session = request.getSession(false);
if (session != null) {
IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY);
if (identityMap != null) {
Identity identity = (Identity)identityMap.get(realm.getID());
if (identity != null) {
return identity;
}
}
}
// HTTP BASIC Authentication (For clients such as for instance Sunbird, OpenOffice or cadaver)
// IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling
String authorizationHeader = request.getHeader("Authorization");
if (log.isDebugEnabled()) log.debug("Checking for Authorization Header: " + authorizationHeader);
if (authorizationHeader != null) {
if (authorizationHeader.toUpperCase().startsWith("BASIC")) {
log.warn("Using BASIC authorization ...");
// Get encoded user and password, comes after "BASIC "
String userpassEncoded = authorizationHeader.substring(6);
// Decode it, using any base 64 decoder
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded));
log.debug("Username and Password Decoded: " + userpassDecoded);
String[] up = userpassDecoded.split(":");
String username = up[0];
String password = up[1];
log.debug("username: " + username + ", password: " + password);
try {
User user = realm.getIdentityManager().getUserManager().getUser(username);
if (user != null && user.authenticate(password)) {
return new Identity(user);
} else {
log.warn("HTTP BASIC Authentication failed for " + username + "!");
/*
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.print("BASIC Authentication Failed!");
return response;
*/
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
} else if (authorizationHeader.toUpperCase().startsWith("DIGEST")) {
log.error("DIGEST is not implemented");
/*
authorized = false;
response.sendError(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\"");
PrintWriter writer = response.getWriter();
writer.print("DIGEST is not implemented!");
*/
} else {
log.warn("No such authorization type implemented: " + authorizationHeader);
}
}
if(log.isDebugEnabled()) log.debug("No identity yet (Neither session nor header based! Identity is set to WORLD!)");
// TBD: Should add world identity to the session?
return new Identity();
}
/**
* Create a DOM Document
*/
static public Document getDocument(String namespace, String localname) throws Exception {
return org.wyona.commons.xml.XMLHelper.createDocument(namespace, localname);
}
private Realm getRealm(HttpServletRequest request) throws Exception {
Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
return realm;
}
private boolean generateResponseFromRTview(HttpServletRequest request, HttpServletResponse response, ResourceConfiguration rc, String path) throws ServletException {
String viewId = request.getParameter(VIEW_ID_PARAM_NAME);
if (request.getParameter("yanel.format") != null) { // backwards compatible
viewId = request.getParameter("yanel.format");
}
try {
Realm realm = getRealm(request);
Resource resource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, path, rc);
View view = ((ViewableV2) resource).getView(viewId);
if (view != null) {
if (generateResponse(view, resource, request, response, getDocument(NAMESPACE, "yanel"), -1, -1) != null) return true;
}
} catch (Exception e) {
throw new ServletException(e);
}
return false;
}
private ResourceConfiguration getYanelResourceConfiguration(String pathPrefix, Environment environment, Realm realm, String path) throws Exception {
HttpServletRequest request = environment.getRequest();
java.util.Map<String, String> properties = new HashMap<String, String>();
//XXX: maybe we should use a configuration file instead!
java.util.Map<String, String> globalRCmap = new HashMap<String, String>();
globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml");
globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml");
final String admin = "admin/";
globalRCmap.put(admin + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml");
globalRCmap.put(admin + "list-users.html", "user-mgmt/list-users_yanel-rc.xml");
globalRCmap.put(admin + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml");
globalRCmap.put(admin + "create-group.html", "user-mgmt/create-group_yanel-rc.xml");
globalRCmap.put(admin + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml");
globalRCmap.put(admin + "update-user.html", "user-mgmt/update-user_yanel-rc.xml");
globalRCmap.put(admin + "create-user.html", "user-mgmt/create-user_yanel-rc.xml");
globalRCmap.put(admin + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml");
String pathSuffix = path.substring(pathPrefix.length());
String globalRCfilename = globalRCmap.get(pathSuffix);
final String usersPathPrefix = pathPrefix + "users/";
if (path.startsWith(usersPathPrefix)) {
final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length());
properties.put("user", userName);
return new ResourceConfiguration("yanel-user", "http:
} else if (globalRCfilename != null) {
return getGlobalResourceConfiguration(globalRCfilename, getRealm(request));
}
return null;
}
/**
* Get global data located below reserved prefix
*/
private void getGlobalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Resource resource = getResource(request, response);
String path = resource.getPath();
java.util.Map<String, String> properties = new HashMap<String, String>();
final String pathPrefix = "/" + reservedPrefix + "/";
final String aboutPagePath = pathPrefix + "about.html";
final String resourceTypesPathPrefix = pathPrefix + "resource-types/";
//XXX REFACTORME: in the cases where we simply use a resource-type's view
Realm realm;
Environment environment = getEnvironment(request, response);
ResourceConfiguration rc;
try {
realm = getRealm(request);
rc = getYanelResourceConfiguration(pathPrefix, environment , realm, path);
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
if (rc != null) {
if (generateResponseFromRTview(request, response, rc, path)) return;
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
return;
}else if (path.equals(aboutPagePath)) {
//XXX REFACTORME: we should define an "about" resource-type instead!
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
response.setHeader("Content-Type", "text/html");
PrintWriter w = response.getWriter();
w.print(About.toHTML(yanelInstance.getVersion(), yanelInstance.getRevision()));
return;
} else if (path.startsWith(resourceTypesPathPrefix)) {
final String[] namespaceURI_and_rest = path.substring(resourceTypesPathPrefix.length()).split("::", 2);
final String namespaceURI = namespaceURI_and_rest[0];
final String[] name_and_rest = namespaceURI_and_rest[1].split("/", 2);
final String name = name_and_rest[0];
final String decoded_namespaceURI = HttpServletRequestHelper.decodeURIinURLpath('^', namespaceURI);
if (log.isDebugEnabled()) log.debug("decoded_namespaceURI: "+decoded_namespaceURI);
final String namespace = ! decoded_namespaceURI.equals(namespaceURI) ? decoded_namespaceURI : namespaceURI.replaceAll("http:/", "http:
rc = new ResourceConfiguration(name, namespace, properties);
try {
Resource resourceOfPrefix = yanelInstance.getResourceManager().getResource(environment, realm, path, rc);
String htdocsPath;
if (name_and_rest[1].startsWith(reservedPrefix + "/")) {
htdocsPath = "rtyanelhtdocs:" + name_and_rest[1].substring(reservedPrefix.length()).replace('/', File.separatorChar);
} else {
htdocsPath = "rthtdocs:" + File.separatorChar + name_and_rest[1].replace('/', File.separatorChar);
}
SourceResolver resolver = new SourceResolver(resourceOfPrefix);
Source source = resolver.resolve(htdocsPath, null);
long sourceLastModified = -1;
// Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag
if (source instanceof YanelStreamSource) {
sourceLastModified = ((YanelStreamSource) source).getLastModified();
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if (log.isDebugEnabled()) log.debug("sourceLastModified <= ifModifiedSince: " + sourceLastModified + " <= " + ifModifiedSince);
if (ifModifiedSince != -1) {
if (sourceLastModified <= ifModifiedSince) {
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
}
InputStream htdocIn = ((StreamSource) source).getInputStream();
if (htdocIn != null) {
log.debug("Resource-Type specific data: " + htdocsPath);
// TODO: Set more HTTP headers (size, etc.)
String mimeType = guessMimeType(FilenameUtils.getExtension(FilenameUtils.getName(htdocsPath)));
if(sourceLastModified >= 0) response.setDateHeader("Last-Modified", sourceLastModified);
response.setHeader("Content-Type", mimeType);
byte buffer[] = new byte[8192];
int bytesRead;
OutputStream out = response.getOutputStream();
while ((bytesRead = htdocIn.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
htdocIn.close();
// allow client-side caching:
if (cacheExpires != 0) {
setExpiresHeader(response, cacheExpires);
}
return;
} else {
log.error("No such file or directory: " + htdocsPath);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
return;
}
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
} else {
File globalFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "htdocs" + File.separator + path.substring(pathPrefix.length()));
if (globalFile.exists()) {
log.debug("Global data: " + globalFile);
// TODO: Set more HTTP headers (size, etc.)
String mimeType = guessMimeType(FilenameUtils.getExtension(globalFile.getName()));
response.setHeader("Content-Type", mimeType);
byte buffer[] = new byte[8192];
int bytesRead;
InputStream in = new java.io.FileInputStream(globalFile);
OutputStream out = response.getOutputStream();
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
// allow client-side caching:
if (cacheExpires != 0) {
setExpiresHeader(response, cacheExpires);
}
return;
} else {
log.error("No such file or directory: " + globalFile);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
return;
}
}
}
private void setExpiresHeader(HttpServletResponse response, int hours) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, hours);
String expires = DateUtil.formatRFC822GMT(calendar.getTime());
response.setHeader("Expires", expires);
}
/**
* Generate response from a resource view
*/
private HttpServletResponse generateResponse(View view, Resource res, HttpServletRequest request, HttpServletResponse response, Document doc, long size, long lastModified) throws ServletException, IOException {
// Check if the view contains the response, otherwise assume that the resource wrote the response, and just return.
// TODO: There seem like no header fields are being set (e.g. Content-Length, ...). Please see below ...
// Check if viewable resource has already created a response
if (!view.isResponse()) return response;
// Set encoding
if (view.getEncoding() != null) {
response.setContentType(patchMimeType(view.getMimeType(), request) + "; charset=" + view.getEncoding());
} else if (res.getConfiguration() != null && res.getConfiguration().getEncoding() != null) {
response.setContentType(patchMimeType(view.getMimeType(), request) + "; charset=" + res.getConfiguration().getEncoding());
} else {
// try to guess if we have to set the default encoding
String mimeType = view.getMimeType();
if (mimeType != null && mimeType.startsWith("text") ||
mimeType.equals("application/xml") ||
mimeType.equals("application/xhtml+xml") ||
mimeType.equals("application/atom+xml") ||
mimeType.equals("application/x-javascript")) {
response.setContentType(patchMimeType(mimeType, request) + "; charset=" + DEFAULT_ENCODING);
} else {
// probably binary mime-type, don't set encoding
response.setContentType(patchMimeType(mimeType, request));
}
}
// Set HTTP headers:
HashMap<?, ?> headers = view.getHttpHeaders();
Iterator<?> iter = headers.keySet().iterator();
while (iter.hasNext()) {
String name = (String)iter.next();
String value = (String)headers.get(name);
if (log.isDebugEnabled()) {
log.debug("set http header: " + name + ": " + value);
}
response.setHeader(name, value);
}
// Possibly embed toolbar:
// TODO: Check if user is authorized to actually see toolbar (Current flaw: Enabled Toolbar, Login, Toolbar is enabled, Logout, Toolbar is still visible!)
if (yanelUI.isToolbarEnabled(request)) {
String mimeType = view.getMimeType();
if (mimeType != null && mimeType.indexOf("html") > 0) {
// TODO: What about other query strings or frames or TinyMCE?
if (request.getParameter(YANEL_RESOURCE_USECASE) == null) {
if (toolbarMasterSwitch.equals("on")) {
OutputStream os = response.getOutputStream();
try {
Usecase usecase = new Usecase(TOOLBAR_USECASE);
Identity identity = getIdentity(request, map);
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
// NOTE: This extra authorization check is necessary within a multi-realm environment, because after activating the toolbar with a query string, the toolbar flag attached to the session will be ignored by doAccessControl(). One could possibly do this check within doAccessControl(), but could be a peformance issue! Or as an alternative one could refactor the code, such that the toolbar session flag is realm aware.
if(realm.getPolicyManager().authorize(path, identity, usecase)) {
yanelUI.mergeToolbarWithContent(request, response, res, view);
return response;
} else {
log.warn("Toolbar authorization denied (Realm: '" + realm.getName() + "', User: '" + identity.getUsername() + "', Path: '" + path + "')!");
}
} catch (Exception e) {
String message = "Error merging toolbar into content: " + e.getMessage();
log.error(message, e);
Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
return response;
}
} else {
log.info("Toolbar has been disabled. Please check web.xml!");
}
} else {
log.warn("Exception to the rule. Yanel resource usecase is not null: " + request.getParameter(YANEL_RESOURCE_USECASE));
}
} else {
log.info("No HTML related mime type: " + mimeType);
}
} else {
log.debug("Toolbar is turned off.");
}
InputStream is = view.getInputStream();
if (is != null) {
// Write actual content into response
byte buffer[] = new byte[8192];
int bytesRead;
bytesRead = is.read(buffer);
try {
// Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if (ifModifiedSince != -1) {
if (res instanceof ModifiableV2) {
long resourceLastMod = ((ModifiableV2)res).getLastModified();
//log.debug(resourceLastMod + " " + ifModifiedSince);
if (resourceLastMod <= ifModifiedSince) {
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED);
return response;
}
} else {
// TODO: Many resources do not implement ModifiableV2 and hence never return a lastModified and hence the browser will never ask for ifModifiedSince!
//log.warn("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!");
if (log.isDebugEnabled()) log.debug("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified);
if(size > 0) {
if (log.isDebugEnabled()) log.debug("Size of " + request.getRequestURI() + ": " + size);
response.setContentLength((int) size);
} else {
if (log.isDebugEnabled()) log.debug("No size for " + request.getRequestURI() + ": " + size);
}
// Check if InputStream is empty
if (bytesRead != -1) {
java.io.OutputStream os = response.getOutputStream();
os.write(buffer, 0, bytesRead);
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
} else {
log.warn("Returned content size of request '" + request.getRequestURI() + "' is 0");
}
is.close();
return response;
} else {
String message = "Returned InputStream of request '" + request.getRequestURI() + "' is null!";
Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
is.close();
return response;
}
}
@Override
public void destroy() {
super.destroy();
yanelInstance.destroy();
log.warn("Yanel webapp has been shut down.");
}
/**
* Get usecase. Maps query strings, etc. to usecases, which then can be used for example within access control policies
*/
private Usecase getUsecase(HttpServletRequest request) {
// TODO: Replace hardcoded roles by mapping between roles amd query strings ...
Usecase usecase = new Usecase("view");
String yanelResUsecaseValue = request.getParameter(YANEL_RESOURCE_USECASE);
if (yanelResUsecaseValue != null) {
if (yanelResUsecaseValue.equals("save")) {
log.debug("Save data ...");
usecase = new Usecase("write");
} else if (yanelResUsecaseValue.equals("checkin")) {
log.debug("Checkin data ...");
usecase = new Usecase("write");
} else if (yanelResUsecaseValue.equals("roll-back")) {
log.debug("Roll back to previous revision ...");
usecase = new Usecase("write");
} else if (yanelResUsecaseValue.equals("introspection")) {
if(log.isDebugEnabled()) log.debug("Dynamically generated introspection ...");
usecase = new Usecase("introspection");
} else if (yanelResUsecaseValue.equals("checkout")) {
log.debug("Checkout data ...");
usecase = new Usecase("open");
} else if (yanelResUsecaseValue.equals("delete")) {
log.info("Delete resource (yanel resource usecase delete)");
usecase = new Usecase("delete");
} else {
log.warn("No such generic Yanel resource usecase: " + yanelResUsecaseValue + " (maybe some custom resource usecase)");
}
}
String yanelUsecaseValue = request.getParameter(YANEL_USECASE);
if (yanelUsecaseValue != null) {
if (yanelUsecaseValue.equals("create")) {
log.debug("Create new resource ...");
usecase = new Usecase("resource.create");
} else {
log.warn("No such usecase: " + yanelUsecaseValue);
}
}
String contentType = request.getContentType();
String method = request.getMethod();
if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) {
// TODO: Is posting atom entries different from a general post (see below)?!
log.warn("Write/Checkin Atom entry ...");
usecase = new Usecase("write");
// TODO: METHOD_POST is not generally protected, but save, checkin, application/atom+xml are being protected. See doPost(....
} else if (method.equals(METHOD_PUT)) {
log.warn("Upload data ...");
usecase = new Usecase("write");
} else if (method.equals(METHOD_DELETE)) {
log.warn("Delete resource (HTTP method delete)");
usecase = new Usecase("delete");
}
String workflowTransitionValue = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION);
if (workflowTransitionValue != null) {
// TODO: How shall we protect workflow transitions?!
log.warn("Workflow transition is currently handled as view usecase: " + workflowTransitionValue);
usecase = new Usecase("view");
}
String toolbarValue = request.getParameter("yanel.toolbar");
if (toolbarValue != null && toolbarValue.equals("on")) {
log.debug("Turn on toolbar ...");
usecase = new Usecase(TOOLBAR_USECASE);
}
String yanelPolicyValue = request.getParameter(YANEL_ACCESS_POLICY_USECASE);
if (yanelPolicyValue != null) {
if (yanelPolicyValue.equals("create")) {
usecase = new Usecase("policy.create");
} else if (yanelPolicyValue.equals("read")) {
usecase = new Usecase("policy.read");
} else if (yanelPolicyValue.equals("update")) {
usecase = new Usecase("policy.update");
} else if (yanelPolicyValue.equals("delete")) {
usecase = new Usecase("policy.delete");
} else {
log.warn("No such policy usecase: " + yanelPolicyValue);
}
}
String showResourceMeta = request.getParameter(RESOURCE_META_ID_PARAM_NAME);
if (showResourceMeta != null) {
usecase = new Usecase(RESOURCE_META_ID_PARAM_NAME);
}
return usecase;
}
/**
* Handle access policy requests (CRUD, whereas delete is not implemented yet!)
*/
private void doAccessPolicyRequest(HttpServletRequest request, HttpServletResponse response, String usecase) throws ServletException, IOException {
try {
String viewId = request.getParameter(VIEW_ID_PARAM_NAME);
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
ResourceConfiguration rc = getGlobalResourceConfiguration("policy-manager_yanel-rc.xml", realm);
if (generateResponseFromRTview(request, response, rc, path)) return;
log.error("Something went terribly wrong!");
response.getWriter().print("Something went terribly wrong!");
return;
} catch(Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
/**
* Handle delete usecase
*/
private void handleDeleteUsecase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String confirmed = request.getParameter("confirmed");
if (confirmed != null) {
String path = getResource(request, response).getPath();
log.warn("Really delete " + path);
doDelete(request, response);
return;
} else {
log.warn("Delete has not been confirmed by client yet!");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
response.setContentType("text/html" + "; charset=" + "UTF-8");
StringBuffer sb = new StringBuffer("<html xmlns=\"http:
PrintWriter w = response.getWriter();
w.print(sb);
return;
}
}
/**
* Get resource configuration from global location of the realm or if not available there, then from global location of Yanel
*
* @param resConfigName Filename of resource configuration
* @param realm Current realm
*/
private ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm) {
// TODO: Introduce a repository for the Yanel webapp
File realmDir = new File(realm.getConfigFile().getParent());
File globalResConfigFile = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + "global-resource-configs/" + resConfigName);
if (!globalResConfigFile.isFile()) {
// Fallback to global configuration
globalResConfigFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "global-resource-configs/" + resConfigName);
}
InputStream is;
try {
is = new java.io.FileInputStream(globalResConfigFile);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
ResourceConfiguration rc;
try {
rc = new ResourceConfiguration(is);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
return rc;
}
private String getStackTrace(Exception e) {
java.io.StringWriter sw = new java.io.StringWriter();
e.printStackTrace(new java.io.PrintWriter(sw));
return sw.toString();
}
private void do404(HttpServletRequest request, HttpServletResponse response, Document doc, String exceptionMessage) throws ServletException {
// TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ...
// Also see logBrowserHistory
//org.wyona.yarep.core.Node node = realm.getRepository().getNode("/yanel-logs/404.txt");
String message = "No such node/resource exception: " + exceptionMessage;
log.warn(message);
/*
Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttributeNS(NAMESPACE, "status", "404");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
setYanelOutput(request, response, doc);
return;
*/
// TODO: Finish the XML (as it used to be before)!
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
try {
Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
String path = getResource(request, response).getPath();
ResourceConfiguration rc = getGlobalResourceConfiguration("404_yanel-rc.xml", realm);
if (generateResponseFromRTview(request, response, rc, path)) return;
log.error("404 seems to be broken!");
return;
} catch (Exception e) {
log.error(e.getMessage(), e);
return;
}
}
/**
* Check if yanel resource usecase is 'roll back" usecase
*/
private boolean isRollBack(HttpServletRequest request) {
String yanelResUsecase = request.getParameter(YANEL_RESOURCE_USECASE);
if (yanelResUsecase != null) {
if (yanelResUsecase.equals("roll-back")) return true;
}
return false;
}
/**
* Check if request comes from Neutron supporting client
*/
private boolean isClientSupportingNeutron(HttpServletRequest request) {
String neutronVersions = request.getHeader("Neutron");
if (neutronVersions != null) {
log.info("Neutron version(s) supported by client: " + neutronVersions);
return true;
}
return false;
}
/**
* Get Neutron versions which are supported by client
*/
private String getClientSupportedNeutronVersions(HttpServletRequest request) {
return request.getHeader("Neutron");
}
/**
* Get client authentication scheme
*/
private String getClientAuthenticationScheme(HttpServletRequest request) {
return request.getHeader("WWW-Authenticate");
}
/**
* Respond with introspection
*/
private void sendIntrospectionAsResponse(Resource res, Document doc, Element rootElement, HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) {
String introspection = ((IntrospectableV1)res).getIntrospection();
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
response.getWriter().print(introspection);
} else {
String message = "Resource is not introspectable.";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(request, response, doc);
}
return;
} catch(Exception e) {
log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception"));
exceptionElement.appendChild(doc.createTextNode(e.getMessage()));
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(request, response, doc);
return;
}
}
/**
* Set/get meta data re resource
*/
private Element getResourceMetaData(Resource res, Document doc, Element rootElement) {
Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource"));
ResourceConfiguration resConfig = res.getConfiguration();
if (resConfig != null) {
Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config"));
resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName());
resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace());
} else {
Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config"));
}
Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm"));
realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName());
realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID());
realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint());
Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager"));
Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager"));
return resourceElement;
}
/**
* Append view descriptors to meta
*/
private void appendViewDescriptors(Document doc, Element viewElement, ViewDescriptor[] vd) {
if (vd != null) {
for (int i = 0; i < vd.length; i++) {
Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor"));
if (vd[i].getMimeType() != null) {
descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType()));
}
descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId());
}
} else {
viewElement.appendChild(doc.createTextNode("No View Descriptors!"));
}
}
/**
* Log browser history of each user
*/
private void logBrowserHistoryOfUser(HttpServletRequest request) {
// See apache-tomcat-5.5.20/logs/localhost_access_log.2009-11-07.txt
// 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464
try {
// TBD/TODO: What if user has logged out, but still has a persistent cookie?!
//String userID = getEnvironment(request, response).getIdentity().getUsername();
Identity identity = getIdentity(request, map);
if (identity != null && identity.getUsername() != null) {
log.warn("DEBUG: Log browser history of user '"+identity.getUsername()+"'.");
Realm realm = map.getRealm(request.getServletPath());
User user = realm.getIdentityManager().getUserManager().getUser(identity.getUsername());
// The log should be attached to the user, because realms can share a UserManager, but the UserManager API has no mean to save such data, so how should we do this?
// What if realm ID is changing?
String logPath = "yanel-logs/browser-history/" + user.getID() + ".txt";
if (!realm.getRepository().existsNode(logPath)) {
org.wyona.yarep.util.YarepUtil.addNodes(realm.getRepository(), logPath, org.wyona.yarep.core.NodeType.RESOURCE);
}
org.wyona.yarep.core.Node node = realm.getRepository().getNode("/yanel-logs/browser-history/" + user.getID() + ".txt");
// Stream into node (append log entry, see for example log4j)
// 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464
} else {
log.warn("DEBUG: Log browser history of anonynmous user");
}
//log.warn("DEBUG: Referer: " + request.getHeader(HTTP_REFERRER));
} catch(Exception e) { // Catch all exceptions, because we do not want to throw exceptions because of logging browser history
log.error(e, e);
}
}
/**
* Check well-formedness of XML
* @param in XML as InputStream
*/
private InputStream isWellFormed(InputStream in) throws Exception {
log.info("Check well-formedness ...");
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
// TODO: Get log messages into log4j ...
//parser.setErrorHandler(...);
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int bytesR;
while ((bytesR = in.read(buf)) != -1) {
baos.write(buf, 0, bytesR);
}
// Buffer within memory (TODO: Maybe replace with File-buffering ...)
byte[] memBuffer = baos.toByteArray();
// NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also
// if isValidating is set to false.
// Hence, for performance and network reasons we use a local catalog ...
// TODO: What about a resolver factory?
parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver());
parser.parse(new ByteArrayInputStream(memBuffer));
in = new ByteArrayInputStream(memBuffer);
//org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer));
log.info("Data seems to be well-formed :-)");
return in;
} catch (org.xml.sax.SAXException e) {
throw new Exception("The received data is not well-formed: " + e.getMessage());
} catch (Exception e) {
throw new Exception("The received data is either not well-formed or some other exception occured: " + e.getMessage());
}
}
}
|
package org.intermine.api.profile;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.intermine.api.template.TemplateQuery;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
public class ModelUpdate {
private ObjectStoreWriter uosw;
private ProfileManager pm;
private Model model;
private Model oldModel;
private Set<String> deletedClasses = new HashSet<String>();
private Map<String, String> renamedClasses = new HashMap<String, String>();
private Map<String, String> renamedFields = new HashMap<String, String>();
public static final String DELETED = "deleted";
public static final String RENAMED = "renamed-";
public ModelUpdate(ObjectStore os, ObjectStoreWriter uosw, String oldModelName) {
this.uosw = uosw;
this.pm = new ProfileManager(os, uosw);
this.model = os.getModel();
this.oldModel = Model.getInstanceByName(oldModelName);
String keyAsString;
String className;
String fieldName;
String update;
Properties modelUpdateProps = new Properties();
try {
modelUpdateProps.load(this.getClass().getClassLoader()
.getResourceAsStream("modelUpdate.properties"));
} catch (Exception e) {
e.printStackTrace();
}
for(Object key : modelUpdateProps.keySet()) {
keyAsString = (String) key;
update = (String) modelUpdateProps.getProperty(keyAsString);
if (!keyAsString.contains(".")) {
//it's a class update
className = keyAsString;
verifyClassAndField(className, null, oldModel);
if (update.equals(DELETED)) {
deletedClasses.add(className);
} else if (update.contains(RENAMED)) {
String newClassName = update.replace(RENAMED, "").trim();
verifyClassAndField(newClassName, null, model);
renamedClasses.put(className, newClassName);
} else {
throw new BuildException("For the class " + className
+ " only deleted or renamed- permitted.");
}
} else {
//it's a field update
int index = keyAsString.indexOf(".");
className = keyAsString.substring(0, index);
fieldName = keyAsString.substring(index + 1);
verifyClassAndField(className, fieldName, oldModel);
if (update.contains(RENAMED)) {
update = update.replace(RENAMED, "").trim();
index = update.indexOf(".");
String newClassName = update.substring(0, index);
String newFieldName = update.substring(index + 1);
verifyClassAndField(newClassName, newFieldName, model);
if (!className.equals(newClassName)) {
//there is a renamed attribute in a renamed class.
//add in renamedClasses this renamed class
if (!renamedClasses.containsKey(className)) {
renamedClasses.put(className, newClassName);
} else {
if (!renamedClasses.get(className).equals(newClassName)) {
throw new BuildException("Class " + className + " has been " +
"renamed in two different classes. Please check" +
" modelUpdate.properties file");
}
}
}
renamedFields.put(newClassName + "." + fieldName, newFieldName);
} else if (!update.contains(DELETED)) {
throw new BuildException("For the field " + keyAsString
+ " only deleted or renamed- permitted.");
}
}
}
}
private void verifyClassAndField(String className, String fieldName, Model model)
throws BuildException {
String checkFileMsg = "Please check modelUpdate.properties file";
if ("".equals(className)) {
throw new BuildException("Class " + className + " can not be blank. " + checkFileMsg);
}
ClassDescriptor cd = model.getClassDescriptorByName(className);
if (cd == null) {
if (fieldName != null) {
throw new BuildException("Class " + className + " containing " + fieldName
+ " not defined in the model " + model.getName() + ". "
+ checkFileMsg);
} else {
throw new BuildException("Class " + className + " not defined in the model "
+ model.getName() + ". " + checkFileMsg);
}
}
if (fieldName != null) {
if (fieldName.equals("")) {
throw new BuildException("Attribute " + fieldName + " in the class " + className
+ " can not be blank. " + checkFileMsg);
}
if (cd.getAttributeDescriptorByName(fieldName) == null) {
throw new BuildException("Attribute " + fieldName + " in the class " + className
+ " not defined in the model " + model.getName() + ". " + checkFileMsg);
}
}
}
public Set<String> getDeletedClasses() {
return deletedClasses;
}
public Map<String, String> getRenamedClasses() {
return renamedClasses;
}
public Map<String, String> getRenamedFields() {
return renamedFields;
}
public void update() throws PathException {
if(!deletedClasses.isEmpty()) {
deleteBags();
}
if(!renamedClasses.isEmpty()) {
updateTypeBag();
}
if(!renamedClasses.isEmpty() || !renamedFields.isEmpty()) {
updateReferredQueryAndTemplate();
}
}
public void deleteBags() {
Query q = new Query();
QueryClass qc = new QueryClass(SavedBag.class);
q.addToSelect(qc);
q.addFrom(qc);
QueryField typeField = new QueryField(qc, "type");
BagConstraint constraint = new BagConstraint(typeField, ConstraintOp.IN, deletedClasses);
q.setConstraint(constraint);
Results bagsToDelete = uosw.execute(q, 1000, false, false, true);
for (Iterator i = bagsToDelete.iterator(); i.hasNext();) {
ResultsRow row = (ResultsRow) i.next();
SavedBag savedBag = (SavedBag) row.get(0);
Profile profile = pm.getProfile(savedBag.getUserProfile().getUsername());
try {
profile.deleteBag(savedBag.getName());
} catch (ObjectStoreException ose) {
System.out.println("Problems deleting bag: " + savedBag.getName());
}
}
}
public void updateTypeBag() {
Query q = new Query();
QueryClass qc = new QueryClass(SavedBag.class);
q.addToSelect(qc);
q.addFrom(qc);
QueryField typeField = new QueryField(qc, "type");
BagConstraint constraint = new BagConstraint(typeField, ConstraintOp.IN,
renamedClasses.keySet());
q.setConstraint(constraint);
Results bagsToUpdate = uosw.execute(q, 1000, false, false, true);
for (Iterator i = bagsToUpdate.iterator(); i.hasNext();) {
ResultsRow row = (ResultsRow) i.next();
SavedBag savedBag = (SavedBag) row.get(0);
String type = savedBag.getType();
String newType = renamedClasses.get(type);
Profile profile = pm.getProfile(savedBag.getUserProfile().getUsername());
try {
if (newType != null) {
profile.updateBagType(savedBag.getName(), newType);
}
} catch (ObjectStoreException ose) {
System.out.println("Problems updating savedBag " + savedBag.getName()
+ ose.getMessage());
}
}
}
public void updateReferredQueryAndTemplate() throws PathException {
Map<String, SavedQuery> savedQueries;
Map<String, TemplateQuery> templateQueries;
String cls, prevField;
List<String> problems;
Query q = new Query();
QueryClass qc = new QueryClass(UserProfile.class);
q.addToSelect(qc);
q.addFrom(qc);
Results userprofiles = uosw.execute(q, 1000, false, false, true);
for (Iterator i = userprofiles.iterator(); i.hasNext();) {
ResultsRow row = (ResultsRow) i.next();
UserProfile user = (UserProfile) row.get(0);
Profile profile = pm.getProfile(user.getUsername());
savedQueries = profile.getSavedQueries();
for (SavedQuery savedQuery : savedQueries.values()) {
PathQuery pathQuery = savedQuery.getPathQuery();
PathQueryUpdate pathQueryUpdate = new PathQueryUpdate(pathQuery, model, oldModel);
for (String prevClass : renamedClasses.keySet()) {
problems = pathQueryUpdate.updateWithRenamedClass(prevClass, renamedClasses.get(prevClass));
if (!problems.isEmpty()) {
System.out.println("Problems updating pathQuery in savedQuery " + savedQuery.getName()
+ " with renamed class " + prevClass + ": " + problems);
continue;
}
}
for (String key : renamedFields.keySet()) {
int index = key.indexOf(".");
cls = key.substring(0, index);
prevField = key.substring(index + 1);
problems = pathQueryUpdate.updateWithRenamedField(cls, prevField, renamedFields.get(key));
if (!problems.isEmpty()) {
System.out.println("Problems updating pathQuery in savedQuery " + savedQuery.getName()
+ " with renamed field " + prevField + ": " + problems);
continue;
}
}
profile.saveQuery(savedQuery.getName(), savedQuery);
}
templateQueries = profile.getSavedTemplates();
for (TemplateQuery templateQuery : templateQueries.values()) {
PathQueryUpdate templateQueryUpdate = new PathQueryUpdate(templateQuery, model, oldModel);
for (String prevClass : renamedClasses.keySet()) {
problems = templateQueryUpdate.updateWithRenamedClass(prevClass,
renamedClasses.get(prevClass));
if (!problems.isEmpty()) {
System.out.println("Problems updating pathQuery in templateQuery " + templateQuery.getName()
+ " with renamed class " + prevClass + ": " + problems);
continue;
}
}
for (String key : renamedFields.keySet()) {
int index = key.indexOf(".");
cls = key.substring(0, index);
prevField = key.substring(index + 1);
problems = templateQueryUpdate.updateWithRenamedField(cls, prevField,
renamedFields.get(key));
if (!problems.isEmpty()) {
System.out.println("Problems updating pathQuery in templateQuery " + templateQuery.getName()
+ " with renamed field " + prevField + ": " + problems);
continue;
}
}
profile.saveTemplate(templateQuery.getName(), templateQuery);
}
}
}
}
|
package com.cloud.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.cloud.agent.AgentManager;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO;
import com.cloud.configuration.ConfigurationService;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.dc.AccountVlanMapVO;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Vlan;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.AccountVlanMapDao;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.Host;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.IPAddressVO;
import com.cloud.network.LoadBalancerVO;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkProfile;
import com.cloud.network.NetworkRuleConfigVO;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkRuleConfigDao;
import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupManager;
import com.cloud.network.security.SecurityGroupVO;
import com.cloud.network.security.dao.SecurityGroupDao;
import com.cloud.offering.ServiceOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.server.Criteria;
import com.cloud.server.ManagementServer;
import com.cloud.server.StatsCollector;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.GuestOS;
import com.cloud.storage.GuestOSCategoryVO;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.StorageStats;
import com.cloud.storage.UploadVO;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.UploadDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.InstanceGroupVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VmStats;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
public class ApiDBUtils {
private static ManagementServer _ms;
private static AccountManager _accountMgr;
private static AgentManager _agentMgr;
public static AsyncJobManager _asyncMgr;
private static SecurityGroupManager _networkGroupMgr;
private static SnapshotManager _snapMgr;
private static StorageManager _storageMgr;
private static UserVmManager _userVmMgr;
private static NetworkManager _networkMgr;
private static StatsCollector _statsCollector;
private static AccountDao _accountDao;
private static AccountVlanMapDao _accountVlanMapDao;
private static ClusterDao _clusterDao;
private static DiskOfferingDao _diskOfferingDao;
private static DomainDao _domainDao;
private static DomainRouterDao _domainRouterDao;
private static GuestOSDao _guestOSDao;
private static GuestOSCategoryDao _guestOSCategoryDao;
private static HostDao _hostDao;
private static IPAddressDao _ipAddressDao;
private static LoadBalancerDao _loadBalancerDao;
private static SecurityGroupDao _networkGroupDao;
private static NetworkRuleConfigDao _networkRuleConfigDao;
private static HostPodDao _podDao;
private static ServiceOfferingDao _serviceOfferingDao;
private static SnapshotDao _snapshotDao;
private static StoragePoolDao _storagePoolDao;
private static VMTemplateDao _templateDao;
private static VMTemplateHostDao _templateHostDao;
private static UploadDao _uploadDao;
private static UserDao _userDao;
private static UserStatisticsDao _userStatsDao;
private static UserVmDao _userVmDao;
private static VlanDao _vlanDao;
private static VolumeDao _volumeDao;
private static DataCenterDao _zoneDao;
private static NetworkOfferingDao _networkOfferingDao;
private static NetworkDao _networkDao;
private static ConfigurationService _configMgr;
static {
_ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_accountMgr = locator.getManager(AccountManager.class);
_agentMgr = locator.getManager(AgentManager.class);
_asyncMgr = locator.getManager(AsyncJobManager.class);
_networkGroupMgr = locator.getManager(SecurityGroupManager.class);
_snapMgr = locator.getManager(SnapshotManager.class);
_storageMgr = locator.getManager(StorageManager.class);
_userVmMgr = locator.getManager(UserVmManager.class);
_networkMgr = locator.getManager(NetworkManager.class);
_configMgr = locator.getManager(ConfigurationService.class);
_accountDao = locator.getDao(AccountDao.class);
_accountVlanMapDao = locator.getDao(AccountVlanMapDao.class);
_clusterDao = locator.getDao(ClusterDao.class);
_diskOfferingDao = locator.getDao(DiskOfferingDao.class);
_domainDao = locator.getDao(DomainDao.class);
_domainRouterDao = locator.getDao(DomainRouterDao.class);
_guestOSDao = locator.getDao(GuestOSDao.class);
_guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class);
_hostDao = locator.getDao(HostDao.class);
_ipAddressDao = locator.getDao(IPAddressDao.class);
_loadBalancerDao = locator.getDao(LoadBalancerDao.class);
_networkRuleConfigDao = locator.getDao(NetworkRuleConfigDao.class);
_podDao = locator.getDao(HostPodDao.class);
_serviceOfferingDao = locator.getDao(ServiceOfferingDao.class);
_snapshotDao = locator.getDao(SnapshotDao.class);
_storagePoolDao = locator.getDao(StoragePoolDao.class);
_templateDao = locator.getDao(VMTemplateDao.class);
_templateHostDao = locator.getDao(VMTemplateHostDao.class);
_uploadDao = locator.getDao(UploadDao.class);
_userDao = locator.getDao(UserDao.class);
_userStatsDao = locator.getDao(UserStatisticsDao.class);
_userVmDao = locator.getDao(UserVmDao.class);
_vlanDao = locator.getDao(VlanDao.class);
_volumeDao = locator.getDao(VolumeDao.class);
_zoneDao = locator.getDao(DataCenterDao.class);
_networkGroupDao = locator.getDao(SecurityGroupDao.class);
_networkOfferingDao = locator.getDao(NetworkOfferingDao.class);
_networkDao = locator.getDao(NetworkDao.class);
// Note: stats collector should already have been initialized by this time, otherwise a null instance is returned
_statsCollector = StatsCollector.getInstance();
}
// ManagementServer methods //
public static VMInstanceVO findVMInstanceById(long vmId) {
return _ms.findVMInstanceById(vmId);
}
public static long getMemoryUsagebyHost(Long hostId) {
// TODO: This method is for the API only, but it has configuration values (ramSize for system vms)
// so if this Utils class can have some kind of config rather than a static initializer (maybe from
// management server instantiation?) then maybe the management server method can be moved entirely
// into this utils class.
return _ms.getMemoryUsagebyHost(hostId);
}
public static Long getPodIdForVlan(long vlanDbId) {
return _ms.getPodIdForVlan(vlanDbId);
}
public static String getVersion() {
return _ms.getVersion();
}
public static List<UserVmVO> searchForUserVMs(Criteria c) {
return _userVmMgr.searchForUserVMs(c);
}
public static List<? extends StoragePoolVO> searchForStoragePools(Criteria c) {
return _ms.searchForStoragePools(c);
}
// Manager methods //
public static long findCorrectResourceLimit(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.findCorrectResourceLimit(account, type);
}
public static AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) {
return _asyncMgr.findInstancePendingAsyncJob(instanceType, instanceId);
}
public static long getResourceCount(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.getResourceCount(account, type);
}
public static String getNetworkGroupsNamesForVm(long vmId) {
return _networkGroupMgr.getSecurityGroupsNamesForVm(vmId);
}
public static List<SecurityGroupVO> getSecurityGroupsForVm(long vmId) {
return _networkGroupMgr.getSecurityGroupsForVm(vmId);
}
public static String getSnapshotIntervalTypes(long snapshotId) {
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
return snapshot.getType().name();
}
public static String getStoragePoolTags(long poolId) {
return _storageMgr.getStoragePoolTags(poolId);
}
public static boolean isLocalStorageActiveOnHost(Host host) {
return _storageMgr.isLocalStorageActiveOnHost(host);
}
public static InstanceGroupVO findInstanceGroupForVM(long vmId) {
return _userVmMgr.getGroupForVm(vmId);
}
// Misc methods //
public static HostStats getHostStatistics(long hostId) {
return _statsCollector.getHostStats(hostId);
}
public static StorageStats getStoragePoolStatistics(long id) {
return _statsCollector.getStoragePoolStats(id);
}
public static VmStats getVmStatistics(long hostId) {
return _statsCollector.getVmStats(hostId);
}
public static StorageStats getSecondaryStorageStatistics(long id){
return _statsCollector.getStorageStats(id);
}
// Dao methods //
public static Account findAccountById(Long accountId) {
return _accountDao.findByIdIncludingRemoved(accountId);
}
public static Account findAccountByIdIncludingRemoved(Long accountId) {
return _accountDao.findByIdIncludingRemoved(accountId);
}
public static Account findAccountByNameDomain(String accountName, Long domainId) {
return _accountDao.findActiveAccount(accountName, domainId);
}
public static ClusterVO findClusterById(long clusterId) {
return _clusterDao.findById(clusterId);
}
public static DiskOfferingVO findDiskOfferingById(Long diskOfferingId) {
return _diskOfferingDao.findByIdIncludingRemoved(diskOfferingId);
}
public static DomainVO findDomainById(Long domainId) {
return _domainDao.findByIdIncludingRemoved(domainId);
}
public static DomainVO findDomainByIdIncludingRemoved(Long domainId) {
return _domainDao.findByIdIncludingRemoved(domainId);
}
public static DomainRouterVO findDomainRouterById(Long routerId) {
return _domainRouterDao.findByIdIncludingRemoved(routerId);
}
public static GuestOS findGuestOSById(Long id) {
return _guestOSDao.findByIdIncludingRemoved(id);
}
public static HostVO findHostById(Long hostId) {
return _hostDao.findByIdIncludingRemoved(hostId);
}
public static IPAddressVO findIpAddressById(long addressId) {
return _ipAddressDao.findById(addressId);
}
public static GuestOSCategoryVO getHostGuestOSCategory(long hostId) {
Long guestOSCategoryID = _agentMgr.getGuestOSCategoryId(hostId);
if (guestOSCategoryID != null) {
return _guestOSCategoryDao.findById(guestOSCategoryID);
} else {
return null;
}
}
public static String getHostTags(long hostId) {
return _agentMgr.getHostTags(hostId);
}
public static LoadBalancerVO findLoadBalancerById(Long loadBalancerId) {
return _loadBalancerDao.findById(loadBalancerId);
}
public static NetworkRuleConfigVO findNetworkRuleById(Long ruleId) {
return _networkRuleConfigDao.findById(ruleId);
}
public static SecurityGroup findNetworkGroupById(Long groupId) {
return _networkGroupDao.findById(groupId);
}
public static HostPodVO findPodById(Long podId) {
return _podDao.findById(podId);
}
public static VolumeVO findRootVolume(long vmId) {
List<VolumeVO> volumes = _volumeDao.findByInstanceAndType(vmId, Type.ROOT);
if (volumes != null && volumes.size() == 1) {
return volumes.get(0);
} else {
return null;
}
}
public static ServiceOffering findServiceOfferingById(Long serviceOfferingId) {
return _serviceOfferingDao.findByIdIncludingRemoved(serviceOfferingId);
}
public static Snapshot findSnapshotById(long snapshotId) {
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
if (snapshot != null && snapshot.getRemoved() == null && snapshot.getStatus() == Snapshot.Status.BackedUp) {
return snapshot;
}
else {
return null;
}
}
public static StoragePoolVO findStoragePoolById(Long storagePoolId) {
return _storagePoolDao.findByIdIncludingRemoved(storagePoolId);
}
public static VMTemplateVO findTemplateById(Long templateId) {
return _templateDao.findByIdIncludingRemoved(templateId);
}
public static VMTemplateHostVO findTemplateHostRef(long templateId, long zoneId) {
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
if (secondaryStorageHost == null) {
return null;
} else {
return _templateHostDao.findByHostTemplate(secondaryStorageHost.getId(), templateId);
}
}
public static UploadVO findUploadById(Long id){
return _uploadDao.findById(id);
}
public static User findUserById(Long userId) {
return _userDao.findById(userId);
}
public static UserVm findUserVmById(Long vmId) {
return _userVmDao.findById(vmId);
}
public static VlanVO findVlanById(long vlanDbId) {
return _vlanDao.findById(vlanDbId);
}
public static VolumeVO findVolumeById(Long volumeId) {
return _volumeDao.findByIdIncludingRemoved(volumeId);
}
public static List<UserVO> listUsersByAccount(long accountId) {
return _userDao.listByAccount(accountId);
}
public static DataCenterVO findZoneById(Long zoneId) {
return _zoneDao.findById(zoneId);
}
public static Long getAccountIdForVlan(long vlanDbId) {
List<AccountVlanMapVO> accountVlanMaps = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId);
if (accountVlanMaps.isEmpty()) {
return null;
} else {
return accountVlanMaps.get(0).getAccountId();
}
}
public static HypervisorType getVolumeHyperType(long volumeId) {
return _volumeDao.getHypervisorType(volumeId);
}
public static List<VMTemplateHostVO> listTemplateHostBy(long templateId, Long zoneId) {
if (zoneId != null) {
HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId);
if (secondaryStorageHost == null) {
return new ArrayList<VMTemplateHostVO>();
} else {
return _templateHostDao.listByHostTemplate(secondaryStorageHost.getId(), templateId);
}
} else {
return _templateHostDao.listByOnlyTemplateId(templateId);
}
}
public static List<UserStatisticsVO> listUserStatsBy(Long accountId) {
return _userStatsDao.listBy(accountId);
}
public static List<UserVmVO> listUserVMsByHostId(long hostId) {
return _userVmDao.listByHostId(hostId);
}
public static List<DataCenterVO> listZones() {
return _zoneDao.listAll();
}
public static boolean volumeIsOnSharedStorage(long volumeId) throws InvalidParameterValueException {
// Check that the volume is valid
VolumeVO volume = _volumeDao.findById(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Please specify a valid volume ID.");
}
return _storageMgr.volumeOnSharedStoragePool(volume);
}
public static List<NicProfile> getNics(VirtualMachine vm) {
return _networkMgr.getNicProfiles(vm);
}
public static NetworkProfile getNetworkProfile(long networkId) {
return _networkMgr.convertNetworkToNetworkProfile(networkId);
}
public static NetworkOfferingVO findNetworkOfferingById(long networkOfferingId) {
return _networkOfferingDao.findByIdIncludingRemoved(networkOfferingId);
}
public static List<? extends Vlan> listVlanByNetworkId(long networkId) {
return _vlanDao.listVlansByNetworkId(networkId);
}
public static NetworkVO findNetworkById(long id) {
return _networkDao.findById(id);
}
public static Map<Service, Map<Capability, String>> getNetworkCapabilities(long networkId) {
return _networkMgr.getNetworkCapabilities(networkId);
}
public static long getPublicNetworkIdByZone(long zoneId) {
return _networkMgr.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
}
public static Long getVlanNetworkId(long vlanId) {
VlanVO vlan = _vlanDao.findById(vlanId);
if (vlan != null) {
return vlan.getNetworkId();
} else {
return null;
}
}
public static Integer getNetworkRate(long networkOfferingId) {
return _configMgr.getNetworkRate(networkOfferingId);
}
public static Account getVlanAccount(long vlanId) {
return _configMgr.getVlanAccount(vlanId);
}
public static boolean isSecurityGroupEnabledInZone(long zoneId) {
DataCenterVO dc = _zoneDao.findById(zoneId);
if (dc == null) {
return false;
} else {
return dc.isSecurityGroupEnabled();
}
}
public static Long getDedicatedNetworkDomain(long networkId) {
return _networkMgr.getDedicatedNetworkDomain(networkId);
}
}
|
package SurveyBot;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.AnswerDataFactory;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xform.util.XFormUtils;
import org.javarosa.core.model.Constants;
import controller.FormController;
import controller.JavaRosaException;
import controller.FormController.InstanceMetadata;
/**
* @author Scott Wells
*
*/
public class SurveyModel {
private FormController formController;
private FormDef formDef;
/**
* Construct a suvey model given xform xml
* @param xformFilePath
*/
public SurveyModel(String xformFilePath){
FormDef formDef = createFormDef(xformFilePath);
this.formDef=formDef;
this.formController = initFormController(formDef);
if(!formController.currentPromptIsQuestion())
jumpToFirstAnswerableQuestion();
}
/**Returns an IAnswerData object which can be used to answer the current question
* @return
*/
public IAnswerData getAnswerContainer(){
return AnswerDataFactory.templateByDataType(formController.getQuestionPrompt().getControlType());
}
public String getPrompt(){
if(isGroup())
return getGroupPropmt();
if(isRepeatPrompt() || isRepeat() || isRepeatGroupJuncture())
return formController.getLastRepeatedGroupName();
FormEntryPrompt entryPrompt = formController.getQuestionPrompt();
return entryPrompt.getShortText();
}
private FormController initFormController(FormDef formDef) {
FormEntryModel formEntryModel = new FormEntryModel(formDef);
FormEntryController formEntryController = new FormEntryController(formEntryModel);
formEntryController.setLanguage(getLocale(0));
formEntryController.jumpToIndex(FormIndex.createBeginningOfFormIndex());
FormController formController = new FormController(new File("a path"), formEntryController, null);
return formController;
}
private String getLocale(int index) {
Localizer l = this.formDef.getLocalizer();
l.setDefaultLocale(l.getAvailableLocales()[index]);
l.setLocale(l.getAvailableLocales()[index]);
return l.getLocale();
}
private FormDef createFormDef(String xformFilePath){
FileInputStream inputStream;
try {
inputStream = new FileInputStream(xformFilePath);
} catch (FileNotFoundException e) {
throw new RuntimeException("Error: the file '" + xformFilePath
+ "' could not be found!");
}
return XFormUtils.getFormFromInputStream(inputStream);
}
private void jumpToFirstAnswerableQuestion(){
if(!formController.currentPromptIsQuestion())
jumpToNextScreenEvent();
}
/**
*Steps to the next question, will always dive into group questions, but will skip over repeats
*/
public void jumpToNextScreenEvent(){
formController.stepToNextEvent(true);
}
public boolean isChoiceQuestion(){
return formController.getQuestionPrompt().getDataType()==Constants.DATATYPE_CHOICE;
}
public boolean isMulitChoiceQuestion(){
return formController.getQuestionPrompt().getDataType()==Constants.DATATYPE_CHOICE_LIST;
}
public void stepIntoRepeat(){
formController.newRepeat();
}
private boolean isGroup(){
return formController.getEvent()== FormEntryController.EVENT_GROUP;
}
private boolean isQuestion(){
return formController.getEvent()== FormEntryController.EVENT_QUESTION;
}
private boolean isRepeat(){
return formController.getEvent()== FormEntryController.EVENT_REPEAT;
}
public boolean isRepeatPrompt(){
return formController.getEvent()== FormEntryController.EVENT_PROMPT_NEW_REPEAT;
}
public int getRepeatCount(){
return formController.getLastRepeatCount();
}
private boolean isRepeatGroupJuncture(){
return formController.getEvent()== FormEntryController.EVENT_REPEAT_JUNCTURE;
}
private String getGroupPropmt(){
return formController.getLastGroupText();
}
public boolean isEndOfSurvey(){
return formController.getEvent() == FormEntryController.EVENT_END_OF_FORM;
}
public void getQuestionInfo(){
System.out.print("Event Type: ");
switch(formController.getEvent()){
case FormEntryController.EVENT_GROUP:
System.out.println("EVENT_GROUP");
break;
case FormEntryController.EVENT_QUESTION:
System.out.println("EVENT_QUESTION");
IAnswerData answerTemplate = getAnswerContainer();
System.out.println("AnswerType: "+answerTemplate.getClass());
if(isChoiceQuestion())
System.out.println("DataType: CHOICE");
if(isMulitChoiceQuestion())
System.out.println("DataType: CHOICE_LIST");
break;
case FormEntryController.EVENT_REPEAT:
System.out.println("EVENT_REPEAT");
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
System.out.println("EVENT_PROMPT_NEW_REPEAT");
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
System.out.println("EVENT_REPEAT_JUNCTURE");
break;
case FormEntryController.EVENT_END_OF_FORM:
System.out.println("END_OF_FORM");
return;
}
System.out.println("Prompt: "+getPrompt());
}
}
|
package org.intermine.web;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.PrimaryKey;
import org.intermine.metadata.PrimaryKeyUtil;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.model.InterMineObject;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.util.SAXParser;
import org.intermine.util.TypeUtil;
import org.intermine.web.bag.IdUpgrader;
import org.intermine.web.bag.InterMineBag;
import org.intermine.web.bag.InterMineBagBinding;
import org.intermine.web.bag.InterMineIdBag;
import org.intermine.xml.full.FullRenderer;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemFactory;
import java.io.Reader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.xml.sax.InputSource;
/**
* Code for reading and writing Profile objects as XML.
*
* @author Kim Rutherford
*/
public class ProfileBinding
{
/**
* Convert a Profile to XML and write XML to given writer.
* @param profile the UserProfile
* @param os the ObjectStore to use when looking up the ids of objects in bags
* @param writer the XMLStreamWriter to write to
*/
public static void marshal(Profile profile, ObjectStore os,
XMLStreamWriter writer) {
marshal(profile, os, writer, true, true, true, true, true, false);
}
/**
* Convert a Profile to XML and write XML to given writer.
* @param profile the UserProfile
* @param os the ObjectStore to use when looking up the ids of objects in bags
* @param writer the XMLStreamWriter to write to
* @param writeQueries save saved queries
* @param writeTemplates write saved templates
* @param writeBags write saved bags
* @param writeTags write saved tags
* @param onlyConfigTags if true, only save tags that contain a ':'
*/
public static void marshal(Profile profile, ObjectStore os,
XMLStreamWriter writer,
boolean writePassword,
boolean writeQueries,
boolean writeTemplates,
boolean writeBags,
boolean writeTags,
boolean onlyConfigTags) {
try {
writer.writeStartElement("userprofile");
writer.writeAttribute("username", profile.getUsername());
if (writePassword) {
writer.writeAttribute("password", profile.getPassword());
}
if (writeBags) {
ItemFactory itemFactory = new ItemFactory(os.getModel());
Set idSet = new HashSet();
getProfileObjectIds(profile, os, idSet);
if (!idSet.isEmpty()) {
List objects = os.getObjectsByIds(idSet);
writer.writeStartElement("items");
Iterator objectsIter = objects.iterator();
while (objectsIter.hasNext()) {
ResultsRow rr = (ResultsRow) objectsIter.next();
InterMineObject o = (InterMineObject) rr.get(0);
Item item = itemFactory.makeItem(o);
FullRenderer.render(writer, item);
}
writer.writeEndElement();
}
writer.writeStartElement("bags");
for (Iterator i = profile.getSavedBags().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String bagName = (String) entry.getKey();
InterMineBag bag = (InterMineBag) entry.getValue();
InterMineBagBinding.marshal(bag, bagName, writer);
}
writer.writeEndElement();
} else {
writer.writeEmptyElement("items");
writer.writeEmptyElement("bags");
}
writer.writeStartElement("queries");
if (writeQueries) {
for (Iterator i = profile.getSavedQueries().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
SavedQuery query = (SavedQuery) entry.getValue();
SavedQueryBinding.marshal(query, writer);
}
}
writer.writeEndElement();
writer.writeStartElement("template-queries");
if (writeTemplates) {
for (Iterator i = profile.getSavedTemplates().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
TemplateQuery template = (TemplateQuery) entry.getValue();
TemplateQueryBinding.marshal(template, writer);
}
}
writer.writeEndElement();
writer.writeStartElement("tags");
if (writeTags) {
List tags = profile.getProfileManager().getTags(null, null, null,
profile.getUsername());
for (Iterator i = tags.iterator(); i.hasNext();) {
Tag tag = (Tag) i.next();
if (!onlyConfigTags || tag.getTagName().indexOf(":") >= 0) {
TagBinding.marshal(tag, writer);
}
}
}
writer.writeEndElement();
writer.writeEndElement();
} catch (XMLStreamException e) {
throw new RuntimeException("exception while marshalling profile", e);
} catch (ObjectStoreException e) {
throw new RuntimeException("exception while marshalling profile", e);
}
}
/**
* Get the ids of objects in all bags and all objects mentioned in primary keys of those
* items (recursively).
* @param profile read the object in the bags from this Profile
* @param os the ObjectStore to use when following references
* @param idsToSerialise object ids are added to this Set
*/
private static void getProfileObjectIds(Profile profile, ObjectStore os, Set idsToSerialise) {
for (Iterator i = profile.getSavedBags().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
InterMineBag bag = (InterMineBag) entry.getValue();
if (bag instanceof InterMineIdBag) {
Iterator iter = bag.iterator();
while (iter.hasNext()) {
Integer id = (Integer) iter.next();
InterMineObject object;
try {
object = os.getObjectById(id);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to find object for id: " + id, e);
}
getIdsFromObject(object, os.getModel(), idsToSerialise);
}
}
}
}
/**
* For the given object, add its ID and all IDs of all objects in any of its primary keys to
* idsToSerialise.
* @param object the InterMineObject to add
* @param model the Model to use for looking up ClassDescriptors
* @param idsToSerialise object ids are added to this Set
*/
protected static void getIdsFromObject(InterMineObject object, Model model,
Set idsToSerialise) {
idsToSerialise.add(object.getId());
Set cds = model.getClassDescriptorsForClass(object.getClass());
Iterator cdIter = cds.iterator();
while (cdIter.hasNext()) {
ClassDescriptor cd = (ClassDescriptor) cdIter.next();
Map primaryKeyMap = PrimaryKeyUtil.getPrimaryKeys(cd);
Iterator primaryKeyIter = primaryKeyMap.values().iterator();
while (primaryKeyIter.hasNext()) {
PrimaryKey pk = (PrimaryKey) primaryKeyIter.next();
Set fieldNames = pk.getFieldNames();
Iterator fieldNameIter = fieldNames.iterator();
while (fieldNameIter.hasNext()) {
String fieldName = (String) fieldNameIter.next();
FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName);
if (fd instanceof ReferenceDescriptor) {
InterMineObject referencedObject;
try {
referencedObject =
(InterMineObject) TypeUtil.getFieldValue(object, fieldName);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to access field " + fieldName
+ " in object: " + object);
}
if (referencedObject != null) {
// recurse
getIdsFromObject(referencedObject, model, idsToSerialise);
}
}
}
}
}
}
/**
* Read a Profile from an XML stream Reader. Note that Tags from the XML are stored immediately
* using the ProfileManager.
* @param reader contains the Profile XML
* @param profileManager the ProfileManager to pass to the Profile constructor
* @param os ObjectStore used to resolve object ids
* @return the new Profile
*/
public static Profile unmarshal(Reader reader, ProfileManager profileManager, ObjectStore os) {
try {
ProfileHandler profileHandler =
new ProfileHandler(profileManager, new IdUpgrader() {
public Set getNewIds(InterMineObject oldObject, ObjectStore os) {
throw new RuntimeException("Shouldn't call getNewIds() in a"
+ " running webapp");
}
});
SAXParser.parse(new InputSource(reader), profileHandler);
return profileHandler.getProfile();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
|
package org.intermine.web;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.PrimaryKey;
import org.intermine.metadata.PrimaryKeyUtil;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.model.InterMineObject;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.SAXParser;
import org.intermine.util.TypeUtil;
import org.intermine.web.bag.BagElement;
import org.intermine.web.bag.IdUpgrader;
import org.intermine.web.bag.InterMineBag;
import org.intermine.web.bag.InterMineBagBinding;
import org.intermine.xml.full.FullRenderer;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemFactory;
import java.io.Reader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
/**
* Code for reading and writing Profile objects as XML.
*
* @author Kim Rutherford
*/
public class ProfileBinding
{
private static final Logger LOG = Logger.getLogger(ProfileBinding.class);
/**
* Convert a Profile to XML and write XML to given writer.
* @param profile the UserProfile
* @param os the ObjectStore to use when looking up the ids of objects in bags
* @param writer the XMLStreamWriter to write to
*/
public static void marshal(Profile profile, ObjectStore os,
XMLStreamWriter writer) {
marshal(profile, os, writer, true, true, true, true, true, false);
}
/**
* Convert a Profile to XML and write XML to given writer.
* @param profile the UserProfile
* @param os the ObjectStore to use when looking up the ids of objects in bags
* @param writer the XMLStreamWriter to write to
* @param writeUserAndPassword write username and password
* @param writeQueries save saved queries
* @param writeTemplates write saved templates
* @param writeBags write saved bags
* @param writeTags write saved tags
* @param onlyConfigTags if true, only save tags that contain a ':'
*/
public static void marshal(Profile profile, ObjectStore os,
XMLStreamWriter writer,
boolean writeUserAndPassword,
boolean writeQueries,
boolean writeTemplates,
boolean writeBags,
boolean writeTags,
boolean onlyConfigTags) {
try {
writer.writeStartElement("userprofile");
if (writeUserAndPassword) {
writer.writeAttribute("password", profile.getPassword());
writer.writeAttribute("username", profile.getUsername());
}
if (writeBags) {
ItemFactory itemFactory = new ItemFactory(os.getModel());
Set idSet = new HashSet();
getProfileObjectIds(profile, os, idSet);
if (!idSet.isEmpty()) {
List objects = os.getObjectsByIds(idSet);
writer.writeStartElement("items");
Iterator objectsIter = objects.iterator();
while (objectsIter.hasNext()) {
ResultsRow rr = (ResultsRow) objectsIter.next();
InterMineObject o = (InterMineObject) rr.get(0);
Item item = itemFactory.makeItemImpl(o, false);
FullRenderer.renderImpl(writer, item, false);
}
writer.writeEndElement();
}
writer.writeStartElement("bags");
for (Iterator i = profile.getSavedBags().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String bagName = (String) entry.getKey();
InterMineBag bag = (InterMineBag) entry.getValue();
if (bag != null) {
InterMineBagBinding.marshal(bag, bagName, writer);
} else {
LOG.error("bag was null for bagName: " + bagName
+ " username: " + profile.getUsername());
}
}
writer.writeEndElement();
} else {
writer.writeEmptyElement("items");
writer.writeEmptyElement("bags");
}
writer.writeStartElement("queries");
if (writeQueries) {
for (Iterator i = profile.getSavedQueries().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
SavedQuery query = (SavedQuery) entry.getValue();
SavedQueryBinding.marshal(query, writer);
}
}
writer.writeEndElement();
writer.writeStartElement("template-queries");
if (writeTemplates) {
for (Iterator i = profile.getSavedTemplates().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
TemplateQuery template = (TemplateQuery) entry.getValue();
TemplateQueryBinding.marshal(template, writer);
}
}
writer.writeEndElement();
writer.writeStartElement("tags");
if (writeTags) {
List tags = profile.getProfileManager().getTags(null, null, null,
profile.getUsername());
for (Iterator i = tags.iterator(); i.hasNext();) {
Tag tag = (Tag) i.next();
if (!onlyConfigTags || tag.getTagName().indexOf(":") >= 0) {
TagBinding.marshal(tag, writer);
}
}
}
writer.writeEndElement();
} catch (XMLStreamException e) {
throw new RuntimeException("exception while marshalling profile", e);
} catch (ObjectStoreException e) {
throw new RuntimeException("exception while marshalling profile", e);
}
}
/**
* Get the ids of objects in all bags and all objects mentioned in primary keys of those
* items (recursively).
* @param profile read the object in the bags from this Profile
* @param os the ObjectStore to use when following references
* @param idsToSerialise object ids are added to this Set
*/
private static void getProfileObjectIds(Profile profile, ObjectStore os, Set idsToSerialise) {
List idsToPreFetch = new ArrayList();
for (Iterator i = profile.getSavedBags().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
InterMineBag bag = (InterMineBag) entry.getValue();
Iterator iter = bag.iterator();
while (iter.hasNext()) {
BagElement bagElement = (BagElement) iter.next();
idsToPreFetch.add(bagElement.getId());
}
}
// pre-fetch objects from all bags into the cache
try {
os.getObjectsByIds(idsToPreFetch);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to find object for ids: " + idsToPreFetch, e);
}
for (Iterator i = profile.getSavedBags().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
InterMineBag bag = (InterMineBag) entry.getValue();
Iterator iter = bag.iterator();
while (iter.hasNext()) {
BagElement bagElement = (BagElement) iter.next();
InterMineObject object;
Integer id = bagElement.getId();
try {
object = os.getObjectById(id);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to find object for id: " + id, e);
}
if (object == null) {
throw new RuntimeException("Unable to find object for id: " + id);
}
getIdsFromObject(object, os.getModel(), idsToSerialise);
}
}
}
/**
* For the given object, add its ID and all IDs of all objects in any of its primary keys to
* idsToSerialise.
* @param object the InterMineObject to add
* @param model the Model to use for looking up ClassDescriptors
* @param idsToSerialise object ids are added to this Set
*/
protected static void getIdsFromObject(InterMineObject object, Model model,
Set idsToSerialise) {
idsToSerialise.add(object.getId());
Set cds = model.getClassDescriptorsForClass(object.getClass());
Iterator cdIter = cds.iterator();
while (cdIter.hasNext()) {
ClassDescriptor cd = (ClassDescriptor) cdIter.next();
Map primaryKeyMap = PrimaryKeyUtil.getPrimaryKeys(cd);
Iterator primaryKeyIter = primaryKeyMap.values().iterator();
while (primaryKeyIter.hasNext()) {
PrimaryKey pk = (PrimaryKey) primaryKeyIter.next();
Set fieldNames = pk.getFieldNames();
Iterator fieldNameIter = fieldNames.iterator();
while (fieldNameIter.hasNext()) {
String fieldName = (String) fieldNameIter.next();
FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName);
if (fd instanceof ReferenceDescriptor) {
InterMineObject referencedObject;
try {
referencedObject =
(InterMineObject) TypeUtil.getFieldValue(object, fieldName);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to access field " + fieldName
+ " in object: " + object);
}
if (referencedObject != null) {
// recurse
getIdsFromObject(referencedObject, model, idsToSerialise);
}
}
}
}
}
}
/**
* Read a Profile from an XML stream Reader. Note that Tags from the XML are stored immediately
* using the ProfileManager.
* @param reader contains the Profile XML
* @param profileManager the ProfileManager to pass to the Profile constructor
* @param os ObjectStore used to resolve object ids
* @param username default username - used if there is no username in the XML
* @param password default password
* @param tags a set to populate with user tags
* @param classKeys class key fields in model
* @return the new Profile
*/
public static Profile unmarshal(Reader reader, ProfileManager profileManager, ObjectStore os,
String username, String password, Set tags, Map classKeys) {
try {
IdUpgrader idUpgrader = new IdUpgrader() {
public Set getNewIds(InterMineObject oldObject, ObjectStore os) {
throw new RuntimeException("Shouldn't call getNewIds() in a"
+ " running webapp");
}
};
ProfileHandler profileHandler =
new ProfileHandler(profileManager, idUpgrader, username, password, tags, classKeys);
SAXParser.parse(new InputSource(reader), profileHandler);
return profileHandler.getProfile();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
|
package jadx.gui.ui.dialog;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.gui.treemodel.JNode;
import jadx.gui.treemodel.JResSearchNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.TabbedPane;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.ui.panel.ProgressPanel;
import jadx.gui.utils.CacheObject;
import jadx.gui.utils.JNodeCache;
import jadx.gui.utils.JumpPosition;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.NodeLabel;
import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
public abstract class CommonSearchDialog extends JFrame {
private static final Logger LOG = LoggerFactory.getLogger(CommonSearchDialog.class);
private static final long serialVersionUID = 8939332306115370276L;
protected final transient TabbedPane tabbedPane;
protected final transient CacheObject cache;
protected final transient MainWindow mainWindow;
protected final transient Font codeFont;
protected final transient String windowTitle;
protected ResultsModel resultsModel;
protected ResultsTable resultsTable;
protected JLabel resultsInfoLabel;
protected JLabel warnLabel;
protected ProgressPanel progressPane;
private SearchContext highlightContext;
public CommonSearchDialog(MainWindow mainWindow, String title) {
this.mainWindow = mainWindow;
this.tabbedPane = mainWindow.getTabbedPane();
this.cache = mainWindow.getCacheObject();
this.codeFont = mainWindow.getSettings().getFont();
this.windowTitle = title;
UiUtils.setWindowIcons(this);
updateTitle("");
}
protected abstract void openInit();
protected abstract void loadFinished();
protected abstract void loadStart();
public void loadWindowPos() {
if (!mainWindow.getSettings().loadWindowPos(this)) {
setSize(800, 500);
}
}
private void updateTitle(String searchText) {
if (searchText == null || searchText.isEmpty() || searchText.trim().isEmpty()) {
setTitle(windowTitle);
} else {
setTitle(windowTitle + ": " + searchText);
}
}
public void updateHighlightContext(String text, boolean caseSensitive, boolean regexp) {
updateTitle(text);
highlightContext = new SearchContext(text);
highlightContext.setMatchCase(caseSensitive);
highlightContext.setRegularExpression(regexp);
highlightContext.setMarkAll(true);
}
public void disableHighlight() {
highlightContext = null;
}
protected void registerInitOnOpen() {
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
SwingUtilities.invokeLater(CommonSearchDialog.this::openInit);
}
});
}
protected void openSelectedItem() {
JNode node = getSelectedNode();
if (node == null) {
return;
}
openItem(node);
}
protected void openItem(JNode node) {
if (node instanceof JResSearchNode) {
JumpPosition jmpPos = new JumpPosition(((JResSearchNode) node).getResNode(), node.getPos());
tabbedPane.codeJump(jmpPos);
} else {
tabbedPane.codeJump(node);
}
if (!mainWindow.getSettings().getKeepCommonDialogOpen()) {
dispose();
}
}
@Nullable
private JNode getSelectedNode() {
try {
int selectedId = resultsTable.getSelectedRow();
if (selectedId == -1 || selectedId >= resultsTable.getRowCount()) {
return null;
}
return (JNode) resultsModel.getValueAt(selectedId, 0);
} catch (Exception e) {
LOG.error("Failed to get results table selected object", e);
return null;
}
}
@Override
public void dispose() {
mainWindow.getSettings().saveWindowPos(this);
super.dispose();
}
protected void initCommon() {
UiUtils.addEscapeShortCutToDispose(this);
}
@NotNull
protected JPanel initButtonsPanel() {
progressPane = new ProgressPanel(mainWindow, false);
JButton cancelButton = new JButton(NLS.str("search_dialog.cancel"));
cancelButton.addActionListener(event -> dispose());
JButton openBtn = new JButton(NLS.str("search_dialog.open"));
openBtn.addActionListener(event -> openSelectedItem());
getRootPane().setDefaultButton(openBtn);
JCheckBox cbKeepOpen = new JCheckBox(NLS.str("search_dialog.keep_open"));
cbKeepOpen.setSelected(mainWindow.getSettings().getKeepCommonDialogOpen());
cbKeepOpen.addActionListener(e -> {
mainWindow.getSettings().setKeepCommonDialogOpen(cbKeepOpen.isSelected());
mainWindow.getSettings().sync();
});
cbKeepOpen.setAlignmentY(Component.CENTER_ALIGNMENT);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(cbKeepOpen);
buttonPane.add(Box.createRigidArea(new Dimension(15, 0)));
buttonPane.add(progressPane);
buttonPane.add(Box.createRigidArea(new Dimension(5, 0)));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(openBtn);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(cancelButton);
return buttonPane;
}
protected JPanel initResultsTable() {
ResultsTableCellRenderer renderer = new ResultsTableCellRenderer();
resultsModel = new ResultsModel();
resultsModel.addTableModelListener(e -> updateProgressLabel(false));
resultsTable = new ResultsTable(resultsModel, renderer);
resultsTable.setShowHorizontalLines(false);
resultsTable.setDragEnabled(false);
resultsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTable.setColumnSelectionAllowed(false);
resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
resultsTable.setAutoscrolls(false);
resultsTable.setDefaultRenderer(Object.class, renderer);
Enumeration<TableColumn> columns = resultsTable.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn column = columns.nextElement();
column.setCellRenderer(renderer);
}
resultsTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
openSelectedItem();
}
}
});
resultsTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
openSelectedItem();
}
}
});
// override copy action to copy long string of node column
resultsTable.getActionMap().put("copy", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JNode selectedNode = getSelectedNode();
if (selectedNode != null) {
UiUtils.copyToClipboard(selectedNode.makeLongString());
}
}
});
warnLabel = new JLabel();
warnLabel.setForeground(Color.RED);
warnLabel.setVisible(false);
JScrollPane scroll = new JScrollPane(resultsTable, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
resultsInfoLabel = new JLabel("");
resultsInfoLabel.setFont(mainWindow.getSettings().getFont());
JPanel resultsActionsPanel = new JPanel();
resultsActionsPanel.setLayout(new BoxLayout(resultsActionsPanel, BoxLayout.LINE_AXIS));
resultsActionsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
addResultsActions(resultsActionsPanel);
JPanel resultsPanel = new JPanel();
resultsPanel.setLayout(new BoxLayout(resultsPanel, BoxLayout.PAGE_AXIS));
resultsPanel.add(warnLabel, BorderLayout.PAGE_START);
resultsPanel.add(scroll, BorderLayout.CENTER);
resultsPanel.add(resultsActionsPanel, BorderLayout.PAGE_END);
return resultsPanel;
}
protected void addResultsActions(JPanel resultsActionsPanel) {
resultsActionsPanel.add(Box.createRigidArea(new Dimension(20, 0)));
resultsActionsPanel.add(resultsInfoLabel);
resultsActionsPanel.add(Box.createHorizontalGlue());
}
protected void updateProgressLabel(boolean complete) {
int count = resultsModel.getRowCount();
String statusText;
if (complete) {
statusText = NLS.str("search_dialog.results_complete", count);
} else {
statusText = NLS.str("search_dialog.results_incomplete", count);
}
resultsInfoLabel.setText(statusText);
}
protected void showSearchState() {
resultsInfoLabel.setText(NLS.str("search_dialog.tip_searching") + "...");
}
protected static final class ResultsTable extends JTable {
private static final long serialVersionUID = 3901184054736618969L;
private final transient ResultsModel model;
public ResultsTable(ResultsModel resultsModel, ResultsTableCellRenderer renderer) {
super(resultsModel);
this.model = resultsModel;
setRowHeight(renderer.getMaxRowHeight());
}
public void initColumnWidth() {
int columnCount = getColumnCount();
int width = getParent().getWidth();
int colWidth = model.isAddDescColumn() ? width / 2 : width;
columnModel.getColumn(0).setPreferredWidth(colWidth);
for (int col = 1; col < columnCount; col++) {
columnModel.getColumn(col).setPreferredWidth(width);
}
}
public void updateTable() {
UiUtils.uiThreadGuard();
int rowCount = getRowCount();
if (rowCount == 0) {
updateUI();
return;
}
long start = System.currentTimeMillis();
int width = getParent().getWidth();
TableColumn firstColumn = columnModel.getColumn(0);
if (model.isAddDescColumn()) {
if (firstColumn.getWidth() > width * 0.8) {
// first column too big and hide second column, resize it
firstColumn.setPreferredWidth(width / 2);
}
TableColumn secondColumn = columnModel.getColumn(1);
int columnMaxWidth = width * 2; // set big enough size to skip per row check
if (secondColumn.getWidth() < columnMaxWidth) {
secondColumn.setPreferredWidth(columnMaxWidth);
}
} else {
firstColumn.setPreferredWidth(width);
}
updateUI();
if (LOG.isDebugEnabled()) {
LOG.debug("Update results table in {}ms, count: {}", System.currentTimeMillis() - start, rowCount);
}
}
@Override
public Object getValueAt(int row, int column) {
return model.getValueAt(row, column);
}
}
protected static final class ResultsModel extends AbstractTableModel {
private static final long serialVersionUID = -7821286846923903208L;
private static final String[] COLUMN_NAMES = { NLS.str("search_dialog.col_node"), NLS.str("search_dialog.col_code") };
private final transient List<JNode> rows = new ArrayList<>();
private transient boolean addDescColumn;
public void addAll(Collection<? extends JNode> nodes) {
rows.addAll(nodes);
if (!addDescColumn) {
for (JNode row : rows) {
if (row.hasDescString()) {
addDescColumn = true;
break;
}
}
}
}
public void clear() {
addDescColumn = false;
rows.clear();
}
public void sort() {
Collections.sort(rows);
}
public boolean isAddDescColumn() {
return addDescColumn;
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int index) {
return COLUMN_NAMES[index];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rows.get(rowIndex);
}
}
protected final class ResultsTableCellRenderer implements TableCellRenderer {
private final NodeLabel label;
private final RSyntaxTextArea codeArea;
private final NodeLabel emptyLabel;
private final Color codeSelectedColor;
private final Color codeBackground;
public ResultsTableCellRenderer() {
codeArea = AbstractCodeArea.getDefaultArea(mainWindow);
codeArea.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
codeArea.setRows(1);
codeBackground = codeArea.getBackground();
codeSelectedColor = codeArea.getSelectionColor();
label = new NodeLabel();
label.setOpaque(true);
label.setFont(codeArea.getFont());
label.setHorizontalAlignment(SwingConstants.LEFT);
emptyLabel = new NodeLabel();
emptyLabel.setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object obj,
boolean isSelected, boolean hasFocus, int row, int column) {
if (obj == null || table == null) {
return emptyLabel;
}
Component comp = makeCell((JNode) obj, column);
updateSelection(table, comp, column, isSelected);
return comp;
}
private void updateSelection(JTable table, Component comp, int column, boolean isSelected) {
if (column == 1) {
if (isSelected) {
comp.setBackground(codeSelectedColor);
} else {
comp.setBackground(codeBackground);
}
} else {
if (isSelected) {
comp.setBackground(table.getSelectionBackground());
comp.setForeground(table.getSelectionForeground());
} else {
comp.setBackground(table.getBackground());
comp.setForeground(table.getForeground());
}
}
}
private Component makeCell(JNode node, int column) {
if (column == 0) {
label.disableHtml(node.disableHtml());
label.setText(node.makeLongStringHtml());
label.setToolTipText(node.getTooltip());
label.setIcon(node.getIcon());
return label;
}
if (!node.hasDescString()) {
return emptyLabel;
}
codeArea.setSyntaxEditingStyle(node.getSyntaxName());
String descStr = node.makeDescString();
codeArea.setText(descStr);
codeArea.setColumns(descStr.length() + 1);
if (highlightContext != null) {
SearchEngine.markAll(codeArea, highlightContext);
}
return codeArea;
}
public int getMaxRowHeight() {
label.setText("Text");
codeArea.setText("Text");
return Math.max(getCompHeight(label), getCompHeight(codeArea));
}
private int getCompHeight(Component comp) {
return Math.max(comp.getHeight(), comp.getPreferredSize().height);
}
}
void progressStartCommon() {
progressPane.setIndeterminate(true);
progressPane.setVisible(true);
warnLabel.setVisible(false);
}
void progressFinishedCommon() {
progressPane.setVisible(false);
}
protected JNodeCache getNodeCache() {
return mainWindow.getCacheObject().getNodeCache();
}
}
|
package com.wavefront.ingester;
import java.util.Map;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.annotation.Nullable;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.ChannelInboundHandler;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
/**
* Ingester thread that sets up decoders and a command handler to listen for metrics on a port.
* @author Mike McLaughlin (mike@wavefront.com)
*/
public class StreamIngester implements Runnable {
protected static final Logger logger = Logger.getLogger(StreamIngester.class.getName());
public interface FrameDecoderFactory {
ChannelInboundHandler getDecoder();
}
private final ChannelHandler commandHandler;
private final int listeningPort;
private final FrameDecoderFactory frameDecoderFactory;
@Nullable
protected Map<ChannelOption<?>, ?> parentChannelOptions;
@Nullable
protected Map<ChannelOption<?>, ?> childChannelOptions;
public StreamIngester(FrameDecoderFactory frameDecoderFactory,
ChannelHandler commandHandler, int port) {
this.listeningPort = port;
this.commandHandler = commandHandler;
this.frameDecoderFactory = frameDecoderFactory;
}
public StreamIngester withParentChannelOptions(Map<ChannelOption<?>, ?> parentChannelOptions) {
this.parentChannelOptions = parentChannelOptions;
return this;
}
public StreamIngester withChildChannelOptions(Map<ChannelOption<?>, ?> childChannelOptions) {
this.childChannelOptions = childChannelOptions;
return this;
}
public void run() {
// Configure the server.
ServerBootstrap b = new ServerBootstrap();
NioEventLoopGroup parentGroup = new NioEventLoopGroup(1);
NioEventLoopGroup childGroup = new NioEventLoopGroup();
try {
b.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.localAddress(listeningPort)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frame decoder", frameDecoderFactory.getDecoder());
pipeline.addLast("byte array decoder", new ByteArrayDecoder());
pipeline.addLast(commandHandler);
}
});
if (parentChannelOptions != null) {
for (Map.Entry<ChannelOption<?>, ?> entry : parentChannelOptions.entrySet())
{
b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
}
}
if (childChannelOptions != null) {
for (Map.Entry<ChannelOption<?>, ?> entry : childChannelOptions.entrySet())
{
b.childOption((ChannelOption<Object>) entry.getKey(), entry.getValue());
}
}
// Start the server.
ChannelFuture f = b.bind().sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} catch (final InterruptedException e) {
logger.log(Level.WARNING, "Interrupted");
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
logger.info("Listener on port " + String.valueOf(listeningPort) + " shut down");
}
}
}
|
package org.voltdb.jni;
import junit.framework.TestCase;
import org.voltdb.LegacyHashinator;
import org.voltdb.ParameterSet;
import org.voltdb.TheHashinator.HashinatorConfig;
import org.voltdb.TheHashinator.HashinatorType;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.benchmark.tpcc.TPCCProjectBuilder;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.PlanFragment;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Statement;
import org.voltdb.planner.ActivePlanRepository;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
public class TestFragmentProgressUpdate extends TestCase {
public void testJNIFragmentProgressUpdate() throws Exception {
m_ee = new ExecutionEngineJNI(
CLUSTER_ID,
NODE_ID,
0,
0,
"",
100,
new HashinatorConfig(HashinatorType.LEGACY,
LegacyHashinator.getConfigureBytes(1),
0,
0));
testFragmentProgressUpdate(m_ee);
}
// test we reset the statistic when start a new fragment
public void testJNIFragmentProgressUpdate2() throws Exception {
m_ee = new ExecutionEngineJNI(
CLUSTER_ID,
NODE_ID,
0,
0,
"",
100,
new HashinatorConfig(HashinatorType.LEGACY,
LegacyHashinator.getConfigureBytes(1),
0,
0));
testTwoUpdates(m_ee);
}
// test sometimes the peak is larger than the current
public void testJNIFragmentProgressUpdate3() throws Exception {
m_ee = new ExecutionEngineJNI(
CLUSTER_ID,
NODE_ID,
0,
0,
"",
100,
new HashinatorConfig(HashinatorType.LEGACY,
LegacyHashinator.getConfigureBytes(1),
0,
0));
testPeakLargerThanCurr(m_ee);
}
/*public void testIPCFragmentProgressUpdate() throws Exception {
m_ee = new ExecutionEngineIPC(
CLUSTER_ID,
NODE_ID,
0,
0,
"",
100,
BackendTarget.NATIVE_EE_IPC,
10000,
new HashinatorConfig(HashinatorType.LEGACY,
LegacyHashinator.getConfigureBytes(1),
0,
0));
testFragmentProgressUpdate(m_ee);
}*/
void testFragmentProgressUpdate(ExecutionEngine ee) throws Exception {
m_ee.loadCatalog( 0, catalog.serialize());
tableSize = 5001;
longOpThreshold = 10000;
warehousedata.clearRowData();
for (int i = 0; i < tableSize; ++i) {
warehousedata.addRow(i, "name" + i, "st1", "st2", "city", "ST", "zip", 0, 0);
}
m_ee.loadTable(WAREHOUSE_TABLEID, warehousedata, 0, 0, false, Long.MAX_VALUE);
assertEquals(tableSize, m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
System.out.println("Rows loaded to table "+m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
Statement selectStmt = testProc.getStatements().getIgnoreCase("warehouse_select");
PlanFragment selectBottomFrag = null;
int i = 0;
// this kinda assumes the right order
for (PlanFragment f : selectStmt.getFragments()) {
if (i != 0) selectBottomFrag = f;
i++;
}
// populate plan cache
ActivePlanRepository.clear();
ActivePlanRepository.addFragmentForTest(
CatalogUtil.getUniqueIdForFragment(selectBottomFrag),
Encoder.decodeBase64AndDecompressToBytes(selectBottomFrag.getPlannodetree()));
ParameterSet params = ParameterSet.emptyParameterSet();
m_ee.executePlanFragments(
1,
new long[] { CatalogUtil.getUniqueIdForFragment(selectBottomFrag) },
null,
new ParameterSet[] { params },
3, 2, 42, Long.MAX_VALUE);
// Like many fully successful operations, a single row fetch counts as 2 logical row operations,
// one for locating the row and one for retrieving it.
assertEquals(1, m_ee.m_callsFromEE);
assertEquals(longOpThreshold, m_ee.m_lastTuplesAccessed);
assertTrue(450000 < m_ee.m_currMemoryInBytes);
assertTrue(550000 > m_ee.m_currMemoryInBytes);
assertTrue(450000 < m_ee.m_peakMemoryInBytes);
assertTrue(550000 > m_ee.m_peakMemoryInBytes);
assertTrue(m_ee.m_peakMemoryInBytes >= m_ee.m_currMemoryInBytes);
}
void testTwoUpdates(ExecutionEngine ee) throws Exception {
m_ee.loadCatalog( 0, catalog.serialize());
tableSize = 10000;
longOpThreshold = 10000;
warehousedata.clearRowData();
for (int i = 0; i < tableSize; ++i) {
warehousedata.addRow(i, "name" + i, "st1", "st2", "city", "ST", "zip", 0, 0);
}
m_ee.loadTable(WAREHOUSE_TABLEID, warehousedata, 0, 0, false, Long.MAX_VALUE);
assertEquals(tableSize, m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
System.out.println("Rows loaded to table "+m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
Statement selectStmt = testProc.getStatements().getIgnoreCase("warehouse_select");
PlanFragment selectBottomFrag = null;
// delete 5000 records
// I have no idea what's going on here, and just copy code from the above methods
int i = 0;
// this kinda assumes the right order
for (PlanFragment f : selectStmt.getFragments()) {
if (i != 0) selectBottomFrag = f;
i++;
}
// populate plan cache
ActivePlanRepository.clear();
ActivePlanRepository.addFragmentForTest(
CatalogUtil.getUniqueIdForFragment(selectBottomFrag),
Encoder.decodeBase64AndDecompressToBytes(selectBottomFrag.getPlannodetree()));
ParameterSet params = ParameterSet.emptyParameterSet();
m_ee.executePlanFragments(
1,
new long[] { CatalogUtil.getUniqueIdForFragment(selectBottomFrag) },
null,
new ParameterSet[] { params },
3, 2, 42, Long.MAX_VALUE);
// Like many fully successful operations, a single row fetch counts as 2 logical row operations,
// one for locating the row and one for retrieving it.
assertEquals(2, m_ee.m_callsFromEE);
assertEquals(longOpThreshold * m_ee.m_callsFromEE, m_ee.m_lastTuplesAccessed);
assertTrue(900000 < m_ee.m_currMemoryInBytes);
assertTrue(1100000 > m_ee.m_currMemoryInBytes);
assertTrue(900000 < m_ee.m_peakMemoryInBytes);
assertTrue(1100000 > m_ee.m_peakMemoryInBytes);
assertTrue(m_ee.m_peakMemoryInBytes >= m_ee.m_currMemoryInBytes);
long previousMemoryInBytes = m_ee.m_currMemoryInBytes;
long previousPeakMemory = m_ee.m_peakMemoryInBytes;
Statement deleteStmt = testProc.getStatements().getIgnoreCase("warehouse_del_half");
assertNotNull(deleteStmt);
PlanFragment deleteBottomFrag = null;
int j = 0;
// this kinda assumes the right order
for (PlanFragment f : deleteStmt.getFragments()) {
if (j != 0) deleteBottomFrag = f;
j++;
}
// populate plan cache
ActivePlanRepository.clear();
ActivePlanRepository.addFragmentForTest(
CatalogUtil.getUniqueIdForFragment(deleteBottomFrag),
Encoder.decodeBase64AndDecompressToBytes(deleteBottomFrag.getPlannodetree()));
params = ParameterSet.emptyParameterSet();
m_ee.executePlanFragments(
1,
new long[] { CatalogUtil.getUniqueIdForFragment(deleteBottomFrag) },
null,
new ParameterSet[] { params },
3, 2, 42, Long.MAX_VALUE);
// populate plan cache
ActivePlanRepository.clear();
ActivePlanRepository.addFragmentForTest(
CatalogUtil.getUniqueIdForFragment(selectBottomFrag),
Encoder.decodeBase64AndDecompressToBytes(selectBottomFrag.getPlannodetree()));
params = ParameterSet.emptyParameterSet();
m_ee.executePlanFragments(
1,
new long[] { CatalogUtil.getUniqueIdForFragment(selectBottomFrag) },
null,
new ParameterSet[] { params },
3, 2, 42, Long.MAX_VALUE);
assertTrue(m_ee.m_callsFromEE > 2);
// here the m_lastTuplesAccessed is just the same as threshold, since we start a new fragment
assertEquals(longOpThreshold, m_ee.m_lastTuplesAccessed);
assertTrue(450000 < m_ee.m_currMemoryInBytes);
assertTrue(550000 > m_ee.m_currMemoryInBytes);
assertTrue(450000 < m_ee.m_peakMemoryInBytes);
assertTrue(550000 > m_ee.m_peakMemoryInBytes);
assertTrue(m_ee.m_peakMemoryInBytes >= m_ee.m_currMemoryInBytes);
// Although it is true, but I don't think we should compare the memory usage here.
//assertTrue(m_ee.m_currMemoryInBytes < previousMemoryInBytes);
assertTrue(m_ee.m_peakMemoryInBytes < previousPeakMemory);
}
void testPeakLargerThanCurr(ExecutionEngine ee) throws Exception {
m_ee.loadCatalog( 0, catalog.serialize());
tableSize = 20000;
longOpThreshold = 10000;
warehousedata.clearRowData();
for (int i = 0; i < tableSize; ++i) {
warehousedata.addRow(i, "name" + i, "st1", "st2", "city", "ST", "zip", 0, 0);
}
m_ee.loadTable(WAREHOUSE_TABLEID, warehousedata, 0, 0, false, Long.MAX_VALUE);
assertEquals(tableSize, m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
System.out.println("Rows loaded to table "+m_ee.serializeTable(WAREHOUSE_TABLEID).getRowCount());
Procedure testProc = procedures.getIgnoreCase("FragmentUpdateTestProcedure");
Statement selectStmt = testProc.getStatements().getIgnoreCase("warehouse_join");
PlanFragment selectBottomFrag = null;
// delete 5000 records
// I have no idea what's going on here, and just copy code from the above methods
int i = 0;
// this kinda assumes the right order
for (PlanFragment f : selectStmt.getFragments()) {
if (i != 0) selectBottomFrag = f;
i++;
}
// populate plan cache
ActivePlanRepository.clear();
ActivePlanRepository.addFragmentForTest(
CatalogUtil.getUniqueIdForFragment(selectBottomFrag),
Encoder.decodeBase64AndDecompressToBytes(selectBottomFrag.getPlannodetree()));
ParameterSet params = ParameterSet.emptyParameterSet();
m_ee.executePlanFragments(
1,
new long[] { CatalogUtil.getUniqueIdForFragment(selectBottomFrag) },
null,
new ParameterSet[] { params },
3, 2, 42, Long.MAX_VALUE);
// If want to see the stats, please uncomment the following line.
// It is '8 393216 262144' on my machine.
//System.out.println(m_ee.m_callsFromEE +" " + m_ee.m_peakMemoryInBytes + " "+ m_ee.m_currMemoryInBytes);
assertEquals(longOpThreshold * m_ee.m_callsFromEE, m_ee.m_lastTuplesAccessed);
assertTrue(m_ee.m_peakMemoryInBytes > m_ee.m_currMemoryInBytes);
}
private ExecutionEngine m_ee;
private static final int CLUSTER_ID = 2;
private static final long NODE_ID = 1;
private int tableSize;
private int longOpThreshold;
private VoltTable warehousedata;
private TPCCProjectBuilder builder;
private Catalog catalog;
private int WAREHOUSE_TABLEID;
private Cluster cluster;
private CatalogMap<Procedure> procedures;
private Procedure testProc;
@Override
protected void setUp() throws Exception {
super.setUp();
VoltDB.instance().readBuildInfo("Test");
warehousedata = new VoltTable(
new VoltTable.ColumnInfo("W_ID", VoltType.SMALLINT),
new VoltTable.ColumnInfo("W_NAME", VoltType.STRING),
new VoltTable.ColumnInfo("W_STREET_1", VoltType.STRING),
new VoltTable.ColumnInfo("W_STREET_2", VoltType.STRING),
new VoltTable.ColumnInfo("W_CITY", VoltType.STRING),
new VoltTable.ColumnInfo("W_STATE", VoltType.STRING),
new VoltTable.ColumnInfo("W_ZIP", VoltType.STRING),
new VoltTable.ColumnInfo("W_TAX", VoltType.FLOAT),
new VoltTable.ColumnInfo("W_YTD", VoltType.FLOAT)
);
builder = new TPCCProjectBuilder();
catalog = builder.createTPCCSchemaCatalog();
WAREHOUSE_TABLEID = catalog.getClusters().get("cluster").getDatabases().
get("database").getTables().get("WAREHOUSE").getRelativeIndex();
cluster = catalog.getClusters().get("cluster");
procedures = cluster.getDatabases().get("database").getProcedures();
testProc = procedures.getIgnoreCase("FragmentUpdateTestProcedure");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
m_ee.release();
m_ee = null;
}
}
|
package alluxio.shell.command;
import alluxio.AlluxioURI;
import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.shell.AbstractAlluxioShellTest;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests the "pin" and "unpin" commands.
*/
public class PinCommandTest extends AbstractAlluxioShellTest {
/**
* Tests the "pin" and "unpin" commands. Creates a file and tests if unpinning it , then pinning
* it and finally unpinning
*/
@Test
public void setIsPinnedTest() throws Exception {
AlluxioURI filePath = new AlluxioURI("/testFile");
FileSystemTestUtils.createByteFile(mFileSystem, filePath, WriteType.MUST_CACHE, 1);
// Ensure that the file exists
Assert.assertTrue(fileExists(filePath));
// Unpin an unpinned file
Assert.assertEquals(0, mFsShell.run("unpin", filePath.toString()));
Assert.assertFalse(mFileSystem.getStatus(filePath).isPinned());
// Pin the file
Assert.assertEquals(0, mFsShell.run("pin", filePath.toString()));
Assert.assertTrue(mFileSystem.getStatus(filePath).isPinned());
// Unpin the file
Assert.assertEquals(0, mFsShell.run("unpin", filePath.toString()));
Assert.assertFalse(mFileSystem.getStatus(filePath).isPinned());
}
/**
* Tests pinned files are not evicted when Alluxio reaches memory limit. This test case creates
* three files, each file is half the size of the cluster's capacity. The three files are added
* sequentially to the cluster, the first file is pinned. When the third file is added, the two
* previous files have already occupied the whole capacity, so one file needs to be evicted to
* spare space for the third file. Since the first file is pinned, it will not be evicted, so only
* the second file will be evicted.
*/
@Test
public void setPinTest() throws Exception {
AlluxioURI filePathA = new AlluxioURI("/testFileA");
AlluxioURI filePathB = new AlluxioURI("/testFileB");
AlluxioURI filePathC = new AlluxioURI("/testFileC");
int fileSize = SIZE_BYTES / 2;
FileSystemTestUtils.createByteFile(mFileSystem, filePathA, WriteType.MUST_CACHE, fileSize);
Assert.assertTrue(fileExists(filePathA));
Assert.assertEquals(0, mFsShell.run("pin", filePathA.toString()));
FileSystemTestUtils.createByteFile(mFileSystem, filePathB, WriteType.MUST_CACHE, fileSize);
Assert.assertTrue(fileExists(filePathB));
Assert.assertEquals(0, mFsShell.run("unpin", filePathB.toString()));
FileSystemTestUtils.createByteFile(mFileSystem, filePathC, WriteType.MUST_CACHE, fileSize);
Assert.assertTrue(fileExists(filePathC));
// fileA is in memory because it is pinned, but fileB should have been evicted to hold fileC.
Assert.assertEquals(100, mFileSystem.getStatus(filePathA).getInMemoryPercentage());
Assert.assertEquals(0, mFileSystem.getStatus(filePathB).getInMemoryPercentage());
// fileC should be in memory because fileB is evicted.
Assert.assertEquals(100, mFileSystem.getStatus(filePathC).getInMemoryPercentage());
}
}
|
package com.cjmalloy.torrentfs.model;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.cjmalloy.torrentfs.extension.Extension;
import com.cjmalloy.torrentfs.extension.Extension.ExtensionFactory;
import com.cjmalloy.torrentfs.util.JsonUtil;
import com.cjmalloy.torrentfs.util.JsonUtil.HasJson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.turn.ttorrent.common.Torrent;
public class Meta implements HasJson
{
private static JsonParser JSON_PARSER = new JsonParser();
/**
* Optional author string. Possibly used by future extensions.
*/
public String author;
/**
* The URL/URI this torrent was downloaded from. Used for checking new versions.
*/
public String origin;
/**
* Download a new torrent from <code>origin</code> for each request.
*/
public boolean doNotCache;
/**
* Marks this torrent as an advertisement. Distributing ads that are not marked
* may result in banning.
*/
public boolean solicitation;
/**
* Mark this as adult content. Distributing adult content that is not marked
* may result in banning.
*/
public boolean adult;
public List<Nested> nested;
public Map<String, Extension> extensions;
public List<Torrent> getNestedTorrents() throws IOException
{
List<Torrent> ret = new ArrayList<Torrent>();
for (Nested n : nested)
{
ret.add(n.getTorrent());
}
return ret;
}
@Override
public Meta parseJson(JsonObject json) throws IllegalStateException
{
if (json.has("author"))
{
author = json.get("author").getAsString();
}
if (json.has("origin"))
{
origin = json.get("origin").getAsString();
}
if (json.has("solicitation"))
{
solicitation = json.get("solicitation").getAsBoolean();
}
if (json.has("adult"))
{
adult = json.get("adult").getAsBoolean();
}
if (json.has("doNotCache"))
{
doNotCache = json.get("doNotCache").getAsBoolean();
}
if (json.has("nested"))
{
nested = JsonUtil.parseList(json.get("nested").getAsJsonArray(), Nested.FACTORY);
}
if (json.has("extensions"))
{
extensions = ExtensionFactory.load(json, JsonUtil.parseStringList(json.get("extensions").getAsJsonArray()));
}
return this;
}
@Override
public JsonElement writeJson()
{
JsonObject o = new JsonObject();
if (author != null)
{
o.add("author", new JsonPrimitive(author));
}
if (origin != null)
{
o.add("origin", new JsonPrimitive(origin));
}
o.add("solicitation", new JsonPrimitive(solicitation));
o.add("adult", new JsonPrimitive(adult));
o.add("doNotCache", new JsonPrimitive(doNotCache));
if (nested != null)
{
o.add("nested", JsonUtil.writeList(nested));
}
if (extensions != null)
{
o.add("extensions", JsonUtil.writeStringList(extensions.keySet()));
for (Extension e : extensions.values())
{
o.add(e.jsonId(), e.writeJson());
}
}
return o;
}
public static Meta load(File metaFile) throws IOException, IllegalStateException
{
if (metaFile == null || !metaFile.exists()) return null;
JsonElement json = JSON_PARSER.parse(new FileReader(metaFile));
return new Meta().parseJson(json.getAsJsonObject());
}
}
|
package functionalTests.security.ruleCheck;
import java.security.Policy;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.api.ProActiveObject;
import org.objectweb.proactive.api.ProDeployment;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.security.exceptions.RuntimeSecurityException;
public class Launcher {
public static void main(String[] args) {
try {
ProActiveDescriptor descriptor1 = ProDeployment.getProactiveDescriptor(
"descriptors/security/simple1.xml");
descriptor1.activateMappings();
VirtualNode virtualNode1 = descriptor1.getVirtualNode("vn1");
Node node1 = virtualNode1.getNodes()[0];
SampleObject a = (SampleObject) ProActiveObject.newActive(SampleObject.class.getName(),
new Object[] { "CN=Garden1" }, node1);
ProActiveDescriptor descriptor2 = ProDeployment.getProactiveDescriptor(
"descriptors/security/simple2.xml");
descriptor2.activateMappings();
VirtualNode virtualNode2 = descriptor2.getVirtualNode("vn2");
Node node2 = virtualNode2.getNodes()[0];
SampleObject b = (SampleObject) ProActiveObject.newActive(SampleObject.class.getName(),
new Object[] { "CN=Garden2" }, node2);
ProActiveDescriptor descriptor3 = ProDeployment.getProactiveDescriptor(
"descriptors/security/simple3.xml");
descriptor3.activateMappings();
VirtualNode virtualNode3 = descriptor3.getVirtualNode("vn3");
Node node3 = virtualNode3.getNodes()[0];
SampleObject c = (SampleObject) ProActiveObject.newActive(SampleObject.class.getName(),
new Object[] { "CN=Garden3" }, node3);
// a.makeTargetDoSomething(a);
// System.out.println("==");
//a.makeTargetDoSomething(b);
// System.out.println("==");
// System.out.println("//////////////////");
// b.makeTargetDoSomething(a);
// System.out.println("==");
// b.makeTargetDoSomething(b);
// System.out.println("==");
b.makeTargetDoSomething(c);
// System.out.println("//////////////////");
//a.makeTargetDoSomething(b);
try {
String s = b.sayhello(c).get();
System.out.println("s : " + s);
} catch (RuntimeSecurityException ex) {
System.out.println("wwwwwwwaaaouuuuu");
}
try {
b.makeTargetDoSomething(c);
} catch (RuntimeSecurityException ex) {
System.out.println("void ");
}
// c.makeTargetDoSomething(a);
// System.out.println("==");
// c.makeTargetDoSomething(b);
// System.out.println("==");
} catch (ActiveObjectCreationException e) {
e.printStackTrace();
} catch (NodeException e) {
e.printStackTrace();
} catch (ProActiveException e) {
e.printStackTrace();
}
}
}
|
package org.webrtc;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Surface;
import android.view.WindowManager;
import org.webrtc.CameraEnumerationAndroid.CaptureFormat;
import org.webrtc.Logging;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
// Android specific implementation of VideoCapturer.
// VideoCapturerAndroid.create();
// This class extends VideoCapturer with a method to easily switch between the
// front and back camera. It also provides methods for enumerating valid device
// names.
// Threading notes: this class is called from C++ code, Android Camera callbacks, and possibly
// arbitrary Java threads. All public entry points are thread safe, and delegate the work to the
// camera thread. The internal *OnCameraThread() methods must check |camera| for null to check if
// the camera has been stopped.
@SuppressWarnings("deprecation")
public class VideoCapturerAndroid implements
VideoCapturer,
android.hardware.Camera.PreviewCallback,
SurfaceTextureHelper.OnTextureFrameAvailableListener {
private final static String TAG = "VideoCapturerAndroid";
private final static int CAMERA_OBSERVER_PERIOD_MS = 2000;
private final static int CAMERA_FREEZE_REPORT_TIMOUT_MS = 4000;
private android.hardware.Camera camera; // Only non-null while capturing.
private Thread cameraThread;
private final Handler cameraThreadHandler;
private Context applicationContext;
// Synchronization lock for |id|.
private final Object cameraIdLock = new Object();
private int id;
private android.hardware.Camera.CameraInfo info;
private final CameraStatistics cameraStatistics;
// Remember the requested format in case we want to switch cameras.
private int requestedWidth;
private int requestedHeight;
private int requestedFramerate;
// The capture format will be the closest supported format to the requested format.
private CaptureFormat captureFormat;
private final Object pendingCameraSwitchLock = new Object();
private volatile boolean pendingCameraSwitch;
private CapturerObserver frameObserver = null;
private final CameraEventsHandler eventsHandler;
private boolean firstFrameReported;
// Arbitrary queue depth. Higher number means more memory allocated & held,
// lower number means more sensitivity to processing time in the client (and
// potentially stalling the capturer if it runs out of buffers to write to).
private static final int NUMBER_OF_CAPTURE_BUFFERS = 3;
private final Set<byte[]> queuedBuffers = new HashSet<byte[]>();
private final boolean isCapturingToTexture;
final SurfaceTextureHelper surfaceHelper; // Package visible for testing purposes.
// The camera API can output one old frame after the camera has been switched or the resolution
// has been changed. This flag is used for dropping the first frame after camera restart.
private boolean dropNextFrame = false;
// |openCameraOnCodecThreadRunner| is used for retrying to open the camera if it is in use by
// another application when startCaptureOnCameraThread is called.
private Runnable openCameraOnCodecThreadRunner;
private final static int MAX_OPEN_CAMERA_ATTEMPTS = 3;
private final static int OPEN_CAMERA_DELAY_MS = 500;
private int openCameraAttempts;
// Camera error callback.
private final android.hardware.Camera.ErrorCallback cameraErrorCallback =
new android.hardware.Camera.ErrorCallback() {
@Override
public void onError(int error, android.hardware.Camera camera) {
String errorMessage;
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
errorMessage = "Camera server died!";
} else {
errorMessage = "Camera error: " + error;
}
Logging.e(TAG, errorMessage);
if (eventsHandler != null) {
eventsHandler.onCameraError(errorMessage);
}
}
};
// Camera observer - monitors camera framerate. Observer is executed on camera thread.
private final Runnable cameraObserver = new Runnable() {
private int freezePeriodCount;
@Override
public void run() {
int cameraFramesCount = cameraStatistics.getAndResetFrameCount();
int cameraFps = (cameraFramesCount * 1000 + CAMERA_OBSERVER_PERIOD_MS / 2)
/ CAMERA_OBSERVER_PERIOD_MS;
Logging.d(TAG, "Camera fps: " + cameraFps +".");
if (cameraFramesCount == 0) {
++freezePeriodCount;
if (CAMERA_OBSERVER_PERIOD_MS * freezePeriodCount >= CAMERA_FREEZE_REPORT_TIMOUT_MS
&& eventsHandler != null) {
Logging.e(TAG, "Camera freezed.");
if (surfaceHelper.isTextureInUse()) {
// This can only happen if we are capturing to textures.
eventsHandler.onCameraFreezed("Camera failure. Client must return video buffers.");
} else {
eventsHandler.onCameraFreezed("Camera failure.");
}
return;
}
} else {
freezePeriodCount = 0;
}
cameraThreadHandler.postDelayed(this, CAMERA_OBSERVER_PERIOD_MS);
}
};
private static class CameraStatistics {
private int frameCount = 0;
private final ThreadUtils.ThreadChecker threadChecker = new ThreadUtils.ThreadChecker();
CameraStatistics() {
threadChecker.detachThread();
}
public void addFrame() {
threadChecker.checkIsOnValidThread();
++frameCount;
}
public int getAndResetFrameCount() {
threadChecker.checkIsOnValidThread();
int count = frameCount;
frameCount = 0;
return count;
}
}
public static interface CameraEventsHandler {
// Camera error handler - invoked when camera can not be opened
// or any camera exception happens on camera thread.
void onCameraError(String errorDescription);
// Invoked when camera stops receiving frames
void onCameraFreezed(String errorDescription);
// Callback invoked when camera is opening.
void onCameraOpening(int cameraId);
// Callback invoked when first camera frame is available after camera is opened.
void onFirstFrameAvailable();
// Callback invoked when camera closed.
void onCameraClosed();
}
// Camera switch handler - one of these functions are invoked with the result of switchCamera().
// The callback may be called on an arbitrary thread.
public interface CameraSwitchHandler {
// Invoked on success. |isFrontCamera| is true if the new camera is front facing.
void onCameraSwitchDone(boolean isFrontCamera);
// Invoked on failure, e.g. camera is stopped or only one camera available.
void onCameraSwitchError(String errorDescription);
}
public static VideoCapturerAndroid create(String name,
CameraEventsHandler eventsHandler) {
return VideoCapturerAndroid.create(name, eventsHandler, null);
}
public static VideoCapturerAndroid create(String name,
CameraEventsHandler eventsHandler, EglBase.Context sharedEglContext) {
final int cameraId = lookupDeviceName(name);
if (cameraId == -1) {
return null;
}
return new VideoCapturerAndroid(cameraId, eventsHandler, sharedEglContext);
}
public void printStackTrace() {
if (cameraThread != null) {
StackTraceElement[] cameraStackTraces = cameraThread.getStackTrace();
if (cameraStackTraces.length > 0) {
Logging.d(TAG, "VideoCapturerAndroid stacks trace:");
for (StackTraceElement stackTrace : cameraStackTraces) {
Logging.d(TAG, stackTrace.toString());
}
}
}
}
// Switch camera to the next valid camera id. This can only be called while
// the camera is running.
public void switchCamera(final CameraSwitchHandler handler) {
if (android.hardware.Camera.getNumberOfCameras() < 2) {
if (handler != null) {
handler.onCameraSwitchError("No camera to switch to.");
}
return;
}
synchronized (pendingCameraSwitchLock) {
if (pendingCameraSwitch) {
// Do not handle multiple camera switch request to avoid blocking
// camera thread by handling too many switch request from a queue.
Logging.w(TAG, "Ignoring camera switch request.");
if (handler != null) {
handler.onCameraSwitchError("Pending camera switch already in progress.");
}
return;
}
pendingCameraSwitch = true;
}
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
if (camera == null) {
if (handler != null) {
handler.onCameraSwitchError("Camera is stopped.");
}
return;
}
switchCameraOnCameraThread();
synchronized (pendingCameraSwitchLock) {
pendingCameraSwitch = false;
}
if (handler != null) {
handler.onCameraSwitchDone(
info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
}
}
});
}
// Requests a new output format from the video capturer. Captured frames
// by the camera will be scaled/or dropped by the video capturer.
// It does not matter if width and height are flipped. I.E, |width| = 640, |height| = 480 produce
// the same result as |width| = 480, |height| = 640.
// TODO(magjed/perkj): Document what this function does. Change name?
public void onOutputFormatRequest(final int width, final int height, final int framerate) {
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
onOutputFormatRequestOnCameraThread(width, height, framerate);
}
});
}
// Reconfigure the camera to capture in a new format. This should only be called while the camera
// is running.
public void changeCaptureFormat(final int width, final int height, final int framerate) {
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
startPreviewOnCameraThread(width, height, framerate);
}
});
}
// Helper function to retrieve the current camera id synchronously. Note that the camera id might
// change at any point by switchCamera() calls.
int getCurrentCameraId() {
synchronized (cameraIdLock) {
return id;
}
}
@Override
public List<CaptureFormat> getSupportedFormats() {
return CameraEnumerationAndroid.getSupportedFormats(getCurrentCameraId());
}
// Returns true if this VideoCapturer is setup to capture video frames to a SurfaceTexture.
public boolean isCapturingToTexture() {
return isCapturingToTexture;
}
@Override
public SurfaceTextureHelper getSurfaceTextureHelper() {
return surfaceHelper;
}
private VideoCapturerAndroid(int cameraId, CameraEventsHandler eventsHandler,
EglBase.Context sharedContext) {
this.id = cameraId;
this.eventsHandler = eventsHandler;
isCapturingToTexture = (sharedContext != null);
cameraStatistics = new CameraStatistics();
surfaceHelper = SurfaceTextureHelper.create(sharedContext);
cameraThreadHandler = surfaceHelper.getHandler();
cameraThread = cameraThreadHandler.getLooper().getThread();
Logging.d(TAG, "VideoCapturerAndroid isCapturingToTexture : " + isCapturingToTexture);
}
private void checkIsOnCameraThread() {
if (Thread.currentThread() != cameraThread) {
throw new IllegalStateException("Wrong thread");
}
}
// Returns the camera index for camera with name |deviceName|, or -1 if no such camera can be
// found. If |deviceName| is empty, the first available device is used.
private static int lookupDeviceName(String deviceName) {
Logging.d(TAG, "lookupDeviceName: " + deviceName);
if (deviceName == null || android.hardware.Camera.getNumberOfCameras() == 0) {
return -1;
}
if (deviceName.isEmpty()) {
return 0;
}
for (int i = 0; i < android.hardware.Camera.getNumberOfCameras(); ++i) {
if (deviceName.equals(CameraEnumerationAndroid.getDeviceName(i))) {
return i;
}
}
return -1;
}
// Quits the camera thread. This needs to be done manually, otherwise the thread and handler will
// not be garbage collected.
@Override
public void dispose() {
Logging.d(TAG, "release");
if (isDisposed()) {
throw new IllegalStateException("Already released");
}
ThreadUtils.invokeUninterruptibly(cameraThreadHandler, new Runnable() {
@Override
public void run() {
if (camera != null) {
throw new IllegalStateException("Release called while camera is running");
}
}
});
surfaceHelper.dispose();
cameraThread = null;
}
// Used for testing purposes to check if dispose() has been called.
public boolean isDisposed() {
return (cameraThread == null);
}
// Note that this actually opens the camera, and Camera callbacks run on the
// thread that calls open(), so this is done on the CameraThread.
@Override
public void startCapture(
final int width, final int height, final int framerate,
final Context applicationContext, final CapturerObserver frameObserver) {
Logging.d(TAG, "startCapture requested: " + width + "x" + height
+ "@" + framerate);
if (applicationContext == null) {
throw new RuntimeException("applicationContext not set.");
}
if (frameObserver == null) {
throw new RuntimeException("frameObserver not set.");
}
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
startCaptureOnCameraThread(width, height, framerate, frameObserver,
applicationContext);
}
});
}
private void startCaptureOnCameraThread(
final int width, final int height, final int framerate, final CapturerObserver frameObserver,
final Context applicationContext) {
Throwable error = null;
checkIsOnCameraThread();
if (camera != null) {
throw new RuntimeException("Camera has already been started.");
}
this.applicationContext = applicationContext;
this.frameObserver = frameObserver;
this.firstFrameReported = false;
try {
try {
synchronized (cameraIdLock) {
Logging.d(TAG, "Opening camera " + id);
if (eventsHandler != null) {
eventsHandler.onCameraOpening(id);
}
camera = android.hardware.Camera.open(id);
info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(id, info);
}
} catch (RuntimeException e) {
openCameraAttempts++;
if (openCameraAttempts < MAX_OPEN_CAMERA_ATTEMPTS) {
Logging.e(TAG, "Camera.open failed, retrying", e);
openCameraOnCodecThreadRunner = new Runnable() {
@Override public void run() {
startCaptureOnCameraThread(width, height, framerate, frameObserver,
applicationContext);
}
};
cameraThreadHandler.postDelayed(openCameraOnCodecThreadRunner, OPEN_CAMERA_DELAY_MS);
return;
}
openCameraAttempts = 0;
throw e;
}
try {
camera.setPreviewTexture(surfaceHelper.getSurfaceTexture());
} catch (IOException e) {
Logging.e(TAG, "setPreviewTexture failed", error);
throw new RuntimeException(e);
}
Logging.d(TAG, "Camera orientation: " + info.orientation +
" .Device orientation: " + getDeviceOrientation());
camera.setErrorCallback(cameraErrorCallback);
startPreviewOnCameraThread(width, height, framerate);
frameObserver.onCapturerStarted(true);
if (isCapturingToTexture) {
surfaceHelper.startListening(this);
}
// Start camera observer.
cameraThreadHandler.postDelayed(cameraObserver, CAMERA_OBSERVER_PERIOD_MS);
return;
} catch (RuntimeException e) {
error = e;
}
Logging.e(TAG, "startCapture failed", error);
stopCaptureOnCameraThread();
frameObserver.onCapturerStarted(false);
if (eventsHandler != null) {
eventsHandler.onCameraError("Camera can not be started.");
}
return;
}
// (Re)start preview with the closest supported format to |width| x |height| @ |framerate|.
private void startPreviewOnCameraThread(int width, int height, int framerate) {
checkIsOnCameraThread();
Logging.d(
TAG, "startPreviewOnCameraThread requested: " + width + "x" + height + "@" + framerate);
if (camera == null) {
Logging.e(TAG, "Calling startPreviewOnCameraThread on stopped camera.");
return;
}
requestedWidth = width;
requestedHeight = height;
requestedFramerate = framerate;
// Find closest supported format for |width| x |height| @ |framerate|.
final android.hardware.Camera.Parameters parameters = camera.getParameters();
final int[] range = CameraEnumerationAndroid.getFramerateRange(parameters, framerate * 1000);
final android.hardware.Camera.Size previewSize =
CameraEnumerationAndroid.getClosestSupportedSize(
parameters.getSupportedPreviewSizes(), width, height);
final CaptureFormat captureFormat = new CaptureFormat(
previewSize.width, previewSize.height,
range[android.hardware.Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
range[android.hardware.Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
// Check if we are already using this capture format, then we don't need to do anything.
if (captureFormat.isSameFormat(this.captureFormat)) {
return;
}
// Update camera parameters.
Logging.d(TAG, "isVideoStabilizationSupported: " +
parameters.isVideoStabilizationSupported());
if (parameters.isVideoStabilizationSupported()) {
parameters.setVideoStabilization(true);
}
// Note: setRecordingHint(true) actually decrease frame rate on N5.
// parameters.setRecordingHint(true);
if (captureFormat.maxFramerate > 0) {
parameters.setPreviewFpsRange(captureFormat.minFramerate, captureFormat.maxFramerate);
}
parameters.setPreviewSize(captureFormat.width, captureFormat.height);
if (!isCapturingToTexture) {
parameters.setPreviewFormat(captureFormat.imageFormat);
}
// Picture size is for taking pictures and not for preview/video, but we need to set it anyway
// as a workaround for an aspect ratio problem on Nexus 7.
final android.hardware.Camera.Size pictureSize =
CameraEnumerationAndroid.getClosestSupportedSize(
parameters.getSupportedPictureSizes(), width, height);
parameters.setPictureSize(pictureSize.width, pictureSize.height);
// Temporarily stop preview if it's already running.
if (this.captureFormat != null) {
camera.stopPreview();
dropNextFrame = true;
// Calling |setPreviewCallbackWithBuffer| with null should clear the internal camera buffer
// queue, but sometimes we receive a frame with the old resolution after this call anyway.
camera.setPreviewCallbackWithBuffer(null);
}
// (Re)start preview.
Logging.d(TAG, "Start capturing: " + captureFormat);
this.captureFormat = captureFormat;
List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
if (!isCapturingToTexture) {
queuedBuffers.clear();
final int frameSize = captureFormat.frameSize();
for (int i = 0; i < NUMBER_OF_CAPTURE_BUFFERS; ++i) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(frameSize);
queuedBuffers.add(buffer.array());
camera.addCallbackBuffer(buffer.array());
}
camera.setPreviewCallbackWithBuffer(this);
}
camera.startPreview();
}
// Blocks until camera is known to be stopped.
@Override
public void stopCapture() throws InterruptedException {
Logging.d(TAG, "stopCapture");
final CountDownLatch barrier = new CountDownLatch(1);
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
// Make sure onTextureFrameAvailable() is not called anymore.
surfaceHelper.stopListening();
stopCaptureOnCameraThread();
barrier.countDown();
}
});
barrier.await();
Logging.d(TAG, "stopCapture done");
}
private void stopCaptureOnCameraThread() {
checkIsOnCameraThread();
Logging.d(TAG, "stopCaptureOnCameraThread");
if (openCameraOnCodecThreadRunner != null) {
cameraThreadHandler.removeCallbacks(openCameraOnCodecThreadRunner);
}
openCameraAttempts = 0;
if (camera == null) {
Logging.e(TAG, "Calling stopCapture() for already stopped camera.");
return;
}
cameraThreadHandler.removeCallbacks(cameraObserver);
cameraStatistics.getAndResetFrameCount();
Logging.d(TAG, "Stop preview.");
camera.stopPreview();
camera.setPreviewCallbackWithBuffer(null);
queuedBuffers.clear();
captureFormat = null;
Logging.d(TAG, "Release camera.");
camera.release();
camera = null;
if (eventsHandler != null) {
eventsHandler.onCameraClosed();
}
}
private void switchCameraOnCameraThread() {
checkIsOnCameraThread();
Logging.d(TAG, "switchCameraOnCameraThread");
stopCaptureOnCameraThread();
synchronized (cameraIdLock) {
id = (id + 1) % android.hardware.Camera.getNumberOfCameras();
}
dropNextFrame = true;
startCaptureOnCameraThread(requestedWidth, requestedHeight, requestedFramerate, frameObserver,
applicationContext);
Logging.d(TAG, "switchCameraOnCameraThread done");
}
private void onOutputFormatRequestOnCameraThread(int width, int height, int framerate) {
checkIsOnCameraThread();
if (camera == null) {
Logging.e(TAG, "Calling onOutputFormatRequest() on stopped camera.");
return;
}
Logging.d(TAG, "onOutputFormatRequestOnCameraThread: " + width + "x" + height +
"@" + framerate);
frameObserver.onOutputFormatRequest(width, height, framerate);
}
// Exposed for testing purposes only.
Handler getCameraThreadHandler() {
return cameraThreadHandler;
}
private int getDeviceOrientation() {
int orientation = 0;
WindowManager wm = (WindowManager) applicationContext.getSystemService(
Context.WINDOW_SERVICE);
switch(wm.getDefaultDisplay().getRotation()) {
case Surface.ROTATION_90:
orientation = 90;
break;
case Surface.ROTATION_180:
orientation = 180;
break;
case Surface.ROTATION_270:
orientation = 270;
break;
case Surface.ROTATION_0:
default:
orientation = 0;
break;
}
return orientation;
}
private int getFrameOrientation() {
int rotation = getDeviceOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK) {
rotation = 360 - rotation;
}
return (info.orientation + rotation) % 360;
}
// Called on cameraThread so must not "synchronized".
@Override
public void onPreviewFrame(byte[] data, android.hardware.Camera callbackCamera) {
checkIsOnCameraThread();
if (camera == null || !queuedBuffers.contains(data)) {
// The camera has been stopped or |data| is an old invalid buffer.
return;
}
if (camera != callbackCamera) {
throw new RuntimeException("Unexpected camera in callback!");
}
final long captureTimeNs =
TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());
if (eventsHandler != null && !firstFrameReported) {
eventsHandler.onFirstFrameAvailable();
firstFrameReported = true;
}
cameraStatistics.addFrame();
frameObserver.onByteBufferFrameCaptured(data, captureFormat.width, captureFormat.height,
getFrameOrientation(), captureTimeNs);
camera.addCallbackBuffer(data);
}
@Override
public void onTextureFrameAvailable(
int oesTextureId, float[] transformMatrix, long timestampNs) {
if (camera == null) {
throw new RuntimeException("onTextureFrameAvailable() called after stopCapture().");
}
checkIsOnCameraThread();
if (dropNextFrame) {
surfaceHelper.returnTextureFrame();
dropNextFrame = false;
return;
}
if (eventsHandler != null && !firstFrameReported) {
eventsHandler.onFirstFrameAvailable();
firstFrameReported = true;
}
int rotation = getFrameOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT) {
// Undo the mirror that the OS "helps" us with.
// http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)
transformMatrix =
RendererCommon.multiplyMatrices(transformMatrix, RendererCommon.horizontalFlipMatrix());
}
cameraStatistics.addFrame();
frameObserver.onTextureFrameCaptured(captureFormat.width, captureFormat.height, oesTextureId,
transformMatrix, rotation, timestampNs);
}
}
|
package com.caseystella.analytics.outlier;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import com.caseystella.analytics.DataPoint;
import com.caseystella.analytics.outlier.batch.OutlierAlgorithm;
import com.caseystella.analytics.outlier.batch.OutlierConfig;
import com.caseystella.analytics.timeseries.PersistenceConfig;
import com.caseystella.analytics.timeseries.TSConstants;
import com.caseystella.analytics.timeseries.TimeseriesDatabaseHandler;
import com.caseystella.analytics.timeseries.TimeseriesDatabaseHandlers;
import com.caseystella.analytics.timeseries.tsdb.TSDBHandler;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class OutlierBolt extends BaseRichBolt {
private static final Logger LOG = Logger.getLogger(OutlierBolt.class);
private OutlierConfig outlierConfig;
private PersistenceConfig persistenceConfig;
private transient OutlierAlgorithm outlierAlgorithm;
private transient TimeseriesDatabaseHandler tsdbHandler;
private transient OutputCollector collector;
boolean isFirst = true;
private int headStart = 0;
public OutlierBolt() {
}
public OutlierBolt(OutlierConfig outlierConfig, PersistenceConfig persistenceConfig) {
withOutlierConfig(outlierConfig);
withPersistenceConfig(persistenceConfig);
}
public OutlierBolt withOutlierConfig(OutlierConfig config) {
this.outlierConfig = config;
return this;
}
public OutlierBolt withPersistenceConfig(PersistenceConfig config) {
this.persistenceConfig = config;
return this;
}
/**
* Called when a task for this component is initialized within a worker on the cluster.
* It provides the bolt with the environment in which the bolt executes.
* <p/>
* <p>This includes the:</p>
*
* @param stormConf The Storm configuration for this bolt. This is the configuration provided to the topology merged in with cluster configuration on this machine.
* @param context This object can be used to get information about this task's place within the topology, including the task id and component id of this task, input and output information, etc.
* @param collector The collector is used to emit tuples from this bolt. Tuples can be emitted at any time, including the prepare and cleanup methods. The collector is thread-safe and should be saved as an instance variable of this bolt object.
*/
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
outlierAlgorithm = outlierConfig.getAlgorithm();
outlierAlgorithm.configure(outlierConfig);
if(!persistenceConfig.getConfig().containsKey(TSConstants.HBASE_CONFIG_KEY)
&& stormConf.containsKey(TSConstants.HBASE_CONFIG_KEY)
)
{
Configuration config = (Configuration) stormConf.get(TSConstants.HBASE_CONFIG_KEY);
persistenceConfig.getConfig().put(TSConstants.HBASE_CONFIG_KEY, config);
}
headStart = outlierConfig.getHeadStart();
tsdbHandler = persistenceConfig.getDatabaseHandler();
tsdbHandler.configure(persistenceConfig.getConfig());
}
private static String getPoints(List<DataPoint> context, DataPoint value) {
Iterable<DataPoint> pts = Iterables.concat(context, Arrays.asList(value));
Iterable<String> vals = Iterables.transform(pts, new Function<DataPoint, String>() {
@Nullable
@Override
public String apply(@Nullable DataPoint dataPoint) {
return dataPoint.getValue() + "";
}
});
return Joiner.on(',').join(vals);
}
/**
* Process a single tuple of input. The Tuple object contains metadata on it
* about which component/stream/task it came from. The values of the Tuple can
* be accessed using Tuple#getValue. The IBolt does not have to process the Tuple
* immediately. It is perfectly fine to hang onto a tuple and process it later
* (for instance, to do an aggregation or join).
* <p/>
* <p>Tuples should be emitted using the OutputCollector provided through the prepare method.
* It is required that all input tuples are acked or failed at some point using the OutputCollector.
* Otherwise, Storm will be unable to determine when tuples coming off the spouts
* have been completed.</p>
* <p/>
* <p>For the common case of acking an input tuple at the end of the execute method,
* see IBasicBolt which automates this.</p>
*
* @param input The input tuple to be processed.
*/
@Override
public void execute(Tuple input) {
if(isFirst) {
//because our timeseries databases often optimize for throughput rather than latency
//we could be getting our outliers before they show up in the TSDB due to async puts in
//the outliercallback. Thus, we're going to give TSDB a head start;
try {
Thread.sleep(headStart);
} catch (InterruptedException e) {
}
isFirst = false;
}
Outlier outlier = (Outlier) input.getValueByField(Constants.OUTLIER);
Integer numPts = outlier.getNumPts();
if(numPts == 0) {
throw new RuntimeException("Unable to proceed. We expect 0 points, so that's a bad state.");
}
LOG.debug("Expecting " + numPts + " datapoints");
DataPoint dp = outlier.getDataPoint();
boolean gotContext = false;
int numGot = 0;
int numTries = 0;
for(;numTries < 60 && !gotContext;numTries++) {
List<DataPoint> context = tsdbHandler.retrieve(dp.getSource()
, dp
, outlier.getRange()
, Outlier.groupingFilter(dp, outlierConfig.getGroupingKeys(), persistenceConfig.getTags())
, numPts
);
numGot = context.size();
gotContext = numGot > Math.min(0.5*numPts, 100);
if (gotContext) {
LOG.debug("Retrieving " + context.size() + " datapoints");
gotContext = true;
long startTime = System.currentTimeMillis();
Outlier realOutlier = outlierAlgorithm.analyze(outlier, context, dp);
long duration = System.currentTimeMillis() - startTime;
LOG.trace("Outlier detection took " + duration + " ms on " + numGot + " points");
String metric = dp.getSource();
if (realOutlier.getSeverity() == Severity.SEVERE_OUTLIER) {
if(LOG.isDebugEnabled()) {
LOG.debug("Persisting to " + metric + " outlier of " + realOutlier.getSeverity() + " with input " + getPoints(context, dp));
}
//write out to tsdb
tsdbHandler.persist(metric
, dp
, TimeseriesDatabaseHandlers.getOutlierTags(realOutlier.getDataPoint()
,realOutlier.getSeverity()
, TimeseriesDatabaseHandlers.OUTLIER_TYPE
)
, TimeseriesDatabaseHandlers.EMPTY_CALLBACK
);
//emit the outlier for downstream processing if necessary.
collector.emit(ImmutableList.of(input.getValueByField(Constants.MEASUREMENT_ID)
, realOutlier
)
);
}
}
else {
try {
Thread.sleep(100);
}
catch(InterruptedException e) {
}
}
}
if(gotContext == false) {
String reason = numGot + "<" + numPts + " with range: " + outlier.getRange() + " and grouping: " + Joiner.on(",").join(Outlier.groupingFilter(dp, outlierConfig.getGroupingKeys(), persistenceConfig.getTags()).entrySet());
reason += ": Unable to retrieve a context after " + numTries + " tries";
LOG.error(reason);
}
collector.ack(input);
}
/**
* Declare the output schema for all the streams of this topology.
*
* @param declarer this is used to declare output stream ids, output fields, and whether or not each output stream is a direct stream
*/
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields(Constants.MEASUREMENT_ID, Constants.OUTLIER));
}
}
|
package hudson.plugins.scm.koji.model;
import hudson.plugins.scm.koji.Constants;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.Optional;
@XmlAccessorType(XmlAccessType.FIELD)
public class RPM implements java.io.Serializable {
@XmlElement(name = Constants.name)
private final String name;
@XmlElement(name = Constants.version)
private final String version;
@XmlElement(name = Constants.release)
private final String release;
@XmlElement(name = Constants.nvr)
private final String nvr;
@XmlElement(name = Constants.arch)
private final String arch;
@XmlElement(name = Constants.filename)
private final String filename;
private String url;
private String hashSum;
public RPM(String name, String version, String release, String nvr, String arch, String filename) {
this.name = name;
this.version = version;
this.release = release;
this.nvr = nvr;
this.arch = arch;
this.filename = filename;
}
public RPM() {
this.name = null;
this.version = null;
this.release = null;
this.nvr = null;
this.arch = null;
this.filename = null;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getRelease() {
return release;
}
public String getNvr() {
return nvr;
}
public String getArch() {
return arch;
}
@Override
public String toString() {
if (Suffix.INSTANCE.endsWithSuffix(nvr)) {
return nvr;
}
Suffix suffix = Suffix.INSTANCE;
return nvr + '.' + arch + '.' + suffix.getSuffix(url);
}
public String getFilename(String suffix) {
return Optional.ofNullable(filename).orElse(nvr + '.' + arch + "." + suffix);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean hasUrl() {
return url != null;
}
public void setHashSum(String hashSum) {
this.hashSum = hashSum;
}
public String getHashSum() {
return hashSum;
}
public static enum Suffix {
INSTANCE;
private final String[] suffixes = {"rpm", "tarxz", "zip", "msi"};
public String[] getSuffixes() {
return suffixes;
}
public String getSuffix(String url) {
if (url == null) {
return "";
}
for (String suffix : suffixes) {
if (url.endsWith(suffix)) {
return suffix;
}
}
return "";
}
public boolean endsWithSuffix(String url) {
if (url == null) {
return false;
}
for (String suffix : suffixes) {
if (url.endsWith(suffix)) {
return true;
}
}
return false;
}
}
}
|
package com.tightdb;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import java.util.Date;
public class JNIQueryTest {
Table table;
void init() {
table = new Table();
TableSpec tableSpec = new TableSpec();
tableSpec.addColumn(ColumnType.ColumnTypeInt, "number");
tableSpec.addColumn(ColumnType.ColumnTypeString, "name");
table.updateFromSpec(tableSpec);
table.add(10, "A");
table.add(11, "B");
table.add(12, "C");
table.add(13, "B");
table.add(14, "D");
table.add(16, "D");
assertEquals(6, table.size());
}
@Test
public void shouldQuery() {
init();
TableQuery query = table.where();
long cnt = query.equal(1, "D").count();
assertEquals(2, cnt);
cnt = query.minimum(0);
assertEquals(14, cnt);
cnt = query.maximum(0);
assertEquals(16, cnt);
cnt = query.sum(0);
assertEquals(14+16, cnt);
double avg = query.average(0);
assertEquals(15.0, avg);
// TODO: Add tests with all parameters
}
@Test
public void EqualWithWrongDataType() {
Table table = new Table();
table.addColumn(ColumnType.ColumnTypeBinary, "binary");
table.addColumn(ColumnType.ColumnTypeBool, "boolean");
table.addColumn(ColumnType.ColumnTypeDate, "date");
table.addColumn(ColumnType.ColumnTypeDouble, "double");
table.addColumn(ColumnType.ColumnTypeFloat, "float");
table.addColumn(ColumnType.ColumnTypeInt, "long");
table.addColumn(ColumnType.ColumnTypeMixed, "mixed");
table.addColumn(ColumnType.ColumnTypeString, "string");
table.addColumn(ColumnType.ColumnTypeTable, "table");
// Query the table
TableQuery query = table.where();
// Compare strings in non string columns
for(int i = 0; i <= 8; i++) {
if(i != 7) {
try { query.equal(0, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqual(0, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.beginsWith(0, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.endsWith(0, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.contains(0, "string"); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare integer in non integer columns
for(int i = 0; i <= 8; i++) {
if(i != 5) {
try { query.equal(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqual(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(0, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(0, 123, 321); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare float in non float columns
for(int i = 0; i <= 8; i++) {
if(i != 4) {
try { query.equal(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqual(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(0, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(0, 123F, 321F); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare double in non double columns
for(int i = 0; i <= 8; i++) {
if(i != 3) {
try { query.equal(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqual(0, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(0, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(0, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(0, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(0, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(0, 123D, 321D); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare boolean in non boolean columns
for(int i = 0; i <= 8; i++) {
if(i != 1) {
try { query.equal(i, true); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare date
}
}
|
package tlc2.debug;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import org.eclipse.lsp4j.debug.Breakpoint;
import org.eclipse.lsp4j.debug.BreakpointLocation;
import org.eclipse.lsp4j.debug.BreakpointLocationsArguments;
import org.eclipse.lsp4j.debug.BreakpointLocationsResponse;
import org.eclipse.lsp4j.debug.CancelArguments;
import org.eclipse.lsp4j.debug.Capabilities;
import org.eclipse.lsp4j.debug.ConfigurationDoneArguments;
import org.eclipse.lsp4j.debug.ContinueArguments;
import org.eclipse.lsp4j.debug.ContinueResponse;
import org.eclipse.lsp4j.debug.InitializeRequestArguments;
import org.eclipse.lsp4j.debug.NextArguments;
import org.eclipse.lsp4j.debug.PauseArguments;
import org.eclipse.lsp4j.debug.ScopesArguments;
import org.eclipse.lsp4j.debug.ScopesResponse;
import org.eclipse.lsp4j.debug.SetBreakpointsArguments;
import org.eclipse.lsp4j.debug.SetBreakpointsResponse;
import org.eclipse.lsp4j.debug.SetVariableArguments;
import org.eclipse.lsp4j.debug.SetVariableResponse;
import org.eclipse.lsp4j.debug.SourceBreakpoint;
import org.eclipse.lsp4j.debug.StackFrame;
import org.eclipse.lsp4j.debug.StackTraceArguments;
import org.eclipse.lsp4j.debug.StackTraceResponse;
import org.eclipse.lsp4j.debug.StepInArguments;
import org.eclipse.lsp4j.debug.StepOutArguments;
import org.eclipse.lsp4j.debug.StoppedEventArguments;
import org.eclipse.lsp4j.debug.Thread;
import org.eclipse.lsp4j.debug.ThreadsResponse;
import org.eclipse.lsp4j.debug.Variable;
import org.eclipse.lsp4j.debug.VariablesArguments;
import org.eclipse.lsp4j.debug.VariablesResponse;
import org.eclipse.lsp4j.debug.services.IDebugProtocolClient;
import org.eclipse.lsp4j.jsonrpc.Launcher;
import tla2sany.semantic.SemanticNode;
import tla2sany.st.Location;
import tlc2.tool.TLCState;
import tlc2.tool.impl.Tool;
import tlc2.util.Context;
public abstract class TLCDebugger extends AbstractDebugger implements IDebugTarget {
protected static Logger LOGGER = Logger.getLogger(TLCDebugger.class.getName());
protected Launcher<IDebugProtocolClient> launcher;
@Override
public synchronized CompletableFuture<Capabilities> initialize(InitializeRequestArguments args) {
LOGGER.finer("initialize");
Executors.newSingleThreadExecutor().submit(() -> {
LOGGER.finer("initialize -> initialized");
// Signal the debugger that we are ready. It seem not relevant in what order the
// response below and the initialized signal arrive at the debugger.
launcher.getRemoteProxy().initialized();
});
// The capabilities define customizations how the debugger will interact with
// this debuggee. Declaring no capabilities causes the most simple protocol to
// be used.
return CompletableFuture.completedFuture(new Capabilities());
}
@Override
public synchronized CompletableFuture<Void> cancel(CancelArguments args) {
return CompletableFuture.completedFuture(null);
}
@Override
public synchronized CompletableFuture<Void> configurationDone(ConfigurationDoneArguments args) {
LOGGER.finer("configurationDone");
return CompletableFuture.completedFuture(null);
}
@Override
public synchronized CompletableFuture<BreakpointLocationsResponse> breakpointLocations(BreakpointLocationsArguments args) {
LOGGER.finer("breakpointLocations");
final BreakpointLocationsResponse response = new BreakpointLocationsResponse();
BreakpointLocation breakpoint = new BreakpointLocation();
breakpoint.setColumn(args.getColumn());
breakpoint.setEndColumn(args.getEndColumn());
breakpoint.setEndLine(args.getEndLine());
breakpoint.setLine(args.getLine());
BreakpointLocation[] breakpoints = new BreakpointLocation[] { breakpoint };
response.setBreakpoints(breakpoints);
return CompletableFuture.completedFuture(response);
}
private final List<Breakpoint> breakpoints = Collections.synchronizedList(new ArrayList<>());
@Override
public synchronized CompletableFuture<SetBreakpointsResponse> setBreakpoints(SetBreakpointsArguments args) {
//TODO: Confirm breakpoint locations (see tlc2.debug.TLCDebugger.matches(SemanticNode))!!!
LOGGER.finer("setBreakpoints");
final SourceBreakpoint[] sbps = args.getBreakpoints();
final ArrayList<Breakpoint> tmp = new ArrayList<>(sbps.length);
for (int j = 0; j < sbps.length; j++) {
Breakpoint breakpoint = new Breakpoint();
breakpoint.setColumn(sbps[j].getColumn());
breakpoint.setLine(sbps[j].getLine());
breakpoint.setId(j);
breakpoint.setVerified(true);
tmp.add(breakpoint);
}
breakpoints.clear();
breakpoints.addAll(tmp);
final SetBreakpointsResponse response = new SetBreakpointsResponse();
response.setBreakpoints(breakpoints.toArray(new Breakpoint[breakpoints.size()]));
return CompletableFuture.completedFuture(response);
}
@Override
public synchronized CompletableFuture<StackTraceResponse> stackTrace(StackTraceArguments args) {
LOGGER.finer(String.format("stackTrace frame: %s, levels: %s\n", args.getStartFrame(), args.getLevels()));
final List<StackFrame> frames = new ArrayList<>(stack.size());
for (int i = stack.size() - 1; i >= 0; i
final TLCStackFrame stackFrame = stack.elementAt(i);
frames.add(stackFrame);
}
final StackTraceResponse res = new StackTraceResponse();
res.setStackFrames(frames.toArray(new StackFrame[frames.size()]));
return CompletableFuture.completedFuture(res);
}
@Override
public synchronized CompletableFuture<ScopesResponse> scopes(ScopesArguments args) {
LOGGER.finer(String.format("scopes frame %s\n", args.getFrameId()));
final ScopesResponse response = new ScopesResponse();
stack.stream().filter(s -> s.getId() == args.getFrameId()).findFirst()
.ifPresent(frame -> response.setScopes(frame.getScopes()));
return CompletableFuture.completedFuture(response);
}
@Override
public synchronized CompletableFuture<VariablesResponse> variables(VariablesArguments args) {
final int vr = args.getVariablesReference();
final VariablesResponse value = new VariablesResponse();
final List<Variable> collect = new ArrayList<>();
for (TLCStackFrame frame : this.stack) {
collect.addAll(Arrays.asList(frame.getVariables(vr)));
}
value.setVariables(collect.toArray(new Variable[collect.size()]));
return CompletableFuture.completedFuture(value);
}
@Override
public synchronized CompletableFuture<SetVariableResponse> setVariable(SetVariableArguments args) {
LOGGER.finer("setVariable");
return CompletableFuture.completedFuture(new SetVariableResponse());
}
@Override
public synchronized CompletableFuture<ThreadsResponse> threads() {
LOGGER.finer("threads");
Thread thread = new Thread();
thread.setId(0);
thread.setName("worker");
ThreadsResponse res = new ThreadsResponse();
res.setThreads(new Thread[] { thread });
return CompletableFuture.completedFuture(res);
}
@Override
public synchronized CompletableFuture<ContinueResponse> continue_(ContinueArguments args) {
LOGGER.finer("continue_");
targetLevel = -1;
step = Step.Continue;
this.notify();
return CompletableFuture.completedFuture(new ContinueResponse());
}
@Override
public synchronized CompletableFuture<Void> next(NextArguments args) {
LOGGER.finer("next/stepOver");
targetLevel = this.stack.size() - 1;
step = Step.Over;
this.notify();
return CompletableFuture.completedFuture(null);
}
@Override
public synchronized CompletableFuture<Void> stepIn(StepInArguments args) {
LOGGER.finer("stepIn");
targetLevel++;
step = Step.In;
this.notify();
return CompletableFuture.completedFuture(null);
}
@Override
public synchronized CompletableFuture<Void> stepOut(StepOutArguments args) {
LOGGER.finer("stepOut");
targetLevel
step = Step.Out;
this.notify();
return CompletableFuture.completedFuture(null);
}
@Override
public synchronized CompletableFuture<Void> pause(PauseArguments args) {
LOGGER.finer("pause");
Executors.newSingleThreadExecutor().submit(() -> {
LOGGER.finer("pause -> stopped");
StoppedEventArguments eventArguments = new StoppedEventArguments();
eventArguments.setThreadId(0);
eventArguments.setReason("pause");
launcher.getRemoteProxy().stopped(eventArguments);
});
return CompletableFuture.completedFuture(null);
}
// 8888888888888888888888888888888888888888888888888888888888888888888888888 //
//TODO: Instead of maintaining the stack here, we could evaluated with CallStackTool
// that will get the job done for us (tlc2.tool.impl.CallStackTool.callStack).
// However, CST only keeps the SemanticNode but skips the Context and the values. We
// would have to make CST take a function that applies a transformation for the debugger
// and a different one when CST does its original job.
private final Stack<TLCStackFrame> stack = new Stack<>();
// Initialize the debugger to immediately halt on the first frame.
private volatile int targetLevel = 1;
private volatile Step step = Step.In;
@Override
public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c, int control) {
final int level = this.stack.size();
LOGGER.finer(String.format("%s Call pushFrame: [%s], level: %s\n",
new String(new char[level]).replace('\0', '#'), expr, level));
stack.push(new TLCStackFrame(expr, c, tool));
haltExecution(expr, level);
return this;
}
@Override
public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c, TLCState ps) {
final int level = this.stack.size();
stack.push(new TLCInitStackFrame(expr, c, tool, ps));
haltExecution(expr, level);
return this;
}
@Override
public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c, TLCState predecessor, TLCState ps) {
final int level = this.stack.size();
stack.push(new TLCNextStackFrame(expr, c, tool, predecessor, ps));
haltExecution(expr, level);
return this;
}
@Override
public synchronized IDebugTarget pushFrame(TLCState state) {
TLCStackFrame f = this.stack.peek();
pushFrame(f.getTool(), f.getNode(), f.getContext(), state);
return this;
}
@Override
public synchronized IDebugTarget pushFrame(TLCState predecessor, TLCState state) {
TLCStackFrame f = this.stack.peek();
return pushFrame(f.getTool(), f.getNode(), f.getContext(), state);
}
@Override
public synchronized IDebugTarget popFrame(TLCState state) {
TLCStackFrame f = this.stack.peek();
return popFrame(f.getTool(), f.getNode(), f.getContext(), state);
}
@Override
public synchronized IDebugTarget popFrame(TLCState predecessor, TLCState state) {
return popFrame(state);
}
@Override
public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, int control) {
LOGGER.finer(String.format("%s Call popFrame: [%s], level: %s\n",
new String(new char[this.stack.size()]).replace('\0', '#'), expr, this.stack.size()));
final TLCStackFrame pop = stack.pop();
assert expr == pop.getNode();
return this;
}
@Override
public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, TLCState ps) {
final TLCStackFrame pop = stack.pop();
assert expr == pop.getNode();
return this;
}
@Override
public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, TLCState predecessor, TLCState ps) {
return popFrame(tool, expr, c, ps);
}
protected void haltExecution(SemanticNode expr, final int level) {
if (matches(step, targetLevel, level) || matches(expr)) {
sendStopped();
try {
// Halt TLC's evaluation by blocking on this (one-element) queue. The DAP
// front-end will add an element that will unblock us.
this.wait();
} catch (InterruptedException notExpectedToHappen) {
notExpectedToHappen.printStackTrace();
java.lang.Thread.currentThread().interrupt();
}
}
}
protected void sendStopped() {
LOGGER.finer("loadSource -> stopped");
StoppedEventArguments eventArguments = new StoppedEventArguments();
eventArguments.setThreadId(0);
launcher.getRemoteProxy().stopped(eventArguments);
}
// TODO: This is only working more or less for step.in.
private static boolean matches(Step dir, int targetLevel, int currentLevel) {
if (dir == Step.In) {
// TODO With this conditional, step.in becomes continue when one steps into a
// leave frame. The debuggers that I know don't continue in this case.
// if (currentLevel >= targetLevel) {
return true;
} else if (dir == Step.Over) {
if (currentLevel == targetLevel) {
return true;
}
} else if (dir == Step.Out) {
// When stepping out, level has to greater than or zero/0;
if (currentLevel < targetLevel || currentLevel == 0) {
return true;
}
}
return false;
}
private boolean matches(final SemanticNode expr) {
//TODO: Better match the location. However, it shouldn't be done down here
// but in setBreakpoints above that lets the debuggee tell the front-end
// that a user-defined location is "corrected" to one that matches the bounds
// of an expression in the semantic graph that is evaluated. In other words,
// setBreakpoints should traverse the semantic graph trying to find the smallest
// i.e. best match for the given editor location. The code here should then
// simple compare the two location instances.
final Location location = expr.getLocation();
return breakpoints.stream().anyMatch(b -> b.getLine() == location.beginLine());
}
}
|
package PageGuest;
import Configuration.Configuration;
import QueueHandlers.JMSStack;
import QueueHandlers.ResultQueue;
import Util.CurrencyHelper;
import Util.DatetimeHelper;
import Util.StringHelper;
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.dom.*;
import com.teamdev.jxbrowser.chromium.events.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.traveloptimizer.browserengine.TeamDevJxBrowser;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import static Util.StringHelper.escapeXML;
import static com.teamdev.jxbrowser.chromium.LoggerProvider.getBrowserLogger;
import static com.teamdev.jxbrowser.chromium.LoggerProvider.getChromiumProcessLogger;
import static com.teamdev.jxbrowser.chromium.LoggerProvider.getIPCLogger;
import java.util.*;
import java.util.logging.Level;
public class BookingDotComPageGuest extends WebPageGuest implements Runnable
{
private static org.apache.log4j.Logger mLogger = Logger.getLogger(BookingDotComPageGuest.class);
private static boolean mSTOP_AT_THE_FIRST_PAGE = false;
private Browser mBrowser = null;
private BrowserView mBrowserView = null;
private JTabbedPane mTabbedPane = null;
private boolean mThreadStopped = true;
private DOMDocument mDOMDocument;
private BookingDotComStatus mStatus = new BookingDotComStatus();
private AccomodationData_INPUT mADI;
private ArrayList<AccomodationData_RESULT> mAccomodationDataResults = new ArrayList<>();
private int mLastOpenedAccomodation = -1;
private ArrayList<AccomodationData_INPUT> mInputList = new ArrayList<>();
private int mInputListIndex = -1;
private String[] mFilters = null;
private int mFilterIndex = -1;
private Integer mLoadReadyTimeout = -1;
private boolean mSeparatorFound = false;
private HashSet<String> mHotelNames = new HashSet<>();
private int mHigherPriceCounter; // if 5 consecutive accomodation have only higher price than my limit, I stop the parsing.
private static final int HIGH_PRICE_FLAT_COUNT = 5;
private int mMatchedAccomodationCounter = 0;
enum MyFilterIds
{
checkin_no_till_limit,
room_size_15p,
room_size_20p,
room_size_25p,
room_size_30p,
room_size_35p,
room_size_50p,
room_size_60p,
room_size_70p,
room_size_80p,
room_size_90p,
room_size_100p,
};
class FilterAttribs {
public FilterAttribs( String name, String value )
{
mName = name;
mValue = value;
}
public String mName;
public String mValue;
}
private HashMap<String,FilterAttribs> mFilterMap = new HashMap<>();
private HashMap<String,MyFilterIds> mMyFilterMap = new HashMap<>();
private HashMap<MyFilterIds,Boolean> mMyFilterMap2 = new HashMap<>();
private boolean mResultSorted = false;
public class BrowserLoadAdapter extends LoadAdapter
{
private BookingDotComPageGuest mGuest;
public BrowserLoadAdapter( BookingDotComPageGuest guest )
{
mGuest = guest;
}
@Override
public void onStartLoadingFrame(StartLoadingEvent event) {
if (event.isMainFrame()) {
//System.out.println("Main frame has started loading");
}
}
@Override
public void onProvisionalLoadingFrame(ProvisionalLoadingEvent event) {
if (event.isMainFrame()) {
//System.out.println("Provisional load was committed for a frame");
}
}
@Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
synchronized( this )
{
if( event.isMainFrame())
{
//System.out.println( "Main frame has finished loading, status: " + mGuest.mStatus.getStatus());
if( !mSTOP_AT_THE_FIRST_PAGE )
{
Sleep( 2000 );
mGuest.mStatus.mainFrameLoaded( mGuest, event.getBrowser().getDocument() );
}
}
}
}
@Override
public void onFailLoadingFrame(FailLoadingEvent event) {
NetError errorCode = event.getErrorCode();
if (event.isMainFrame()) {
mLogger.error("Main frame has failed loading: " + errorCode);
}
}
@Override
public void onDocumentLoadedInFrame(FrameLoadEvent event) {
synchronized( mLoadReadyTimeout )
{
mLoadReadyTimeout = 50;
}
}
@Override
public void onDocumentLoadedInMainFrame(LoadEvent event) {
//System.out.println("Main frame document is loaded.");
}
}
// public void InitJMS()
// mLogger.trace( "begin, thread name: " + getThreadName());
// synchronized (mMutex)
// mSearchQueue = new JMSStack<>();
// mSearchQueue.setQueueName( "booking.com" );
// mLogger.trace( "end, thread name: " + getThreadName());
public void Init()
{
DoSearchFromConfig();
getBrowserLogger().setLevel( Level.WARNING );
getChromiumProcessLogger().setLevel( Level.WARNING );
getIPCLogger().setLevel( Level.WARNING );
mTabbedPane = new JTabbedPane();
JFrame frame = new JFrame( "Travel Optimizer - Booking.com - jxBrowser " + ProductInfo.getVersion());
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
mLogger.info( "Window is closing" );
mThreadStopped = true;
e.getWindow().dispose();
}
});
frame.getContentPane().add( mTabbedPane, BorderLayout.CENTER );
frame.setSize( 1152, 964 );
frame.setLocation( 50, 50 );
frame.setVisible( true );
mBrowser = TeamDevJxBrowser.getInstance().getJxBrowser( "Booking.com" );
mBrowserView = new BrowserView( mBrowser );
mTabbedPane.addTab( "Browser", mBrowserView );
mBrowser.addLoadListener(new BrowserLoadAdapter( this ));
// booking.com filters
mFilterMap.put( "price_0-50", new FilterAttribs( "data-id", "pri-1"));
mFilterMap.put( "price_50-100", new FilterAttribs( "data-id", "pri-2") );
mFilterMap.put( "price_100-150", new FilterAttribs( "data-id", "pri-3") );
mFilterMap.put( "price_150-200", new FilterAttribs( "data-id", "pri-4") );
mFilterMap.put( "price_200+", new FilterAttribs( "data-id", "pri-5") );
mFilterMap.put( "free_wifi", new FilterAttribs( "data-id", "hotelfacility-107" ));
mFilterMap.put( "parking_place", new FilterAttribs( "data-id", "hotelfacility-2" ));
mFilterMap.put( "non_smoking_rooms", new FilterAttribs( "data-id", "hotelfacility-16" ));
mFilterMap.put( "restaurant", new FilterAttribs( "data-id", "hotelfacility-3" ));
mFilterMap.put( "apartments", new FilterAttribs( "data-id", "ht_id-201" ));
mFilterMap.put( "hotels", new FilterAttribs( "data-id", "ht_id-204" ));
mFilterMap.put( "free_cancellation", new FilterAttribs( "data-id", "fc-1" ));
mFilterMap.put( "24h_reception", new FilterAttribs( "data-id", "hr_24-8" ));
mFilterMap.put( "private_bathroom", new FilterAttribs( "data-id", "roomfacility-800038" ));
mFilterMap.put( "air_conditioning", new FilterAttribs( "data-id", "roomfacility-800011" ));
mFilterMap.put( "bath", new FilterAttribs( "data-id", "roomfacility-80005" ));
mFilterMap.put( "electric_kettle", new FilterAttribs( "data-id", "roomfacility-800086" ));
mFilterMap.put( "washing_machine", new FilterAttribs( "data-id", "roomfacility-800034" ));
mFilterMap.put( "score_9+", new FilterAttribs( "data-id", "review_score-90" ));
mFilterMap.put( "score_8+", new FilterAttribs( "data-id", "review_score-80" ));
mFilterMap.put( "score_7+", new FilterAttribs( "data-id", "review_score-70" ));
mFilterMap.put( "score_6+", new FilterAttribs( "data-id", "review_score-60" ));
mFilterMap.put( "score_no", new FilterAttribs( "data-id", "review_score-999" ));
mFilterMap.put( "exclude_sold_out", new FilterAttribs( "data-id", "oos-1" ));
// My filters
mMyFilterMap.put( "checkin_no_till_limit", MyFilterIds.checkin_no_till_limit );
mMyFilterMap.put( "room_size_15+", MyFilterIds.room_size_15p );
mMyFilterMap.put( "room_size_20+", MyFilterIds.room_size_20p );
mMyFilterMap.put( "room_size_25+", MyFilterIds.room_size_25p );
mMyFilterMap.put( "room_size_30+", MyFilterIds.room_size_30p );
mMyFilterMap.put( "room_size_35+", MyFilterIds.room_size_35p );
mMyFilterMap.put( "room_size_50+", MyFilterIds.room_size_50p );
mMyFilterMap.put( "room_size_60+", MyFilterIds.room_size_60p );
mMyFilterMap.put( "room_size_70+", MyFilterIds.room_size_70p );
mMyFilterMap.put( "room_size_80+", MyFilterIds.room_size_80p );
mMyFilterMap.put( "room_size_90+", MyFilterIds.room_size_90p );
mMyFilterMap.put( "room_size_100+", MyFilterIds.room_size_100p );
for( MyFilterIds id : MyFilterIds.values())
mMyFilterMap2.put( id, false );
//InitJMS();
startANewSearch();
}
public void startANewSearch()
{
mStatus.starting( this );
mAccomodationDataResults = new ArrayList<>();
mHotelNames = new HashSet<>();
mResultSorted = false;
mHigherPriceCounter = HIGH_PRICE_FLAT_COUNT;
mMatchedAccomodationCounter = 0;
mBrowser.loadURL( getURL());
}
public BookingDotComPageGuest()
{
super( null, "https:
mThread = new Thread(this);
mThread.setName("BookingDotComPageGuest " + LocalDateTime.now().format( DateTimeFormatter.ISO_LOCAL_DATE_TIME));
mThread.start();
}
public void DoSearch(String aFrom, String aTo, String aDepartureDate, String aReturnDate )
{
}
public void DoSearchFromConfig()
{
ArrayList<AccomodationData_INPUT> lSearchList = Configuration.getInstance().getSearchListAccom();
for( AccomodationData_INPUT lADI : lSearchList )
{
if( lADI.mSite != 'B' )
continue;
PageGuest.DateValidity lValidity = ValidateDate(lADI.mCheckIn, lADI.mCheckOut);
if( lValidity == PageGuest.DateValidity.INVALID_COMBINATION )
{
mLogger.warn( "DoSearch: the departure date (" + lADI.mCheckIn + ") and/or the return date " +
lADI.mCheckOut + " is/are invalid!" );
continue;
}
if( lValidity == PageGuest.DateValidity.BOTH_OF_THEM_VALID )
{
mInputList.add( lADI );
}
}
}
@Override
public void run()
{
mThreadStopped = false;
while( !mThreadStopped )
{
try
{
Thread.sleep( 100 );
synchronized( mLoadReadyTimeout )
{
if( mLoadReadyTimeout > 0 )
{
--mLoadReadyTimeout;
if( mLoadReadyTimeout == 0 )
{
if( mStatus.getStatus() == BookingDotComStatus.Status.APPLYING_A_FILTER && isResultPage( mBrowser.getDocument()))
{
//mBrowser.saveWebPage( "filtered_result.html", "c:\\temp", SavePageType.ONLY_HTML);
mLogger.info( "run Status: " + mStatus.getStatus());
mStatus.mainFrameLoaded( this, mBrowser.getDocument());
}
else if(( mStatus.getStatus() == BookingDotComStatus.Status.NEXT_PAGE_LOADING )
&& isResultPage( mBrowser.getDocument()))
{
mLogger.info("run Status: " + mStatus.getStatus());
mStatus.mainFrameLoaded( this, mBrowser.getDocument());
}
}
}
}
}
catch( InterruptedException e )
{
mLogger.warn( StringHelper.getTraceInformation( e ));
}
}
}
private boolean setChecked( String path, boolean checked )
{
DOMElement lElement = mDOMDocument.findElement( By.xpath( path ));
if( lElement == null )
return false;
DOMInputElement lRadio = (DOMInputElement)lElement;
//lRadio.isRadioButton()
lRadio.setChecked( checked );
return true;
}
private boolean jQuerySetSelect( String id, String value )
{
mBrowser.executeJavaScript( "$(\"#" + id + "\").val('" + value + "').change();");
return true;
}
private boolean jQuerySetSelect2( String jQuery, String value )
{
mBrowser.executeJavaScript( jQuery + ".val('" + value + "').change();");
return true;
}
public void FillTheFormByRobot()
{
// destination
MouseLeftClick( 120, 440 );
Sleep( 500 );
PressCtrlA();
Sleep( 500 );
PressDelete();
Sleep( 500 );
//TypeText( "Budapest, Pest, Hungary" );
TypeText( mADI.mCity );
Sleep( 5000 );
PressDown();
Sleep( 1000 );
TypeText( "\n" );
Sleep( 1000 );
TypeText( "\t" );
Sleep( 1000 );
// check-in
//TypeText( "24072017\t" );
//System.out.println( mADI.mCheckIn );
TypeText( DatetimeHelper.ReverseDate( mADI.mCheckIn ) + "\t" );
Sleep( 1000 );
// check-out
//TypeText( "01082017\t" );
//System.out.println( mADI.mCheckOut );
TypeText( DatetimeHelper.ReverseDate( mADI.mCheckOut ) + "\t" );
Sleep( 1000 );
// travelling for leisure radio
/**
*
* @param filter
* @return true, if my filter was applied, otherwise false
*/
boolean ApplyMyFilters( String filter )
{
if( mMyFilterMap.containsKey( filter ))
{
mMyFilterMap2.put( mMyFilterMap.get( filter ), true );
//mCheckinNoTillLimitation = true;
return true;
}
return false;
}
boolean ApplySortingFilter( DOMDocument aDOMDocument )
{
// sort_by_price
// <div id="sort_by" class=" hilite ">
// <li class=" sort_category sort_price sort_category__button ">
// <a href="/searchresults.en-gb.html?label=gen173nr-1DCAEoggJCAlhYSDNiBW5vcmVmaDuIAQGYAS7CAQNhYm7IAQzYAQPoAQGSAgF5qAIE;sid=bb513d800525df12982c6f7fd2158280;age=11;age=8;checkin_month=9;checkin_monthday=8;checkin_year=2017;checkout_month=9;checkout_monthday=11;checkout_year=2017;class_interval=1;dest_id=-850553;dest_type=city;dtdisc=0;group_adults=1;group_children=2;inac=0;index_postcard=0;label_click=undef;no_rooms=1;postcard=0;raw_dest_type=city;req_age=11;req_age=8;room1=A%2C8%2C11;sb_price_type=total;sb_travel_purpose=leisure;src_elem=sb;ss=Budapest;ss_all=0;ssb=empty;sshis=0;ssne=Budapest;ssne_untouched=Budapest&;order=price" class="sort_option sort_options__button">
// Cheapest properties first
DOMElement sortBar = aDOMDocument.findElement( By.id( "sort_by" ));
if( sortBar == null )
return false;
DOMElement priceLi = sortBar.findElement( By.className( "sort_price" ));
if( priceLi == null )
return false;
DOMElement priceA = priceLi.findElement( By.tagName( "a" ));
if( priceA == null )
return false;
priceA.click();
return true;
}
boolean ApplyBookingFilters( DOMDocument aDOMDocument, String filter )
{
FilterAttribs f = mFilterMap.get( filter );
if( f == null )
return false;
java.util.List<DOMElement> lFilters = aDOMDocument.findElements( By.className( "filterelement" ));
for( DOMElement lElement : lFilters )
{
// System.out.println( f.mName );
// System.out.println( f.mValue );
// System.out.println( "'" + lElement.getAttribute( f.mName ) + "'" );
if( lElement.getAttribute( f.mName ).equals( f.mValue ))
{
mStatus.ApplyAFilter( this );
//Sleep( 7000 );
lElement.click();
return true;
}
}
return false;
}
boolean ApplyFilter( DOMDocument aDOMDocument, String filter ) {
mLogger.info( "FILTER: " + filter );
if( ApplyMyFilters( filter ))
return false;
if( ApplyBookingFilters( aDOMDocument, filter ))
return true;
mLogger.warn( "Illegal filter: " + filter );
return false;
}
void ApplyFilter( DOMDocument aDOMDocument )
{
if( !mResultSorted )
{
if( ApplySortingFilter( aDOMDocument ))
mResultSorted = true;
}
// if the form was not filled, because the rearch result was loaded from url, then
// the getNextFilter returns with null
for( String filter = getNextFilter(); filter != null; filter = getNextFilter())
{
if( ApplyFilter( aDOMDocument, filter ))
return;
}
mLogger.info( "mBrowser.getURL: " + mBrowser.getURL());
mLogger.info( "escaped URL: " + escapeXML( mBrowser.getURL()));
ParseTheResult( aDOMDocument );
}
boolean testSoldOut( DOMElement element )
{
if( element.getAttribute( "class" ).contains( "sr_item--soldout" ))
return true;
if( element.findElement( By.className( "sold_out_msg" )) != null )
return true;
if( element.findElement( By.className( "sold_out_property" )) != null )
return true;
if( element.findElement( By.className( "sold_out_msg" )) != null )
return true;
if( element.getInnerHTML().contains( "You missed it!" ))
return true;
return false;
}
boolean testRecommendation( DOMElement element )
{
if( element.getInnerHTML().contains( "We recommend this property in" ))
return true;
return false;
}
void ParseTheResult( DOMDocument aDOMDocument )
{
mStatus.parsingTheResult( this );
mDOMDocument = aDOMDocument;
//Sleep( 10_000 );
java.util.List<DOMElement> lElements = mDOMDocument.findElements( By.className( "sr_item" ));
if( lElements != null )
{
for( DOMElement lElement : lElements )
{
if( testSoldOut( lElement ) || testRecommendation( lElement ))
continue;
if( lElement.getAttribute( "class" ).contains( "sr_separator" ))
{
mSeparatorFound = true;
break;
}
AccomodationData_RESULT lResult = new AccomodationData_RESULT();
lResult.mAccomodationData_INPUT = mADI;
DOMElement lName = lElement.findElement( By.className( "sr-hotel__name" ));
DOMElement lURL = lElement.findElement( By.className( "hotel_name_link url" ));
DOMElement lPrice = lElement.findElement( By.className( "sr_gs_price_total" ));
if( lName != null )
{
lResult.mName = lName.getInnerText();
if( mHotelNames.contains( lResult.mName ))
continue;
mHotelNames.add( lResult.mName );
//System.out.println( "Name: " + lResult.mName );
} else {
continue;
}
if( lURL != null )
{
lResult.mURL = lURL.getAttribute( "href" );
//System.out.println( "URL: " + getURL() + lResult.mURL );
}
if( lPrice != null )
{
//lResult.mPrice = CurrencyHelper.convertPriceToPriceInEuro( lPrice.getInnerText(), false );
//System.out.println( "Price: " + lResult.mPrice );
}
if( lElement.hasAttribute( "data-score" ))
{
try
{
lResult.mScore = Double.parseDouble( lElement.getAttribute( "data-score" ) );
//System.out.println( "Score: " + lResult.mScore );
}
catch( java.lang.NumberFormatException e )
{
}
}
mAccomodationDataResults.add( lResult );
}
}
// The mDOMDocument mustn't be null, because the pageNext will be called from the parsingFinished.
mStatus.parsingFinished( this );
mDOMDocument = null;
}
public boolean pageNext()
{
if( mSeparatorFound )
return false;
// <a class="paging-next ga_sr_gotopage_2_18" data-page-next="" href="...">Next page</a>
DOMElement lElement = mDOMDocument.findElement( By.className( "paging-next" ));
if( lElement == null )
return false;
lElement.click();
return true;
}
public boolean isResultPage( DOMDocument aDOMDocument )
{
DOMElement lElement = aDOMDocument.findElement( By.className( "sr_item" ));
return lElement != null;
}
public boolean openTheNextHotel()
{
if( mADI.mAccomodationLimit != 0 && mMatchedAccomodationCounter == mADI.mAccomodationLimit )
{
mLogger.info( "We have reached the accomodation limit." );
return false;
}
if( mHigherPriceCounter >= 0 && mLastOpenedAccomodation + 1 < mAccomodationDataResults.size())
{
++mLastOpenedAccomodation;
mBrowser.loadURL( getURL() + mAccomodationDataResults.get( mLastOpenedAccomodation ).mURL );
return true;
}
if( mHigherPriceCounter < 0 )
mLogger.info( "The last 5 accomodation haven't had lower price than the limit." );
return false;
}
boolean testCheckinPolicy( String checkinPolicy )
{
if( !mMyFilterMap2.getOrDefault( MyFilterIds.checkin_no_till_limit, false ))
return true;
if( checkinPolicy.length() == 0 || checkinPolicy.startsWith( "From" ))
return true;
// CheckInPolicy: 15:00 - 23:00
return false;
}
private String getRoomSize( String roomMetaId )
{
String roomSize = "";
if( roomMetaId != null )
{
// cutting the starting
roomMetaId = roomMetaId.substring( 1 );
// blocktoggle #RD17925503
DOMElement lRoomMetaBlock = mDOMDocument.findElement( By.id( "blocktoggle" + roomMetaId ));
if( lRoomMetaBlock != null )
{
DOMElement lRoomInfo = lRoomMetaBlock.findElement( By.className( "info" ));
if( lRoomInfo != null )
{
roomSize = lRoomInfo.getInnerText()
.replaceAll( "\n", "" )
.replace( "Room size:", "" )
.replace( "Apartment size:", "" )
.trim();
}
}
}
return roomSize;
}
boolean testRoomSize( String roomSize )
{
if( roomSize == null || roomSize.length() == 0 )
return true;
try
{
int size = Integer.parseInt( roomSize.substring( 0, roomSize.indexOf( " " ) ) );
if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_15p, false ) && size < 15 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_20p, false ) && size < 20 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_25p, false ) && size < 25 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_30p, false ) && size < 30 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_35p, false ) && size < 35 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_50p, false ) && size < 50 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_60p, false ) && size < 60 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_70p, false ) && size < 70 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_80p, false ) && size < 80 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_90p, false ) && size < 90 )
return false;
else if( mMyFilterMap2.getOrDefault( MyFilterIds.room_size_100p, false ) && size < 100 )
return false;
}
catch( NumberFormatException e )
{
mLogger.warn( StringHelper.getTraceInformation( e ));
mLogger.warn( "roomSize: '" + roomSize + "'" );
return true;
}
return true;
}
private void ParseAHotelPage_S( AccomodationData_RESULT lAccomodation )
{
// check-out policy:
// <div class="description" id="checkout_policy"><p class="policy_name"><span>Check-out</span></p><p>Until 11:00 hours</p><div style="clear:both"></div></div>
DOMElement lCheckoutPolicy = mDOMDocument.findElement( By.id( "checkout_policy" ));
if( lCheckoutPolicy != null )
{
lAccomodation.mCheckOutPolicy = lCheckoutPolicy.getInnerText();
if( lAccomodation.mCheckOutPolicy.startsWith( "Check-out\n" ))
lAccomodation.mCheckOutPolicy = lAccomodation.mCheckOutPolicy.substring( "Check-out\n".length());
lAccomodation.mCheckOutPolicy = lAccomodation.mCheckOutPolicy.trim();
}
// Address
DOMElement lAddress = mDOMDocument.findElement( By.className( "hp_address_subtitle" ));
if( lAddress != null )
{
lAccomodation.mAddress = lAddress.getInnerText();
}
// map link
// <a data-source="top_link" class="show_map jq_tooltip show_map_with_endorsements " href="javascript:void(0);" data-bbox="19.0532273054123,47.4821070329846,19.1041785478592,47.506432153588" data-coords="," rel="" data-node_tt_id="show_map_endorsements_tooltip" data-width="300" id="show_id75172" style="white-space:nowrap" data-title="Atlas City Hotel, Budapest - Check location">Show map</a>
// room link: <a href="#RD7517221" class="jqrt togglelink js-track-hp-rt-room-name" data-room-name-en="Family Room" title="" aria-haspopup="true"><i class="rt_room_type_ico bicon-triangleright"></i>Family Room</a>
// room link: <a href="#RD7517204" class="jqrt togglelink js-track-hp-rt-room-name" data-room-name-en="Quadruple Room" title="" aria-haspopup="true"><i class="rt_room_type_ico bicon-triangleright"></i>Quadruple Room</a>
// room block:
// room name: <a href="#RD7517222" class="jqrt togglelink js-track-hp-rt-room-name" data-room-name-en="Comfort Double or Twin Room" title="" aria-haspopup="true"><i class="rt_room_type_ico bicon-triangleright"></i>Comfort Double or Twin Room</a>
//mStatus.Done( this );
boolean foundLowerPrice = false;
for( int i = 1; ; i++ )
{
java.util.List<DOMElement> lRooms = mDOMDocument.findElements( By.className( "room_loop_counter" + i ));
if( lRooms == null || lRooms.size() == 0 )
break;
String roomName = "";
String roomSize = "";
AccomodationData_RESULT.Room lRoomResult = new AccomodationData_RESULT.Room();
for( DOMElement lRoom : lRooms )
{
String cssClassName = lRoom.getAttribute( "class" );
if( cssClassName.contains( "extendedRow" ))
{
// this is the very last row without valueable information
continue;
}
if( cssClassName.contains( "maintr" ))
{
// here are the main information, which can be common among more rooms
DOMElement lRoomName = lRoom.findElement( By.className( "js-track-hp-rt-room-name" ));
if( lRoomName != null )
{
lRoomResult.mName = lRoomName.getAttribute( "data-room-name-en" );
lRoomResult.mRoomHook = lRoomName.getAttribute( "href" );
lRoomResult.mRoomSize = getRoomSize( lRoomResult.mRoomHook );
if( !testRoomSize( lRoomResult.mRoomSize ))
continue;
}
}
else
{
// MAX OCCUPAMCY
String maxOccupancy = lRoom.getAttribute( "data-occupancy" );
if( maxOccupancy != null && maxOccupancy.length() > 0 )
lRoomResult.mMaxOccupancy = maxOccupancy;
try
{
//System.out.println( "lRoomResult.mMaxOccupancy: '" + lRoomResult.mMaxOccupancy + "'" );
if( Integer.parseInt( lRoomResult.mMaxOccupancy ) < mADI.mAdultNumber + mADI.mChildrenNumber )
continue;
}
catch( NumberFormatException e )
{
mLogger.warn( StringHelper.getTraceInformation( e ));
}
// PRICE
DOMElement lPrice = lRoom.findElement( By.className( "js-track-hp-rt-room-price" ));
if( lPrice == null && mADI.mPriceLimit != 0 )
continue;
if( lPrice != null )
{
lRoomResult.mPrice = CurrencyHelper.convertPriceToPriceInEuro( lPrice.getInnerText(), false );
if( mADI.mPriceLimit != 0 )
{
if( lRoomResult.mPrice > (double) mADI.mPriceLimit )
continue;
foundLowerPrice = true;
}
}
// BREAKFAST
lRoomResult.mBreakfastIncluded = "1".equals( lRoom.getAttribute( "data-breakfast-included" ));
// Cancellation
DOMElement lCancellation = lRoom.findElement( By.id( "cancel_policy_first" ));
if( lCancellation != null )
lRoomResult.mCancellationPolicy = lCancellation.getInnerText();
lAccomodation.mAvailableRooms.add( lRoomResult );
try
{
lRoomResult = (AccomodationData_RESULT.Room) lRoomResult.clone();
}
catch( CloneNotSupportedException e )
{
e.printStackTrace();
}
}
}
}
if( mADI.mPriceLimit > 0 )
{
if( foundLowerPrice )
mHigherPriceCounter = HIGH_PRICE_FLAT_COUNT;
else
--mHigherPriceCounter;
}
if( lAccomodation.mAvailableRooms.size() > 0 )
++mMatchedAccomodationCounter;
}
public void ParseAHotelPage( DOMDocument aDOMDocument )
{
mStatus.parsingAHotelPage( this );
mDOMDocument = aDOMDocument;
AccomodationData_RESULT lAccomodation = mAccomodationDataResults.get( mLastOpenedAccomodation );
lAccomodation.mSite = 'B';
// check-in policy:
// <div class="description" id="checkin_policy"><p class="policy_name"><span>Check-in</span></p><p>From 14:00 hours</p><div style="clear:both"></div></div>
DOMElement lCheckinPolicy = mDOMDocument.findElement( By.id( "checkin_policy" ));
if( lCheckinPolicy != null )
{
lAccomodation.mCheckInPolicy = lCheckinPolicy.getInnerText();
if( lAccomodation.mCheckInPolicy.startsWith( "Check-in\n" ))
lAccomodation.mCheckInPolicy = lAccomodation.mCheckInPolicy.substring( "Check-in\n".length());
lAccomodation.mCheckInPolicy = lAccomodation.mCheckInPolicy.trim();
}
if( testCheckinPolicy( lAccomodation.mCheckInPolicy ))
ParseAHotelPage_S( lAccomodation );
mStatus.parsingFinished( this );
mDOMDocument = null;
}
public void printTheMatches()
{
mLogger.info( "**************************************************************" );
mLogger.info( "**************************** MATCHES *************************" );
mLogger.info( "**************************************************************" );
mLogger.info( "Search data:\n" + mADI.toString());
for( AccomodationData_RESULT lAccomodation : mAccomodationDataResults )
{
if( lAccomodation.mAvailableRooms.size() == 0 )
continue;
ResultQueue.getInstance().push( lAccomodation );
mLogger.info( "HOTEL: " + lAccomodation.mName + "; Score: " + lAccomodation.mScore );
mLogger.info( getURL() + lAccomodation.mURL );
mLogger.info( "Address: " + lAccomodation.mAddress );
for( AccomodationData_RESULT.Room lRoom : lAccomodation.mAvailableRooms )
{
mLogger.info( "Room: " + lRoom.mName );
mLogger.info( " Size: " + lRoom.mRoomSize );
mLogger.info( " MaxOccupancy: " + lRoom.mMaxOccupancy );
mLogger.info( " BreakfastIncluded: " + lRoom.mBreakfastIncluded );
mLogger.info( " Price: " + lRoom.mPrice );
}
mLogger.info( "CheckInPolicy: " + lAccomodation.mCheckInPolicy );
mLogger.info( "CheckOutPolicy: " + lAccomodation.mCheckOutPolicy );
}
}
}
|
package to.etc.domui.component.layout;
import to.etc.domui.component.buttons.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.state.*;
public class ButtonBar extends Table {
private final TD m_center;
public ButtonBar() {
setCssClass("ui-buttonbar");
setCellSpacing("0");
setCellPadding("0");
setTableWidth("100%");
TBody b = new TBody();
add(b);
b.addRow();
TD td = b.addCell();
// td.setWidth("15px");
// td.setHeight("26px");
td.setCssClass("ui-bb-left");
m_center = b.addCell();
m_center.setCssClass("ui-bb-middle");
td = b.addCell();
td.setCssClass("ui-bb-right");
}
public DefaultButton addButton(final String txt, final String icon, final IClicked<DefaultButton> click) {
DefaultButton b = new DefaultButton(txt, icon, click);
m_center.add(b);
return b;
}
public DefaultButton addButton(final String txt, final IClicked<DefaultButton> click) {
DefaultButton b = new DefaultButton(txt, click);
m_center.add(b);
return b;
}
public DefaultButton addBackButton(final String txt, final String icon) {
DefaultButton b = new DefaultButton(txt, icon, new IClicked<DefaultButton>() {
public void clicked(final DefaultButton bxx) throws Exception {
UIGoto.back();
}
});
m_center.add(b);
return b;
}
public DefaultButton addBackButton() {
return addBackButton("Terug", "THEME/btnCancel.png");
}
public NodeContainer getContent() {
return m_center;
}
}
|
package edu.cs4730.fitdemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.Bucket;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataDeleteRequest;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.request.DataUpdateRequest;
import com.google.android.gms.fitness.result.DailyTotalResult;
import com.google.android.gms.fitness.result.DataReadResult;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* A simple example of how to use the history API.
*/
public class HistoryFragment extends Fragment implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
Handler handler;
static final int REQUEST_OAUTH = 3;
String TAG = "HistoryFrag";
TextView logger;
Button btn_ViewWeek, btn_ViewToday, btn_AddSteps, btn_UpdateSteps, btn_DeleteSteps;
public HistoryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create the client needed.
mGoogleApiClient = new GoogleApiClient.Builder(getActivity().getApplicationContext())
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
//have it login the user instead of us doing it manually.
.enableAutoManage(getActivity(), REQUEST_OAUTH, this)
.build();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_history, container, false);
handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == 0) {
Bundle stuff = msg.getData();
logthis(stuff.getString("logthis"));
}
return true;
}
});
logger = (TextView) myView.findViewById(R.id.loggerh);
btn_ViewWeek = (Button) myView.findViewById(R.id.btn_view_week);
btn_ViewWeek.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ViewWeekStepCountTask().execute();
}
});
btn_ViewToday = (Button) myView.findViewById(R.id.btn_view_today);
btn_ViewToday.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ViewTodaysStepCountTask().execute();
}
});
btn_AddSteps = (Button) myView.findViewById(R.id.btn_add_steps);
btn_AddSteps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AddStepsToGoogleFitTask().execute();
}
});
btn_UpdateSteps = (Button) myView.findViewById(R.id.btn_update_steps);
btn_UpdateSteps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new UpdateStepsOnGoogleFitTask().execute();
}
});
btn_DeleteSteps = (Button) myView.findViewById(R.id.btn_delete_steps);
btn_DeleteSteps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// new DeleteYesterdaysStepsTask().execute(); //this one uses an asynctask
DeleteYesterdaysStepsResultcallBack(); //this one uses a resultcallback() method.
}
});
return myView;
}
public void logthis(String item) {
Log.i(TAG, item);
logger.append(item + "\n");
}
public void sendmessage(String logthis) {
Bundle b = new Bundle();
b.putString("logthis", logthis);
Message msg = handler.obtainMessage();
msg.setData(b);
msg.arg1 = 1;
msg.what = 0;
handler.sendMessage(msg);
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
}
}
@Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
}
}
@Override
public void onConnected(Bundle bundle) {
logthis("OnConnected!");
}
@Override
public void onConnectionSuspended(int i) {
logthis("OnConnectionSuspected");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
logthis("onConnectionFailed cause:" + connectionResult.toString());
}
//A method to display the dataset data. It's google method, but modified fo this example.
private void showDataSet(DataSet dataSet) {
sendmessage("Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getDateInstance();
DateFormat timeFormat = DateFormat.getTimeInstance();
for (DataPoint dp : dataSet.getDataPoints()) {
//I'm using a handler here to cheat, since I'm not in the asynctask and can't call publishprogress.
sendmessage("Data point:");
sendmessage("\tType: " + dp.getDataType().getName());
sendmessage("\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
sendmessage("\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
for (Field field : dp.getDataType().getFields()) {
sendmessage("\tField: " + field.getName() +
" Value: " + dp.getValue(field));
}
}
}
//this method is called from many of the aysnctask below, so it is all here instead
//This method will list the step data for the last week
private void displayLastWeeksData() {
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
//show the dates requested
java.text.DateFormat dateFormat = DateFormat.getDateInstance();
sendmessage("Range Start: " + dateFormat.format(startTime));
sendmessage("Range End: " + dateFormat.format(endTime));
//Check how many steps were walked and recorded in the last 7 days
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
//now submit the request.
DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1, TimeUnit.MINUTES);
//Used for aggregated data
if (dataReadResult.getBuckets().size() > 0) {
sendmessage("Number of buckets: " + dataReadResult.getBuckets().size());
for (Bucket bucket : dataReadResult.getBuckets()) {
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
showDataSet(dataSet);
}
}
}
//Used for non-aggregated data
else if (dataReadResult.getDataSets().size() > 0) {
sendmessage("Number of returned DataSets: " + dataReadResult.getDataSets().size());
for (DataSet dataSet : dataReadResult.getDataSets()) {
showDataSet(dataSet);
}
}
}
//Asnyc Task to complete the choices
//This one is very simple, because it is only today information
// A note, that step count doesn't actually require authenication, so it can be easily used for wear
// In use, call this every 30 seconds in active mode, 60 in ambient for watch faces
class ViewTodaysStepCountTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
DailyTotalResult result = Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA).await(1, TimeUnit.MINUTES);
showDataSet(result.getTotal());
return null;
}
}
//show the step count for the last 7 days.
class ViewWeekStepCountTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
displayLastWeeksData();
return null;
}
}
//add data into the fit system.
//Note, you can't over lapping data, it will be ignored, so use update if data already exists for this time period.
class AddStepsToGoogleFitTask extends AsyncTask<Void, String, Void> {
protected Void doInBackground(Void... params) {
//Adds steps spread out evenly from start time to end time
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();
DataSource dataSource = new DataSource.Builder()
.setAppPackageName(getActivity())
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setName("Step Count")
.setType(DataSource.TYPE_RAW)
.build();
int stepCountDelta = 10000; //we will add 10,000 steps for yesterday.
DataSet dataSet = DataSet.create(dataSource);
DataPoint point = dataSet.createDataPoint()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
dataSet.add(point);
com.google.android.gms.common.api.Status status = Fitness.HistoryApi.insertData(mGoogleApiClient, dataSet).await(1, TimeUnit.MINUTES);
if (!status.isSuccess()) {
publishProgress("Problem with inserting data: " + status.getStatusMessage());
} else {
publishProgress("data inserted");
}
displayLastWeeksData();
return null;
}
protected void onProgressUpdate(String... item) {
logthis(item[0]);
}
}
//This will update the existing data and add the step count.
class UpdateStepsOnGoogleFitTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//If two entries overlap, the new data is dropped when trying to insert. Instead, you need to use update
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();
DataSource dataSource = new DataSource.Builder()
.setAppPackageName(getActivity())
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setName("Step Count")
.setType(DataSource.TYPE_RAW)
.build();
int stepCountDelta = 20000; //add another 20K steps to the data already there.
DataSet dataSet = DataSet.create(dataSource);
DataPoint point = dataSet.createDataPoint()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
dataSet.add(point);
DataUpdateRequest updateRequest = new DataUpdateRequest.Builder().setDataSet(dataSet).setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS).build();
Fitness.HistoryApi.updateData(mGoogleApiClient, updateRequest).await(1, TimeUnit.MINUTES);
displayLastWeeksData();
return null;
}
}
//simple function to delete data. this case the step_count for today.
class DeleteYesterdaysStepsTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
DataDeleteRequest request = new DataDeleteRequest.Builder()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.addDataType(DataType.TYPE_STEP_COUNT_DELTA)
.build();
Fitness.HistoryApi.deleteData(mGoogleApiClient, request).await(1, TimeUnit.MINUTES);
displayLastWeeksData();
return null;
}
}
//using a resultcallback, we don't need to use an ansyctask/thread.
//not the result is NOT on the main thread.
void DeleteYesterdaysStepsResultcallBack() {
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
DataDeleteRequest request = new DataDeleteRequest.Builder()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.addDataType(DataType.TYPE_STEP_COUNT_DELTA)
.build();
Fitness.HistoryApi.deleteData(mGoogleApiClient, request)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
sendmessage("Successfully deleted today's step count");
} else {
sendmessage("FAILED to delete today's step count");
}
//wait, we are on the UI thread! doc's say we are not supported to be.
new ViewWeekStepCountTask().execute();
//displayLastWeeksData();
}
});
}
}
|
package com.backendless.push;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;
import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.messaging.AndroidPushTemplate;
import com.backendless.messaging.PublishOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class BackendlessPushService extends IntentService implements PushReceiverCallback
{
private static final String TAG = "BackendlessPushService";
private static final Random random = new Random();
private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis( 3600 );
private static final String TOKEN = Long.toBinaryString( random.nextLong() );
private static final String EXTRA_TOKEN = "token";
private PushReceiverCallback callback;
public BackendlessPushService()
{
this( "BackendlessPushService" );
}
public BackendlessPushService( String name )
{
super( name );
this.callback = this;
}
public BackendlessPushService( PushReceiverCallback callback )
{
super(null);
this.callback = callback;
}
/**
* At this point {@link com.backendless.push.BackendlessBroadcastReceiver}
* is still holding a wake lock
* for us. We can do whatever we need to here and then tell it that
* it can release the wakelock. This sample just does some slow work,
* but more complicated implementations could take their own wake
* lock here before releasing the receiver's.
* <p/>
* Note that when using this approach you should be aware that if your
* service gets killed and restarted while in the middle of such work
* (so the Intent gets re-delivered to perform the work again), it will
* at that point no longer be holding a wake lock since we are depending
* on SimpleWakefulReceiver to that for us. If this is a concern, you can
* acquire a separate wake lock here.
*/
@Override
protected void onHandleIntent( Intent intent )
{
try
{
handleIntent( this, intent );
}
finally
{
BackendlessBroadcastReceiver.completeWakefulIntent( intent );
}
}
public void onRegistered( Context context, String registrationId )
{
}
public void onUnregistered( Context context, Boolean unregistered )
{
}
public boolean onMessage( Context context, Intent intent )
{
return true;
}
public void onError( Context context, String message )
{
throw new RuntimeException( message );
}
void handleIntent( Context context, Intent intent )
{
String action = intent.getAction();
switch ( action )
{
case GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK:
handleRegistration( context, intent );
break;
case GCMConstants.INTENT_FROM_GCM_MESSAGE:
handleMessage( context, intent );
break;
case GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY:
handleRetry( context, intent );
break;
}
}
private void handleRetry( Context context, Intent intent )
{
String token = intent.getStringExtra( EXTRA_TOKEN );
if( !TOKEN.equals( token ) )
return;
// retry last call
if( GCMRegistrar.isRegistered( context ) )
GCMRegistrar.internalUnregister( context );
else
GCMRegistrar.internalRegister( context, GCMRegistrar.getSenderId( context ) );
}
private void handleMessage( final Context context, Intent intent )
{
final int messageId = intent.getIntExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, 0 );
final String message = intent.getStringExtra( PublishOptions.MESSAGE_TAG );
try
{
final String templateName = intent.getStringExtra( PublishOptions.TEMPLATE_NAME );
if( templateName != null )
{
if( PushTemplateHelper.getPushNotificationTemplates() == null )
PushTemplateHelper.restorePushTemplates();
AndroidPushTemplate androidPushTemplate = PushTemplateHelper.getPushNotificationTemplates().get( templateName );
if( androidPushTemplate != null )
{
if( androidPushTemplate.getContentAvailable() != null && androidPushTemplate.getContentAvailable() == 1 )
{
callback.onMessage( context, intent );
return;
}
Notification notification = PushTemplateHelper.convertFromTemplate( context, androidPushTemplate, message, messageId );
PushTemplateHelper.showNotification( context, notification, androidPushTemplate.getName(), messageId );
}
return;
}
String immediatePush = intent.getStringExtra( PublishOptions.ANDROID_IMMEDIATE_PUSH );
if( immediatePush != null )
{
AndroidPushTemplate androidPushTemplate = (AndroidPushTemplate) weborb.util.io.Serializer.fromBytes( immediatePush.getBytes(), weborb.util.io.Serializer.JSON, false );
if( androidPushTemplate.getContentAvailable() != null && androidPushTemplate.getContentAvailable() == 1 )
{
callback.onMessage( context, intent );
return;
}
androidPushTemplate.setName("ImmediateMessage");
Notification notification = PushTemplateHelper.convertFromTemplate( context, androidPushTemplate, message, messageId );
PushTemplateHelper.showNotification( context, notification, androidPushTemplate.getName(), messageId );
return;
}
boolean showPushNotification = callback.onMessage( context, intent );
if( showPushNotification )
{
CharSequence tickerText = intent.getStringExtra( PublishOptions.ANDROID_TICKER_TEXT_TAG );
CharSequence contentTitle = intent.getStringExtra( PublishOptions.ANDROID_CONTENT_TITLE_TAG );
if( tickerText != null && tickerText.length() > 0 )
{
final String contentText = intent.getStringExtra( PublishOptions.ANDROID_CONTENT_TEXT_TAG );
int appIcon = context.getApplicationInfo().icon;
if( appIcon == 0 )
appIcon = android.R.drawable.sym_def_app_icon;
Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage( context.getApplicationInfo().packageName );
PendingIntent contentIntent = PendingIntent.getActivity( context, 0, notificationIntent, 0 );
Notification notification = new Notification.Builder( context )
.setSmallIcon( appIcon )
.setTicker( tickerText )
.setContentTitle( contentTitle )
.setContentText( contentText )
.setContentIntent( contentIntent )
.setWhen( System.currentTimeMillis() )
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
int customLayout = context.getResources().getIdentifier( "notification", "layout", context.getPackageName() );
int customLayoutTitle = context.getResources().getIdentifier( "title", "id", context.getPackageName() );
int customLayoutDescription = context.getResources().getIdentifier( "text", "id", context.getPackageName() );
int customLayoutImageContainer = context.getResources().getIdentifier( "image", "id", context.getPackageName() );
int customLayoutImage = context.getResources().getIdentifier( "push_icon", "drawable", context.getPackageName() );
if( customLayout > 0 && customLayoutTitle > 0 && customLayoutDescription > 0 && customLayoutImageContainer > 0 )
{
NotificationLookAndFeel lookAndFeel = new NotificationLookAndFeel();
lookAndFeel.extractColors( context );
RemoteViews contentView = new RemoteViews( context.getPackageName(), customLayout );
contentView.setTextViewText( customLayoutTitle, contentTitle );
contentView.setTextViewText( customLayoutDescription, contentText );
contentView.setTextColor( customLayoutTitle, lookAndFeel.getTextColor() );
contentView.setFloat( customLayoutTitle, "setTextSize", lookAndFeel.getTextSize() );
contentView.setTextColor( customLayoutDescription, lookAndFeel.getTextColor() );
contentView.setFloat( customLayoutDescription, "setTextSize", lookAndFeel.getTextSize() );
contentView.setImageViewResource( customLayoutImageContainer, customLayoutImage );
notification.contentView = contentView;
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE );
notificationManager.notify( intent.getIntExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, 0 ), notification );
}
}
}
catch ( Throwable throwable )
{
Log.e( TAG, "Error processing push notification", throwable );
}
}
private void handleRegistration( final Context context, Intent intent )
{
String registrationIds = intent.getStringExtra( GCMConstants.EXTRA_REGISTRATION_IDS );
String error = intent.getStringExtra( GCMConstants.EXTRA_ERROR );
String unregistered = intent.getStringExtra( GCMConstants.EXTRA_UNREGISTERED );
boolean isInternal = intent.getBooleanExtra( GCMConstants.EXTRA_IS_INTERNAL, false );
// registration succeeded
if( registrationIds != null )
{
if( isInternal )
{
callback.onRegistered( context, registrationIds );
}
GCMRegistrar.resetBackoff( context );
GCMRegistrar.setGCMdeviceToken( context, registrationIds );
registerFurther( context, registrationIds );
return;
}
// unregistration succeeded
if( unregistered != null )
{
// Remember we are unregistered
GCMRegistrar.resetBackoff( context );
GCMRegistrar.setGCMdeviceToken( context, "" );
GCMRegistrar.setChannels( context, Collections.<String>emptyList() );
GCMRegistrar.setRegistrationExpiration( context, null );
unregisterFurther( context );
return;
}
// Registration failed
if( error.equals( GCMConstants.ERROR_SERVICE_NOT_AVAILABLE ) )
{
int backoffTimeMs = GCMRegistrar.getBackoff( context );
int nextAttempt = backoffTimeMs / 2 + random.nextInt( backoffTimeMs );
Intent retryIntent = new Intent( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY );
retryIntent.putExtra( EXTRA_TOKEN, TOKEN );
PendingIntent retryPendingIntent = PendingIntent.getBroadcast( context, 0, retryIntent, 0 );
AlarmManager am = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE );
am.set( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent );
// Next retry should wait longer.
if( backoffTimeMs < MAX_BACKOFF_MS )
GCMRegistrar.setBackoff( context, backoffTimeMs * 2 );
}
else
{
callback.onError( context, error );
}
}
private void registerFurther( final Context context, String GCMregistrationId )
{
final long registrationExpiration = GCMRegistrar.getRegistrationExpiration( context );
Backendless.Messaging.registerDeviceOnServer( GCMregistrationId, new ArrayList<>( GCMRegistrar.getChannels( context ) ), registrationExpiration, new AsyncCallback<String>()
{
@Override
public void handleResponse( String registrationInfo )
{
String ids;
try
{
Object[] obj = (Object[]) weborb.util.io.Serializer.fromBytes( registrationInfo.getBytes(), weborb.util.io.Serializer.JSON, false );
ids = (String) obj[0];
PushTemplateHelper.deleteNotificationChannel( context );
Map<String,AndroidPushTemplate> templates = (Map<String,AndroidPushTemplate>) obj[1];
if( android.os.Build.VERSION.SDK_INT > 25 )
for( AndroidPushTemplate templ : templates.values() )
PushTemplateHelper.getOrCreateNotificationChannel( context.getApplicationContext(), templ );
PushTemplateHelper.setPushNotificationTemplates( templates, registrationInfo.getBytes() );
}
catch( IOException e )
{
callback.onError( context, "Could not deserialize server response: " + e.getMessage() );
return;
}
GCMRegistrar.setRegistrationIds( context, ids, registrationExpiration );
callback.onRegistered( context, registrationInfo );
}
@Override
public void handleFault( BackendlessFault fault )
{
callback.onError( context, "Could not register device on Backendless server: " + fault.toString() );
}
} );
}
private void unregisterFurther( final Context context )
{
Backendless.Messaging.unregisterDeviceOnServer( new AsyncCallback<Boolean>()
{
@Override
public void handleResponse( Boolean unregistered )
{
GCMRegistrar.setRegistrationIds( context, "", 0 );
callback.onUnregistered( context, unregistered );
}
@Override
public void handleFault( BackendlessFault fault )
{
callback.onError( context, "Could not unregister device on Backendless server: " + fault.toString() );
}
} );
}
}
|
package com.itti7.itimeu;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.itti7.itimeu.data.ItemContract;
import com.itti7.itimeu.data.ItemDbHelper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class StatisticsFragment extends Fragment {
// For access ITimeU database
ItemDbHelper dbHelper;
SQLiteDatabase db;
// Identifier for the item data loader
private View mStatisticsView;
private Activity mStatisticsActivity;
private Context mStatisticsContext;
// Statistics view components
private Spinner mStatSpinner;
private LineChart mChart;
private TextView mStatResultText;
private TextView mStatPeriodText;
// Spinner item's text
private String mSpinnerText;
// Date format
private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy.MM.dd", Locale.KOREA);
// Today's date for getting period
private Date mTodayDate;
// Today : Date -> String
private String mTodayStr;
// A week ago date
private Date mAWeekAgoDate;
// A week ago: Date -> String
private String mAWeekAgoStr;
// A month ago
private Date mAMonthAgoDate;
// A month ago: Date -> String
private String mAMonthAgoStr;
// Percent in the period
private double mPercent;
private ArrayList<Integer> sumOfDayUnit;
private ArrayList<Integer> sumOfDayTotalUnit;
private ArrayList<String> dates;
/*ToDo:
week, month !
1. week, month unit sum, total unit sum
2. (x , y )
3.
4.
5. UI
*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
// Set identifier
mStatisticsView = inflater.inflate(R.layout.fragment_statistics, container, false);
mStatisticsActivity = getActivity();
mStatisticsContext = mStatisticsView.getContext();
dbHelper = new ItemDbHelper(mStatisticsContext);
db = dbHelper.getReadableDatabase();
// Get id from fragment_statistics
mStatSpinner = mStatisticsView.findViewById(R.id.stat_spinner);
selectedSpinnerItem();
mChart = mStatisticsView.findViewById(R.id.chart);
mStatResultText = mStatisticsView.findViewById(R.id.stat_result);
mStatPeriodText = mStatisticsView.findViewById(R.id.stat_period);
// Add data
addData();
// Customize legends
Legend l = mChart.getLegend();
l.setXEntrySpace(7);
l.setYEntrySpace(5);
return mStatisticsView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**
* Set data to chart view (?)
*/
private void addData() {
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
super.onCreateOptionsMenu(menu, menuInflater);
}
/**
* This function is branched according to selected item.
*/
void selectedSpinnerItem() {
mStatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mSpinnerText = mStatSpinner.getSelectedItem().toString();
if (mSpinnerText.equals(getString(R.string.arrays_week))) {
// Get Date
getToday();
getAWeekAgo();
// Set period to text view
mStatPeriodText.setText(mAWeekAgoStr + " - " + mTodayStr);
/* Get sum of unit/total unit each days, whole value of these,
and set text result.*/
getPeriodFromSql(mAWeekAgoDate, mTodayDate);
} else if (mSpinnerText.equals(getString(R.string.arrays_month))) {
// Get Date
getToday();
getAMonthAgo();
// Set period to text view
mStatPeriodText.setText(mAMonthAgoStr + " - " + mTodayStr);
/* Get sum of unit/total unit each days, whole value of these,
and set text result.*/
getPeriodFromSql(mAMonthAgoDate, mTodayDate);
} else {
// @ToDo
Toast.makeText(mStatisticsContext, "custom", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/**
* Get today's date
*/
void getToday() {
mTodayDate = new Date();
mTodayStr = mDateFormat.format(mTodayDate);
}
/**
* Get a week ago's date
*/
void getAWeekAgo() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);
mAWeekAgoDate = calendar.getTime();
mAWeekAgoStr = mDateFormat.format(mAWeekAgoDate);
}
/**
* Get a month ago's date
*/
void getAMonthAgo() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
mAMonthAgoDate = calendar.getTime();
mAMonthAgoStr = mDateFormat.format(mAMonthAgoDate);
}
void getPeriodFromSql(Date startDate, Date endDate) {
int itemUnit = 0;
int itemTotalUnit = 0;
sumOfDayUnit = new ArrayList<>();
sumOfDayTotalUnit = new ArrayList<>();
int sumOfWholeUnits = 0;
int sumOfWholeTotalUnits = 0;
dates = new ArrayList<>();
Date currentDate = startDate;
while (currentDate.compareTo(endDate) <= 0) {
dates.add(mDateFormat.format(currentDate));
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_MONTH, 1);
currentDate = calendar.getTime();
}
for (String date : dates) {
String[] dateStr = {date};
Cursor cursor = db.rawQuery("SELECT unit, totalUnit FROM list WHERE date = ?", dateStr);
// Get each day's sum of unit/totalUnit
if (cursor.moveToFirst()) {
do {
itemUnit += cursor.getInt(
cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_ITEM_UNIT));
itemTotalUnit += cursor.getInt(
cursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_ITEM_TOTAL_UNIT));
} while (cursor.moveToNext());
}
sumOfDayUnit.add(itemUnit);
sumOfDayTotalUnit.add(itemTotalUnit);
// Re-initialize
itemUnit = 0;
itemTotalUnit = 0;
}
// Sum units
for (int i : sumOfDayUnit) {
sumOfWholeUnits += i;
}
// Sum total units
for (int i : sumOfDayTotalUnit) {
sumOfWholeTotalUnits += i;
}
mStatResultText.setText(getPercent(sumOfWholeTotalUnits, sumOfWholeUnits));
}
String getPercent(int sumOfWholeTotalUnits, int sumOfWholeUnits){
if (sumOfWholeTotalUnits != 0) {
mPercent = Math.round(((double) sumOfWholeUnits / sumOfWholeTotalUnits) * 100);
} else {
mPercent = 0;
}
return mPercent + "% ( "+sumOfWholeUnits+" / "+sumOfWholeTotalUnits+ ")";
}
}
|
package com.ecyrd.jspwiki.providers;
import java.lang.ref.SoftReference;
import java.util.Properties;
import java.util.Collection;
import java.util.HashMap;
import java.util.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.IOException;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
/**
* Heavily based on ideas by Chris Brooking.
*
* @author Janne Jalkanen
* @since 1.6.4
*/
// FIXME: Keeps a list of all WikiPages in memory - should cache them too.
public class CachingProvider
implements WikiPageProvider
{
private static final Category log = Category.getInstance(CachingProvider.class);
private WikiPageProvider m_provider;
private HashMap m_cache = new HashMap();
private long m_cacheMisses = 0;
private long m_cacheHits = 0;
public void initialize( Properties properties )
throws NoRequiredPropertyException,
IOException
{
log.debug("Initing CachingProvider");
String classname = WikiEngine.getRequiredProperty( properties,
PageManager.PROP_PAGEPROVIDER );
try
{
Class providerclass = WikiEngine.findWikiClass( classname, "com.ecyrd.jspwiki.providers" );
m_provider = (WikiPageProvider)providerclass.newInstance();
log.debug("Initializing real provider class "+m_provider);
m_provider.initialize( properties );
}
catch( ClassNotFoundException e )
{
log.error("Unable to locate provider class "+classname,e);
throw new IllegalArgumentException("no provider class");
}
catch( InstantiationException e )
{
log.error("Unable to create provider class "+classname,e);
throw new IllegalArgumentException("faulty provider class");
}
catch( IllegalAccessException e )
{
log.error("Illegal access to provider class "+classname,e);
throw new IllegalArgumentException("illegal provider class");
}
}
public boolean pageExists( String page )
{
return m_provider.pageExists( page );
}
public String getPageText( String page, int version )
throws ProviderException
{
String result;
if( version == WikiPageProvider.LATEST_VERSION )
{
result = getTextFromCache( page );
}
else
{
CacheItem item = (CacheItem)m_cache.get( page );
// Or is this the latest version fetched by version number?
if( item != null && item.m_page.getVersion() == version )
{
result = getTextFromCache( page );
}
else
{
result = m_provider.getPageText( page, version );
}
}
return result;
}
private String getTextFromCache( String page )
throws ProviderException
{
CacheItem item = (CacheItem)m_cache.get( page );
if( item == null )
{
// Page has never been seen.
log.debug("Page "+page+" never seen.");
String text = m_provider.getPageText( page, WikiPageProvider.LATEST_VERSION );
addPage( page, text );
m_cacheMisses++;
return text;
}
else
{
String text = (String)item.m_text.get();
if( text == null )
{
// Oops, expired already
log.debug("Page "+page+" expired.");
text = m_provider.getPageText( page, WikiPageProvider.LATEST_VERSION );
item.m_text = new SoftReference( text );
m_cacheMisses++;
return text;
}
log.debug("Page "+page+" found in cache.");
m_cacheHits++;
return text;
}
}
public void putPageText( WikiPage page, String text )
throws ProviderException
{
m_provider.putPageText( page, text );
// Invalidate cache after writing to it.
// FIXME: possible race condition here. Someone might still get
// the old version.
synchronized(this)
{
m_cache.remove( page.getName() );
addPage( page.getName(), null ); // If fetch fails, we want info to go directly to user
}
}
// FIXME: This MUST be cached somehow.
private boolean m_gotall = false;
public Collection getAllPages()
throws ProviderException
{
Collection all;
if( m_gotall == false )
{
all = m_provider.getAllPages();
// Make sure that all pages are in the cache.
// FIXME: This has the unfortunate side effect of clearing
// the cache.
synchronized(this)
{
for( Iterator i = all.iterator(); i.hasNext(); )
{
CacheItem item = new CacheItem();
item.m_page = (WikiPage) i.next();
item.m_text = new SoftReference( null );
m_cache.put( item.m_page.getName(), item );
}
m_gotall = true;
}
}
else
{
all = new ArrayList();
for( Iterator i = m_cache.values().iterator(); i.hasNext(); )
{
all.add( ((CacheItem)i.next()).m_page );
}
}
return all;
}
// Null text for no page
// Returns null if no page could be found.
private synchronized CacheItem addPage( String pageName, String text )
throws ProviderException
{
CacheItem item = null;
WikiPage newpage = m_provider.getPageInfo( pageName, WikiPageProvider.LATEST_VERSION );
if( newpage != null )
{
item = new CacheItem();
item.m_page = newpage;
item.m_text = new SoftReference( text );
m_cache.put( pageName, item );
}
return item;
}
public Collection getAllChangedSince( Date date )
{
return m_provider.getAllChangedSince( date );
}
public int getPageCount()
throws ProviderException
{
return m_provider.getPageCount();
}
public Collection findPages( QueryItem[] query )
{
return m_provider.findPages( query );
}
public WikiPage getPageInfo( String page, int version )
throws ProviderException
{
CacheItem item = (CacheItem)m_cache.get( page );
int latestcached = (item != null) ? item.m_page.getVersion() : Integer.MIN_VALUE;
if( version == WikiPageProvider.LATEST_VERSION ||
version == latestcached )
{
if( item == null )
{
item = addPage( page, null );
if( item == null )
{
return null;
}
}
return item.m_page;
}
else
{
// We do not cache old versions.
return m_provider.getPageInfo( page, version );
}
}
public Collection getVersionHistory( String page )
throws ProviderException
{
return m_provider.getVersionHistory( page );
}
public String getProviderInfo()
{
return("Real provider: "+m_provider.getClass().getName()+
"<BR>Cache misses: "+m_cacheMisses+
"<BR>Cache hits: "+m_cacheHits);
}
/**
* Returns the actual used provider.
* @since 2.0
*/
public WikiPageProvider getRealProvider()
{
return m_provider;
}
private class CacheItem
{
WikiPage m_page;
SoftReference m_text;
}
}
|
package com.gmail.harleenssahni.mbr;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.gmail.harleenssahni.mbr.receivers.MediaButtonReceiver;
/**
* Allows the user to choose which media receiver will handle a media button
* press. Can be navigated via touch screen or media button keys. Provides voice
* feedback.
*
* @author harleenssahni@gmail.com
*/
public class MediaButtonList extends ListActivity implements OnInitListener {
private class SweepBroadcastReceiver extends BroadcastReceiver {
String name;
public SweepBroadcastReceiver(String name) {
this.name = name;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "After running broadcast receiver " + name + "have resultcode: " + getResultCode()
+ " result Data: " + getResultData());
}
}
/** Our tag for logging purposes and identification purposes. */
private static final String TAG = "MediaButtonRouter.Selector";
/**
* Key used to store and retrieve last selected receiver.
*/
private static final String SELECTION_KEY = "btButtonSelection";
/**
* Number of seconds to wait before timing out and just cancelling.
*/
private static final long TIMEOUT_TIME = 7;
/**
* The media button event that {@link MediaButtonReceiver} captured, and
* that we will be forwarding to a music player's {@code BroadcastReceiver}
* on selection.
*/
private KeyEvent trappedKeyEvent;
/**
* The {@code BroadcastReceiver}'s registered in the system for *
* {@link Intent.ACTION_MEDIA_BUTTON}.
*/
private List<ResolveInfo> receivers;
/** The intent filter for registering our local {@code BroadcastReceiver}. */
private IntentFilter uiIntentFilter;
/** The text to speech engine used to announce navigation to the user. */
private TextToSpeech textToSpeech;
/**
* The receiver currently selected by bluetooth next/prev navigation. We
* track this ourselves because there isn't persisted selection w/ touch
* screen interfaces.
*/
private int btButtonSelection;
/**
* The power manager used to wake the device with a wake lock so that we can
* handle input. Allows us to have a regular activity life cycle when media
* buttons are pressed when and the screen is off.
*/
private PowerManager powerManager;
/**
* Used to wake up screen so that we can navigate our UI and select an app
* to handle media button presses when display is off.
*/
private WakeLock wakeLock;
/**
* Local broadcast receiver that allows us to handle media button events for
* navigation inside the activity.
*/
private BroadcastReceiver uiMediaReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent navigationKeyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
int keyCode = navigationKeyEvent.getKeyCode();
if (Utils.isMediaButton(keyCode)) {
Log.i(TAG, "Media Button Selector UI is directly handling key: " + navigationKeyEvent);
if (navigationKeyEvent.getAction() == KeyEvent.ACTION_UP) {
switch (keyCode) {
case KeyEvent.KEYCODE_MEDIA_NEXT:
moveSelection(1);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
moveSelection(-1);
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
select();
break;
default:
break;
}
}
abortBroadcast();
}
}
}
};
/**
* ScheduledExecutorService used to time out and close activity if the user
* doesn't make a selection within certain amount of time. Resets on user
* interaction.
*/
private ScheduledExecutorService timeoutExecutor;
/**
* ScheduledFuture of timeout.
*/
private ScheduledFuture<?> timeoutScheduledFuture;
private View cancelButton;
private View disableButton;
private ImageView mediaImage;
private TextView header;
/**
* {@inheritDoc}
*/
@Override
public void onInit(int status) {
// text to speech initialized
// XXX This is where we announce to the user what we're handling. It's
// not clear that this will always get called. I don't know how else to
// query if the text to speech is started though.
if (trappedKeyEvent != null) {
String actionText = "";
switch (trappedKeyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// This is just play even though the keycode is both play/pause,
// the app shouldn't handle
// pause if music is already playing, it should go to whoever is
// playing the music.
actionText = "Playing";
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
actionText = "Going to Next";
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
actionText = "Going to Previous";
break;
}
String textToSpeak = null;
if (btButtonSelection > 0 && btButtonSelection < receivers.size()) {
textToSpeak = "Select app to use for " + actionText + ", currently "
+ getAppName(receivers.get(btButtonSelection));
} else {
textToSpeak = "Select app to use for " + actionText;
}
textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "On Create Called");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.media_button_list);
uiIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
uiIntentFilter.setPriority(Integer.MAX_VALUE);
// TODO Handle text engine not installed, etc. Documented on android
// developer guide
textToSpeech = new TextToSpeech(this, this);
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
// btButtonSelection = savedInstanceState != null ?
// savedInstanceState.getInt(SELECTION_KEY, -1) : -1;
btButtonSelection = getPreferences(MODE_PRIVATE).getInt(SELECTION_KEY, -1);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
receivers = getPackageManager().queryBroadcastReceivers(mediaButtonIntent,
PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RESOLVED_FILTER);
// Remove our app's receiver from the list so users can't select it.
// NOTE: Our local receiver isn't registered at this point so we don't
// have to remove it.
if (receivers != null) {
for (int i = 0; i < receivers.size(); i++) {
if (MediaButtonReceiver.class.getName().equals(receivers.get(i).activityInfo.name)) {
receivers.remove(i);
break;
}
}
}
// TODO MAYBE sort receivers by MRU so user doesn't have to skip as many
// apps,
// right now apps are sorted by priority (not set by the user, set by
// the app authors.. )
setListAdapter(new BaseAdapter() {
@Override
public int getCount() {
return receivers.size();
}
@Override
public Object getItem(int position) {
return receivers.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.media_receiver_view, null);
}
ResolveInfo resolveInfo = receivers.get(position);
ImageView iv = (ImageView) v.findViewById(R.id.receiverAppImage);
iv.setImageDrawable(resolveInfo.loadIcon(getPackageManager()));
TextView textView = (TextView) v.findViewById(R.id.receiverAppName);
textView.setText(getAppName(resolveInfo));
return v;
}
});
header = (TextView) findViewById(R.id.dialogHeader);
cancelButton = findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
disableButton = findViewById(R.id.disableButton);
mediaImage = (ImageView) findViewById(R.id.mediaImage);
Log.i(TAG, "Media button selector created.");
}
/**
* {@inheritDoc}
*/
@Override
protected void onDestroy() {
super.onDestroy();
textToSpeech.shutdown();
Log.d(TAG, "Media button selector destroyed.");
}
/**
* {@inheritDoc}
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
btButtonSelection = position;
forwardToMediaReceiver(position);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
Log.d(TAG, "unegistered UI receiver");
unregisterReceiver(uiMediaReceiver);
if (wakeLock.isHeld()) {
wakeLock.release();
}
textToSpeech.stop();
timeoutExecutor.shutdownNow();
getPreferences(MODE_PRIVATE).edit().putInt(SELECTION_KEY, btButtonSelection).commit();
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "On Start called");
}
/**
* {@inheritDoc}
*/
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
// TODO Add timeout so this activity finishes after x seconds of no user
// interaction without
// forwarding selection.
// TODO Clean this up, figure out which things need to be set on the
// list view and which don't.
if (getIntent().getExtras() != null && getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT) != null) {
trappedKeyEvent = (KeyEvent) getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT);
Log.i(TAG, "Media button selector handling event: " + trappedKeyEvent + " from intent:" + getIntent());
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setClickable(true);
getListView().setFocusable(true);
getListView().setFocusableInTouchMode(true);
switch (trappedKeyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
header.setText("Android Media Router: Play");
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
header.setText("Android Media Router: Next");
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
header.setText("Android Media Router: Previous");
break;
}
} else {
Log.i(TAG, "Media button selector launched without key event, started with intent: " + getIntent());
trappedKeyEvent = null;
getListView().setClickable(false);
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
getListView().setFocusable(false);
getListView().setFocusableInTouchMode(false);
}
Log.d(TAG, "Registered UI receiver");
registerReceiver(uiMediaReceiver, uiIntentFilter);
// power on device's screen so we can interact with it, otherwise on
// pause gets called immediately.
// alternative would be to change all of the selection logic to happen
// in a service?? don't know if that process life cycle would fit well
// -- look into
// added On after release so screen stays on a little longer instead of
// immediately to try and stop resume pause cycle that sometimes
// happens.
wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, TAG);
wakeLock.setReferenceCounted(false);
// FIXME The wakelock is too late here. We end up doing multiple
// resume/pause cycles (at least three) before the screen turns on and
// our app is stable (not flickering). What to do?
wakeLock.acquire();
timeoutExecutor = Executors.newSingleThreadScheduledExecutor();
resetTimeout();
}
private void resetTimeout() {
if (timeoutScheduledFuture != null) {
timeoutScheduledFuture.cancel(false);
}
// TODO Clean this up
timeoutScheduledFuture = timeoutExecutor.schedule(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Timed out waiting for user interaction, finishing activity");
finish();
}
});
}
}, TIMEOUT_TIME, TimeUnit.SECONDS);
}
/**
* {@inheritDoc}
*/
@Override
public void onUserInteraction() {
super.onUserInteraction();
// Reset timeout to finish
resetTimeout();
}
// /**
// * {@inheritDoc}
// */
// @Override
// protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putInt(SELECTION_KEY, btButtonSelection);
// Log.d(TAG, "Saving selection state, selected is " + btButtonSelection);
/**
* Forwards the {@code #trappedKeyEvent} to the receiver at specified
* position.
*
* @param position
* The index of the receiver to select. Must be in bounds.
*/
private void forwardToMediaReceiver(int position) {
ResolveInfo resolveInfo = receivers.get(position);
if (resolveInfo != null) {
if (trappedKeyEvent != null) {
ComponentName selectedReceiver = new ComponentName(resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name);
Utils.forwardKeyCodeToComponent(this, selectedReceiver, true, trappedKeyEvent.getKeyCode(),
new SweepBroadcastReceiver(selectedReceiver.toString()));
finish();
}
}
}
/**
* Returns the name of the application of the broadcast receiver specified
* by {@code resolveInfo}.
*
* @param resolveInfo
* The receiver.
* @return The name of the application.
*/
private String getAppName(ResolveInfo resolveInfo) {
return resolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
}
/**
* Moves selection by the amount specified in the list. If we're already at
* the last item and we're moving forward, wraps to the first item. If we're
* already at the first item, and we're moving backwards, wraps to the last
* item.
*
* @param amount
* The amount to move, may be positive or negative.
*/
private void moveSelection(int amount) {
resetTimeout();
btButtonSelection += amount;
if (btButtonSelection >= receivers.size()) {
// wrap
btButtonSelection = 0;
} else if (btButtonSelection < 0) {
// wrap
btButtonSelection = receivers.size() - 1;
}
// todo scroll to item, highlight it
textToSpeech.speak(getAppName(receivers.get(btButtonSelection)), TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Select the currently selected receiver.
*/
private void select() {
// TODO if there is no selection, we should either forward to whoever
// would have handled if we didn't exist, or to mru
if (btButtonSelection == -1) {
finish();
} else {
forwardToMediaReceiver(btButtonSelection);
}
}
}
|
package com.haxademic.sketch.render;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.draw.context.DrawUtil;
import com.haxademic.core.draw.context.OpenGLUtil;
public class ConcentricCubes
extends PAppletHax {
public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
// protected ControlP5 _cp5;
protected int _x = 0;
protected int _y = 0;
protected int _frames = 100;
protected void overridePropsFile() {
p.appConfig.setProperty( AppSettings.WIDTH, 800 );
p.appConfig.setProperty( AppSettings.HEIGHT, 800 );
p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, false );
}
public void drawApp() {
background(20);
DrawUtil.setDrawCenter(p);
p.noFill();
p.translate(p.width/2, p.height/2, -1200);
float percentComplete = ((float)(p.frameCount%_frames)/_frames);
p.sphereDetail(4);
// p.blendMode(P.SCREEN);
// p.blendMode(P.MULTIPLY);
// p.blendMode(P.ADD);
float cubeSize = p.width/1f;
float cubScaleDown = 300f + 270 * P.sin(P.TWO_PI * percentComplete);
int i=0;
while(cubeSize > 10) {
p.pushMatrix();
p.stroke(127 + 127f * P.sin(i/20f), 127 + 127f * P.sin(i/30f), 127 + 127f * P.sin(i/10f));
p.strokeWeight(2.2f);
// p.rotateY(0.5f * P.sin(P.TWO_PI * percentComplete + i));
p.rotateY(1.1f * P.sin(P.TWO_PI * percentComplete + i * 0.03f));
p.rotateZ(2.1f * P.sin(P.TWO_PI * percentComplete + i * 0.03f));
p.rotateX(1.1f * P.sin(P.TWO_PI * percentComplete + i * 0.03f));
// p.box(cubeSize);
p.sphere(cubeSize);
p.popMatrix();
cubeSize -= p.width / cubScaleDown;
i++;
}
}
}
|
// Package
package com.hp.hpl.jena.ontology;
// Imports
import java.io.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xerces.util.XMLChar;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.*;
import com.hp.hpl.jena.vocabulary.OntDocManagerVocab;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.shared.impl.PrefixMappingImpl;
public class OntDocumentManager
{
// Constants
/** The default path for searching for the metadata on locally cached ontologies */
public static final String DEFAULT_METADATA_PATH = "file:ont-policy.rdf;file:etc/ont-policy.rdf";
/** Namespace for ontology metadata resources and properties */
public static final String NS = "http://jena.hpl.hp.com/schemas/2003/03/ont-manager
/** The anchor char is added to the end of namespace prefix expansions */
public static final String ANCHOR = "
/** rdf:type for ontology specification nodes in meta-data file */
public static final Resource ONTOLOGY_SPEC = OntDocManagerVocab.OntologySpec;
/** Represents the public URI of an ontology; also used to derive the namespace */
public static final Property PUBLIC_URI = OntDocManagerVocab.publicURI;
/** Represents the alternative local copy of the public ontology; assumed to be resolvable, hence URL not URI */
public static final Property ALT_URL = OntDocManagerVocab.altURL;
/** Represents the standard prefix for this namespace */
public static final Property PREFIX = OntDocManagerVocab.prefix;
/** Represents the ontology language used to encode the ontology */
public static final Property LANGUAGE = OntDocManagerVocab.language;
/** rdf:type for document manager policy nodes */
public static final Resource DOC_MGR_POLICY = OntDocManagerVocab.DocumentManagerPolicy;
/** Defines boolean policy choice of caching loaded models */
public static final Property CACHE_MODELS = OntDocManagerVocab.cacheModels;
/** Defines boolean policy choice of loading the imports closure */
public static final Property PROCESS_IMPORTS = OntDocManagerVocab.processImports;
/** Specifies the URI of an ontology that we do not want to import, even if processImports is true. */
public static final Property IGNORE_IMPORT = OntDocManagerVocab.ignoreImport;
/** The policy property for including the pre-declared namespace prefixes in a model. */
public static final Property USE_DECLARED_NS_PREFIXES = OntDocManagerVocab.useDeclaredNsPrefixes;
// Static variables
/** Default document manager instance */
private static OntDocumentManager s_instance = null;
/** Log for this class */
private static Log log = LogFactory.getLog( OntDocumentManager.class );
// Instance variables
/** The search path for metadata */
protected String m_searchPath = DEFAULT_METADATA_PATH;
/** FileManager instance that provides location resolution service - defaults to global instance */
protected FileManager m_fileMgr = null;
/** Flag to indicate we're using a copy of the global file manager */
protected boolean m_usingGlobalFileMgr = false;
/** Mapping of public public URI's to language resources */
protected Map m_languageMap = new HashMap();
/** Flag: process the imports closure */
protected boolean m_processImports = true;
/** List of URI's that will be ignored when doing imports processing */
protected Set m_ignoreImports = new HashSet();
/** Default prefix mapping to use to seed all models */
protected PrefixMapping m_prefixMap = new PrefixMappingImpl();
/** Flag to control whether we include the standard prefixes in generated models - default true. */
protected boolean m_useDeclaredPrefixes = true;
/** The URL of the policy file that was loaded, or null if no external policy file has yet been loaded */
protected String m_policyURL = null;
// Constructors
/**
* <p>
* Initialise a document manager by searching the default path for ontology
* metadata about known ontologies cached locally.
* </p>
*/
public OntDocumentManager() {
this( DEFAULT_METADATA_PATH );
}
/**
* <p>
* Initialise a document manager by searching the given path for ontology
* metadata about known ontologies cached locally.
* </p>
*
* @param path The search path to search for initial metadata, which will
* also replace the current search path for this document manager. Use
* null to prevent loading of any initial ontology metadata. The path is a series
* of URL's, separated by a semi-colon (;).
*/
public OntDocumentManager( String path ) {
this( null, path );
}
/**
* <p>
* Initialise a document manager by with the given FileManager, and
* then searching the given path for ontology
* metadata about known ontologies cached locally.
* </p>
*
* @param path The search path to search for initial metadata
* @see #OntDocumentManager(String)
*/
public OntDocumentManager( FileManager fileMgr, String path ) {
setFileManager( fileMgr );
setDefaults();
m_searchPath = (path == null) ? "" : path;
initialiseMetadata( m_searchPath );
}
/**
* <p>Initialise a document manager with the given configuration model. This model
* is used in place of any model that might be
* found by searching the meta-data search path. Uses the default file manager,
* i.e. a copy of the global file manager.</p>
* @param config An RDF model containing configuration information for this document manager.
*/
public OntDocumentManager( Model config ) {
this( null, config );
}
/**
* <p>Initialise a document manager with the given configuration model. This model
* is used in place of any model that might be
* found by searching the meta-data search path.</p>
* @param fileMgr A file manager to use when locating source files for ontologies
* @param config An RDF model containing configuration information for this document manager.
*/
public OntDocumentManager( FileManager fileMgr, Model config ) {
// we don't need to reset first since this is a new doc mgr
setFileManager( fileMgr );
setDefaults();
configure( config, false );
}
// External signature methods
/**
* <p>
* OntDocumentManager is not a singleton, but a global default instance is available
* for applications where a single shared document manager is sufficient.
* </p>
*
* @return The default, global instance of a document manager
*/
public static OntDocumentManager getInstance() {
if (s_instance == null) {
s_instance = new OntDocumentManager();
}
return s_instance;
}
/**
* <p>Answer the file manager instance being used by this document manager.</p>
* @return This object's file manager
*/
public FileManager getFileManager() {
return m_fileMgr;
}
/**
* <p>Set the file manager used by this ODM instance to <strong>a
* copy</strong> of the global file manager (and, by extension, the
* global location mapper).</p>
*/
public void setFileManager() {
setFileManager( new FileManager( FileManager.get() ) );
m_usingGlobalFileMgr = true;
}
/**
* <p>Set the file manager used by this ODM instance to <strong>a
* copy</strong> of the global file manager (and, by extension, the
* global location mapper).</p>
* @param fileMgr The new file manager
*/
public void setFileManager( FileManager fileMgr ) {
if (fileMgr == null) {
// use default fm
setFileManager();
}
else {
m_fileMgr = fileMgr;
m_usingGlobalFileMgr = false;
}
}
/**
* <p>
* Answer the path used to search for the ontology metadata to load. The format is
* a ';' separated list of URI's. The first URI on the path that is readable is
* taken to be the location of the local ontology metadata.
* </p>
*
* @return The ontology metadata search path, as a string.
*/
public String getMetadataSearchPath() {
return m_searchPath;
}
/**
* <p>
* Change the search path for loading ontology metadata to the given path. If
* <code>replace</code> is true, any existing mappings are removed before the
* new path is searched. Otherwise, existing data will only be replaced if
* it is clobbered by keys loaded from the metadata loaded from the new path.
* </p>
*
* @param path The new metadata search path (see {@link #getMetadataSearchPath} for format)
* @param replace If true, clear existing mappings first
*/
public void setMetadataSearchPath( String path, boolean replace ) {
if (replace) {
reset();
}
m_searchPath = path;
m_policyURL = null;
initialiseMetadata( path );
}
/**
* <p>Configure this document manager using the given configuration information, after
* first resetting the model back to all default values.</p>
* @param config Document manager configuration as an RDF model
* @see #configure( Model, boolean )
*/
public void configure( Model config ) {
configure( config, true );
}
/**
* <p>Configure this document manager according to the configuration options
* supplied by the given configuration model. If <code>reset</code> is true, the
* document manager is first reset back to all default values.</p>
* @param config Document manager configuration as an RDF model
* @param reset If true, reset the document manager to default values, before
* attempting to configure the document manager using the given model.
* @see #reset
*/
public void configure( Model config, boolean reset ) {
if (reset) {
reset( false );
}
processMetadata( config );
}
/**
* <p>Reset all state in this document manager back to the default
* values it would have had when the object was created. Optionally
* reload the profile metadata from the search path. <strong>Note</strong>
* that the metadata search path is not changed by this reset.</p>
* @param reload If true, reload the configuration file from the
* search path.
*/
public void reset( boolean reload ) {
// first check if we are using the global file manager, or a local one
if (m_usingGlobalFileMgr) {
// we can do a general reset by throwing away the old FM and creating a new one
setFileManager();
}
else {
// not using the global default FM, so we reset to best effort
getFileManager().resetCache();
}
setDefaults();
m_languageMap.clear();
m_ignoreImports.clear();
// copy the standard prefixes
m_prefixMap = new PrefixMappingImpl();
m_prefixMap.setNsPrefixes( PrefixMapping.Standard );
if (reload) {
initialiseMetadata( m_searchPath );
}
}
/**
* <p>Reset all state in this document manager back to the default
* values it would have had when the object was created. This does
* <strong>not</strong> reload the configuration information from
* the search path. Note also that the metadata search path is one
* of the values that is reset back to its default value.</p>
* @see #reset( boolean )
*/
public void reset() {
reset( false );
}
/**
* <p>
* Answer an iterator over the ontology document URI's that this document manager
* knows to re-direct to other URL's. <strong>Note</strong> that being in this
* iteration does <em>not</em> mean that a document with the given name is in
* the set of cached models held by this document manager.
* </p>
*
* @return An Iterator ranging over the public URI strings for the known
* document URI's.
*/
public Iterator listDocuments() {
return getFileManager().getLocationMapper().listAltEntries();
}
/**
* <p>
* Answer the URL of the alternative copy of the ontology document with the given URI, if known,
* or the URI unchanged if no alternative is known.
* </p>
*
* @param uri The ontology document to lookup
* @return The resolvable location of the alternative copy, if known, or <code>uri</code> otherwise
*/
public String doAltURLMapping( String uri ) {
return getFileManager().mapURI( uri );
}
/**
* <p>
* Answer the representation of the ontology document with the given URI, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The URI of the representation language, or null.
* @deprecated Language determination via the ODM will be removed from Jena 2.4 onwards
*/
public String getLanguage( String uri ) {
return (String) m_languageMap.get( uri );
}
/**
* <p>
* Answer the prefix for the qnames in the given document, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The string to use as a prefix when serialising qnames in the
* given document's namespace, or null if not known
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public String getPrefixForURI( String uri ) {
return m_prefixMap.getNsURIPrefix( uri );
}
/**
* <p>
* Answer the base URI for qnames with the given prefix, if known.
* </p>
*
* @param prefix A prefix string
* @return The basename that the prefix expands to, or null
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public String getURIForPrefix( String prefix ) {
return m_prefixMap.getNsPrefixURI( prefix );
}
/**
* <p>
* Answer the cached model corresponding to the given document, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The model for the document, or null if the model is not known.
* @see #getOntology
*/
public Model getModel( String uri ) {
return getFileManager().getFromCache( uri );
}
/**
* <p>Answer true if, according to the policy expressed by this document manager, newly
* generated ontology models should include the pre-declared namespace prefixes.
* </p>
*
* @return True if pre-declared prefixes should be added to the models
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public boolean useDeclaredPrefixes() {
return m_useDeclaredPrefixes;
}
/**
* <p>Set the flag that determines whether pre-declared namespace prefixes will be added to newly
* generated ontology models.</p>
*
* @param useDeclaredPrefixes If true, new models will include the pre-declared prefixes set held
* by this document manager.
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public void setUseDeclaredPrefixes( boolean useDeclaredPrefixes ) {
m_useDeclaredPrefixes = useDeclaredPrefixes;
}
/**
* <p>Answer the namespace prefix map that contains the shared prefixes managed by this
* document manager.</p>
*
* @return The namespace prefix mapping
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public PrefixMapping getDeclaredPrefixMapping() {
return m_prefixMap;
}
/**
* <p>
* Add a prefix mapping between the given public base URI and the
* given prefix.
* </p>
*
* @param uri The base URI that <code>prefix</code> expands to
* @param prefix A qname prefix
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public void addPrefixMapping( String uri, String prefix ) {
m_prefixMap.setNsPrefix( prefix, uri );
}
/**
* <p>
* Add an entry for an alternative copy of the document with the given document
* URI.
* </p>
*
* @param docURI The public URI of the ontology document
* @param locationURL A locally resolvable URL where an alternative copy of the
* ontology document can be found
*/
public void addAltEntry( String docURI, String locationURL ) {
getFileManager().getLocationMapper().addAltEntry( docURI, locationURL );
}
/**
* <p>
* Add an entry that <code>model</code> is the appropriate model to use
* for the given ontology document. Will not replace any existing
* model that is cached for this URI (see
* {@link #addModel(String, Model, boolean)} for an alternative
* that can replace existing models).
* </p>
*
* @param docURI The public URI of the ontology document
* @param model A model containing the triples from the document
*/
public void addModel( String docURI, Model model ) {
addModel( docURI, model, false );
}
/**
* <p>
* Add an entry that <code>model</code> is the appropriate model to use
* for the given ontology document
* </p>
*
* @param docURI The public URI of the ontology document
* @param model A model containing the triples from the document
* @param replace If true, replace any existing entry with this one.
*/
public void addModel( String docURI, Model model, boolean replace ) {
if (getFileManager().getCachingModels() &&
(replace || !getFileManager().hasCachedModel( docURI )))
{
getFileManager().addCacheModel( docURI, model );
}
}
/**
* <p>
* Add an entry that <code>language</code> is the URI defining the
* representation language for the given document
* </p>
*
* @param docURI The public URI of the ontology document
* @param language A string defining the URI of the language
* @deprecated Language determination via the ODM will be removed from Jena 2.4 onwards
*/
public void addLanguageEntry( String docURI, String language ) {
m_languageMap.put( docURI, language );
}
/**
* <p>
* Remove all managed entries for the given document. Note does not side-effect
* the prefixes table: this will have to be done separately.
* </p>
*
* @param docURI The public URI for an ontology document
*/
public void forget( String docURI ) {
getFileManager().getLocationMapper().removeAltEntry( docURI );
getFileManager().removeCacheModel( docURI );
m_languageMap.remove( docURI );
}
/**
* <p>
* Answer the ontology model that results from loading the document with the
* given URI. This may be a cached model, if this document manager's policy
* is to cache loaded models. If not, or if no model is cached, the document
* will be read into a suitable model. The model will contain the imports closure
* of the ontology, if that is the current policy of this document manager.
* </p>
*
* @param uri Identifies the model to load.
* @param spec Specifies the structure of the ontology model to create
* @return An ontology model containing the statements from the ontology document.
* @see #getModel
*/
public OntModel getOntology( String uri, OntModelSpec spec ) {
// ensure consistency of document managers (to allow access to cached documents)
OntModelSpec _spec = spec;
if (_spec.getDocumentManager() != this) {
_spec = new OntModelSpec( spec );
_spec.setDocumentManager( this );
}
// cached already?
if (getFileManager().hasCachedModel( uri )) {
Model cached = getFileManager().getFromCache( uri );
if (cached instanceof OntModel) {
return (OntModel) cached;
}
else {
return ModelFactory.createOntologyModel( _spec, cached );
}
}
else {
OntModel m = ModelFactory.createOntologyModel( _spec, null );
read( m, uri, true );
// cache this model for future re-use
getFileManager().addCacheModel( uri, m );
return m;
}
}
/**
* <p>
* Answer the policy flag indicating whether the imports statements of
* loaded ontologies will be processed to build a union of s.
* </p>
*
* @return True if imported models will be included in a loaded model
*/
public boolean getProcessImports() {
return m_processImports;
}
/**
* <p>
* Answer true if the models loaded by this document manager from a given
* URI will be cached, so that they can be re-used in other compound
* ontology models.
* </p>
*
* @return If true, a cache is maintained of loaded models from their URI's.
*/
public boolean getCacheModels() {
return getFileManager().getCachingModels();
}
/**
* <p>
* Set the policy flag for processing imports of loaded ontologies.
* </p>
*
* @param processImports If true, load imported ontologies during load
* @see #getProcessImports
*/
public void setProcessImports( boolean processImports ) {
m_processImports = processImports;
}
/**
* <p>
* Set the policy flag that indicates whether loaded models are cached by URI
* </p>
*
* @param cacheModels If true, models will be cached by URI
* @see #getCacheModels()
*/
public void setCacheModels( boolean cacheModels ) {
getFileManager().setModelCaching( cacheModels );
}
/**
* <p>Add the given URI to the set of URI's we ignore in imports statements</p>
* @param uri A URI to ignore when importing
*/
public void addIgnoreImport( String uri ) {
m_ignoreImports.add( uri );
}
/**
* <p>Remove the given URI from the set of URI's we ignore in imports statements</p>
* @param uri A URI to ignore no longer when importing
*/
public void removeIgnoreImport( String uri ) {
m_ignoreImports.remove( uri );
}
/**
* <p>Answer an iterator over the set of URI's we're ignoring</p>
* @return An iterator over ignored imports
*/
public Iterator listIgnoredImports() {
return m_ignoreImports.iterator();
}
/**
* <p>Answer true if the given URI is one that will be ignored during imports </p>
* @param uri A URI to test
* @return True if uri will be ignored as an import
*/
public boolean ignoringImport( String uri ) {
return m_ignoreImports.contains( uri );
}
/**
* <p>
* Remove all entries from the model cache
* </p>
*/
public void clearCache() {
getFileManager().resetCache();
}
/**
* <p>
* Inspect the statements in the graph expressed by the given model, and load
* into the model any imported documents. Imports statements are recognised according
* to the model's language profile. An occurs check allows cycles of importing
* safely. This method will do nothing if the {@linkplain #getProcessImports policy}
* for this manager is not to process imports. If the {@linkplain #getCacheModels cache policy}
* for this doc manager allows, models will be cached by URI and re-used where possible.
* </p>
*
* @param model An ontology model whose imports are to be loaded.
*/
public void loadImports( OntModel model ) {
if (m_processImports) {
List readQueue = new ArrayList();
// add the imported statements from the given model to the processing queue
queueImports( model, readQueue, model.getProfile() );
loadImports( model, readQueue );
}
}
/**
* <p>Add the given model from the given URI as an import to the given model. Any models imported by the given
* URI will also be imported.</p>
*
* @param model A model to import into
* @param uri The URI of a document to import
*/
public void loadImport( OntModel model, String uri ) {
if (m_processImports) {
List readQueue = new ArrayList();
readQueue.add( uri );
loadImports( model, readQueue );
}
}
/**
* <p>Remove from the given model the import denoted by the given URI.</p>
*
* @param model A model
* @param uri The URI of a document to no longer import
*/
public void unloadImport( OntModel model, String uri ) {
if (m_processImports) {
List unloadQueue = new ArrayList();
unloadQueue.add( uri );
unloadImports( model, unloadQueue );
}
}
/**
* <p>Answer the URL of the most recently loaded policy URL, or null
* if no document manager policy has yet been loaded since the metadata
* search path was last set.</p>
* @return The most recently loaded policy URL or null.
*/
public String getLoadedPolicyURL() {
return m_policyURL;
}
// Internal implementation methods
/**
* <p>Load all of the imports in the queue</p>
* @param model The model to load the imports into
* @param readQueue The queue of imports to load
*/
protected void loadImports( OntModel model, List readQueue ) {
while (!readQueue.isEmpty()) {
// we process the import statements as a FIFO queue
String importURI = (String) readQueue.remove( 0 );
if (!model.hasLoadedImport( importURI ) && !ignoringImport( importURI )) {
// this file has not been processed yet
loadImport( model, importURI, readQueue );
}
}
}
/**
* <p>Unload all of the imports in the queue</p>
* @param model The model to unload the imports from
* @param unloadQueue The queue of imports to unload
*/
protected void unloadImports( OntModel model, List unloadQueue ) {
while (!unloadQueue.isEmpty()) {
// we process the import statements as a FIFO queue
String importURI = (String) unloadQueue.remove( 0 );
if (model.hasLoadedImport( importURI )) {
// this import has not been unloaded yet
// look up the cached model - if we can't find it, we can't unload the import
Model importModel = getModel( importURI );
if (importModel != null) {
List imports = new ArrayList();
// collect a list of the imports from the model that is scheduled for removal
for (StmtIterator i = importModel.listStatements( null, model.getProfile().IMPORTS(), (RDFNode) null ); i.hasNext(); ) {
imports.add( i.nextStatement().getResource().getURI() );
}
// now remove the sub-model
model.removeSubModel( importModel, false );
model.removeLoadedImport( importURI );
// check the list of imports of the model we have removed - if they are not
// imported by other imports that remain, we should remove them as well
for (StmtIterator i = model.listStatements( null, model.getProfile().IMPORTS(), (RDFNode) null ); i.hasNext(); ) {
imports.remove( i.nextStatement().getResource().getURI() );
}
// any imports that remain are scheduled for removal
unloadQueue.addAll( imports );
}
}
}
model.rebind();
}
/**
* <p>Add the ontologies imported by the given model to the end of the queue.</p>
*/
protected void queueImports( Model model, List readQueue, Profile profile ) {
if (model instanceof OntModel) {
// add the imported ontologies to the queue
readQueue.addAll( ((OntModel) model).listImportedOntologyURIs() );
}
else {
// we have to do the query manually
StmtIterator i = model.listStatements( null, profile.IMPORTS(), (RDFNode) null );
while (i.hasNext()) {
// read the next import statement and add to the queue
readQueue.add( i.nextStatement().getResource().getURI() );
}
}
}
/**
* <p>
* Initialise the mappings for uri's and prefixes by loading metadata
* from an RDF model.
* </p>
*
* @param path The URI path to search for a loadable model
*/
protected void initialiseMetadata( String path ) {
// search the path for metadata about locally cached models
Model metadata = findMetadata( path );
if (metadata != null) {
processMetadata( metadata );
}
}
/**
* <p>
* Search the given path for a resolvable URI, from which we load a model
* (assuming RDF/XML).
* </p>
*
* @param configPath The path to search
* @return A model loaded by resolving an entry on the path, or null if
* no path entries succeed.
*/
protected Model findMetadata( String configPath ) {
if (configPath == null) {
return null;
}
// Make a temporary file manager to look for the metadata file
FileManager fm = new FileManager();
fm.addLocatorFile();
fm.addLocatorURL();
fm.addLocatorClassLoader( fm.getClass().getClassLoader() );
try {
String uri = null ;
InputStream in = null ;
StringTokenizer pathElems = new StringTokenizer( configPath, FileManager.PATH_DELIMITER );
while (in == null && pathElems.hasMoreTokens()) {
uri = pathElems.nextToken();
in = fm.openNoMap( uri );
}
if (in != null) {
String syntax = FileUtils.guessLang(uri);
Model model = ModelFactory.createDefaultModel() ;
model.read( in, uri, syntax );
m_policyURL = uri;
return model;
}
}
catch (JenaException e) {
log.warn( "Exception while reading configuration: " + e.getMessage(), e);
}
return null;
}
/**
* <p>
* Load the ontology specification metadata from the model into the local
* mapping tables.
* </p>
*
* @param metadata A model containing metadata about ontologies.
*/
protected void processMetadata( Model metadata ) {
// there may be configuration for the location mapper in the ODM metadata file
getFileManager().getLocationMapper().processConfig( metadata );
// first we process the general policy statements for this document manager
for (ResIterator i = metadata.listSubjectsWithProperty( RDF.type, DOC_MGR_POLICY ); i.hasNext(); ) {
Resource policy = i.nextResource();
// iterate over each policy statement
for (StmtIterator j = policy.listProperties(); j.hasNext(); ) {
Statement s = j.nextStatement();
Property pred = s.getPredicate();
if (pred.equals( CACHE_MODELS )) {
setCacheModels( s.getBoolean() );
}
else if (pred.equals( PROCESS_IMPORTS )) {
setProcessImports( s.getBoolean() );
}
else if (pred.equals( IGNORE_IMPORT )) {
addIgnoreImport( s.getResource().getURI() );
}
else if (pred.equals( USE_DECLARED_NS_PREFIXES )) {
setUseDeclaredPrefixes( s.getBoolean() );
}
}
}
// then we look up individual meta-data for particular ontologies
for (ResIterator i = metadata.listSubjectsWithProperty( RDF.type, ONTOLOGY_SPEC ); i.hasNext(); ) {
Resource root = i.nextResource();
Statement s = root.getProperty( PUBLIC_URI );
if (s != null) {
// this will be the key in the mappings
String publicURI = s.getResource().getURI();
// there may be a cached copy for this ontology
s = root.getProperty( ALT_URL );
if (s != null) addAltEntry( publicURI, s.getResource().getURI() );
// there may be a standard prefix for this ontology
s = root.getProperty( PREFIX );
if (s != null) {
// if the namespace doesn't end with a suitable split point character, add a
boolean endWithNCNameCh = XMLChar.isNCName( publicURI.charAt( publicURI.length() - 1 ) );
String prefixExpansion = endWithNCNameCh ? (publicURI + ANCHOR) : publicURI;
addPrefixMapping( prefixExpansion, s.getString() );
}
// there may be a language specified for this ontology
s = root.getProperty( LANGUAGE );
if (s != null) addLanguageEntry( publicURI, s.getResource().getURI() );
}
else {
log.warn( "Ontology specification node lists no public URI - node ignored");
}
}
}
/**
* <p>
* Load the document referenced by the given URI into the model. The cache will be
* used if permitted by the policy, and the imports of loaded model will be added to
* the end of the queue.
* </p>
*
* @param model The composite model to load into
* @param importURI The URI of the document to load
* @param readQueue Cumulative read queue for this operation
*/
protected void loadImport( OntModel model, String importURI, List readQueue ) {
if (m_processImports) {
log.debug( "OntDocumentManager loading " + importURI );
// add this model to occurs check list
model.addLoadedImport( importURI );
Model in = fetchPossiblyCachedImportModel( model, importURI );
// we trap the case of importing ourself (which may happen via an indirect imports chain)
if (in != model) {
// queue the imports from the input model on the end of the read queue
queueImports( in, readQueue, model.getProfile() );
// add to the imports union graph, but don't do the rebind yet
model.addSubModel( in, false );
// we also cache the model if we haven't seen it before (and caching is on)
addModel( importURI, in );
}
}
}
/**
if we have a cached version get that, otherwise load from the URI but don't do the imports closure
* @param model
* @param importURI
* @return
*/
private Model fetchPossiblyCachedImportModel( OntModel model, String importURI ) {
Model in = getModel( importURI );
// if not cached, we must load it from source
if (in == null) {
in = fetchLoadedImportModel( model.getSpecification(), importURI );
}
return in;
}
/**
* @param spec
* @param importURI
* @return
*/
private Model fetchLoadedImportModel( OntModelSpec spec, String importURI )
{
ModelReader loader = new ModelReader()
{
public Model readModel( Model toRead, String URL )
{
read( toRead, URL, true );
return toRead;
}
};
return spec.getImportModelGetter().getModel( importURI, loader );
// Model in;
// // create a sub ontology model and load it from the source
// // note that we do this to ensure we recursively load imports
// ModelMaker maker = spec.getImportModelMaker();
// boolean loaded = maker.hasModel( importURI );
// in = maker.openModel( importURI );
// // if the graph was already in existence, we don't need to read the contents (we assume)!
// if (!loaded) {
// read( in, importURI, true );
// return in;
}
/**
* <p>
* Load into the given model from the given URI, or from a local cache URI if defined.
* </p>
*
* @param model A model to read statements into
* @param uri A URI string
* @param warn If true, warn on RDF exception
* @return True if the uri was read successfully
*/
protected boolean read( Model model, String uri, boolean warn ) {
boolean success = false;
try {
getFileManager().readModel( model, uri );
success = true;
}
catch (Exception e) {
log.warn( "An error occurred while attempting to read from " + uri + ". Msg was '" + e.getMessage() + "'.", e );
}
return success;
}
/**
* <p>Set the default option settings.</p>
*/
protected void setDefaults() {
setCacheModels( true );
setUseDeclaredPrefixes( true );
setProcessImports( true );
}
// Inner class definitions
}
|
package com.lekebilen.quasseldroid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class BufferCollection extends Observable implements Observer {
private HashMap<Integer, Buffer> buffers = new HashMap<Integer, Buffer>();
private List<Buffer> bufferList = new ArrayList<Buffer>();
private static final String TAG = BufferCollection.class.getSimpleName();
public BufferCollection() {
}
public void addBuffer(Buffer buffer) {
buffers.put(buffer.getInfo().id, buffer);
bufferList.add(buffer);
Collections.sort(bufferList);
this.setChanged();
buffer.addObserver(this);
notifyObservers();
}
public int getBufferCount() {
return buffers.size();
}
public Buffer getPos(int pos) {
//TODO: might want to make something better then this. For when we want to change possitions and crap we need to be able to move stuff around
return (Buffer) bufferList.get(pos);
}
public Buffer getBuffer(int bufferId) {
return this.buffers.get(bufferId);
}
public boolean hasBuffer(int id) {
return buffers.containsKey(id);
}
public void addBuffers(Collection<Buffer> buffers) {
for (Buffer buffer: buffers) {
this.buffers.put(buffer.getInfo().id, buffer);
bufferList.add(buffer);
buffer.addObserver(this);
}
Collections.sort(bufferList);
this.setChanged();
notifyObservers();
}
@Override
public void update(Observable arg0, Object arg1) {
this.setChanged();
notifyObservers();
}
}
|
package com.projects.gui.panel;
import com.projects.gui.SubscribedView;
import com.projects.models.PowerPlant;
import com.projects.models.WorldTimer;
import com.projects.systems.simulation.SimulationStatus;
import com.projects.systems.simulation.World;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
public class SupplyAndDemandPanel extends JPanel implements SubscribedView
{
private ChartPanel supplyChartPanel;
private ChartPanel demandChartPanel;
private DynamicTimeSeriesCollection supplyData;
private DynamicTimeSeriesCollection demandData;
private HashMap<Integer, Integer> powerPlantIdToSeriesNumberMap;
private final int TWO_MINUTES = 120;
private int displayInterval = TWO_MINUTES;
private int timeInterval = 1; // 1 second
private RegularTimePeriod timeBase;
private double previousTime;
public SupplyAndDemandPanel()
{
setLayout(new GridLayout(1,2));
timeBase = new Second(0, 58, 23, 1, 1, 2015);
powerPlantIdToSeriesNumberMap = new HashMap<Integer, Integer>();
supplyChartPanel = new ChartPanel(createSupplyChart(new ArrayList<PowerPlant>()));
demandChartPanel = new ChartPanel(createDemandChart());
add(supplyChartPanel);
add(demandChartPanel);
previousTime = 0;
}
public void modelPropertyChange(PropertyChangeEvent event)
{
if (event.getPropertyName().equals(World.PC_WORLD_UPDATE))
{
SimulationStatus status = (SimulationStatus)event.getNewValue();
updateCharts(status);
}
else if (event.getPropertyName().equals(World.PC_UPDATE_RATE_CHANGE))
{
WorldTimer.UpdateRate rate = (WorldTimer.UpdateRate)event.getNewValue();
switch(rate)
{
case SECONDS:
{
displayInterval = TWO_MINUTES;
timeInterval = 1;
timeBase = new Second(0, 58, 23, 1, 1, 2015);
} break;
case MINUTES:
{
displayInterval = 60;
timeInterval = (int)WorldTimer.SECONDS_IN_MINUTE;
timeBase = new Minute(59, 23, 1, 1, 2015);
} break;
case HOURS:
{
displayInterval = WorldTimer.HOURS_IN_DAY / 4;
timeInterval = (int)WorldTimer.SECONDS_IN_HOUR;
timeBase = new Hour(19, 1, 1, 2015);
} break;
case DAYS:
{
displayInterval = (int)(WorldTimer.DAYS_IN_WEEK * WorldTimer.HOURS_IN_DAY);
timeInterval = (int)WorldTimer.SECONDS_IN_HOUR;
timeBase = new Hour(0, 1, 1, 2015);
} break;
// TODO: handle others
}
}
else if (event.getPropertyName().equals(World.PC_WORLD_RESET))
{
previousTime = 0;
SimulationStatus status = (SimulationStatus)event.getNewValue();
remove(supplyChartPanel);
supplyChartPanel = new ChartPanel(createSupplyChart(status.powerPlants));
add(supplyChartPanel);
remove(demandChartPanel);
demandChartPanel = new ChartPanel(createDemandChart());
add(demandChartPanel);
}
else if (event.getPropertyName().equals(World.PC_SIMULATION_STARTED)) // TODO: find a way to keep the power pant map up to date without having to create two charts (reset and start) potencially right after the other.
{
SimulationStatus status = (SimulationStatus)event.getNewValue();
remove(supplyChartPanel);
supplyChartPanel = new ChartPanel(createSupplyChart(status.powerPlants));
add(supplyChartPanel);
remove(demandChartPanel);
demandChartPanel = new ChartPanel(createDemandChart());
add(demandChartPanel);
}
}
private void updateCharts(SimulationStatus status)
{
int difference = (int)(Math.floor(status.worldTimer.getTotalTimeInSeconds() - previousTime));
if (difference/timeInterval > 0)
{
difference /= timeInterval;
for (int i = 0; i < difference; ++i)
{
updateDemand(status);
updateSupply(status);
previousTime += timeInterval;
}
}
}
private void updateSupply(SimulationStatus status)
{
float[] newData = new float[status.powerPlants.size()];
supplyData.advanceTime();
for (PowerPlant powerPlant : status.powerPlants)
{
newData[powerPlantIdToSeriesNumberMap.get(powerPlant.getId())] = (float)powerPlant.getCurrentOutput();
}
supplyData.appendData(newData);
}
private void updateDemand(SimulationStatus status)
{
float[] newData = new float[1];
newData[0] = (float)status.electricityDemand;
demandData.advanceTime();
demandData.appendData(newData);
}
private JFreeChart createSupplyChart(List<PowerPlant> powerPlants)
{
supplyData = new DynamicTimeSeriesCollection(powerPlants.size(), displayInterval, timeBase);
supplyData.setTimeBase(timeBase); // Offset so that it will begin at 00:00:00
int seriesNumber = 0;
powerPlantIdToSeriesNumberMap.clear();
for (PowerPlant powerPlant : powerPlants)
{
float[] series = {};
supplyData.addSeries(series, seriesNumber, powerPlant.getName());
powerPlantIdToSeriesNumberMap.put(powerPlant.getId(), seriesNumber);
++seriesNumber;
}
JFreeChart result = ChartFactory.createTimeSeriesChart(
"Supply", // chart title
"Time of Day",
"Supply(kWh)",
supplyData,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true); // TODO: try and find a way to change the lower and upper bound...
ValueAxis range = plot.getRangeAxis();
range.setLowerBound(0);
range.setUpperBound(1000);
return result;
}
private JFreeChart createDemandChart()
{
demandData = new DynamicTimeSeriesCollection(1, displayInterval, timeBase);
demandData.setTimeBase(timeBase); // Offset so that it will begin at 00:00:00
float[] series = {};
demandData.addSeries(series, 0, "Usage");
JFreeChart result = ChartFactory.createTimeSeriesChart(
"Demand", // chart title
"Time",
"Demand(W)",
demandData,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
ValueAxis range = plot.getRangeAxis();
range.setLowerBound(0);
range.setUpperBound(2000);
return result;
}
}
|
package com.twu.biblioteca.Biblioteca;
import com.twu.biblioteca.Library.Library;
import com.twu.biblioteca.Menu.MainMenu;
public class BibliotecaApp {
public static void main(String[] args) {
Library library = new Library();
MainMenu launch = new MainMenu(library);
launch.mainMenu();
}
}
|
package com.tzapps.tzpalette.ui;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import com.tzapps.common.ui.BaseFragment;
import com.tzapps.common.utils.BitmapUtils;
import com.tzapps.common.utils.ColorUtils;
import com.tzapps.common.utils.MediaHelper;
import com.tzapps.tzpalette.Constants;
import com.tzapps.tzpalette.R;
import com.tzapps.tzpalette.data.PaletteData;
import com.tzapps.tzpalette.data.PaletteDataHelper;
import com.tzapps.tzpalette.debug.MyDebug;
import com.tzapps.tzpalette.ui.view.ColorEditView;
import com.tzapps.tzpalette.ui.view.ColorImageView;
import com.tzapps.tzpalette.ui.view.ColorRow;
public class PaletteEditFragment extends BaseFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,
ColorImageView.OnColorImageClickListener, ColorEditView.OnColorEditViewChangedListener
{
private static final String TAG = "PaletteEditFragment";
private PaletteData mData;
private View mView;
private ColorImageView mImageView;
private ColorRow mColorsRow;
private TextView mTitle;
private CheckBox mFavourite;
private ColorEditView mColorEditView;
/** the current selected color - original color */
private int mSelOriColor = Color.GRAY;
/** the current selected color - new color */
private int mSelNewColor = Color.GRAY;
/** the current selected color position */
private int mSelColorPosition = -1;
/** the current tab in color edit View */
private int mCurTab = ColorEditView.TAB_INDEX_RGB;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.d(TAG, "onCreateView()");
setRetainInstance(true);
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.palette_edit_view, container, false);
mImageView = (ColorImageView) mView.findViewById(R.id.palette_edit_view_picture);
mImageView.setOnColorImageClickListener(this);
mTitle = (TextView) mView.findViewById(R.id.palette_edit_view_title);
mFavourite = (CheckBox) mView.findViewById(R.id.palette_edit_view_favourite);
mColorsRow = (ColorRow) mView.findViewById(R.id.palette_edit_view_colors);
mColorsRow.setOnItemClickListener(this);
mColorsRow.setOnItemLongClickListener(this);
mColorEditView = (ColorEditView) mView.findViewById(R.id.palette_edit_view_color_edit_area);
mColorEditView.setOnColorEditViewChangedListener(this);
refresh(true);
return mView;
}
public PaletteData getData()
{
return mData;
}
public void refresh(boolean updatePicture)
{
if (mData == null)
return;
mTitle.setText(mData.getTitle());
mFavourite.setChecked(mData.isFavourite());
mColorsRow.setColors(mData.getColors());
mColorsRow.setSelection(mSelColorPosition);
mColorEditView.setColor(mSelOriColor, mSelNewColor);
mColorEditView.setCurrentTab(mCurTab);
if (updatePicture)
{
Bitmap bitmap = null;
bitmap = PaletteDataHelper.getInstance(getActivity()).getThumb(mData.getId());
if (bitmap == null)
{
String imagePath = mData.getImageUrl();
Uri imageUri = imagePath == null ? null : Uri.parse(imagePath);
bitmap = BitmapUtils.getBitmapFromUri(getActivity(), imageUri, Constants.THUMB_MAX_SIZE);
if (bitmap != null)
{
int orientation;
/*
* This is a quick fix on picture orientation for the picture taken
* from the camera, as it will be always rotated to landscape
* incorrectly even if we take it in portrait mode...
*/
orientation = MediaHelper.getPictureOrientation(getActivity(), imageUri);
bitmap = BitmapUtils.getRotatedBitmap(bitmap, orientation);
}
}
updateImageView(bitmap);
}
}
public void updateData(PaletteData data, boolean updatePicture)
{
mData = data;
if (data.getColors().length != 0)
{
mSelOriColor = data.getColors()[0];
mSelNewColor = data.getColors()[0];
mSelColorPosition = 0;
}
refresh(updatePicture);
}
public void updateImageView(Bitmap bitmap)
{
Log.d(TAG, "updateImageView");
if (mImageView == null)
return;
mImageView.setImageBitmap(bitmap);
}
public void updateColors(int[] colors)
{
if (MyDebug.LOG)
Log.d(TAG, "updateColors");
mData.addColors(colors, false);
refresh(false);
}
public void clearColors()
{
if (MyDebug.LOG)
Log.d(TAG, "clearColors");
mData.clearColors();
mColorsRow.clear();
}
public void updateTitle(String title)
{
if (MyDebug.LOG)
Log.d(TAG, "update title " + title);
mData.setTitle(title);
refresh(false);
}
public void updateFavourite(boolean favourite)
{
if (MyDebug.LOG)
Log.d(TAG, "update favourite" + favourite);
mData.setFavourite(favourite);
refresh(false);
}
public void addNewColorIntoColorsBar(int color, boolean selected)
{
mData.addColor(color);
mColorsRow.addColor(color, selected);
}
@Override
public void onColorImageClicked(ColorImageView view, int xPos, int yPos, int color)
{
if (MyDebug.LOG)
Log.d(TAG, "image clicked at x=" + xPos + " y=" + yPos + " color=" + ColorUtils.colorToHtml(color));
if (mColorsRow.getColorCount() < Constants.COLOR_SLOT_MAX_SIZE)
{
// if there is an empty color slot existing
// then add user's picking color into a new color slot
addNewColorIntoColorsBar(color, /*selected*/true);
mSelOriColor = color;
mSelNewColor = color;
mSelColorPosition = mColorsRow.getSelection();
mColorEditView.setColor(color,color);
}
else if (mSelColorPosition != -1)
{
// if the ColorsRow's slots have been full, then
// the picked color will be set as the new color for
// changing current selected color slot
mSelNewColor = color;
mColorEditView.setColor(mSelOriColor, mSelNewColor);
}
}
@Override
public void onColorChanged(ColorEditView view, int oriColor, int newColor)
{
if (MyDebug.LOG)
Log.d(TAG, "update color: color=" + ColorUtils.colorToHtml(oriColor) + " newColor=" + ColorUtils.colorToHtml(newColor) +
" selected color slot=" + mSelColorPosition);
mSelNewColor = newColor;
mSelColorPosition = mColorsRow.getSelection();
if (mSelColorPosition != -1)
{
mData.replaceAt(mSelColorPosition, newColor);
mColorsRow.updateColorAt(mSelColorPosition, newColor);
}
}
@Override
public void onTabChanged(ColorEditView view, int index, String tag)
{
mCurTab = index;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
int color = mColorsRow.getColor(position);
if (MyDebug.LOG)
Log.d(TAG, "select a color position= " + position + " Color=" + ColorUtils.colorToHtml(color));
if (position != mColorsRow.getSelection())
{
mSelOriColor = color;
mSelNewColor = color;
mSelColorPosition = position;
mColorsRow.setSelection(position);
mColorEditView.setColor(color,color);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
//long click to remove this color from palette data and colors bar
int color = mColorsRow.getColor(position);
mColorsRow.removeColorAt(position);
mData.removeColor(color);
return true;
}
}
|
package com.xruby.runtime.builtin;
import com.xruby.runtime.lang.*;
import com.xruby.runtime.value.*;
class Array_length extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return ObjectFactory.createFixnum(value.size());
}
}
class Array_clear extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return value.clear();
}
}
class Array_to_s extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return value.to_s();
}
}
class Array_array_first extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a = (RubyArray) receiver;
if (null == args) {
return a.get(0);
} else {
RubyFixnum n = (RubyFixnum) args.get(0);
return a.subarray(0, n.intValue());
}
}
}
class Array_array_last extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a = (RubyArray) receiver;
if (null == args) {
return a.get(-1);
} else {
RubyFixnum n = (RubyFixnum) args.get(0);
return a.subarray(a.size() - n.intValue(), n.intValue());
}
}
}
class Array_array_access extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (1 == args.size()) {
Object argValue = args.get(0);
if (argValue instanceof RubyFixnum) {
RubyFixnum index = (RubyFixnum) argValue;
return value.get(index.intValue());
} else if (args.get(0) instanceof RubyRange) {
int begin = ((RubyFixnum) ((RubyRange) args.get(0)).getLeft()).intValue();
int end = ((RubyFixnum) ((RubyRange) args.get(0)).getRight()).intValue();
if (begin < 0) {
begin = value.size() + begin;
}
if (end < 0) {
end = value.size() + end;
}
if (!((RubyRange) args.get(0)).isExcludeEnd()) {
++end;
}
RubyArray resultValue = value.subarray(begin, end - begin);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
} else if (2 == args.size()) {
Object arg0Value = args.get(0);
Object arg1Value = args.get(1);
if (arg0Value instanceof RubyFixnum && arg1Value instanceof RubyFixnum) {
int begin = ((RubyFixnum) arg0Value).intValue();
int length = ((RubyFixnum) arg1Value).intValue();
RubyArray resultValue = value.subarray(begin, length);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
}
//TODO
throw new RubyException("not implemented");
}
}
class Array_slice_danger extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (1 == args.size()) {
Object argValue = args.get(0);
if (argValue instanceof RubyFixnum) {
RubyFixnum index = (RubyFixnum) argValue;
return value.delete_at(index.intValue());
} else if (args.get(0) instanceof RubyRange) {
int begin = ((RubyFixnum) ((RubyRange) args.get(0)).getLeft()).intValue();
int end = ((RubyFixnum) ((RubyRange) args.get(0)).getRight()).intValue();
if (begin < 0) {
begin = value.size() + begin;
}
if (end < 0) {
end = value.size() + end;
}
if (!((RubyRange) args.get(0)).isExcludeEnd()) {
++end;
}
RubyArray resultValue = value.delete_at(begin, end - begin);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
} else if (2 == args.size()) {
Object arg0Value = args.get(0);
Object arg1Value = args.get(1);
if (arg0Value instanceof RubyFixnum && arg1Value instanceof RubyFixnum) {
int begin = ((RubyFixnum) arg0Value).intValue();
int length = ((RubyFixnum) arg1Value).intValue();
RubyArray resultValue = value.delete_at(begin, length);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
}
//TODO
throw new RubyException("not implemented");
}
}
class Array_array_at extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
RubyFixnum index = (RubyFixnum) arg;
return value.get(index.intValue());
}
}
class Array_array_set extends RubyVarArgMethod {
private int getRealIndex(int size,int i) {
int index = i;
if (index < 0) {
index = size + index;
}
if (index < 0) {
throw new RubyException(RubyRuntime.IndexErrorClass, "index " + i + " out of array");
}
return index;
}
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (2 == args.size()) {
if (args.get(0) instanceof RubyRange) {
RubyRange range = (RubyRange) args.get(0);
RubyFixnum left = (RubyFixnum)range.getLeft();
RubyFixnum right = (RubyFixnum)range.getRight();
int l_index = getRealIndex(value.size(), left.intValue());
int r_index = getRealIndex(value.size(), right.intValue());
int length = r_index-l_index+1;
return value.replace(l_index, length, args.get(1));
} else {
RubyFixnum index = (RubyFixnum) args.get(0);
return value.set(index.intValue(), args.get(1));
}
} else if (3 == args.size()) {
RubyFixnum index = (RubyFixnum) args.get(0);
RubyFixnum length = (RubyFixnum) args.get(1);
return value.replace(index.intValue(), length.intValue(), args.get(2));
}
throw new RubyException("not implemented");
}
}
class Array_equal extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
Object right = arg;
if (!(right instanceof RubyArray)) {
return ObjectFactory.FALSE_VALUE;
}
return left.equals((RubyArray) right) ? ObjectFactory.TRUE_VALUE : ObjectFactory.FALSE_VALUE;
}
}
class Array_compare extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
Object right = arg;
if (!(right instanceof RubyArray)) {
throw new RubyException(RubyRuntime.TypeErrorClass, "Can't convert " + arg.getRubyClass().getName() + " into Array");
}
return left.compare((RubyArray) right);
}
}
class Array_concat extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
left.concat(arg);
return receiver;
}
}
class Array_left_shift_operator extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
left.add(arg);
return receiver;
}
}
class Array_plus extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
RubyArray right = (RubyArray) arg;
return left.plus(right);
}
}
class Array_minus extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
RubyArray right = (RubyArray) arg;
return left.minus(right);
}
}
class Array_times extends RubyOneArgMethod {
private RubyID joinID = StringMap.intern("join");
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (arg instanceof RubyFixnum) {
RubyFixnum times = (RubyFixnum) arg;
return array.times(times.intValue());
} else if (arg instanceof RubyString) {
return RubyAPI.callOneArgMethod(receiver, arg, block, joinID);
}
throw new RubyException(RubyRuntime.TypeErrorClass, "no implicit conversion from " + arg + " to integer");
}
}
class Array_operator_and extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.and((RubyArray) arg);
}
}
class Array_operator_or extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.or((RubyArray) arg);
}
}
class Array_push extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (null != args) {
for (RubyValue v : args) {
array.add(v);
}
}
return array;
}
}
class Array_insert extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyFixnum index = (RubyFixnum) args.get(0);
int start = index.intValue();
if (start < 0) {
start+=array.size()+1;
}
return array.insert(start, args.subarray(1, args.size()-1));
}
}
class Array_pop extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_at(array.size() - 1);
}
}
class Array_delete_at extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyFixnum pos = (RubyFixnum) arg;
return array.delete_at(pos.intValue());
}
}
class Array_delete_if extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_if(block);
}
}
class Array_delete extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyValue return_value = array.delete(arg);
if (null != block && return_value == ObjectFactory.NIL_VALUE) {
return block.invoke(receiver, new RubyArray(arg));
} else {
return return_value;
}
}
}
class Array_include extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (array.include(arg)) {
return ObjectFactory.TRUE_VALUE;
} else {
return ObjectFactory.FALSE_VALUE;
}
}
}
class Array_each extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.each(receiver, block);
}
}
class Array_each_index extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.each_index(receiver, block);
}
}
class Array_reverse_each extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.reverse_each(receiver, block);
}
}
class Array_unshift extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.unshift(args);
}
}
class Array_new extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a;
if (null == args) {
a = new RubyArray();
} else if (null == block) {
if (args.get(0) instanceof RubyArray) {
a = (RubyArray)args.get(0).clone();
} else {
RubyFixnum size = (RubyFixnum) args.get(0);
RubyValue default_value = args.get(1);
a = ObjectFactory.createArray(size.intValue(), default_value);
}
} else {
RubyFixnum size = (RubyFixnum) args.get(0);
a = new RubyArray();
for (int i=0; i<size.intValue(); i++) {
RubyValue return_value = block.invoke(receiver, new RubyArray(ObjectFactory.createFixnum(i)));
a.add(return_value);
}
}
a.setRubyClass((RubyClass) receiver);
return a;
}
}
class Array_new_with_given_objects extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a;
if (null == args) {
a = new RubyArray();
} else {
a = args.copy();
}
a.setRubyClass((RubyClass) receiver);
return a;
}
}
class Array_shift extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_at(0);
}
}
class Array_sort_dangers extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (null == block) {
array.sort();
} else {
array.sort(block);
}
return array;
}
}
class Array_sort extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
if (null == block) {
array.sort();
} else {
array.sort(block);
}
return array;
}
}
class Array_hash extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return ObjectFactory.createFixnum(array.hash());
}
}
class Array_compact_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.compact() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_compact extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
return array.compact() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_uniq_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.uniq() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_uniq extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
return array.uniq() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_reverse_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
array.reverse();
return array;
}
}
class Array_reverse extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
array.reverse();
return array;
}
}
class Array_pack extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
String format = ((RubyString) arg).toString();
return ObjectFactory.createString(ArrayPacker.pack(array, format));
}
}
class Array_index extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
for(int i=0; i<array.size(); i++){
if(array.get(i).equals(arg))
return ObjectFactory.createFixnum(i);
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_rindex extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
for(int i=array.size()-1; i>=0; i
if(array.get(i).equals(arg))
return ObjectFactory.createFixnum(i);
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_replace extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray anotherArray = (RubyArray)arg;
if(array == anotherArray)
return array;
array.clear();
for(int i=0;i<anotherArray.size();i++){
array.add(anotherArray.get(i));
}
return array;
}
}
class Array_indexes extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray)receiver;
RubyArray a = new RubyArray(args.size());
for(int i=0;i<args.size();i++){
RubyFixnum n = (RubyFixnum) args.get(i);
a.add(array.get(n.intValue()));
}
return a;
}
}
class Array_nitems extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
int n = 0;
for(int i=0;i<array.size();i++){
if(array.get(i) != ObjectFactory.NIL_VALUE)
n++;
}
return ObjectFactory.createFixnum(n);
}
}
class Array_flatten extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray a = new RubyArray();
recursiveAdd(a,array);
return a;
}
private void recursiveAdd(RubyArray receiver,RubyArray array){
for(int i=0;i<array.size();i++){
RubyValue val = array.get(i);
if(val instanceof RubyArray){
recursiveAdd(receiver,(RubyArray)val);
}else{
receiver.add(val);
}
}
}
}
class Array_flatten_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray copy = array.copy();
array.clear();
boolean hasModified = recursiveAdd(array,copy);
if(hasModified){
return array;
}else{
return ObjectFactory.NIL_VALUE;
}
}
private boolean recursiveAdd(RubyArray receiver,RubyArray array){
boolean flag = false;
for(int i=0;i<array.size();i++){
RubyValue val = array.get(i);
if(val instanceof RubyArray){
flag = true;
recursiveAdd(receiver,(RubyArray)val);
}else{
receiver.add(val);
}
}
return flag;
}
}
class Array_collect_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray a = (RubyArray)RubyAPI.callPublicMethod(receiver, null, block, StringMap.intern("collect"));
RubyArray array = (RubyArray) receiver;
array.clear();
for(int i=0;i<a.size();i++){
array.add(a.get(i));
}
return array;
}
}
class Array_assoc extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyValue val = null;
for(int i=0;i<array.size();i++){
val = array.get(i);
if(val instanceof RubyArray){
if(((RubyArray)val).size() > 0){
RubyValue tmp = ((RubyArray)val).get(0);
if(arg.equals(tmp)){
return val;
}
}
}
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_rassoc extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyValue val = null;
for(int i=0;i<array.size();i++){
val = array.get(i);
if(val instanceof RubyArray){
if(((RubyArray)val).size() > 1){
RubyValue tmp = ((RubyArray)val).get(1);
if(arg.equals(tmp)){
return val;
}
}
}
}
return ObjectFactory.NIL_VALUE;
}
}
public class ArrayClassBuilder {
public static void initialize() {
RubyClass c = RubyRuntime.ArrayClass;
c.getSingletonClass().defineMethod("new", new Array_new());
c.getSingletonClass().defineMethod("[]", new Array_new_with_given_objects());
c.defineMethod("length", new Array_length());
c.defineMethod("clear", new Array_clear());
c.defineMethod("to_s", new Array_to_s());
c.defineMethod("[]", new Array_array_access());
c.defineMethod("first", new Array_array_first());
c.defineMethod("last", new Array_array_last());
c.defineMethod("at", new Array_array_at());
c.defineMethod("[]=", new Array_array_set());
c.defineMethod("==", new Array_equal());
c.defineMethod("<=>", new Array_compare());
c.defineMethod("<<", new Array_left_shift_operator());
c.defineMethod("concat", new Array_concat());
c.defineMethod("+", new Array_plus());
c.defineMethod("-", new Array_minus());
c.defineMethod("*", new Array_times());
c.defineMethod("&", new Array_operator_and());
c.defineMethod("|", new Array_operator_or());
c.defineMethod("push", new Array_push());
c.defineMethod("insert", new Array_insert());
c.defineMethod("pop", new Array_pop());
c.defineMethod("delete", new Array_delete());
c.defineMethod("delete_at", new Array_delete_at());
c.defineMethod("delete_if", new Array_delete_if());
c.defineMethod("include?", new Array_include());
c.defineMethod("unshift", new Array_unshift());
c.defineMethod("each", new Array_each());
c.defineMethod("reverse_each", new Array_reverse_each());
c.defineMethod("pack", new Array_pack());
c.defineMethod("shift", new Array_shift());
c.defineMethod("sort!", new Array_sort_dangers());
c.defineMethod("sort", new Array_sort());
c.defineMethod("hash", new Array_hash());
c.defineMethod("compact!", new Array_compact_danger());
c.defineMethod("compact", new Array_compact());
c.defineMethod("uniq!", new Array_uniq_danger());
c.defineMethod("uniq", new Array_uniq());
c.defineMethod("reverse!", new Array_reverse_danger());
c.defineMethod("reverse", new Array_reverse());
c.defineMethod("slice", new Array_array_access());
c.defineMethod("slice!", new Array_slice_danger());
c.defineMethod("index",new Array_index());
c.defineMethod("rindex",new Array_rindex());
c.defineMethod("replace", new Array_replace());
c.defineMethod("eql?", new Array_equal());
c.defineMethod("indexes", new Array_indexes());
c.defineMethod("indices", new Array_indexes());
c.defineMethod("nitems",new Array_nitems());
c.defineMethod("flatten", new Array_flatten());
c.defineMethod("flatten!", new Array_flatten_danger());
c.defineMethod("each_index", new Array_each_index());
c.defineMethod("collect!", new Array_collect_danger());
c.defineMethod("assoc", new Array_assoc());
c.defineMethod("rassoc", new Array_rassoc());
c.includeModule(RubyRuntime.EnumerableModule);
}
}
|
package lombok.javac.apt;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
// Can't use SimpleJavaFileObject so we copy/paste most of its content here, because javac doesn't follow the interface,
// and casts to its own BaseFileObject type. D'oh!
class EmptyLombokFileObject implements LombokFileObject {
private final String name;
private final Kind kind;
public EmptyLombokFileObject(String name, Kind kind) {
this.name = name;
this.kind = kind;
}
@Override public boolean isNameCompatible(String simpleName, Kind kind) {
String baseName = simpleName + kind.extension;
return kind.equals(getKind())
&& (baseName.equals(toUri().getPath())
|| toUri().getPath().endsWith("/" + baseName));
}
@Override public URI toUri() {
return URI.create("file://" + name);
}
@Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return "";
}
@Override public InputStream openInputStream() throws IOException {
return new ByteArrayInputStream(new byte[0]);
}
@Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
return new StringReader("");
}
@Override public Writer openWriter() throws IOException {
return new OutputStreamWriter(openOutputStream());
}
@Override public OutputStream openOutputStream() throws IOException {
return new ByteArrayOutputStream();
}
@Override public long getLastModified() {
return 0L;
}
@Override public boolean delete() {
return false;
}
@Override public Kind getKind() {
return kind;
}
@SuppressWarnings("all")
@Override public String getName() {
return toUri().getPath();
}
@Override public NestingKind getNestingKind() {
return null;
}
@Override public Modifier getAccessLevel() {
return null;
}
@Override public CharsetDecoder getDecoder(boolean ignoreEncodingErrors) {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
CodingErrorAction action = ignoreEncodingErrors ? CodingErrorAction.REPLACE : CodingErrorAction.REPORT;
return decoder.onMalformedInput(action).onUnmappableCharacter(action);
}
@Override public boolean equals(Object obj) {
if (!(obj instanceof EmptyLombokFileObject)) {
return false;
}
if (obj == this) {
return true;
}
EmptyLombokFileObject other = (EmptyLombokFileObject) obj;
return name.equals(other.name) && kind.equals(other.kind);
}
@Override public int hashCode() {
return name.hashCode() ^ kind.hashCode();
}
}
|
package net.simpvp.Misc;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.OfflinePlayer;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.Statistic;
/**
* A command to let /everybody/ see when somebody first joined.
*/
public class AgeCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player)
player = (Player) sender;
if (cmd.getName().equals("firstjoined")) {
if (player == null) {
Misc.instance.getLogger().info("firstjoined has been renamed to age.");
} else {
player.sendMessage(ChatColor.RED +
"/firstjoined has been renamed to /age.");
}
return true;
}
if (args.length < 1 && player == null) {
Misc.instance.getLogger().info("You must specify a player to use this command.");
return true;
}
Player target;
if (args.length > 0) {
@SuppressWarnings("deprecation") /* Only used for online players */
Player tmp = Misc.instance.getServer().getPlayer(args[0]);
target = tmp;
} else {
target = player;
}
final UUID uuid;
if (player == null) {
uuid = null;
} else {
uuid = player.getUniqueId();
}
if (target == null) {
get_uuid(args[0], uuid);
} else {
send_result(uuid, target.getUniqueId(), target.getName());
}
return true;
}
private void get_uuid(final String name, final UUID caller_uuid) {
new BukkitRunnable() {
@Override
public void run() {
try {
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
URLConnection conn = url.openConnection();
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String resp = reader.readLine();
if (resp == null)
resp = "";
Pattern p = Pattern.compile("\"id\":\"(\\S+?)\"");
Matcher m = p.matcher(resp);
m.find();
String uuid_str = m.group(1);
uuid_str = uuid_str.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
final UUID uuid = UUID.fromString(uuid_str);
new BukkitRunnable() {
@Override
public void run() {
send_result(caller_uuid, uuid, name);
}
}.runTask(Misc.instance);
} catch (Exception e) {
new BukkitRunnable() {
@Override
public void run() {
send_result(caller_uuid, null, name);
}
}.runTask(Misc.instance);
}
}
}.runTaskAsynchronously(Misc.instance);
}
private void send_result(UUID uuid, UUID target_uuid, String target_name) {
Player player = Misc.instance.getServer().getPlayer(uuid);
String msg;
if (target_uuid == null) {
msg = "Error retrieving data of " + target_name + ".";
} else {
OfflinePlayer off_player = Misc.instance.getServer().getOfflinePlayer(target_uuid);
if (off_player.getFirstPlayed() == 0) {
msg = target_name + " has never played on this server.";
} else {
long days = ((System.currentTimeMillis() - off_player.getFirstPlayed())
/ (1000L * 60 * 60 * 24));
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy");
msg = off_player.getName() + " first joined on "
+ ChatColor.AQUA + sdf.format(new Date(off_player.getFirstPlayed()))
+ ChatColor.GREEN + ", " + days + " day";
if (days != 1)
msg += "s";
msg += " ago.";
/* FIXME, currently this for some reason is only possible for online players, but it should be possible at all times */
Player on_player = Misc.instance.getServer().getPlayer(target_uuid);
/* We can't show this if the target player is
* offline, or if the target player is invis. */
if (on_player != null
&& (player == null
|| player.canSee(on_player))) {
int played_ticks = on_player.getStatistic(Statistic.PLAY_ONE_TICK);
double played_minutes = played_ticks / (20 * 60);
double played_hours = played_minutes / 60;
double played_days = played_hours / 24;
double played_years = played_days / 365;
double avg_hours = played_hours / (days + 1);
msg += String.format("They have played for %.0f minutes = %.1f hours = %.1f days = %.4f years. For an average of %.2f hours per day.",
played_minutes, played_hours, played_days, played_years, avg_hours);
}
}
}
if (player == null) {
Misc.instance.getLogger().info(msg);
} else {
player.sendMessage(ChatColor.GREEN + msg);
}
}
}
|
package dae.animation.rig;
import dae.prefabs.Prefab;
import dae.prefabs.standard.PrefabPlaceHolder;
/**
* Defines a call back for PrefabPlaceHolder objects.
* @author Koen Samyn
*/
public interface PrefabPlaceHolderCallback {
/**
* Called when the actual prefab has been found.
* @param actualPrefab the prefab that was found.
* @param placeHolder the placeholder object that held the place of the actual prefab.
*/
public void prefabFound(Prefab actualPrefab, PrefabPlaceHolder placeHolder);
}
|
package data_structure;
import java.util.*;
public class TwoSumIIIDataStructureDesign {
//TAG: LinkedIn
//TAG: Data structure
//Difficulty: Easy
/**
* 170. Two Sum III - Data structure design
* Design and implement a Q1TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
*/
/*
* Solution 1: slow in add(), fast in find()
* The key point is find(), most efficient way is using HashMap/Set structure to search
* So we try to add as many sums as possible in the set, when adding one number from num array
* So the find will just check if the sum is in the sum set
*/
public class TwoSumS1 {
List<Integer> num;
HashSet<Integer> sum;
/** Initialize your data structure here. */
public TwoSumS1() {
num = new ArrayList<>();
sum = new HashSet<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
for (int cur: num) sum.add(cur + number);
num.add(number);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
return sum.contains(value);
}
}
/*
* Solution 2: fast in add(), slow in find()
* Store every added number into a hashMap, value have two types, if only one, value == 1, if more than 1, value == 2
* Find(): check if sum - value is in hashMap, there are two conditions:
* 1. if sum - value == value, means the searched value may be the value itself, so, if value == 2, means there are more than one sum - value, return true, otherwise false
* 2. if sum - value != value, just verify if in hashMap, if so, return true, otherwise false
*/
public class TwoSumS2 {
HashMap<Integer, Integer> map;
/** Initialize your data structure here. */
public TwoSumS2() {
map = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
if (map.containsKey(number)) {
map.put(number, 2);
} else map.put(number, 1);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for (int key: map.keySet()) {
int num2 = value - key;
if (map.containsKey(num2)) {
/*
Need check if num2 == key, if not, return true, otherwise only num2 appears more than once,
it's true
*/
if (num2 != key || map.get(num2) == 2) return true;
}
}
return false;
}
}
}
|
package de.gurkenlabs.litiengine.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.text.MessageFormat;
import javax.swing.JLabel;
import de.gurkenlabs.litiengine.graphics.ImageCache;
import de.gurkenlabs.litiengine.graphics.RenderEngine;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.sound.Sound;
import de.gurkenlabs.util.ImageProcessing;
public class ImageComponent extends GuiComponent {
private Sound hoverSound;
private Image image;
private Spritesheet spritesheet;
public ImageComponent(final double x, final double y, final Image image) {
super(x, y, image.getWidth(null), image.getHeight(null));
this.image = image;
}
public ImageComponent(final double x, final double y, final double width, final double height, final Spritesheet spritesheet, final String text, final Image image) {
super(x, y, width, height);
this.spritesheet = spritesheet;
this.setFont(new JLabel().getFont().deriveFont((float) (this.getHeight() * 3 / 6f)));
this.setTextColor(Color.BLACK);
this.setText(text);
if (image != null) {
this.image = image;
}
}
public Image getBackground() {
if (this.getSpritesheet() == null) {
return null;
}
final String cacheKey = MessageFormat.format("{0}_{1}_{2}_{3}x{4}", this.getSpritesheet().getName().hashCode(), this.isHovered(), this.isPressed(), this.getWidth(), this.getHeight());
if (ImageCache.SPRITES.containsKey(cacheKey)) {
return ImageCache.SPRITES.get(cacheKey);
}
BufferedImage img;
if (this.isHovered() && this.getSpritesheet().getTotalNumberOfSprites() > 1) {
if (this.isPressed()) {
img = ImageProcessing.scaleImage(this.getSpritesheet().getSprite(2), (int) this.getWidth(), (int) this.getHeight());
} else {
img = ImageProcessing.scaleImage(this.getSpritesheet().getSprite(1), (int) this.getWidth(), (int) this.getHeight());
}
} else {
img = ImageProcessing.scaleImage(this.getSpritesheet().getSprite(0), (int) this.getWidth(), (int) this.getHeight());
}
if (img != null) {
ImageCache.SPRITES.put(cacheKey, img);
}
return img;
}
@Override
public Sound getHoverSound() {
return this.hoverSound;
}
public Image getImage() {
return this.image;
}
protected Spritesheet getSpritesheet() {
return this.spritesheet;
}
@Override
public void render(final Graphics2D g) {
if (this.isSuspended() || !this.isVisible()) {
return;
}
final Image bg = this.getBackground();
if (bg != null) {
RenderEngine.renderImage(g, bg, this.getLocation());
}
final Image img = this.getImage();
if (img != null) {
RenderEngine.renderImage(g, img, this.getLocation());
}
super.render(g);
}
@Override
public void setHeight(final double height) {
super.setHeight(height);
}
@Override
public void setHoverSound(final Sound hoverSound) {
this.hoverSound = hoverSound;
}
public void setImage(final Image image) {
this.image = image;
}
public void setSpriteSheet(final Spritesheet spr) {
this.spritesheet = spr;
}
@Override
public void setWidth(final double width) {
super.setWidth(width);
}
@Override
protected void initializeComponents() {
}
}
|
package de.lmu.ifi.dbs.elki.persistent;
/**
* Page file statistic utility functions.
*
* @author Erich Schubert
*
* @apiviz.landmark
*
* @apiviz.uses PageFileStatistics oneway - - analyses
*/
public final class PageFileUtil {
/**
* Append the page file statistics to the output buffer.
*
* @param buffer Buffer to append to
*/
public static void appendPageFileStatistics(StringBuffer buffer, PageFileStatistics statistics) {
if(statistics != null) {
buffer.append("Page File Layer: ").append(statistics.getClass()).append("\n");
buffer.append("Read Operations: ").append(statistics.getReadOperations()).append("\n");
buffer.append("Write Operations: ").append(statistics.getWriteOperations()).append("\n");
PageFileStatistics inner = statistics.getInnerStatistics();
if(inner != null) {
appendPageFileStatistics(buffer, inner);
}
}
}
/**
* Get the number of (logical) read operations (without caching).
*
* @param statistics Statistics.
* @return logical read operations.
*/
public static long getLogicalReadOperations(PageFileStatistics statistics) {
return statistics.getReadOperations();
}
/**
* Get the number of (logical) write operations (without caching).
*
* @param statistics Statistics.
* @return logical write operations.
*/
public static long getLogicalWriteOperations(PageFileStatistics statistics) {
return statistics.getWriteOperations();
}
/**
* Get the number of (physical) read operations (with caching).
*
* @param statistics Statistics.
* @return physical read operations.
*/
public static long getPhysicalReadOperations(PageFileStatistics statistics) {
PageFileStatistics inner = statistics.getInnerStatistics();
if(inner != null) {
return getPhysicalReadOperations(inner);
}
return statistics.getReadOperations();
}
/**
* Get the number of (physical) write operations (with caching).
*
* @param statistics Statistics.
* @return physical write operations.
*/
public static long getPhysicalWriteOperations(PageFileStatistics statistics) {
PageFileStatistics inner = statistics.getInnerStatistics();
if(inner != null) {
return getPhysicalWriteOperations(inner);
}
return statistics.getWriteOperations();
}
}
|
package test.ccn.data.content;
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.content.CollectionData;
import com.parc.ccn.data.security.PublisherPublicKeyDigest;
import com.parc.ccn.data.util.CCNEncodableObject;
import com.parc.ccn.library.CCNLibrary;
/**
* This will become the basis of the new Collection class once its functionality is merged
* with existing Collections. Put it here temporarily so as to be able to test
* CCNEncodableObject itself.
*
* Force raw in order to be able to test raw object writes to ccnd.
* @author smetters
*
*/
public class CCNRawEncodableCollectionData extends CCNEncodableObject<CollectionData> {
public CCNRawEncodableCollectionData(ContentName name, CollectionData data, CCNLibrary library) throws ConfigurationException, IOException {
this(name, data, null, library);
}
public CCNRawEncodableCollectionData(ContentName name, CollectionData data, PublisherPublicKeyDigest publisher, CCNLibrary library) throws ConfigurationException, IOException {
super(CollectionData.class, name, data, true, publisher, library);
}
public CCNRawEncodableCollectionData(ContentName name, PublisherPublicKeyDigest publisher,
CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException {
super(CollectionData.class, name, publisher, true, library);
}
/**
* Read constructor -- opens existing object.
* @param type
* @param name
* @param library
* @throws XMLStreamException
* @throws IOException
* @throws ClassNotFoundException
*/
public CCNRawEncodableCollectionData(ContentName name,
CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException {
super(CollectionData.class, name, (PublisherPublicKeyDigest)null, true, library);
}
public CCNRawEncodableCollectionData(ContentObject firstBlock,
CCNLibrary library) throws ConfigurationException, IOException, XMLStreamException {
super(CollectionData.class, firstBlock, true, library);
}
}
|
package org.intermine.web;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* Implementation of <strong>Action</strong> to modify bags
* @author Mark Woodbridge
*/
public class ModifyBagAction extends LookupDispatchAction
{
/**
* Union the selected bags
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward union(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Map savedBags = (Map) session.getAttribute(Constants.SAVED_BAGS);
ModifyBagForm mbf = (ModifyBagForm) form;
String bag1Name = mbf.getSelectedBags()[0];
String bag2Name = mbf.getSelectedBags()[0];
Collection bag1 = (Collection) savedBags.get(bag1Name);
Collection bag2 = (Collection) savedBags.get(bag2Name);
Set combined = new InterMineBag();
combined.addAll(bag1);
combined.addAll(bag2);
savedBags.put(bag1Name + " u " + bag2Name, combined);
return mapping.findForward("history");
}
/**
* Intersect the selected bags
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward intersect(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Map savedBags = (Map) session.getAttribute(Constants.SAVED_BAGS);
ModifyBagForm mbf = (ModifyBagForm) form;
String bag1Name = mbf.getSelectedBags()[0];
String bag2Name = mbf.getSelectedBags()[0];
Collection bag1 = (Collection) savedBags.get(bag1Name);
Collection bag2 = (Collection) savedBags.get(bag2Name);
Set combined = new InterMineBag();
combined.addAll(bag1);
combined.retainAll(bag2);
savedBags.put(bag1Name + " n " + bag2Name, combined);
return mapping.findForward("history");
}
/**
* Delete the selected bags
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Map savedBags = (Map) session.getAttribute(Constants.SAVED_BAGS);
ModifyBagForm mbf = (ModifyBagForm) form;
for (int i = 0; i < mbf.getSelectedBags().length; i++) {
savedBags.remove(mbf.getSelectedBags()[i]);
}
return mapping.findForward("history");
}
/**
* Distributes the actions to the necessary methods, by providing a Map from action to
* the name of a method.
*
* @return a Map
*/
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("history.union", "union");
map.put("history.intersect", "intersect");
map.put("history.delete", "delete");
return map;
}
}
|
package org.intermine.web;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import java.util.HashMap;
/**
* Perform InterMine-specific actions when a Session is constructed or destroyed
* @author Mark Woodbridge
*/
public class SessionListener implements HttpSessionListener
{
/**
* @see HttpSessionListener#sessionCreated
*/
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
ServletContext servletContext = session.getServletContext();
ProfileManager pm = (ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER);
session.setAttribute(Constants.PROFILE,
new Profile(pm, null, new HashMap(), new HashMap(), new HashMap()));
}
/**
* @see HttpSessionListener#sessionDestroyed
*/
public void sessionDestroyed(HttpSessionEvent se) {
}
}
|
package dr.app.beauti.priorsPanel;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.types.PriorType;
import dr.app.beauti.util.PanelUtils;
import dr.app.gui.components.RealNumberField;
import dr.app.util.OSType;
import dr.math.distributions.*;
import jam.panels.OptionsPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Alexei Drummond
* @author Walter Xie
*/
abstract class PriorOptionsPanel extends OptionsPanel {
interface Listener {
void optionsPanelChanged();
}
private List<JComponent> argumentFields = new ArrayList<JComponent>();
private List<String> argumentNames = new ArrayList<String>();
private boolean isCalibratedYule = true;
private boolean isInitializable = true;
private final boolean isTruncatable;
private final RealNumberField initialField = new RealNumberField();
private final JButton negativeInfinityButton;
private final JButton positiveInfinityButton;
private final JCheckBox isTruncatedCheck = new JCheckBox("Truncate to:");
private final RealNumberField lowerField = new RealNumberField();
private final JLabel lowerLabel = new JLabel("Lower: ");
private final RealNumberField upperField = new RealNumberField();
private final JLabel upperLabel = new JLabel("Upper: ");
protected final Set<Listener> listeners = new HashSet<Listener>();
PriorOptionsPanel(boolean isTruncatable) {
super(12, (OSType.isMac() ? 6 : 24));
this.isTruncatable = isTruncatable;
negativeInfinityButton = new JButton(NumberFormat.getNumberInstance().format(Double.NEGATIVE_INFINITY));
PanelUtils.setupComponent(negativeInfinityButton);
negativeInfinityButton.setFocusable(false);
negativeInfinityButton.setActionCommand(RealNumberField.NEGATIVE_INFINITY);
negativeInfinityButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
lowerField.setText(e.getActionCommand());
}
});
negativeInfinityButton.setToolTipText("Click to set 'Positive Infinity' in the numerical field.");
positiveInfinityButton = new JButton(NumberFormat.getNumberInstance().format(Double.POSITIVE_INFINITY));
PanelUtils.setupComponent(positiveInfinityButton);
positiveInfinityButton.setFocusable(false);
positiveInfinityButton.setActionCommand(RealNumberField.POSITIVE_INFINITY);
positiveInfinityButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
upperField.setText(e.getActionCommand());
}
});
positiveInfinityButton.setToolTipText("Click to set 'Negative Infinity' in the numerical field.");
initialField.setColumns(10);
lowerField.setColumns(10);
upperField.setColumns(10);
setup();
isTruncatedCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
lowerField.setEnabled(isTruncatedCheck.isSelected());
lowerLabel.setEnabled(isTruncatedCheck.isSelected());
negativeInfinityButton.setEnabled(isTruncatedCheck.isSelected());
upperField.setEnabled(isTruncatedCheck.isSelected());
upperLabel.setEnabled(isTruncatedCheck.isSelected());
positiveInfinityButton.setEnabled(isTruncatedCheck.isSelected());
}
});
KeyListener listener = new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getComponent() instanceof RealNumberField) {
String number = ((RealNumberField) e.getComponent()).getText();
if (!(number.equals("") || number.endsWith("e") || number.endsWith("E") || number.endsWith("-"))) {
// System.out.println(e.getID() + " = \"" + ((RealNumberField) e.getComponent()).getText() + "\"");
// setupChart();
// dialog.repaint();
for (Listener listener : listeners) {
listener.optionsPanelChanged();
}
}
}
}
};
initialField.addKeyListener(listener);
for (JComponent component : argumentFields) {
if (component instanceof RealNumberField) {
component.addKeyListener(listener);
}
}
lowerField.addKeyListener(listener);
upperField.addKeyListener(listener);
}
protected RealNumberField getInitialField() {
return initialField;
}
void addListener(Listener listener) {
listeners.add(listener);
}
void removeAllListeners() {
listeners.clear();
}
protected void setFieldRange(RealNumberField field, boolean isNonNegative, boolean isZeroOne) {
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (isZeroOne) {
lower = 0.0;
upper = 1.0;
} else if (isNonNegative) {
lower = 0.0;
}
field.setRange(lower, upper);
}
protected void setFieldRange(RealNumberField field, boolean isNonNegative, boolean isZeroOne, double truncationLower, double truncationUpper) {
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (isZeroOne) {
lower = 0.0;
upper = 1.0;
} else if (isNonNegative) {
lower = 0.0;
}
if (lower < truncationLower) {
lower = truncationLower;
}
if (upper > truncationUpper) {
upper = truncationUpper;
}
field.setRange(lower, upper);
}
protected void addField(String name, double initialValue, double min, double max) {
RealNumberField field = new RealNumberField(min, max);
field.setValue(initialValue);
addField(name, field);
}
protected void addField(String name, RealNumberField field) {
argumentNames.add(name);
field.setColumns(10);
argumentFields.add(field);
setupComponents();
}
protected void addCheckBox(String name, JCheckBox jCheckBox) {
argumentNames.add(name);
argumentFields.add(jCheckBox);
setupComponents();
}
protected void replaceFieldName(int i, String name) {
argumentNames.set(i, name);
setupComponents();
}
protected double getValue(int i) {
return ((RealNumberField) argumentFields.get(i)).getValue();
}
private void setupComponents() {
removeAll();
if (isInitializable && !isCalibratedYule) {
addComponentWithLabel("Initial value: ", initialField);
}
for (int i = 0; i < argumentFields.size(); i++) {
addComponentWithLabel(argumentNames.get(i) + ":", argumentFields.get(i));
}
if (isTruncatable && !isCalibratedYule) {
addSpanningComponent(isTruncatedCheck);
JPanel panel = new JPanel();
panel.add(upperField);
panel.add(positiveInfinityButton);
addComponents(upperLabel, panel);
panel = new JPanel();
panel.add(lowerField);
panel.add(negativeInfinityButton);
addComponents(lowerLabel, panel);
positiveInfinityButton.setMinimumSize(new Dimension(negativeInfinityButton.getWidth(), negativeInfinityButton.getHeight()));
lowerField.setEnabled(isTruncatedCheck.isSelected());
lowerLabel.setEnabled(isTruncatedCheck.isSelected());
negativeInfinityButton.setEnabled(isTruncatedCheck.isSelected());
upperField.setEnabled(isTruncatedCheck.isSelected());
upperLabel.setEnabled(isTruncatedCheck.isSelected());
positiveInfinityButton.setEnabled(isTruncatedCheck.isSelected());
}
}
RealNumberField getField(int i) {
return (RealNumberField) argumentFields.get(i);
}
Distribution getDistribution(Parameter parameter) {
Distribution dist = getDistribution();
boolean isBounded = isTruncatedCheck.isSelected();
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (parameter.isZeroOne) {
lower = 0.0;
upper = 1.0;
isBounded = true;
} else if (parameter.isNonNegative) {
lower = 0.0;
isBounded = true;
}
if (dist != null && isTruncatable && isBounded) {
if (isTruncatedCheck.isSelected()) {
lower = lowerField.getValue();
upper = upperField.getValue();
}
dist = new TruncatedDistribution(dist, lower, upper);
}
return dist;
}
void setArguments(Parameter parameter, PriorType priorType) {
this.isCalibratedYule = parameter.isCalibratedYule;
if (!parameter.isStatistic) {
setFieldRange(initialField, parameter.isNonNegative, parameter.isZeroOne);
initialField.setValue(parameter.initial);
}
isTruncatedCheck.setSelected(parameter.isTruncated);
lowerField.setValue(parameter.getLowerBound());
upperField.setValue(parameter.getUpperBound());
setArguments(parameter);
setupComponents();
}
void getArguments(Parameter parameter, PriorType priorType) {
if (!parameter.isStatistic) {
parameter.initial = initialField.getValue();
}
parameter.isTruncated = isTruncatedCheck.isSelected();
if (parameter.isTruncated) {
parameter.truncationLower = lowerField.getValue();
parameter.truncationUpper = upperField.getValue();
}
getArguments(parameter);
}
abstract void setup();
abstract Distribution getDistribution();
abstract void setArguments(Parameter parameter);
abstract void getArguments(Parameter parameter);
static final PriorOptionsPanel UNIFORM = new PriorOptionsPanel(false) {
void setup() {
addField("Upper", 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Lower", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
Distribution getDistribution() {
return new UniformDistribution(
getValue(1), // lower
getValue(0) // upper
);
}
void setArguments(Parameter parameter) {
super.setFieldRange(getField(0), parameter.isNonNegative, parameter.isZeroOne, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
super.setFieldRange(getField(1), parameter.isNonNegative, parameter.isZeroOne, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
getField(0).setValue(parameter.uniformUpper);
getField(1).setValue(parameter.uniformLower);
}
void getArguments(Parameter parameter) {
parameter.isTruncated = false;
parameter.uniformUpper = getValue(0);
parameter.uniformLower = getValue(1);
}
};
static final PriorOptionsPanel EXPONENTIAL = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Offset", 0.0, 0.0, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new ExponentialDistribution(1.0 / getValue(0)), getValue(1));
}
public void setArguments(Parameter parameter) {
setFieldRange(getField(0), true, parameter.isZeroOne);
getField(0).setValue(parameter.mean != 0.0 ? parameter.mean : 1.0);
getField(1).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.offset = getValue(1);
}
};
static final PriorOptionsPanel LAPLACE = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Scale", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new LaplaceDistribution(getValue(0), getValue(1));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
setFieldRange(getField(0), true, false);
getField(1).setValue(parameter.scale);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.scale = getValue(1);
}
};
static final PriorOptionsPanel NORMAL = new PriorOptionsPanel(true) {
void setup() {
addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
addField("Stdev", 1.0, 0.0, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new NormalDistribution(getValue(0), getValue(1));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
getField(1).setValue(parameter.stdev);
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.stdev = getValue(1);
}
};
static final PriorOptionsPanel LOG_NORMAL = new PriorOptionsPanel(true) {
private JCheckBox meanInRealSpaceCheck;
void setup() {
meanInRealSpaceCheck = new JCheckBox();
if (meanInRealSpaceCheck.isSelected()) {
addField("Mean", 0.01, 0.0, Double.POSITIVE_INFINITY);
} else {
addField("Log(Mean)", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
addField("Log(Stdev)", 1.0, 0.0, Double.POSITIVE_INFINITY);
addField("Offset", 0.0, 0.0, Double.POSITIVE_INFINITY);
addCheckBox("Mean In Real Space", meanInRealSpaceCheck);
meanInRealSpaceCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
if (meanInRealSpaceCheck.isSelected()) {
replaceFieldName(0, "Mean");
if (getValue(0) <= 0) {
getField(0).setValue(0.01);
}
getField(0).setRange(0.0, Double.POSITIVE_INFINITY);
} else {
replaceFieldName(0, "Log(Mean)");
getField(0).setRange(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
for (Listener listener : listeners) {
listener.optionsPanelChanged();
}
}
});
}
public Distribution getDistribution() {
double mean = getValue(0);
if (meanInRealSpaceCheck.isSelected()) {
if (mean <= 0) {
throw new IllegalArgumentException("meanInRealSpace works only for a positive mean");
}
mean = Math.log(getValue(0)) - 0.5 * getValue(1) * getValue(1);
}
return new OffsetPositiveDistribution(
new LogNormalDistribution(mean, getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.mean);
getField(1).setValue(parameter.stdev);
getField(2).setValue(parameter.offset);
meanInRealSpaceCheck.setSelected(parameter.isMeanInRealSpace());
}
public void getArguments(Parameter parameter) {
parameter.mean = getValue(0);
parameter.stdev = getValue(1);
parameter.offset = getValue(2);
parameter.setMeanInRealSpace(meanInRealSpaceCheck.isSelected());
}
};
static final PriorOptionsPanel GAMMA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Scale", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Offset", 0.0, 0.0, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new GammaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.scale);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.scale = getValue(1);
parameter.offset = getValue(2);
}
};
static final PriorOptionsPanel INVERSE_GAMMA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Scale", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Offset", 0.0, 0.0, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new InverseGammaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.scale);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.scale = getValue(1);
parameter.offset = getValue(2);
}
};
// class TruncatedNormalOptionsPanel extends PriorOptionsPanel {
// public TruncatedNormalOptionsPanel() {
// addField("Mean", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// addField("Stdev", 1.0, 0.0, Parameter.UNIFORM_MAX_BOUND);
// addField("Lower", 0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// addField("Upper", 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
// public Distribution getDistribution() {
// return new TruncatedNormalDistribution(getValue(0), getValue(1), getValue(2), getValue(3));
// public void setParameterPrior(Parameter parameter) {
// parameter.mean = getValue(0);
// parameter.stdev = getValue(1);
// parameter.isTruncated = true;
// parameter.truncationLower = getValue(2);
// parameter.truncationUpper = getValue(3);
static final PriorOptionsPanel BETA = new PriorOptionsPanel(true) {
void setup() {
addField("Shape", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("ShapeB", 1.0, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
addField("Offset", 0.0, 0.0, Double.POSITIVE_INFINITY);
}
public Distribution getDistribution() {
return new OffsetPositiveDistribution(
new BetaDistribution(getValue(0), getValue(1)), getValue(2));
}
public void setArguments(Parameter parameter) {
getField(0).setValue(parameter.shape);
getField(1).setValue(parameter.shapeB);
getField(2).setValue(parameter.offset);
}
public void getArguments(Parameter parameter) {
parameter.shape = getValue(0);
parameter.shapeB = getValue(1);
parameter.offset = getValue(2);
}
};
static final PriorOptionsPanel CTMC_RATE_REFERENCE = new PriorOptionsPanel(false) {
void setup() {
}
public Distribution getDistribution() {
return null;
}
public void setArguments(Parameter parameter) {
}
public void getArguments(Parameter parameter) {
}
};
static final PriorOptionsPanel ONE_OVER_X = new PriorOptionsPanel(false) {
void setup() {
}
public Distribution getDistribution() {
return null;
}
public void setArguments(Parameter parameter) {
}
public void getArguments(Parameter parameter) {
}
};
}
|
package alfredo.sprite;
import alfredo.geom.Point;
/**
* Sprites are containers that have their own position and direction. They can be used
* to build constructs of multiple other Entities, such as Skeletons.
* @author TheMonsterFromTheDeep
*/
public class Sprite extends Entity {
protected Point position;
protected double direction;
public Sprite() {
position = new Point(0, 0);
direction = 0;
}
public void update() { }
public void draw(SpriteBatch sb) { }
@Override
public float getLocalX() {
return position.x;
}
@Override
public float getLocalY() {
return position.y;
}
@Override
public double getLocalDirection() {
return direction;
}
@Override
public void setLocalX(float x) {
position.x = x;
}
@Override
public void setLocalY(float y) {
position.y = y;
}
@Override
public void setLocalDirection(double dir) {
direction = dir;
}
}
|
package org.zstack.identity;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.Platform;
import org.zstack.core.cascade.CascadeConstant;
import org.zstack.core.cascade.CascadeFacade;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.EventFacade;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.*;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.notification.N;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.core.Completion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.identity.*;
import org.zstack.header.identity.IdentityCanonicalEvents.AccountDeletedData;
import org.zstack.header.identity.IdentityCanonicalEvents.UserDeletedData;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.ExceptionDSL;
import org.zstack.utils.Utils;
import org.zstack.utils.function.ForEachFunction;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Query;
import javax.persistence.Tuple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.zstack.core.Platform.argerr;
import static org.zstack.utils.CollectionDSL.list;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class AccountBase extends AbstractAccount {
private static final CLogger logger = Utils.getLogger(AccountBase.class);
@Autowired
private CloudBus bus;
@Autowired
private DatabaseFacade dbf;
@Autowired
private ErrorFacade errf;
@Autowired
private AccountManager acntMgr;
@Autowired
private CascadeFacade casf;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private EventFacade evtf;
private AccountVO self;
public AccountBase(AccountVO self) {
this.self = self;
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
}
private void handle(APIUpdateAccountMsg msg) {
AccountVO account = dbf.findByUuid(msg.getUuid(), AccountVO.class);
if (msg.getName() != null) {
account.setName(msg.getName());
}
if (msg.getDescription() != null) {
account.setDescription(msg.getDescription());
}
if (msg.getPassword() != null) {
account.setPassword(msg.getPassword());
}
account = dbf.updateAndRefresh(account);
APIUpdateAccountEvent evt = new APIUpdateAccountEvent(msg.getId());
evt.setInventory(AccountInventory.valueOf(account));
bus.publish(evt);
}
private void handleLocalMessage(Message msg) {
if (msg instanceof AccountDeletionMsg) {
handle((AccountDeletionMsg) msg);
} else if (msg instanceof DeleteAccountMsg) {
handle((DeleteAccountMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(DeleteAccountMsg msg) {
DeleteAccountReply reply = new DeleteAccountReply();
deleteAccount(new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void deleteAccount(Completion completion) {
final String issuer = AccountVO.class.getSimpleName();
final List<AccountInventory> ctx = list(AccountInventory.valueOf(self));
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("delete-account-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "delete";
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
dbf.remove(self);
acntMgr.adminAdoptAllOrphanedResource();
AccountDeletedData evtData = new AccountDeletedData();
evtData.setAccountUuid(self.getUuid());
evtData.setInventory(AccountInventory.valueOf(self));
evtf.fire(IdentityCanonicalEvents.ACCOUNT_DELETED_PATH, evtData);
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final APIDeleteAccountMsg msg) {
final APIDeleteAccountEvent evt = new APIDeleteAccountEvent(msg.getId());
deleteAccount(new Completion(msg) {
@Override
public void success() {
bus.publish(evt);
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(errorCode);
bus.publish(evt);
}
});
}
@Transactional
private void deleteRelatedResources() {
String sql = "delete from QuotaVO q where q.identityUuid = :uuid and q.identityType = :itype";
Query q = dbf.getEntityManager().createQuery(sql);
q.setParameter("uuid", self.getUuid());
q.setParameter("itype", AccountVO.class.getSimpleName());
q.executeUpdate();
sql = "delete from UserVO u where u.accountUuid = :uuid";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("uuid", self.getUuid());
q.executeUpdate();
sql = "delete from UserGroupVO g where g.accountUuid = :uuid";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("uuid", self.getUuid());
q.executeUpdate();
sql = "delete from PolicyVO p where p.accountUuid = :uuid";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("uuid", self.getUuid());
q.executeUpdate();
sql = "delete from SharedResourceVO s where s.ownerAccountUuid = :uuid or s.receiverAccountUuid = :uuid";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("uuid", self.getUuid());
q.executeUpdate();
}
private void handle(AccountDeletionMsg msg) {
AccountDeletionReply reply = new AccountDeletionReply();
deleteRelatedResources();
bus.reply(msg, reply);
}
private void handleApiMessage(APIMessage msg) {
if (msg instanceof APIUpdateAccountMsg) {
handle((APIUpdateAccountMsg) msg);
} else if (msg instanceof APICreateUserMsg) {
handle((APICreateUserMsg) msg);
} else if (msg instanceof APICreatePolicyMsg) {
handle((APICreatePolicyMsg) msg);
} else if (msg instanceof APIAttachPolicyToUserMsg) {
handle((APIAttachPolicyToUserMsg) msg);
} else if (msg instanceof APICreateUserGroupMsg) {
handle((APICreateUserGroupMsg) msg);
} else if (msg instanceof APIAttachPolicyToUserGroupMsg) {
handle((APIAttachPolicyToUserGroupMsg) msg);
} else if (msg instanceof APIAddUserToGroupMsg) {
handle((APIAddUserToGroupMsg) msg);
} else if (msg instanceof APIDeleteUserGroupMsg) {
handle((APIDeleteUserGroupMsg) msg);
} else if (msg instanceof APIDeleteUserMsg) {
handle((APIDeleteUserMsg) msg);
} else if (msg instanceof APIDeletePolicyMsg) {
handle((APIDeletePolicyMsg) msg);
} else if (msg instanceof APIDetachPolicyFromUserMsg) {
handle((APIDetachPolicyFromUserMsg) msg);
} else if (msg instanceof APIDetachPolicyFromUserGroupMsg) {
handle((APIDetachPolicyFromUserGroupMsg) msg);
} else if (msg instanceof APIRemoveUserFromGroupMsg) {
handle((APIRemoveUserFromGroupMsg) msg);
} else if (msg instanceof APIUpdateUserMsg) {
handle((APIUpdateUserMsg) msg);
} else if (msg instanceof APIShareResourceMsg) {
handle((APIShareResourceMsg) msg);
} else if (msg instanceof APIRevokeResourceSharingMsg) {
handle((APIRevokeResourceSharingMsg) msg);
} else if (msg instanceof APIUpdateQuotaMsg) {
handle((APIUpdateQuotaMsg) msg);
} else if (msg instanceof APIDeleteAccountMsg) {
handle((APIDeleteAccountMsg) msg);
} else if (msg instanceof APIGetAccountQuotaUsageMsg) {
handle((APIGetAccountQuotaUsageMsg) msg);
} else if (msg instanceof APIAttachPoliciesToUserMsg) {
handle((APIAttachPoliciesToUserMsg) msg);
} else if (msg instanceof APIDetachPoliciesFromUserMsg) {
handle((APIDetachPoliciesFromUserMsg) msg);
} else if (msg instanceof APIUpdateUserGroupMsg) {
handle((APIUpdateUserGroupMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(APIUpdateUserGroupMsg msg) {
UserGroupVO group = dbf.findByUuid(msg.getUuid(), UserGroupVO.class);
if (!AccountConstant.INITIAL_SYSTEM_ADMIN_UUID.equals(msg.getAccountUuid()) &&
!group.getAccountUuid().equals(msg.getAccountUuid())) {
throw new OperationFailureException(argerr("the user group[uuid:%s] does not belong to the account[uuid:%s]", group.getUuid(), msg.getAccountUuid()));
}
boolean update = false;
if (msg.getName() != null) {
group.setName(msg.getName());
update = true;
}
if (msg.getDescription() != null) {
group.setDescription(msg.getDescription());
update = true;
}
if (update) {
group = dbf.updateAndRefresh(group);
}
APIUpdateUserGroupEvent evt = new APIUpdateUserGroupEvent(msg.getId());
evt.setInventory(UserGroupInventory.valueOf(group));
bus.publish(evt);
}
@Transactional
private void handle(APIDetachPoliciesFromUserMsg msg) {
String sql = "delete from UserPolicyRefVO ref where ref.policyUuid in (:puuids) and ref.userUuid = :userUuid";
Query q = dbf.getEntityManager().createQuery(sql);
q.setParameter("puuids", msg.getPolicyUuids());
q.setParameter("userUuid", msg.getUserUuid());
q.executeUpdate();
APIDetachPoliciesFromUserEvent evt = new APIDetachPoliciesFromUserEvent(msg.getId());
bus.publish(evt);
}
@Transactional
private void handle(APIAttachPoliciesToUserMsg msg) {
for (String puuid : msg.getPolicyUuids()) {
try {
UserPolicyRefVO refVO = new UserPolicyRefVO();
refVO.setUserUuid(msg.getUserUuid());
refVO.setPolicyUuid(puuid);
dbf.getEntityManager().persist(refVO);
dbf.getEntityManager().flush();
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
}
APIAttachPoliciesToUserEvent evt = new APIAttachPoliciesToUserEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIGetAccountQuotaUsageMsg msg) {
APIGetAccountQuotaUsageReply reply = new APIGetAccountQuotaUsageReply();
List<Quota> quotas = acntMgr.getQuotas();
List<Quota.QuotaUsage> usages = new ArrayList<Quota.QuotaUsage>();
for (Quota q : quotas) {
List<Quota.QuotaUsage> us = q.getOperator().getQuotaUsageByAccount(msg.getAccountUuid());
DebugUtils.Assert(us != null, String.format("%s returns null quotas", q.getOperator().getClass()));
usages.addAll(us);
}
Map<String, Quota.QuotaUsage> umap = new HashMap<String, Quota.QuotaUsage>();
for (Quota.QuotaUsage usage : usages) {
umap.put(usage.getName(), usage);
}
SimpleQuery<QuotaVO> q = dbf.createQuery(QuotaVO.class);
q.add(QuotaVO_.identityUuid, Op.EQ, msg.getAccountUuid());
q.add(QuotaVO_.identityType, Op.EQ, AccountVO.class.getSimpleName());
q.add(QuotaVO_.name, Op.IN, umap.keySet());
List<QuotaVO> vos = q.list();
Map<String, QuotaVO> vmap = new HashMap<String, QuotaVO>();
for (QuotaVO vo : vos) {
vmap.put(vo.getName(), vo);
}
for (Map.Entry<String, Quota.QuotaUsage> e : umap.entrySet()) {
Quota.QuotaUsage u = e.getValue();
QuotaVO vo = vmap.get(u.getName());
u.setTotal(vo == null ? 0 : vo.getValue());
}
List<Quota.QuotaUsage> ret = new ArrayList<Quota.QuotaUsage>();
ret.addAll(umap.values());
reply.setUsages(ret);
bus.reply(msg, reply);
}
private void handle(APIUpdateQuotaMsg msg) {
SimpleQuery<QuotaVO> q = dbf.createQuery(QuotaVO.class);
q.add(QuotaVO_.identityUuid, Op.EQ, msg.getIdentityUuid());
q.add(QuotaVO_.name, Op.EQ, msg.getName());
QuotaVO quota = q.find();
if (quota == null) {
throw new OperationFailureException(argerr("cannot find Quota[name: %s] for the account[uuid: %s]", msg.getName(), msg.getIdentityUuid()));
}
quota.setValue(msg.getValue());
quota = dbf.updateAndRefresh(quota);
APIUpdateQuotaEvent evt = new APIUpdateQuotaEvent(msg.getId());
evt.setInventory(QuotaInventory.valueOf(quota));
bus.publish(evt);
}
@Transactional
private void handle(APIRevokeResourceSharingMsg msg) {
Query q = null;
if (msg.isAll()) {
String sql = "delete from SharedResourceVO vo where vo.ownerAccountUuid = :auuid and vo.resourceUuid in (:resUuids)";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("auuid", self.getUuid());
q.setParameter("resUuids", msg.getResourceUuids());
}
if (msg.isToPublic()) {
String sql = "delete from SharedResourceVO vo where vo.toPublic = :public and vo.ownerAccountUuid = :auuid and vo.resourceUuid in (:resUuids)";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("public", msg.isToPublic());
q.setParameter("auuid", self.getUuid());
q.setParameter("resUuids", msg.getResourceUuids());
}
if (msg.getAccountUuids() != null && !msg.getAccountUuids().isEmpty()) {
String sql = "delete from SharedResourceVO vo where vo.receiverAccountUuid in (:ruuids) and vo.ownerAccountUuid = :auuid and vo.resourceUuid in (:resUuids)";
q = dbf.getEntityManager().createQuery(sql);
q.setParameter("auuid", self.getUuid());
q.setParameter("ruuids", msg.getAccountUuids());
q.setParameter("resUuids", msg.getResourceUuids());
}
if (q != null) {
q.executeUpdate();
}
Map<String, String> uuidType = getUuidTypeMapByResourceUuids(msg.getResourceUuids());
for (String ruuid : msg.getResourceUuids()) {
String resourceType = uuidType.get(ruuid);
if (msg.getAccountUuids() != null) {
for (String auuid : msg.getAccountUuids()) {
N.New(resourceType, ruuid).info_("Revoke Shared resource[uuid:%s type:%s] of account[uuid:%s] from account[uuid:%s]", ruuid, resourceType, self.getUuid(), auuid);
}
} else {
N.New(resourceType, ruuid).info_("Revoke Shared resource[uuid:%s type:%s] of account[uuid:%s]", ruuid, resourceType, self.getUuid());
}
}
APIRevokeResourceSharingEvent evt = new APIRevokeResourceSharingEvent(msg.getId());
bus.publish(evt);
}
private Map<String, String> getUuidTypeMapByResourceUuids(List<String> resourceUuids) {
List<Tuple> ts = Q.New(AccountResourceRefVO.class)
.select(AccountResourceRefVO_.resourceUuid, AccountResourceRefVO_.resourceType)
.in(AccountResourceRefVO_.resourceUuid, resourceUuids)
.listTuple();
Map<String, String> uuidType = new HashMap<String, String>();
for (Tuple t : ts) {
String resUuid = t.get(0, String.class);
String resType = t.get(1, String.class);
uuidType.put(resUuid, resType);
}
return uuidType;
}
private void handle(APIShareResourceMsg msg) {
Map<String, String> uuidType = getUuidTypeMapByResourceUuids(msg.getResourceUuids());
for (String ruuid : msg.getResourceUuids()) {
if (!uuidType.containsKey(ruuid)) {
throw new OperationFailureException(argerr("the account[uuid: %s] doesn't have a resource[uuid: %s]", self.getUuid(), ruuid));
}
}
new SQLBatch(){
@Override
protected void scripts() {
if (msg.isToPublic()) {
for (String ruuid : msg.getResourceUuids()) {
if(Q.New(SharedResourceVO.class)
.eq(SharedResourceVO_.ownerAccountUuid, msg.getAccountUuid())
.eq(SharedResourceVO_.resourceUuid, ruuid)
.eq(SharedResourceVO_.toPublic, msg.isToPublic())
.isExists()){
continue;
}
String resourceType = uuidType.get(ruuid);
SharedResourceVO svo = new SharedResourceVO();
svo.setOwnerAccountUuid(msg.getAccountUuid());
svo.setResourceType(resourceType);
svo.setResourceUuid(ruuid);
svo.setToPublic(true);
dbf.persist(svo);
N.New(resourceType, ruuid).info_("Shared resource[uuid:%s type:%s] to public", ruuid, resourceType);
}
} else {
for (String ruuid : msg.getResourceUuids()) {
String resourceType = uuidType.get(ruuid);
for (String auuid : msg.getAccountUuids()) {
if (! Q.New(SharedResourceVO.class)
.eq(SharedResourceVO_.ownerAccountUuid, msg.getAccountUuid())
.eq(SharedResourceVO_.resourceUuid, ruuid)
.eq(SharedResourceVO_.receiverAccountUuid,auuid)
.isExists()){
SharedResourceVO svo = new SharedResourceVO();
svo.setOwnerAccountUuid(msg.getAccountUuid());
svo.setResourceType(resourceType);
svo.setResourceUuid(ruuid);
svo.setReceiverAccountUuid(auuid);
dbf.persist(svo);
N.New(resourceType, ruuid).info_("Shared resource[uuid:%s type:%s] to account[uuid:%s]", ruuid, resourceType, auuid);
}
}
}
}
}
}.execute();
APIShareResourceEvent evt = new APIShareResourceEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIUpdateUserMsg msg) {
UserVO user = dbf.findByUuid(msg.getUuid(), UserVO.class);
if (!AccountConstant.INITIAL_SYSTEM_ADMIN_UUID.equals(msg.getAccountUuid()) && !user.getAccountUuid().equals(msg.getAccountUuid())) {
throw new OperationFailureException(argerr("the user[uuid:%s] does not belong to the" +
" account[uuid:%s]", user.getUuid(), msg.getAccountUuid()));
}
boolean update = false;
if (msg.getName() != null) {
user.setName(msg.getName());
update = true;
}
if (msg.getDescription() != null) {
user.setDescription(msg.getDescription());
update = true;
}
if (msg.getPassword() != null) {
user.setPassword(msg.getPassword());
update = true;
}
if (update) {
user = dbf.updateAndRefresh(user);
}
APIUpdateUserEvent evt = new APIUpdateUserEvent(msg.getId());
evt.setInventory(UserInventory.valueOf(user));
bus.publish(evt);
}
private void handle(APIRemoveUserFromGroupMsg msg) {
SimpleQuery<UserGroupUserRefVO> q = dbf.createQuery(UserGroupUserRefVO.class);
q.add(UserGroupUserRefVO_.groupUuid, Op.EQ, msg.getGroupUuid());
q.add(UserGroupUserRefVO_.userUuid, Op.EQ, msg.getUserUuid());
UserGroupUserRefVO ref = q.find();
if (ref != null) {
dbf.remove(ref);
}
bus.publish(new APIRemoveUserFromGroupEvent(msg.getId()));
}
private void handle(APIDetachPolicyFromUserGroupMsg msg) {
SimpleQuery<UserGroupPolicyRefVO> q = dbf.createQuery(UserGroupPolicyRefVO.class);
q.add(UserGroupPolicyRefVO_.groupUuid, Op.EQ, msg.getGroupUuid());
q.add(UserGroupPolicyRefVO_.policyUuid, Op.EQ, msg.getPolicyUuid());
UserGroupPolicyRefVO ref = q.find();
if (ref != null) {
dbf.remove(ref);
}
bus.publish(new APIDetachPolicyFromUserGroupEvent(msg.getId()));
}
private void handle(APIDetachPolicyFromUserMsg msg) {
SimpleQuery<UserPolicyRefVO> q = dbf.createQuery(UserPolicyRefVO.class);
q.add(UserPolicyRefVO_.policyUuid, Op.EQ, msg.getPolicyUuid());
q.add(UserPolicyRefVO_.userUuid, Op.EQ, msg.getUserUuid());
UserPolicyRefVO ref = q.find();
if (ref != null) {
dbf.remove(ref);
}
bus.publish(new APIDetachPolicyFromUserEvent(msg.getId()));
}
private void handle(APIDeletePolicyMsg msg) {
dbf.removeByPrimaryKey(msg.getUuid(), PolicyVO.class);
APIDeletePolicyEvent evt = new APIDeletePolicyEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIDeleteUserMsg msg) {
UserVO user = dbf.findByUuid(msg.getUuid(), UserVO.class);
if (user != null) {
UserInventory inv = UserInventory.valueOf(user);
UserDeletedData d = new UserDeletedData();
d.setInventory(inv);
d.setUserUuid(inv.getUuid());
evtf.fire(IdentityCanonicalEvents.USER_DELETED_PATH, d);
dbf.remove(user);
}
APIDeleteUserEvent evt = new APIDeleteUserEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIDeleteUserGroupMsg msg) {
dbf.removeByPrimaryKey(msg.getUuid(), UserGroupVO.class);
APIDeleteUserGroupEvent evt = new APIDeleteUserGroupEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIAddUserToGroupMsg msg) {
UserGroupUserRefVO ugvo = new UserGroupUserRefVO();
ugvo.setGroupUuid(msg.getGroupUuid());
ugvo.setUserUuid(msg.getUserUuid());
dbf.persist(ugvo);
APIAddUserToGroupEvent evt = new APIAddUserToGroupEvent(msg.getId());
bus.publish(evt);
}
private void handle(APIAttachPolicyToUserGroupMsg msg) {
UserGroupPolicyRefVO grvo = new UserGroupPolicyRefVO();
grvo.setGroupUuid(msg.getGroupUuid());
grvo.setPolicyUuid(msg.getPolicyUuid());
try {
dbf.persist(grvo);
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
APIAttachPolicyToUserGroupEvent evt = new APIAttachPolicyToUserGroupEvent(msg.getId());
bus.publish(evt);
}
private void handle(APICreateUserGroupMsg msg) {
UserGroupVO gvo = new UserGroupVO();
if (msg.getResourceUuid() != null) {
gvo.setUuid(msg.getResourceUuid());
} else {
gvo.setUuid(Platform.getUuid());
}
gvo.setAccountUuid(self.getUuid());
gvo.setDescription(msg.getDescription());
gvo.setName(msg.getName());
UserGroupVO finalGvo = gvo;
gvo = new SQLBatchWithReturn<UserGroupVO>() {
@Override
protected UserGroupVO scripts() {
persist(finalGvo);
reload(finalGvo);
return finalGvo;
}
}.execute();
UserGroupInventory inv = UserGroupInventory.valueOf(gvo);
APICreateUserGroupEvent evt = new APICreateUserGroupEvent(msg.getId());
evt.setInventory(inv);
bus.publish(evt);
}
private void handle(APIAttachPolicyToUserMsg msg) {
UserPolicyRefVO upvo = new UserPolicyRefVO();
upvo.setPolicyUuid(msg.getPolicyUuid());
upvo.setUserUuid(msg.getUserUuid());
try {
dbf.persist(upvo);
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
APIAttachPolicyToUserEvent evt = new APIAttachPolicyToUserEvent(msg.getId());
bus.publish(evt);
}
private void handle(APICreatePolicyMsg msg) {
PolicyVO pvo = new PolicyVO();
if (msg.getResourceUuid() != null) {
pvo.setUuid(msg.getResourceUuid());
} else {
pvo.setUuid(Platform.getUuid());
}
pvo.setAccountUuid(self.getUuid());
pvo.setName(msg.getName());
pvo.setData(JSONObjectUtil.toJsonString(msg.getStatements()));
pvo.setType(PolicyType.Customized);
PolicyVO finalPvo = pvo;
pvo = new SQLBatchWithReturn<PolicyVO>() {
@Override
protected PolicyVO scripts() {
persist(finalPvo);
reload(finalPvo);
return finalPvo;
}
}.execute();
PolicyInventory pinv = PolicyInventory.valueOf(pvo);
APICreatePolicyEvent evt = new APICreatePolicyEvent(msg.getId());
evt.setInventory(pinv);
bus.publish(evt);
}
private void handle(APICreateUserMsg msg) {
APICreateUserEvent evt = new APICreateUserEvent(msg.getId());
UserVO uvo = new SQLBatchWithReturn<UserVO>() {
@Override
protected UserVO scripts() {
UserVO uvo = new UserVO();
if (msg.getResourceUuid() != null) {
uvo.setUuid(msg.getResourceUuid());
} else {
uvo.setUuid(Platform.getUuid());
}
uvo.setAccountUuid(self.getUuid());
uvo.setName(msg.getName());
uvo.setPassword(msg.getPassword());
uvo.setDescription(msg.getDescription());
persist(uvo);
reload(uvo);
PolicyVO p = Q.New(PolicyVO.class).eq(PolicyVO_.name, "DEFAULT-READ")
.eq(PolicyVO_.accountUuid, self.getUuid()).find();
if (p != null) {
UserPolicyRefVO uref = new UserPolicyRefVO();
uref.setPolicyUuid(p.getUuid());
uref.setUserUuid(uvo.getUuid());
persist(uref);
}
p = Q.New(PolicyVO.class).eq(PolicyVO_.name, "USER-RESET-PASSWORD")
.eq(PolicyVO_.accountUuid, self.getUuid()).find();
if (p != null) {
UserPolicyRefVO uref = new UserPolicyRefVO();
uref.setPolicyUuid(p.getUuid());
uref.setUserUuid(uvo.getUuid());
persist(uref);
}
return uvo;
}
}.execute();
final UserInventory inv = UserInventory.valueOf(uvo);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AfterCreateUserExtensionPoint.class), new ForEachFunction<AfterCreateUserExtensionPoint>() {
@Override
public void run(AfterCreateUserExtensionPoint arg) {
arg.afterCreateUser(inv);
}
});
evt.setInventory(inv);
bus.publish(evt);
}
}
|
package dr.evomodel.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Logger;
import dr.app.beast.BeastVersion;
import dr.evomodel.coalescent.GMRFSkyrideLikelihood;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.LogFormatter;
import dr.inference.loggers.MCLogger;
import dr.inference.loggers.TabDelimitedFormatter;
import dr.xml.AbstractXMLObjectParser;
import dr.xml.AttributeRule;
import dr.xml.ElementRule;
import dr.xml.XMLObject;
import dr.xml.XMLObjectParser;
import dr.xml.XMLParseException;
import dr.xml.XMLSyntaxRule;
/**
* Projects and logs the random grid of the skyride onto a fixed grid.
*
* @author Erik Bloomquist
*/
public class GMRFSkyrideFixedGridLogger extends MCLogger{
public static final String SKYRIDE_FIXED_GRID = "logSkyrideFixedGrid";
public static final String NUMBER_OF_INTERVALS = "numberOfIntervals";
public static final String GRID_HEIGHT = "gridHeight";
public static final String LOG_SCALE = "logScale";
private GMRFSkyrideLikelihood gmrfLike;
private double[] fixedPopSize;
private double intervalNumber;
private double gridHeight;
private final boolean gridHeightSameAsTreeHeight;
private final boolean logScale;
public GMRFSkyrideFixedGridLogger(LogFormatter formatter, int logEvery,
GMRFSkyrideLikelihood gmrfLike, int intervalNumber, double gridHeight,boolean logScale) {
super(formatter, logEvery);
this.gmrfLike = gmrfLike;
this.intervalNumber = intervalNumber;
this.gridHeight = gridHeight;
if(gridHeight == -99){
gridHeightSameAsTreeHeight = true;
}else{
gridHeightSameAsTreeHeight = false;
}
this.logScale = logScale;
fixedPopSize = new double[intervalNumber];
}
private void calculateGrid(){
//The first random interval is the coalescent interval closest to the sampling time
//The last random interval corresponds to the root.
double[] randomInterval = gmrfLike.getCopyOfCoalescentIntervals();
double[] randomPopSize = gmrfLike.getPopSizeParameter().getParameterValues();
for(int i = 1; i < randomInterval.length; i++)
randomInterval[i] += randomInterval[i-1];
if(gridHeightSameAsTreeHeight){
gridHeight = randomInterval[randomInterval.length-1];
}
if(!logScale){
for(int i = 0; i < randomPopSize.length; i++)
randomPopSize[i] = Math.exp(randomPopSize[i]);
}
double intervalLength = gridHeight/intervalNumber;
double startTime = 0;
double endTime = 0;
int interval = 0;
for(int i = 0; i < fixedPopSize.length; i++){
fixedPopSize[i] = 0;
if(interval < randomInterval.length){
endTime += intervalLength;
double timeLeft = intervalLength;
while(interval < randomInterval.length &&
randomInterval[interval] <= endTime){
fixedPopSize[i] += (randomInterval[interval] - startTime - intervalLength + timeLeft)*
randomPopSize[interval];
timeLeft = (intervalLength - randomInterval[interval] + startTime);
interval++;
}
if(interval < randomInterval.length){
fixedPopSize[i] += timeLeft*randomPopSize[interval];
fixedPopSize[i] /= intervalLength;
}else{
fixedPopSize[i] /= (intervalLength - timeLeft);
}
startTime += intervalLength;
}else{
fixedPopSize[i] = -99;
}
}
}
private void getStringGrid(String[] values){
calculateGrid();
//First value in the string array is the state.
for(int i = 0; i < fixedPopSize.length; i++){
if(fixedPopSize[i] == -99){
values[i+1] = "NA";
}else{
values[i+1] = Double.toString(fixedPopSize[i]);
}
}
}
public void log(int state){
if (logEvery <= 0 || ((state % logEvery) == 0)) {
String[] values = new String[fixedPopSize.length + 1];
values[0] = Integer.toString(state);
getStringGrid(values);
logValues(values);
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){
public String getParserDescription() {
return "Creates a fixed grid";
}
public Class getReturnType() {
return GMRFSkyrideFixedGridLogger.class;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
AttributeRule.newIntegerRule(NUMBER_OF_INTERVALS),
AttributeRule.newDoubleRule(GRID_HEIGHT,true), //If no grid height specified, uses tree height.
AttributeRule.newBooleanRule(LOG_SCALE,true),
new ElementRule(GMRFSkyrideLikelihood.class),
};
public XMLSyntaxRule[] getSyntaxRules() {
return null;
}
public String getParserName() {
return SKYRIDE_FIXED_GRID;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Logger.getLogger("dr.evolmodel").info("Creating GMRF Skyride Fixed Grid Logger");
GMRFSkyrideLikelihood g = (GMRFSkyrideLikelihood)xo.getChild(GMRFSkyrideLikelihood.class);
String fileName = null;
int logEvery = 1;
int intervalNumber = xo.getIntegerAttribute(NUMBER_OF_INTERVALS);
Logger.getLogger("dr.evomodel").info("Number of Intervals = " + intervalNumber);
double gridHeight = -99;
if(xo.hasAttribute(GRID_HEIGHT)){
gridHeight = xo.getDoubleAttribute(GRID_HEIGHT);
Logger.getLogger("dr.evomodel").info("Grid Height = " + gridHeight);
}else{
Logger.getLogger("dr.evomodel").info("Grid Height = same as tree height");
}
if (xo.hasAttribute(FILE_NAME)) {
fileName = xo.getStringAttribute(FILE_NAME);
}
if (xo.hasAttribute(LOG_EVERY)) {
logEvery = xo.getIntegerAttribute(LOG_EVERY);
}
boolean logScale = true;
if (xo.hasAttribute(LOG_SCALE)){
logScale = xo.getBooleanAttribute(LOG_SCALE);
}
PrintWriter pw;
if (fileName != null) {
try {
File file = new File(fileName);
String name = file.getName();
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
pw = new PrintWriter(new FileOutputStream(new File(parent, name)));
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
}
} else {
pw = new PrintWriter(System.out);
}
LogFormatter lf = new TabDelimitedFormatter(pw);
MCLogger logger = new GMRFSkyrideFixedGridLogger(lf,logEvery,g,intervalNumber,gridHeight,logScale);
//After constructing the logger, setup the columns.
final BeastVersion version = new BeastVersion();
logger.setTitle("BEAST " + version.getVersionString() + ", " +
version.getBuildString() + "\n" +
"Generated " + (new Date()).toString() +
"\nFirst value corresponds to coalescent interval closet to sampling time\n" +
"Last value corresponds to coalescent interval closet to the root\n" +
"Grid Height = " +
(gridHeight == -99 ? "Based on tree height" : Double.toString(gridHeight)) +
"\nNumber of intervals = " + intervalNumber);
for(int i = 0 ; i < intervalNumber; i++){
logger.addColumn(new LogColumn.Default("V" + (i+1),null));
}
return (GMRFSkyrideFixedGridLogger)logger;
}
};
}
|
package dr.evomodel.treelikelihood;
import dr.evolution.alignment.PatternList;
import dr.evolution.tree.Tree;
import dr.evolution.util.TaxonList;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import java.util.HashMap;
import java.util.Map;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id$
*/
public abstract class TipPartialsModel extends AbstractModel {
/**
* @param name Model Name
*/
public TipPartialsModel(String name, TaxonList includeTaxa, TaxonList excludeTaxa) {
super(name);
this.includeTaxa = includeTaxa;
this.excludeTaxa = excludeTaxa;
}
public final void setTree(Tree tree) {
this.tree = tree;
int extNodeCount = tree.getExternalNodeCount();
excluded = new boolean[extNodeCount];
if (includeTaxa != null) {
for (int i = 0; i < extNodeCount; i++) {
if (includeTaxa.getTaxonIndex(tree.getNodeTaxon(tree.getExternalNode(i))) == -1) {
excluded[i] = true;
}
}
}
if (excludeTaxa != null) {
for (int i = 0; i < extNodeCount; i++) {
if (excludeTaxa.getTaxonIndex(tree.getNodeTaxon(tree.getExternalNode(i))) != -1) {
excluded[i] = true;
}
}
}
states = new int[extNodeCount][];
taxaChanged();
}
protected abstract void taxaChanged();
public final void setStates(PatternList patternList, int sequenceIndex, int nodeIndex, String taxonId) {
if (patternCount == 0) {
if (patternList != null) {
throw new RuntimeException("The TipPartialsModel with id, " + getId() + ", has already been associated with a patternList.");
}
this.patternList = patternList;
patternCount = patternList.getPatternCount();
stateCount = patternList.getDataType().getStateCount();
}
if (this.states[nodeIndex] == null) {
this.states[nodeIndex] = new int[patternCount];
}
for (int i = 0; i < patternCount; i++) {
this.states[nodeIndex][i] = patternList.getPatternState(sequenceIndex, i);
}
taxonMap.put(nodeIndex, taxonId);
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
fireModelChanged();
}
/**
* This method is called whenever a parameter is changed.
* <p/>
* It is strongly recommended that the model component sets a "dirty" flag and does no
* further calculations. Recalculation is typically done when the model component is asked for
* some information that requires them. This mechanism is 'lazy' so that this method
* can be safely called multiple times with minimal computational cost.
*/
protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
fireModelChanged();
}
/**
* Additional state information, outside of the sub-model is stored by this call.
*/
protected void storeState() {
}
/**
* After this call the model is guaranteed to have returned its extra state information to
* the values coinciding with the last storeState call.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
protected void restoreState() {
}
/**
* This call specifies that the current state is accept. Most models will not need to do anything.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
protected void acceptState() {
}
public abstract void getTipPartials(int nodeIndex, double[] tipPartials);
protected int[][] states;
protected boolean[] excluded;
protected int patternCount = 0;
protected int stateCount;
protected TaxonList includeTaxa;
protected TaxonList excludeTaxa;
protected Tree tree;
private PatternList patternList = null;
protected Map<Integer, String> taxonMap = new HashMap<Integer, String>();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.isi.pegasus.planner.refiner;
import edu.isi.pegasus.planner.classes.ADag;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.partitioner.graph.Adapter;
import edu.isi.pegasus.planner.partitioner.graph.Graph;
import edu.isi.pegasus.planner.partitioner.graph.GraphNode;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
/**
* An algorithm to reduce remove edges in the workflow, based on a DFS of a graph
* and doing least common ancestor tranversals to detect duplicate edges.
*
* @author Rajiv Mayani
* @author Karan Vahi
*/
public class ReduceEdges {
public ReduceEdges(){
}
/**
* Prunes redundant edges from the workflow.
* For example if
* A->B->C and A->D exists, we can delete edge A->D
*
* @param dag the workflow
*
* @return
*/
public ADag reduce( ADag dag ){
ADag result;
//we first need to convert internally into graph format
Graph resultGraph = this.reduce( Adapter.convert(dag ) );
//convert back to ADag and return
result = dag;
//we need to reset the jobs and the relations in it
result.clearJobs();
//traverse through the graph and jobs and edges
for( Iterator it = resultGraph.nodeIterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
//get the job associated with node
result.add( ( Job )node.getContent() );
//all the children of the node are the edges of the DAG
for( Iterator childrenIt = node.getChildren().iterator(); childrenIt.hasNext(); ){
GraphNode child = ( GraphNode ) childrenIt.next();
result.addNewRelation( node.getID(), child.getID() );
}
}
return result;
}
/**
* Prunes redundant edges from the workflow.
*
* @param workflow
*
* @return the workflow with non essential edges removed
*/
public Graph reduce( Graph workflow ) {
//start a DFS for the graph at root.
//get all the roots of the workflow
for( GraphNode root: workflow.getRoots() ){
reset( workflow );
//mCurrentDepth = 0;
root.setDepth( 0 );
root.setColor( GraphNode.GRAY_COLOR );
//System.out.println( "Traversing node " + root.getID() );
//start an iterative DFS on the root
Stack<GraphNode> stack = new Stack();
stack.push(root);
while( !stack.isEmpty() ){
GraphNode top = stack.peek();
int newDepth = top.getDepth() + 1;
List<GraphNode> parentsForDeletion = new LinkedList();
//deletion map maps children to list of their ancestors to delete
//this is to prevent concurrent modification error in the loop below
Map<GraphNode,Collection<GraphNode>> deletionMap = new HashMap();
for( GraphNode child : top.getChildren() ){
//we always update the depth to max of current and new depth
child.setDepth( Math.max( child.getDepth(), newDepth) );
if( child.isColor( GraphNode.GRAY_COLOR )){
//this is where the collision is happening
//find LCA of the top and child
//Collection<GraphNode> ancestors = findLCA( top, child );
//we now do LCA between child and all it's parents
for( GraphNode parent: child.getParents() ){
Collection<GraphNode> ancestors = findLCA( parent, child );
if( !ancestors.isEmpty() ){
if( deletionMap.containsKey( child ) ){
Collection<GraphNode> existing = deletionMap.get( child );
existing.addAll( ancestors );
}
else{
deletionMap.put( child, ancestors );
}
}
}
//we set the child color to Black to ensure that if
//we visit child again, we don't attempt LCA procedure again
//one call to LCA is sufficient to remove all the redundant
//edges making up a cycle
child.setColor( GraphNode.BLACK_COLOR );
continue;
}
if( child.isColor( GraphNode.WHITE_COLOR )){
child.setColor( GraphNode.GRAY_COLOR );
//System.out.println( "Traversing node " + child.getID() + " with depth " + child.getDepth());
stack.push( child );
}
}
//delete from the deletion map the edges
for( Map.Entry<GraphNode,Collection<GraphNode>> entry : deletionMap.entrySet()){
GraphNode child = entry.getKey();
for( GraphNode ancestor: entry.getValue() ){
System.out.println( "\tDeleting Edge " + ancestor.getID() + " -> " + child.getID() );
ancestor.removeChild( child);
//remove from the child hte parent
child.removeParent(ancestor);
}
}
//set the color of the node to be black
//top.setColor( GraphNode.BLACK_COLOR );
stack.pop();
}
}
return workflow;
}
/**
* We find LCA of from and to.
*
* @param from
* @param to
*
* @return the ancestors for which the edge from ancestor to the "to" node that have to be deleted.
*/
private Collection<GraphNode> findLCA(GraphNode from, GraphNode to) {
Set<GraphNode> ancestors = new HashSet();
Queue<GraphNode> parents = new LinkedList();
parents.addAll( to.getParents() );
//the from node should never be considered initially
parents.remove( from );
parents.addAll( from.getParents() );
//find min depth of all the parents of the to node
int minDepth = Integer.MAX_VALUE;
for( GraphNode parent: to.getParents() ){
minDepth = Math.min( minDepth, parent.getDepth() );
}
if( minDepth == Integer.MAX_VALUE ){
throw new RuntimeException( "Inconsistent state for LCA " + from.getID() + " -> " + to.getID() );
}
System.out.println( "Find LCA for " + from.getID() + " -> " + to.getID() );
Set<GraphNode> deletedAncestors = new HashSet();
while( !parents.isEmpty() ){
GraphNode parent = parents.remove();
if( parent.getDepth() < 0 || parent.getDepth() < minDepth ){
//if the depth is -1 we don't do backtracking
//as that is associated with a different root
//also, we only want the lca search to go as far back as
//the min depth of the parents of the to node.
continue;
}
//System.out.println( parent.getID() );
if( !ancestors.add( parent )){
//means the parent was already present
//check if from this parent this is a direct edge to the "to" node
if( parent.getChildren().contains(to) ){
//we need to delete edge parent to the to
//System.out.println( "Scheduling deletion of Edge " + parent.getID() + " -> " + to.getID() );
deletedAncestors.add( parent );
//parent.removeChild(to);
//remove from the child hte parent
//to.removeParent(parent);
}
}
parents.addAll( parent.getParents());
}
return deletedAncestors;
}
/**
* Resets internal depth and color counters associated with the nodes in the
* workflow, before doing any graph traversals.
*
* @param workflow the workflow
*/
private void reset(Graph workflow) {
int depth = -1;
//sanity intialization of all nodes depth
for( Iterator it = workflow.nodeIterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
node.setDepth( depth );
node.setColor( GraphNode.WHITE_COLOR );
}
}
}
|
package io.perfmark.impl;
import io.perfmark.Impl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
final class SecretPerfMarkImpl {
public static final class PerfMarkImpl extends Impl {
static final String NO_TAG_NAME = Impl.NO_TAG_NAME;
static final Long NO_TAG_ID = Impl.NO_TAG_ID;
static final Long NO_LINK_ID = Impl.NO_LINK_ID;
private static final long INCREMENT = 1L << Generator.GEN_OFFSET;
private static final String START_ENABLED_PROPERTY = "io.perfmark.PerfMark.startEnabled";
private static final AtomicLong linkIdAlloc = new AtomicLong(1);
private static final Generator generator;
private static final Logger logger;
private static long actualGeneration;
static {
List<Generator> generators = new ArrayList<Generator>();
List<Throwable> fines = new ArrayList<Throwable>();
List<Throwable> warnings = new ArrayList<Throwable>();
Class<?> clz = null;
try {
clz = Class.forName("io.perfmark.java7.SecretMethodHandleGenerator$MethodHandleGenerator");
} catch (ClassNotFoundException e) {
fines.add(e);
} catch (Throwable t) {
warnings.add(t);
}
if (clz != null) {
try {
generators.add(clz.asSubclass(Generator.class).getConstructor().newInstance());
} catch (Throwable t) {
warnings.add(t);
}
clz = null;
}
try {
clz = Class.forName("io.perfmark.java9.SecretVarHandleGenerator$VarHandleGenerator");
} catch (ClassNotFoundException e) {
fines.add(e);
} catch (Throwable t) {
warnings.add(t);
}
if (clz != null) {
try {
generators.add(clz.asSubclass(Generator.class).getConstructor().newInstance());
} catch (Throwable t) {
warnings.add(t);
}
clz = null;
}
try {
clz = Class.forName("io.perfmark.java6.SecretVolatileGenerator$VolatileGenerator");
} catch (ClassNotFoundException e) {
fines.add(e);
} catch (Throwable t) {
warnings.add(t);
}
if (clz != null) {
try {
generators.add(clz.asSubclass(Generator.class).getConstructor().newInstance());
} catch (Throwable t) {
warnings.add(t);
}
clz = null;
}
if (!generators.isEmpty()) {
generator = generators.get(0);
} else {
generator = new NoopGenerator();
}
boolean startEnabled = false;
try {
startEnabled = Boolean.parseBoolean(System.getProperty(START_ENABLED_PROPERTY, "false"));
} catch (Throwable t) {
warnings.add(t);
}
boolean success = setEnabledQuiet(startEnabled);
logger = Logger.getLogger(PerfMarkImpl.class.getName());
logger.log(Level.FINE, "Using {0}", new Object[] {generator.getClass().getName()});
for (Throwable error : warnings) {
logger.log(Level.WARNING, "Error loading MarkHolderProvider", error);
}
for (Throwable error : fines) {
logger.log(Level.FINE, "Error loading MarkHolderProvider", error);
}
logEnabledChange(startEnabled, success);
}
public PerfMarkImpl() {
super();
}
@Override
protected synchronized void setEnabled(boolean value) {
logEnabledChange(value, setEnabledQuiet(value));
}
private static synchronized void logEnabledChange(boolean value, boolean success) {
if (success && logger.isLoggable(Level.FINE)) {
logger.fine((value ? "Enabling" : "Disabling") + " PerfMark recorder");
}
}
/** Returns true if successfully changed. */
private static synchronized boolean setEnabledQuiet(boolean value) {
if (isEnabled(actualGeneration) == value) {
return false;
}
if (actualGeneration == Generator.FAILURE) {
return false;
}
generator.setGeneration(actualGeneration += INCREMENT);
return true;
}
@Override
protected void startTask(String taskName, @Nullable String tagName, long tagId) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.startAnyways(gen, taskName, tagName, tagId);
}
@Override
protected void startTask(String taskName) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.startAnyways(gen, taskName);
}
public static void startTask(
String taskName, @Nullable String tagName, long tagId, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.startAnyways(gen, taskName, marker, tagName, tagId);
}
public static void startTask(String taskName, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.startAnyways(gen, taskName, marker);
}
@Override
protected void stopTask(String taskName, @Nullable String tagName, long tagId) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.stopAnyways(gen, taskName, tagName, tagId);
}
@Override
protected void stopTask(String taskName) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.stopAnyways(gen, taskName);
}
public static void stopTask(
String taskName, @Nullable String tagName, long tagId, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.stopAnyways(gen, taskName, marker, tagName, tagId);
}
public static void stopTask(String taskName, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.stopAnyways(gen, taskName, marker);
}
@Override
protected void event(String eventName, @Nullable String tagName, long tagId) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.eventAnyways(gen, eventName, tagName, tagId);
}
@Override
protected void event(String eventName) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.eventAnyways(gen, eventName);
}
public static void event(
String eventName, @Nullable String tagName, long tagId, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.eventAnyways(gen, eventName, marker, tagName, tagId);
}
public static void event(String eventName, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.eventAnyways(gen, eventName, marker);
}
@Override
protected boolean shouldCreateTag() {
return isEnabled(getGen());
}
@Override
protected long linkAndGetId() {
final long gen = getGen();
if (!isEnabled(gen)) {
return NO_LINK_ID;
}
long linkId = linkIdAlloc.getAndIncrement();
Storage.linkAnyways(gen, linkId);
return linkId;
}
public static long linkAndGetId(Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return NO_LINK_ID;
}
long linkId = linkIdAlloc.getAndIncrement();
Storage.linkAnyways(gen, linkId, marker);
return linkId;
}
@Override
protected void link(long linkId) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.linkAnyways(gen, -linkId);
}
public static void link(long linkId, Marker marker) {
final long gen = getGen();
if (!isEnabled(gen)) {
return;
}
Storage.linkAnyways(gen, -linkId, marker);
}
private static long getGen() {
return generator.getGeneration();
}
private static boolean isEnabled(long gen) {
return ((gen >>> Generator.GEN_OFFSET) & 0x1L) != 0L;
}
}
}
|
/**
* Expression.java
*
* Wrapper for JEval
*
* @author Agent Team
*/
package edu.wheaton.simulator.expression;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
import net.sourceforge.jeval.EvaluationException;
import net.sourceforge.jeval.Evaluator;
import net.sourceforge.jeval.VariableResolver;
import net.sourceforge.jeval.function.FunctionException;
import edu.wheaton.simulator.behavior.CloneAgentAtPositionBehavior;
import edu.wheaton.simulator.behavior.CloneBehavior;
import edu.wheaton.simulator.behavior.ClonePrototype;
import edu.wheaton.simulator.behavior.DieBehavior;
import edu.wheaton.simulator.behavior.KillBehavior;
import edu.wheaton.simulator.behavior.MoveBehavior;
import edu.wheaton.simulator.behavior.MoveDownBehavior;
import edu.wheaton.simulator.behavior.MoveLeftBehavior;
import edu.wheaton.simulator.behavior.MoveRightBehavior;
import edu.wheaton.simulator.behavior.MoveUpBehavior;
import edu.wheaton.simulator.behavior.SetFieldBehavior;
import edu.wheaton.simulator.behavior.SetFieldOfAgentBehavior;
import edu.wheaton.simulator.entity.Entity;
public class Expression {
/**
* All variables that JEval evaluates are first passed to an associated
* instance of VariableResolver. If the 'VR' returns a null then the JEval
* 'Evaluator' will look for the variable name in its internal map. This
* 'VR' implementation is solely for the purpose of enabling a shorter
* Expression syntax: "#{this.x}" rather than something like
* "getField('this','x')" which would require implementing a "getField"
* ExpressionFunction.
*
* @author bgarcia
*
*/
protected class EntityFieldResolver implements VariableResolver {
/**
* Keeps track of all the entities in the grid
*/
private Map<String, Entity> entityMap;
/**
* Default constructor
*/
protected EntityFieldResolver() {
entityMap = new HashMap<String, Entity>();
}
/**
* Constructor for copying
*/
protected EntityFieldResolver(EntityFieldResolver resolver) {
entityMap = new HashMap<String, Entity>();
entityMap.putAll(resolver.entityMap);
}
/**
* Given the name of an entity and a field (for example this.x), this
* method provides the actual value of the field.
*
* @param variableName
* @return
*/
@Override
public String resolveVariable(String variableName)
throws FunctionException {
// splits with delimiter '.'
String[] args = variableName.split("\\x2e");
if (args.length != 2) {
return null;
}
String targetName = args[0];
String fieldName = args[1];
Entity target = getEntity(targetName);
if (target == null) {
throw new FunctionException("Target entity not found: "
+ targetName);
}
try {
String toReturn = target.getFieldValue(fieldName);
return toReturn;
} catch (NoSuchElementException e) {
throw new FunctionException("Target field not found: "
+ fieldName);
}
}
protected void setEntity(String name, Entity entity) {
entityMap.put(name, entity);
}
protected Entity getEntity(String name) {
return entityMap.get(name);
}
}
// boolean constants
public static final String TRUE = "1.0";
public static final String FALSE = "0.0";
private Evaluator evaluator;
private EntityFieldResolver resolver;
private Object expr;
private String exprStr;
private static HashMap<String, AbstractExpressionFunction> behaviorFunctions;
private static HashMap<String, AbstractExpressionFunction> conditionFunctions;
/**
* Default constructor
*
* The expression string is retrieved by calling expr.toString()
*/
public Expression(Object exprStr) {
setString(exprStr);
evaluator = new Evaluator();
resolver = new EntityFieldResolver();
evaluator.setVariableResolver(resolver);
// make all project-defined ExpressionFunction implementations
// recognizable by default
this.importFunction(new CloneBehavior());
this.importFunction(new DieBehavior());
this.importFunction(new KillBehavior());
this.importFunction(new MoveBehavior());
this.importFunction(new SetFieldBehavior());
this.importFunction(new IsSlotOpen());
this.importFunction(new GetFieldOfAgentAt());
this.importFunction(new IsValidCoord());
this.importFunction(new CloneAgentAtPositionBehavior());
this.importFunction(new SetFieldOfAgentBehavior());
this.importFunction(new ClonePrototype());
this.importFunction(new GetGlobalField());
this.importFunction(new MoveRightBehavior());
this.importFunction(new MoveLeftBehavior());
this.importFunction(new MoveUpBehavior());
this.importFunction(new MoveDownBehavior());
// make a hashmap of names and actual objects.
initializeFunctions();
}
/**
* Helper method that adds all the behavior and conditional functions to
* the HashMaps
*/
private static void initializeFunctions() {
behaviorFunctions = new HashMap<String, AbstractExpressionFunction>();
conditionFunctions = new HashMap<String, AbstractExpressionFunction>();
behaviorFunctions.put("clone", new CloneBehavior());
behaviorFunctions.put("cloneAgentAtPosition",
new CloneAgentAtPositionBehavior());
behaviorFunctions.put("die", new DieBehavior());
behaviorFunctions.put("kill", new KillBehavior());
behaviorFunctions.put("move", new MoveBehavior());
behaviorFunctions.put("setField", new SetFieldBehavior());
behaviorFunctions
.put("setFieldOfAgent", new SetFieldOfAgentBehavior());
behaviorFunctions.put("clonePrototype", new ClonePrototype());
behaviorFunctions.put("moveRight", new MoveRightBehavior());
behaviorFunctions.put("moveLeft", new MoveLeftBehavior());
behaviorFunctions.put("moveDown", new MoveDownBehavior());
behaviorFunctions.put("moveUp", new MoveUpBehavior());
behaviorFunctions.put("getFieldOfAgent", new GetFieldOfAgentAt());
behaviorFunctions.put("isSlotOpen", new IsSlotOpen());
behaviorFunctions.put("isValidCoord", new IsValidCoord());
behaviorFunctions.put("getGlobalField", new GetGlobalField());
conditionFunctions.put("getFieldOfAgent", new GetFieldOfAgentAt());
conditionFunctions.put("isSlotOpen", new IsSlotOpen());
conditionFunctions.put("isValidCoord", new IsValidCoord());
conditionFunctions.put("getGlobalField", new GetGlobalField());
}
/**
* Copy constructor
*/
private Expression(Expression expr) {
evaluator = new Evaluator();
evaluator.setFunctions(expr.evaluator.getFunctions());
evaluator.setVariables(expr.evaluator.getVariables());
resolver = new EntityFieldResolver(expr.resolver);
evaluator.setVariableResolver(resolver);
setString(expr.expr);
}
protected Expression(Evaluator eval, EntityFieldResolver res) {
this.evaluator = eval;
this.resolver = res;
}
public static Map<String, AbstractExpressionFunction> getBehaviorFunction() {
if (behaviorFunctions == null)
initializeFunctions();
return behaviorFunctions;
}
public static Map<String, AbstractExpressionFunction> getConditionFunction() {
if (conditionFunctions == null)
initializeFunctions();
return conditionFunctions;
}
/**
* Returns a properly formatted variable reference.
*
* fGet("x") == "#{x}"
*
* fGet("this.x") == "#{this.x}"
*
* @param entityName
* @param fieldName
* @return
*/
private static String fGet(String variableName) {
return "#{" + variableName + "}";
}
/**
* Returns a properly formatted string to be passed to an Expression
* method.
*
* "setField(" + fParams("this,x,8") + ")" == "setField('this','x',8)
*
* @param params
* @return
*/
public static String fParams(String params) {
params = params.replaceAll(" ", "");
String[] paramList = params.split(",");
for (int i = 0; i < paramList.length; ++i) {
paramList[i] = fParam(paramList[i]);
}
String toReturn = "";
for (int i = 0; i < paramList.length; ++i)
toReturn += paramList[i] + ",";
if (toReturn.isEmpty() == false)
toReturn = toReturn.substring(0, toReturn.length() - 1);
return toReturn;
}
/**
* Returns a properly formatted string value
*
* correctStrVal("I am a banana!") == "'I am a banana!'"
*
* @param value
* @return
*/
public static String correctStrVal(String value) {
if (isStrVal(value))
return value;
return "'" + value + "'";
}
/**
*
* When a reference is passed to a function (ex: "setField('this','x',8)")
* This method can be used within the example method
* SetFieldBehavior.execute(...) to eliminate the single quotes surrounding
* the parameter, thus preventing someone from accidentally requesting a
* field with the name "'x'" when they really meant "x".
*
* @param entity
* @param str
* @return
*/
public static String correctNonStrVal(String str) {
if (isStrVal(str))
return str.substring(1, str.length() - 1);
return str;
}
private static boolean isStrVal(String str) {
return str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'';
}
/**
* Returns a properly formatted string to be passed to an Expression
* method.
*
* "setField(" + fParam("this") + "," + fParam("x") + "," + fParam("8") +
* ")" == "setField('this','x',8)
*
* @param name
* @return
*/
private static String fParam(String param) {
if (param.equalsIgnoreCase("true"))
return TRUE;
else if (param.equalsIgnoreCase("false"))
return FALSE;
else {
try {
return Double.valueOf(param).toString();
}
catch (Exception e) {
return correctStrVal(param);
}
}
}
/**
* calls the copy constructor
*/
@Override
public Expression clone() {
return new Expression(this);
}
/**
* sets the string that is evaluated by JEval/JEval-wrapper
*/
public void setString(Object exprStr) {
this.expr = exprStr;
this.exprStr = formatExpr(expr);
}
/**
* Define a variable
*
* @Param name Do not format this String as you must do when creating an
* expression String. Simply pass the desired variable name.
*/
public void importVariable(String name, String value) {
evaluator.putVariable(name, value);
}
/**
* Make an entity recognizable by this expression and all functions called
* within
*
* @Param aliasName The name used to refer to the Entity in the expression
* String ("this", "other", etc.)
*/
public void importEntity(String aliasName, Entity entity) {
resolver.setEntity(aliasName, entity);
}
/**
* Make an ExpressionFunction recognizable by this expression and all
* functions called within
*/
public void importFunction(AbstractExpressionFunction function) {
evaluator.putFunction(function.toJEvalFunction());
}
/**
* get an imported Entity
*/
public Entity getEntity(String aliasName) {
return resolver.getEntity(aliasName);
}
/**
* get the value of an imported variable
*/
public String getVariableValue(String variableName)
throws EvaluationException {
return evaluator.getVariableValue(variableName);
}
/**
* clear all variables added with 'importVariable'
*
*/
public void clearVariables() {
evaluator.clearVariables();
}
/**
* clear all entities added with 'importEntity'
*/
public void clearEntities() {
resolver.entityMap.clear();
}
/**
* clear all functions added with 'importFunction
*/
public void clearFunctions() {
evaluator.clearFunctions();
}
public Boolean evaluateBool() throws EvaluationException {
try {
return evaluator.getBooleanResult(exprStr);
} catch (EvaluationException e) {
System.err.println(e.getMessage());
throw e;
}
}
public Double evaluateDouble() throws EvaluationException {
try {
return evaluator.getNumberResult(exprStr);
} catch (EvaluationException e) {
System.err.println(e.getMessage());
throw e;
}
}
public String evaluateString() throws EvaluationException {
try {
return evaluator.evaluate(exprStr);
} catch (EvaluationException e) {
System.err.println(e.getMessage());
throw e;
}
}
@Override
public String toString() {
return expr.toString();
}
public static Boolean evaluateBool(Object exprStr)
throws EvaluationException {
Expression expr = new Expression(exprStr);
return expr.evaluateBool();
}
public static Double evaluateDouble(Object exprStr)
throws EvaluationException {
Expression expr = new Expression(exprStr);
return expr.evaluateDouble();
}
public static String evaluateString(Object exprStr)
throws EvaluationException {
Expression expr = new Expression(exprStr);
return expr.evaluateString();
}
/**
* Parses/formats the parameter according to expression syntax
*
* This method is called before evaluating the expression.
*/
private static String formatExpr(Object expr) {
String str = expr.toString();
// format booleans
str = formatBools(str);
String regexVariableRef = "\\b[_a-zA-Z][_a-zA-Z0-9]*(\\.[_a-zA-Z][_a-zA-Z0-9]*)?\\b(?![('])(?=([^']*'[^']*')*[^']*$)";
// string with all matches replaced with '@'
String temp = str.replaceAll(regexVariableRef, "@");
// list of all non-matching segments
String[] nonMatchingSegs = temp.split("@");
// construct string with all non-matches replaced with '@'
String temp2 = str;
for (String segment : nonMatchingSegs)
temp2 = Pattern.compile(segment, Pattern.LITERAL).matcher(temp2)
.replaceFirst("@");
// temp2 = temp2.replaceAll(segment, "@");
// list of all matches
String[] matches = temp2.split("@");
String toReturn = temp;
for (String match : matches) {
if (match.length() > 0) {
toReturn = toReturn.replaceFirst("@", fGet(match));
}
}
return toReturn;
}
/**
* Uses regular expressions to replace all boolean values (no matter their
* formatting) with actual, recognizable booleans.
*
* @param str
* @return
*/
private static String formatBools(String str) {
str = str.replaceAll("\\b[Tt][Rr][Uu][Ee]\\b", TRUE);
str = str.replaceAll("\\b[Ff][Aa][Ll][Ss][Ee]\\b", FALSE);
return str;
}
}
|
package com.cordovaplugincamerapreview;
import android.Manifest;
import android.content.pm.PackageManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.List;
import java.util.Arrays;
public class CameraPreview extends CordovaPlugin implements CameraActivity.CameraPreviewListener {
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String setZoomAction = "setZoom";
private final String setFlashModeAction = "setFlashMode";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String previewSizeAction = "setPreviewSize";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private final String getSupportedPreviewSizeAction = "getSupportedPreviewSize";
private final String getSupportedPictureSizeAction = "getSupportedPictureSize";
private final String [] permissions = {
Manifest.permission.CAMERA
};
private final int permissionsReqId = 0;
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private CallbackContext execCallback;
private JSONArray execArgs;
private int containerViewId = 1;
public CameraPreview(){
super();
Log.d(TAG, "Constructing");
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (setOnPictureTakenHandlerAction.equals(action)){
return setOnPictureTakenHandler(args, callbackContext);
} else if (startCameraAction.equals(action)) {
if (cordova.hasPermission(permissions[0])) {
return startCamera(args, callbackContext);
} else {
execCallback = callbackContext;
execArgs = args;
cordova.requestPermissions(this, 0, permissions);
}
} else if (takePictureAction.equals(action)) {
return takePicture(args, callbackContext);
} else if (setColorEffectAction.equals(action)) {
return setColorEffect(args, callbackContext);
} else if (setZoomAction.equals(action)) {
return setZoom(args, callbackContext);
} else if (previewSizeAction.equals(action)) {
return setPreviewSize(args, callbackContext);
} else if (setFlashModeAction.equals(action)) {
return setFlashMode(args, callbackContext);
} else if (stopCameraAction.equals(action)){
return stopCamera(args, callbackContext);
} else if (hideCameraAction.equals(action)) {
return hideCamera(args, callbackContext);
} else if (showCameraAction.equals(action)) {
return showCamera(args, callbackContext);
} else if (switchCameraAction.equals(action)) {
return switchCamera(args, callbackContext);
} else if (getSupportedPreviewSizeAction.equals(action)) {
return getSupportedResolutions("preview", callbackContext);
} else if (getSupportedPictureSizeAction.equals(action)) {
return getSupportedResolutions("picture", callbackContext);
}
return false;
}
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
for(int r:grantResults){
if(r == PackageManager.PERMISSION_DENIED){
execCallback.sendPluginResult(new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION));
return;
}
}
if (requestCode == permissionsReqId) {
startCamera(execArgs, execCallback);
}
}
private boolean getSupportedResolutions(final String type, CallbackContext callbackContext) {
List<Camera.Size> supportedSizes;
Camera camera = fragment.getCamera();
if (camera != null) {
supportedSizes = (type.equals("preview")) ? camera.getParameters().getSupportedPreviewSizes() : camera.getParameters().getSupportedPictureSizes();
if (supportedSizes != null) {
JSONArray sizes = new JSONArray();
for (int i=0; i<supportedSizes.size(); i++) {
Camera.Size size = supportedSizes.get(i);
int h = size.height;
int w = size.width;
JSONObject jsonSize = new JSONObject();
try {
jsonSize.put("height", new Integer(h));
jsonSize.put("width", new Integer(w));
}
catch(Exception e){
e.printStackTrace();
}
sizes.put(jsonSize);
}
callbackContext.success(sizes);
return true;
}
callbackContext.error("Camera Parameters access error");
return false;
}
callbackContext.error("Camera needs to be started first");
return false;
}
private boolean startCamera(final JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "start camera action");
if (fragment != null) {
callbackContext.error("Camera already started");
return false;
}
fragment = new CameraActivity();
fragment.setEventListener(this);
final CallbackContext cb = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
// offset
int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(0), metrics);
int y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(1), metrics);
// size
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(2), metrics);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(3), metrics);
String defaultCamera = args.getString(4);
Boolean tapToTakePicture = args.getBoolean(5);
Boolean dragEnabled = args.getBoolean(6);
Boolean toBack = args.getBoolean(7);
fragment.defaultCamera = defaultCamera;
fragment.tapToTakePicture = tapToTakePicture;
fragment.dragEnabled = dragEnabled;
fragment.setRect(x, y, width, height);
//create or update the layout params for the container view
FrameLayout containerView = (FrameLayout)cordova.getActivity().findViewById(containerViewId);
if(containerView == null){
containerView = new FrameLayout(cordova.getActivity().getApplicationContext());
containerView.setId(containerViewId);
FrameLayout.LayoutParams containerLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
cordova.getActivity().addContentView(containerView, containerLayoutParams);
}
//display camera bellow the webview
if(toBack){
webView.getView().setBackgroundColor(0x00000000);
((ViewGroup)webView.getView()).bringToFront();
}else{
//set camera back to front
containerView.setAlpha(Float.parseFloat(args.getString(8)));
containerView.bringToFront();
}
//add the fragment to the container
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(containerView.getId(), fragment);
fragmentTransaction.commit();
cb.success("Camera started");
} catch (Exception e) {
e.printStackTrace();
cb.error("Camera start error");
}
}
});
return true;
}
private String invertCamera(String originalCamera){
return originalCamera == "front" ? "back" : "front";
}
private boolean takePicture(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
try {
DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
double width = (double) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(0), metrics);
double height = (double) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(1), metrics);
int quality = args.getInt(2);
fragment.takePicture(width, height, quality);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("takePicture failed");
return false;
}
}
public void onPictureTaken(String originalPicture) {
JSONArray data = new JSONArray();
data.put(originalPicture);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
pluginResult.setKeepCallback(true);
Log.d(TAG, "returning picture");
takePictureCallbackContext.sendPluginResult(pluginResult);
}
private boolean setColorEffect(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null){
callbackContext.error("No camera");
return true;
}
Camera.Parameters params = camera.getParameters();
try {
String effect = args.getString(0);
if (effect.equals("aqua")) {
params.setColorEffect(Camera.Parameters.EFFECT_AQUA);
} else if (effect.equals("blackboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_BLACKBOARD);
} else if (effect.equals("mono")) {
params.setColorEffect(Camera.Parameters.EFFECT_MONO);
} else if (effect.equals("negative")) {
params.setColorEffect(Camera.Parameters.EFFECT_NEGATIVE);
} else if (effect.equals("none")) {
params.setColorEffect(Camera.Parameters.EFFECT_NONE);
} else if (effect.equals("posterize")) {
params.setColorEffect(Camera.Parameters.EFFECT_POSTERIZE);
} else if (effect.equals("sepia")) {
params.setColorEffect(Camera.Parameters.EFFECT_SEPIA);
} else if (effect.equals("solarize")) {
params.setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
} else if (effect.equals("whiteboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_WHITEBOARD);
}
fragment.setCameraParameters(params);
callbackContext.success(effect);
return true;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error("Could not set effect");
return false;
}
}
private boolean setZoom(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int zoom = (int) args.getInt(0);
if (camera.getParameters().isZoomSupported()) {
params.setZoom(zoom);
fragment.setCameraParameters(params);
callbackContext.success(zoom);
return true;
}else{
callbackContext.error("Zoom not supported");
return false;
}
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set zoom");
return false;
}
}
private boolean setPreviewSize(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int width = (int) args.getInt(0);
int height = (int) args.getInt(1);
params.setPreviewSize(width, height);
fragment.setCameraParameters(params);
camera.startPreview();
callbackContext.success();
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set preview size");
return false;
}
}
private boolean setFlashMode(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int mode = (int) args.getInt(0);
switch(mode) {
case 0:
params.setFlashMode(params.FLASH_MODE_OFF);
break;
case 1:
params.setFlashMode(params.FLASH_MODE_ON);
break;
case 2:
params.setFlashMode(params.FLASH_MODE_TORCH);
break;
case 3:
params.setFlashMode(params.FLASH_MODE_AUTO);
break;
}
fragment.setCameraParameters(params);
callbackContext.success(mode);
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set flash mode");
return false;
}
}
private boolean stopCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
fragment = null;
callbackContext.success();
return true;
}
private boolean showCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
callbackContext.success();
return true;
}
private boolean hideCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null) {
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
callbackContext.success();
return true;
}
private boolean switchCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
fragment.switchCamera();
callbackContext.success();
return true;
}
private boolean setOnPictureTakenHandler(JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "setOnPictureTakenHandler");
takePictureCallbackContext = callbackContext;
return true;
}
}
|
package com.just.agentweb;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public abstract class BaseAgentWebFragment extends Fragment {
protected AgentWeb mAgentWeb;
private MiddleWareWebChromeBase mMiddleWareWebChrome;
private MiddleWareWebClientBase mMiddleWareWebClient;
private ErrorLayoutEntity mErrorLayoutEntity;
private AgentWebUIControllerImplBase mAgentWebUIController;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ErrorLayoutEntity mErrorLayoutEntity = getErrorLayoutEntity();
mAgentWeb = AgentWeb.with(this)
.setAgentWebParent(getAgentWebParent(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
.setIndicatorColorWithHeight(getIndicatorColor(), getIndicatorHeight())
.setWebView(getWebView())
.setWebLayout(getWebLayout())
.setAgentWebWebSettings(getAgentWebSettings())
.setWebViewClient(getWebViewClient())
.setPermissionInterceptor(getPermissionInterceptor())
.setWebChromeClient(getWebChromeClient())
.interceptUnkownScheme()
.setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
.setReceivedTitleCallback(getReceivedTitleCallback())
.setSecurityType(AgentWeb.SecurityType.strict)
.addDownLoadResultListener(getDownLoadResultListener())
.setAgentWebUIController(getAgentWebUIController())
.setMainFrameErrorView(mErrorLayoutEntity.layoutRes, mErrorLayoutEntity.reloadId)
.useMiddleWareWebChrome(getMiddleWareWebChrome())
.useMiddleWareWebClient(getMiddleWareWebClient())
.createAgentWeb()
.ready()
.go(getUrl());
}
protected void setTitle(WebView view, String title) {
}
protected @NonNull ErrorLayoutEntity getErrorLayoutEntity() {
if (this.mErrorLayoutEntity == null) {
this.mErrorLayoutEntity = new ErrorLayoutEntity();
}
return mErrorLayoutEntity;
}
protected @Nullable AgentWebUIControllerImplBase getAgentWebUIController() {
return mAgentWebUIController;
}
protected static class ErrorLayoutEntity {
private int layoutRes = R.layout.agentweb_error_page;
private int reloadId;
public void setLayoutRes(int layoutRes) {
this.layoutRes = layoutRes;
if (layoutRes <= 0) {
layoutRes = -1;
}
}
public void setReloadId(int reloadId) {
this.reloadId = reloadId;
if (reloadId <= 0) {
reloadId = -1;
}
}
}
@Override
public void onPause() {
if (mAgentWeb != null)
mAgentWeb.getWebLifeCycle().onPause();
super.onPause();
}
@Override
public void onResume() {
if (mAgentWeb != null)
mAgentWeb.getWebLifeCycle().onResume();
super.onResume();
}
private @Nullable
ChromeClientCallbackManager.ReceivedTitleCallback getReceivedTitleCallback() {
return new ChromeClientCallbackManager.ReceivedTitleCallback() {
@Override
public void onReceivedTitle(WebView view, String title) {
setTitle(view, title);
}
};
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mAgentWeb != null)
mAgentWeb.uploadFileResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
protected @Nullable
String getUrl() {
return "";
}
@Override
public void onDestroy() {
if (mAgentWeb != null)
mAgentWeb.getWebLifeCycle().onDestroy();
super.onDestroy();
}
protected @Nullable
AgentWebSettings getAgentWebSettings() {
return WebDefaultSettingsManager.getInstance();
}
protected @Nullable
DownLoadResultListener getDownLoadResultListener() {
return null;
}
protected @Nullable
WebChromeClient getWebChromeClient() {
return null;
}
protected abstract @NonNull
ViewGroup getAgentWebParent();
protected @ColorInt
int getIndicatorColor() {
return -1;
}
protected int getIndicatorHeight() {
return -1;
}
protected @Nullable
WebViewClient getWebViewClient() {
return null;
}
protected @Nullable
WebView getWebView() {
return null;
}
protected @Nullable
IWebLayout getWebLayout() {
return null;
}
protected @Nullable PermissionInterceptor getPermissionInterceptor() {
return null;
}
protected @NonNull MiddleWareWebChromeBase getMiddleWareWebChrome() {
return this.mMiddleWareWebChrome = new MiddleWareWebChromeBase();
}
protected @NonNull MiddleWareWebClientBase getMiddleWareWebClient() {
return this.mMiddleWareWebClient = new MiddleWareWebClientBase();
}
}
|
package org.broadinstitute.sting.utils;
public class QualityUtils {
private QualityUtils() {}
static public double qualToProb(byte qual) {
return 1.0 - Math.pow(10.0, ((double) qual)/-10.0);
}
static public byte probToQual(double prob) {
return (byte) Math.round(-10.0*Math.log10(1.0 - prob + 0.0001));
}
static public byte baseAndProbToCompressedQuality(int baseIndex, double prob) {
byte compressedQual = (byte) baseIndex;
byte cprob = (byte) (100.0*prob);
byte qualmask = (byte) 252;
compressedQual += ((cprob << 2) & qualmask);
return compressedQual;
}
}
|
package org.codepond.wizardroid;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ViewGroup;
import org.codepond.wizardroid.infrastructure.Bus;
import org.codepond.wizardroid.infrastructure.Disposable;
import org.codepond.wizardroid.infrastructure.Subscriber;
import org.codepond.wizardroid.infrastructure.events.StepCompletedEvent;
import org.codepond.wizardroid.persistence.ContextManager;
/**
* The engine of the Wizard. This class controls the flow of the wizard
* and is using {@link ViewPager} under the hood. You would normally want to
* extend {@link WizardFragment} instead of using this class directly and make calls to the wizard API
* via {@link org.codepond.wizardroid.WizardFragment#wizard} field. Use this
* class only if you wish to create a custom WizardFragment to control the wizard.
*/
public class Wizard implements Disposable, Subscriber {
/**
* Interface for key wizard events. Implement this interface if you wish to create
* a custom WizardFragment.
*/
public static interface WizardCallbacks {
/**
* Event called when the wizard is completed
*/
public void onWizardComplete();
/**
* Event called after a step was changed
*/
public void onStepChanged();
}
private static final boolean DEBUG = false;
private static final String TAG = Wizard.class.getSimpleName();
private final WizardFlow wizardFlow;
private final ContextManager contextManager;
private final WizardCallbacks callbacks;
private final ViewPager mPager;
private final FragmentManager mFragmentManager;
private int backStackEntryCount;
private WizardStep mPreviousStep;
private int mPreviousPosition;
/**
* Constructor for Wizard
* @param wizardFlow WizardFlow instance. See WizardFlow.Builder for more information on creating WizardFlow objects.
* @param contextManager ContextManager instance would normally be {@link org.codepond.wizardroid.persistence.ContextManagerImpl}
* @param callbacks implementation of WizardCallbacks
* @param activity the hosting activity
*/
public Wizard(final WizardFlow wizardFlow,
final ContextManager contextManager,
final WizardCallbacks callbacks,
final FragmentActivity activity) {
this.wizardFlow = wizardFlow;
this.contextManager = contextManager;
this.callbacks = callbacks;
this.mPager = (ViewPager) activity.findViewById(R.id.step_container);
this.mFragmentManager = activity.getSupportFragmentManager();
if (mPager == null) {
throw new RuntimeException("Cannot initialize Wizard. View with ID: step_container not found!" +
" The hosting Activity/Fragment must have a ViewPager in its layout with ID: step_container");
}
mPager.setAdapter(new WizardPagerAdapter(activity.getSupportFragmentManager()));
backStackEntryCount = mFragmentManager.getBackStackEntryCount();
mFragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
backStackEntryCount = mFragmentManager.getBackStackEntryCount();
//onBackPressed
if (backStackEntryCount < getCurrentStepPosition()){
mPager.setCurrentItem(getCurrentStepPosition() - 1);
}
}
});
//Implementation of OnPageChangeListener to handle wizard control via user finger slides
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int mPreviousState = ViewPager.SCROLL_STATE_IDLE;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (backStackEntryCount < position){
mFragmentManager.beginTransaction().addToBackStack(null).commit();
}
else if (backStackEntryCount > position){
mFragmentManager.popBackStack();
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (DEBUG) Log.v(TAG, "onPageScrollStateChanged " + state);
switch (state) {
case ViewPager.SCROLL_STATE_DRAGGING:
mPreviousPosition = getCurrentStepPosition();
mPreviousStep = getCurrentStep();
break;
case ViewPager.SCROLL_STATE_SETTLING:
callbacks.onStepChanged();
break;
case ViewPager.SCROLL_STATE_IDLE:
if (mPreviousState == ViewPager.SCROLL_STATE_SETTLING) {
if (getCurrentStepPosition() > mPreviousPosition) {
if (DEBUG) Log.v(TAG, "goNext");
processStepBeforeChange(mPreviousStep, mPreviousPosition);
mPager.getAdapter().notifyDataSetChanged();
}
else {
if (DEBUG) Log.v(TAG, "goBack");
mPreviousStep.onExit(WizardStep.EXIT_PREVIOUS);
}
}
break;
}
mPreviousState = state;
}
});
Bus.getInstance().register(this, StepCompletedEvent.class);
}
@Override
public void dispose() {
Bus.getInstance().unregister(this);
}
@Override
public void receive(Object event) {
StepCompletedEvent stepCompletedEvent = (StepCompletedEvent) event;
onStepCompleted(stepCompletedEvent.isStepCompleted(), stepCompletedEvent.getStep());
}
private void onStepCompleted(boolean isComplete, WizardStep step) {
if (step != getCurrentStep()) return;
int stepPosition = getCurrentStepPosition();
// Check that the step is not already in this state to avoid spamming the viewpager
if (wizardFlow.isStepCompleted(stepPosition) != isComplete) {
wizardFlow.setStepCompleted(stepPosition, isComplete);
mPager.getAdapter().notifyDataSetChanged();
//Refresh the UI
callbacks.onStepChanged();
}
}
private void processStepBeforeChange(WizardStep step, int position) {
step.onExit(WizardStep.EXIT_NEXT);
wizardFlow.setStepCompleted(position, true);
contextManager.persistStepContext(step);
}
/**
* Advance the wizard to the next step
*/
public void goNext() {
if (canGoNext()) {
if (isLastStep()) {
processStepBeforeChange(getCurrentStep(), getCurrentStepPosition());
callbacks.onWizardComplete();
}
else {
mPreviousPosition = getCurrentStepPosition();
mPreviousStep = getCurrentStep();
setCurrentStep(mPager.getCurrentItem() + 1);
}
}
}
/**
* Takes the wizard one step back
*/
public void goBack() {
if (!isFirstStep()) {
mPreviousPosition = getCurrentStepPosition();
mPreviousStep = getCurrentStep();
setCurrentStep(mPager.getCurrentItem() - 1);
}
}
/**
* Sets the current step of the wizard
* @param stepPosition the position of the step within the WizardFlow
*/
public void setCurrentStep(int stepPosition) {
mPager.setCurrentItem(stepPosition);
}
/**
* Gets the current step position
* @return integer representing the position of the step in the WizardFlow
*/
public int getCurrentStepPosition() {
return mPager.getCurrentItem();
}
/**
* Gets the current step
* @return WizardStep the current WizardStep instance
*/
public WizardStep getCurrentStep() {
return ((WizardPagerAdapter)mPager.getAdapter()).getPrimaryItem();
}
/**
* Checks if the current step is the last step in the Wizard
* @return boolean representing the result of the check
*/
public boolean isLastStep() {
return mPager.getCurrentItem() == wizardFlow.getStepsCount() - 1;
}
/**
* Checks if the step is the first step in the Wizard
* @return boolean representing the result of the check
*/
public boolean isFirstStep() {
return mPager.getCurrentItem() == 0;
}
/**
* Check if the wizard can proceed to the next step by verifying that the current step
* is completed
*/
public boolean canGoNext() {
int stepPosition = getCurrentStepPosition();
if (wizardFlow.isStepRequired(stepPosition)) {
return wizardFlow.isStepCompleted(stepPosition);
}
return true;
}
/**
* Custom adapter for the ViewPager
*/
public class WizardPagerAdapter extends FragmentStatePagerAdapter {
private Fragment mPrimaryItem;
public WizardPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
try {
WizardStep step = wizardFlow.getSteps().get(i).newInstance();
contextManager.loadStepContext(step);
return step;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (Fragment) object;
}
@Override
public int getItemPosition(Object object) {
if (object.equals(mPreviousStep)) {
return POSITION_UNCHANGED;
}
else {
return POSITION_NONE;
}
}
@Override
public int getCount() {
return wizardFlow.getSteps().size();
}
public WizardStep getPrimaryItem() {
return (WizardStep) mPrimaryItem;
}
}
}
|
package org.yamcs.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TaiUtcConverter {
long[] timesecs; //TAI time in seconds when leap seconds are added
int diffTaiUtc; //the difference between the TAI and UTC at the last interval
static String UTC_TAI_HISTORY_FN="UTC-TAI.history";
static final int[] times365 = new int[]{ 0, 365, 730, 1095 } ;
static final int[] times36524 = new int[]{ 0, 36524, 73048, 109572 } ;
static final int[] montab = new int[] { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337 } ;
/* month length after february is (306 * m + 5) / 10 */
public TaiUtcConverter() throws IOException, ParseException {
InputStream is = TaiUtcConverter.class.getResourceAsStream("/"+UTC_TAI_HISTORY_FN);
if(is==null) throw new RuntimeException("Cannot find "+UTC_TAI_HISTORY_FN+" in the classpath");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line =null;
// 1974 Jan. 1 - 1975 Jan. 1 13s
String dp = "\\s?(\\d+)?\\s+(\\w{3})\\.?\\s+(\\d+)";
Pattern p = Pattern.compile(dp+"\\s*\\.?\\-\\s*("+dp+")?\\s*(\\d+)s\\s*");
ArrayList<Long> tmp1 = new ArrayList<Long>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
diffTaiUtc = -1;
int lineNum=0;
String prevYear = null;
while((line=reader.readLine()) != null) {
lineNum++;
Matcher m = p.matcher(line);
if(m.matches()) {
String year = m.group(1);
if(year==null) {
year = prevYear;
}
Date d = sdf.parse(year+" "+m.group(2)+ " "+m.group(3));
tmp1.add(d.getTime());
int ls = Integer.valueOf(m.group(8));
if((diffTaiUtc!=-1) && (ls!=diffTaiUtc+1)) {
throw new RuntimeException("Error reading line "+lineNum+" of UTC-TAI.history: only positive leap seconds are supported");
}
diffTaiUtc = ls;
prevYear = year;
}
}
timesecs = new long[tmp1.size()];
for(int i = 0; i<timesecs.length; i++) {
timesecs[i]=tmp1.get(i)/1000 + diffTaiUtc - timesecs.length + i;
}
}
//converts Modified Julian Day to calendar day
private void caldateFromMjd(DateTimeComponents cd, long day) {
int year;
int month;
int yday;
year = (int)(day / 146097);
day %= 146097L;
day += 678881L;
while (day >= 146097L) { day -= 146097L; ++year; }
/* year * 146097 + day - 678881 is MJD; 0 <= day < 146097 */
/* 2000-03-01, MJD 51604, is year 5, day 0 */
year *= 4;
if (day == 146096L) { year += 3; day = 36524; }
else { year += day / 36524L; day %= 36524L; }
year *= 25;
year += day / 1461;
day %= 1461;
year *= 4;
yday = (day < 306)?1:0;
if (day == 1460) { year += 3; day = 365; }
else { year += day / 365; day %= 365; }
yday += day;
day *= 10;
month = (int)((day + 5) / 306);
day = (day + 5) % 306;
day /= 10;
if (month >= 10) { yday -= 306; ++year; month -= 10; }
else { yday += 59; month += 2; }
cd.year = year;
cd.month = month + 1;
cd.day = (int)(day + 1);
cd.doy=yday+1;
}
//converts calendar date to Modified Julian Day
//doy is ignored
private long caldateToMjd(DateTimeComponents dtc) {
int y;
int m;
int d;
d = dtc.day - 678882;
m = dtc.month - 1;
y = dtc.year;
d += 146097L * (y / 400);
y %= 400;
if (m >= 2) m -= 2; else { m += 10; --y; }
y += (m / 12);
m %= 12;
if (m < 0) { m += 12; --y; }
d += montab[m];
d += 146097L * (y / 400);
y %= 400;
if (y < 0) { y += 400; d -= 146097L; }
d += times365[y & 3];
y >>= 2;
d += 1461L * (y % 25);
y /= 25;
d += times36524[y & 3];
return d;
}
DateTimeComponents instantToUtc(long t) {
DateTimeComponents dtc = new DateTimeComponents();
long u;
int leap;
long s;
/* XXX: check for overfow? */
u = t/1000;
dtc.millisec = (int)( t % 1000);
//leap = leapsecs_sub(&t2);
leap = 0;
int ls = diffTaiUtc;
for(int i = timesecs.length -1 ; i>=0; i
if (u > timesecs[i]) break;
if (u == timesecs[i]) { leap = 1; break;}
ls
}
u-=ls;
s = u % 86400L;
dtc.second = (int)((s % 60) + leap); s /= 60;
dtc.minute = (int)(s % 60); s /= 60;
dtc.hour = (int)s;
u /= 86400L;
long mjd = 40587+u;
//long mjd = u - 53375995543064L;
caldateFromMjd(dtc, mjd);
return dtc;
}
/**
* transforms Instant to Unix time expressed in milliseconds since 1970
* @param t
* @return
*/
long instantToUnix(long t) {
long u = t/1000;
int ls = diffTaiUtc;
for(int i = timesecs.length -1 ; i>=0; i
if (u >= timesecs[i]) break;
ls
}
return t-ls*1000;
}
/**
* Converts UTC to instant.
* WARNING: DOY is ignored.
* @param dtc
* @return
*/
long utcToInstant(DateTimeComponents dtc) {
long day = caldateToMjd(dtc);
long s = dtc.hour * 60 + dtc.minute;
s = s * 60 + dtc.second + (day - 40587) * 86400L;
int ls = diffTaiUtc;
for(int i = timesecs.length -1 ; i>=0; i
long u = timesecs[i]-ls+1;
if (s > u) break;
if((s < u) || (dtc.second==60)) ls
}
s+=ls;
return dtc.millisec + 1000 * s;
}
/**
* transforms unix time expressed in milliseconds since 1970 to instant
* @param t
* @return
*/
long unixToInstant(long t) {
long u = t/1000;
int ls = diffTaiUtc;
for(int i = timesecs.length -1 ; i>=0; i
if (u >= timesecs[i]-ls+1) break;
ls
}
return t+ls*1000;
}
public static class DateTimeComponents {
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
public int millisec;
public int doy;
@Override
public String toString() {
return "DateTimeComponents [year=" + year + ", month=" + month
+ ", day=" + day + ", hour=" + hour + ", minute=" + minute
+ ", second=" + second + ", millisec=" + millisec
+ ", doy=" + doy + "]";
}
public String toIso8860String() {
return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d", year, month, day, hour, minute,second,millisec);
}
}
public static void main(String[] args) throws Exception {
DateTimeComponents dtc= new DateTimeComponents();
TaiUtcConverter te = new TaiUtcConverter();
//caltime_utc(dtc, 0x400000002a2b2c2dL);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String[] sa = new String[] {"2012.07.01 00:00:00.323", "2012.07.01 00:00:35.323" , "2012.07.01 00:00:34.323", "2012.07.01 00:00:33.323", "2012.07.02 00:00:00.323" };
for(String s:sa) {
Date d = sdf.parse(s);
dtc = te.instantToUtc(d.getTime());
}
}
}
|
package org.burntgameproductions.PathToMani.menu;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Rectangle;
import org.burntgameproductions.PathToMani.GameOptions;
import org.burntgameproductions.PathToMani.ManiApplication;
import org.burntgameproductions.PathToMani.TextureManager;
import org.burntgameproductions.PathToMani.common.ManiColor;
import org.burntgameproductions.PathToMani.files.FileManager;
import org.burntgameproductions.PathToMani.game.DebugOptions;
import org.burntgameproductions.PathToMani.game.sound.MusicManager;
import org.burntgameproductions.PathToMani.ui.ManiInputManager;
import org.burntgameproductions.PathToMani.ui.ManiUiControl;
import org.burntgameproductions.PathToMani.ui.ManiUiScreen;
import org.burntgameproductions.PathToMani.ui.UiDrawer;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class PlayScreen implements ManiUiScreen {
public static final float CREDITS_BTN_W = .15f;
public static final float CREDITS_BTN_H = .07f;
private final ArrayList<ManiUiControl> myControls;
private final ManiUiControl myTutCtrl;
private final ManiUiControl myNewCtrl;
private final ManiUiControl myLoadCtrl;
private final ManiUiControl myBackCtrl;
//logos
private final TextureAtlas.AtlasRegion logo;
private final TextureAtlas.AtlasRegion newyears;
private final TextureAtlas.AtlasRegion aprilfools;
private final TextureAtlas.AtlasRegion australiaday;
//boolean's for date checker.
private boolean isNewYears;
private boolean isAustraliaDay;
private boolean isAprilFools;
private final boolean isMobile;
GameOptions gameOptions;
public PlayScreen(MenuLayout menuLayout, TextureManager textureManager, boolean mobile, float r, GameOptions gameOptions) {
isMobile = mobile;
myControls = new ArrayList<ManiUiControl>();
this.gameOptions = gameOptions;
myTutCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 1), true, Input.Keys.T);
myTutCtrl.setDisplayName("Tutorial");
myControls.add(myTutCtrl);
myNewCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 2), true, Input.Keys.N);
myNewCtrl.setDisplayName("New Game");
myControls.add(myNewCtrl);
myLoadCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 3), true, Input.Keys.L);
myLoadCtrl.setDisplayName("Load Game");
myControls.add(myLoadCtrl);
myBackCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 4), true, Input.Keys.B);
myBackCtrl.setDisplayName("Back");
myControls.add(myBackCtrl);
/**
*The reason why we are doing it like this is so it doesnt have to use a texture atlas.
*/
//Normal
FileHandle imageFile = FileManager.getInstance().getImagesDirectory().child("logo.png");
logo = textureManager.getTexture(imageFile);
//Australia day.
FileHandle imageFile1 = FileManager.getInstance().getImagesDirectory().child("australiaday.png");
australiaday = textureManager.getTexture(imageFile1);
//April fools.
FileHandle imageFile2 = FileManager.getInstance().getImagesDirectory().child("aprilfools.png");
aprilfools = textureManager.getTexture(imageFile2);
//New years.
FileHandle imageFile3 = FileManager.getInstance().getImagesDirectory().child("newyears.png");
newyears = textureManager.getTexture(imageFile3);
//Date changer.
Calendar var1 = Calendar.getInstance();
if (var1.get(2) + 1 == 04 && var1.get(5) >= 01 && var1.get(5) <= 03)
{
this.isAprilFools = true;
}
else if (var1.get(2) + 1 == 01 && var1.get(5) >= 26 && var1.get(5) <= 28)
{
this.isAustraliaDay = true;
}
else if (var1.get(2) + 1 == 01 && var1.get(5) >= 01 && var1.get(5) <= 07)
{//This ^^^^ here... We want to display the logo between these days of this month.
this.isNewYears = true;
}
}
public static Rectangle creditsBtnRect(float r) {
return new Rectangle(r - CREDITS_BTN_W, 1 - CREDITS_BTN_H, CREDITS_BTN_W, CREDITS_BTN_H);
}
public List<ManiUiControl> getControls() {
return myControls;
}
@Override
public void updateCustom(ManiApplication cmp, ManiInputManager.Ptr[] ptrs, boolean clickedOutside) {
ManiInputManager im = cmp.getInputMan();
MenuScreens screens = cmp.getMenuScreens();
//What to do when "Tutorial" button is pressed.
if (cmp.getOptions().controlType == GameOptions.CONTROL_CONTROLLER) {
//Load this version of the tutorial if you are using a tutorial.
myTutCtrl.setEnabled(false);
} else {
//Load this version of the tutorial if you are using anything but a controller.
myTutCtrl.setEnabled(true);
}
//What to do when "New" button is pressed.
if (myNewCtrl.isJustOff()) {
//If you have tried to load a game, it will load that instead.
if (!myLoadCtrl.isEnabled()) {
cmp.loadNewGame(false, false);
//If you havent tried to load a game... it should be good to start.
} else {
im.setScreen(cmp, screens.newShip);
}
}
//What to do when "Load" button is pressed.
if (myLoadCtrl.isJustOff()) {
cmp.loadNewGame(false, true);
return;
}
//What to do when "Back" button is pressed.
if (myBackCtrl.isJustOff()) {
im.setScreen(cmp, screens.main);
return;
}
}
@Override
public boolean isCursorOnBg(ManiInputManager.Ptr ptr) {
return false;
}
@Override
public void onAdd(ManiApplication cmp) {
MusicManager.getInstance().PlayMenuMusic(gameOptions);
}
@Override
public void drawBg(UiDrawer uiDrawer, ManiApplication cmp) {
}
@Override
public void drawImgs(UiDrawer uiDrawer, ManiApplication cmp) {
/**We are now loading the correct image for the date**/
if (this.isNewYears)
{
float sz = .55f;
//Load this logo when the date on the players computer is the same as the one we set above.
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(newyears, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else if (this.isAustraliaDay)
{
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(australiaday, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else if (this.isAprilFools)
{
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(aprilfools, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else
{
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(logo, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
}
@Override
public void drawText(UiDrawer uiDrawer, ManiApplication cmp) {
}
@Override
public boolean reactsToClickOutside() {
return false;
}
@Override
public void blurCustom(ManiApplication cmp) {
}
}
|
package org.modmine.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.intermine.api.InterMineAPI;
import org.intermine.objectstore.ObjectStore;
import org.intermine.web.logic.session.SessionMethods;
import org.modmine.web.MetadataCache.GBrowseTrack;
public class ProjectsSummaryController extends TilesAction
{
/**
* {@inheritDoc}
*/
public ActionForward execute(@SuppressWarnings("unused") ComponentContext context,
@SuppressWarnings("unused") ActionMapping mapping,
@SuppressWarnings("unused") ActionForm form,
HttpServletRequest request,
@SuppressWarnings("unused") HttpServletResponse response)
throws Exception {
try {
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
ObjectStore os = im.getObjectStore();
Map<String, List<DisplayExperiment>> experiments = MetadataCache.getProjectExperiments(os);
request.setAttribute("experiments", experiments);
Map<String, List<GBrowseTrack>> tracks = MetadataCache.getExperimentGBrowseTracks(os);
request.setAttribute("tracks", tracks);
} catch (Exception err) {
err.printStackTrace();
}
return null;
}
}
|
package injection;
import injection.InjectorParseException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.*;
import java.lang.reflect.Modifier;
import persistence.Attribute;
import persistence.AttributeValue;
import persistence.ConstraintViolationException;
import persistence.EnumerationValue;
import persistence.NotNullViolationException;
import persistence.ReadOnlyViolationException;
import persistence.SystemException;
import persistence.Type;
import persistence.UniqueConstraint;
import persistence.UniqueViolationException;
import tools.ClassComparator;
public final class Instrumentor implements InjectionConsumer
{
private final Writer output;
/**
* Holds several properties of the class currently
* worked on.
*/
private JavaClass class_state=null;
/**
* Collects the class states of outer classes,
* when operating on a inner class.
* @see #class_state
* @element-type InstrumentorClass
*/
private ArrayList class_state_stack=new ArrayList();
protected final String lineSeparator;
/**
* The last file level doccomment that was read.
*/
private String lastFileDocComment = null;
public Instrumentor(Writer output)
{
this.output=output;
final String systemLineSeparator = System.getProperty("line.separator");
if(systemLineSeparator==null)
{
System.out.println("warning: property \"line.separator\" is null, using LF (unix style).");
lineSeparator = "\n";
}
else
lineSeparator = systemLineSeparator;
}
public void onPackage(JavaFile javafile)
throws InjectorParseException
{
}
public void onImport(String importname)
{
}
private boolean discardnextfeature=false;
/**
* Tag name for persistent classes.
*/
private static final String PERSISTENT_CLASS = "persistent";
/**
* Tag name for persistent attributes.
*/
private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS;
/**
* Tag name for unique attributes.
*/
private static final String UNIQUE_ATTRIBUTE = "unique";
/**
* Tag name for read-only attributes.
*/
private static final String READ_ONLY_ATTRIBUTE = "read-only";
/**
* Tag name for not-null attributes.
*/
private static final String NOT_NULL_ATTRIBUTE = "not-null";
/**
* Tag name for mapped attributes.
*/
private static final String MAPPED_ATTRIBUTE = "mapped";
/**
* Tag name for one qualifier of qualified attributes.
*/
private static final String ATTRIBUTE_QUALIFIER = "qualifier";
/**
* Tag name for one variant of media attributes.
*/
private static final String VARIANT_MEDIA_ATTRIBUTE = "variant";
/**
* Tag name for media attributes with a constant major mime type.
*/
private static final String MIME_MAJOR = "mime-major";
/**
* Tag name for media attributes with a constant minor mime type.
*/
private static final String MIME_MINOR = "mime-minor";
/**
* Tag name for enumeration values of enumeration attributes.
*/
private static final String ENUMERATION_VALUE = "value";
/**
* All generated class features get this doccomment tag.
*/
private static final String GENERATED = "generated";
private List uniqueConstraints=null;
private void handleClassComment(final JavaClass jc, final String docComment)
{
if(containsTag(docComment, PERSISTENT_CLASS))
jc.setPersistent();
final String uniqueConstraint = Injector.findWholeDocTag(docComment, UNIQUE_ATTRIBUTE);
if(uniqueConstraint!=null)
{
if(uniqueConstraints==null)
uniqueConstraints = new ArrayList();
uniqueConstraints.add(uniqueConstraint);
}
}
public void onClass(final JavaClass jc)
{
//System.out.println("onClass("+jc.getName()+")");
discardnextfeature=false;
class_state_stack.add(class_state);
class_state=jc;
if(lastFileDocComment != null)
{
handleClassComment(jc, lastFileDocComment);
lastFileDocComment = null;
}
}
private static final String lowerCamelCase(final String s)
{
final char first = s.charAt(0);
if(Character.isLowerCase(first))
return s;
else
return Character.toLowerCase(first) + s.substring(1);
}
private static final String getShortName(final Class aClass)
{
final String name = aClass.getName();
final int pos = name.lastIndexOf('.');
return name.substring(pos+1);
}
private void writeParameterDeclarationList(final Collection parameters)
throws IOException
{
if(parameters!=null)
{
boolean first = true;
for(Iterator i = parameters.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
final String parameter = (String)i.next();
output.write("final ");
output.write(parameter);
output.write(' ');
output.write(lowerCamelCase(parameter));
}
}
}
private void writeParameterCallList(final Collection parameters)
throws IOException
{
if(parameters!=null)
{
boolean first = true;
for(Iterator i = parameters.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
final String parameter = (String)i.next();
output.write(lowerCamelCase(parameter));
}
}
}
private void writeThrowsClause(final Collection exceptions)
throws IOException
{
if(!exceptions.isEmpty())
{
output.write(" throws ");
boolean first = true;
for(final Iterator i = exceptions.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
output.write(((Class)i.next()).getName());
}
}
}
private final void writeCommentHeader()
throws IOException
{
output.write("/**");
output.write(lineSeparator);
output.write(lineSeparator);
output.write("\t **");
output.write(lineSeparator);
}
private final void writeCommentFooter()
throws IOException
{
output.write("\t * @"+GENERATED);
output.write(lineSeparator);
output.write("\t *");
output.write(lineSeparator);
output.write(" */");
}
public void writeConstructor(final JavaClass javaClass)
throws IOException
{
final List initialAttributes = javaClass.getInitialAttributes();
writeCommentHeader();
output.write("\t * Constructs a new ");
output.write(javaClass.getName());
output.write(" with all the attributes initially needed.");
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
final JavaAttribute initialAttribute = (JavaAttribute)i.next();
output.write(lineSeparator);
output.write("\t * @param initial");
output.write(initialAttribute.getCamelCaseName());
output.write(" the initial value for attribute {@link
output.write(initialAttribute.getName());
output.write("}.");
}
output.write(lineSeparator);
writeCommentFooter();
output.write(Modifier.toString(javaClass.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)));
output.write(' ');
output.write(javaClass.getName());
output.write('(');
boolean first = true;
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
final JavaAttribute initialAttribute = (JavaAttribute)i.next();
output.write("final ");
output.write(initialAttribute.getBoxedType());
output.write(" initial");
output.write(initialAttribute.getCamelCaseName());
}
output.write(')');
writeThrowsClause(javaClass.getContructorExceptions());
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
output.write("\t\tsuper(new "+AttributeValue.class.getName()+"[]{");
output.write(lineSeparator);
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
final JavaAttribute initialAttribute = (JavaAttribute)i.next();
output.write("\t\t\tnew "+AttributeValue.class.getName()+"(");
output.write(initialAttribute.getName());
output.write(',');
if(initialAttribute.isBoxed())
output.write(initialAttribute.getBoxingCode());
output.write("initial");
output.write(initialAttribute.getCamelCaseName());
if(initialAttribute.isBoxed())
output.write(')');
output.write("),");
output.write(lineSeparator);
}
output.write("\t\t});");
output.write(lineSeparator);
for(Iterator i = javaClass.getContructorExceptions().iterator(); i.hasNext(); )
{
final Class exception = (Class)i.next();
output.write("\t\tthrowInitial");
output.write(getShortName(exception));
output.write("();");
output.write(lineSeparator);
}
output.write("\t}");
}
private static final int ENUMERATION_NUMBER_AUTO_INCREMENT = 100;
private void writeEnumerationClass(final JavaAttribute enumerationAttribute)
throws IOException
{
// deactivated, since the parser cannot remove generated inner classes.
if(true)
return;
writeCommentHeader();
output.write("\t * A class representing the possible states of the persistent enumeration attribute {@link
output.write(enumerationAttribute.getName());
output.write("}.");
output.write(lineSeparator);
writeCommentFooter();
output.write("public static final class ");
output.write(enumerationAttribute.getCamelCaseName());
output.write(" extends "+EnumerationValue.class.getName());
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
int enumerationNumber = ENUMERATION_NUMBER_AUTO_INCREMENT;
for(Iterator i = enumerationAttribute.getEnumerationValues().iterator(); i.hasNext(); )
{
final String enumerationValue = (String)i.next();
output.write("\t\tpublic static final int ");
output.write(enumerationValue);
output.write("NUM = ");
output.write(Integer.toString(enumerationNumber));
output.write(';');
output.write(lineSeparator);
output.write("\t\tpublic static final ");
output.write(enumerationAttribute.getCamelCaseName());
output.write(' ');
output.write(enumerationValue);
output.write(" = new ");
output.write(enumerationAttribute.getCamelCaseName());
output.write('(');
output.write(Integer.toString(enumerationNumber));
output.write(", \"");
output.write(enumerationValue);
output.write("\");");
output.write(lineSeparator);
output.write(lineSeparator);
enumerationNumber += ENUMERATION_NUMBER_AUTO_INCREMENT;
}
output.write("\t\tprivate State(final int number, final String code)");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write("\t\t\tsuper(number, code);");
output.write(lineSeparator);
output.write("\t\t}");
output.write(lineSeparator);
output.write("\t}");
}
private void writeAccessMethods(final JavaAttribute persistentAttribute)
throws IOException
{
if(persistentAttribute.isEnumerationAttribute())
writeEnumerationClass(persistentAttribute);
final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers());
final String type = persistentAttribute.getBoxedType();
final List qualifiers = persistentAttribute.getQualifiers();
// getter
writeCommentHeader();
output.write("\t * Returns the value of the persistent attribute {@link
output.write(persistentAttribute.getName());
output.write("}.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(' ');
output.write(type);
output.write(" get");
output.write(persistentAttribute.getCamelCaseName());
output.write('(');
writeParameterDeclarationList(qualifiers);
output.write(')');
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
writeGetterBody(output, persistentAttribute);
output.write("\t}");
// setter
if(persistentAttribute.hasSetter())
{
writeCommentHeader();
output.write("\t * Sets a new value for the persistent attribute {@link
output.write(persistentAttribute.getName());
output.write("}.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(" void set");
output.write(persistentAttribute.getCamelCaseName());
output.write('(');
if(qualifiers!=null)
{
writeParameterDeclarationList(qualifiers);
output.write(',');
}
output.write("final ");
output.write(type);
output.write(' ');
output.write(persistentAttribute.getName());
output.write(')');
writeThrowsClause(persistentAttribute.getSetterExceptions());
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
writeSetterBody(output, persistentAttribute);
output.write("\t}");
}
}
private void writeMediaGetterMethod(final JavaAttribute mediaAttribute,
final Class returnType,
final String part,
final String variant,
final String literal,
final String comment)
throws IOException
{
final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers());
final List qualifiers = mediaAttribute.getQualifiers();
writeCommentHeader();
output.write("\t * ");
output.write(comment);
output.write(" {@link
output.write(mediaAttribute.getName());
output.write("}.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(' ');
output.write(returnType.getName());
output.write(" get");
output.write(mediaAttribute.getCamelCaseName());
output.write(part);
if(variant!=null)
output.write(variant);
output.write('(');
writeParameterDeclarationList(qualifiers);
output.write(')');
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
output.write("\t\treturn ");
if(literal!=null)
{
output.write('\"');
output.write(literal);
output.write("\";");
}
else
{
output.write("getMedia");
output.write(part);
output.write("(this.");
output.write(mediaAttribute.getName());
if(variant!=null)
{
if(variant.length()>0)
{
output.write(",\"");
output.write(variant);
output.write('\"');
}
else
output.write(",null");
}
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(");");
}
output.write(lineSeparator);
output.write("\t}");
}
private void writeMediaAccessMethods(final JavaAttribute mediaAttribute)
throws IOException
{
final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers());
final List qualifiers = mediaAttribute.getQualifiers();
final String mimeMajor = mediaAttribute.getMimeMajor();
final String mimeMinor = mediaAttribute.getMimeMinor();
// getters
writeMediaGetterMethod(mediaAttribute, String.class, "URL", "", null,
"Returns a URL pointing to the data of the persistent attribute");
final List mediaVariants = mediaAttribute.getMediaVariants();
if(mediaVariants!=null)
{
for(Iterator i = mediaVariants.iterator(); i.hasNext(); )
writeMediaGetterMethod(mediaAttribute, String.class, "URL", (String)i.next(), null,
"Returns a URL pointing to the varied data of the persistent attribute");
}
writeMediaGetterMethod(mediaAttribute, String.class, "MimeMajor", null, mimeMajor,
"Returns the major mime type of the persistent media attribute");
writeMediaGetterMethod(mediaAttribute, String.class, "MimeMinor", null, mimeMinor,
"Returns the minor mime type of the persistent media attribute");
writeMediaGetterMethod(mediaAttribute, InputStream.class, "Data", null, null,
"Returns a stream for fetching the data of the persistent media attribute");
// setters
if(mediaAttribute.hasSetter())
{
writeCommentHeader();
output.write("\t * Provides data for the persistent media attribute {@link
output.write(mediaAttribute.getName());
output.write("}.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(" void set");
output.write(mediaAttribute.getCamelCaseName());
output.write("Data(");
if(qualifiers!=null)
{
writeParameterDeclarationList(qualifiers);
output.write(',');
}
output.write("final " + OutputStream.class.getName() + " data");
if(mimeMajor==null)
output.write(",final "+String.class.getName()+" mimeMajor");
if(mimeMinor==null)
output.write(",final "+String.class.getName()+" mimeMinor");
output.write(')');
final SortedSet setterExceptions = mediaAttribute.getSetterExceptions();
writeThrowsClause(setterExceptions);
if(setterExceptions.isEmpty())
output.write("throws ");
output.write(IOException.class.getName());
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
final SortedSet exceptionsToCatch = new TreeSet(mediaAttribute.getExceptionsToCatchInSetter());
exceptionsToCatch.remove(ReadOnlyViolationException.class);
exceptionsToCatch.remove(UniqueViolationException.class);
if(!exceptionsToCatch.isEmpty())
{
output.write("\t\ttry");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write('\t');
}
output.write("\t\tsetMediaData(this.");
output.write(mediaAttribute.getName());
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(",data");
output.write(mimeMajor==null ? ",mimeMajor" : ",null");
output.write(mimeMinor==null ? ",mimeMinor" : ",null");
output.write(");");
output.write(lineSeparator);
if(!exceptionsToCatch.isEmpty())
{
output.write("\t\t}");
output.write(lineSeparator);
for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); )
writeViolationExceptionCatchClause(output, (Class)i.next());
}
output.write("\t}");
}
}
private final void writeEquals(final JavaAttribute attribute)
throws IOException
{
output.write("equal(");
output.write(attribute.getName());
output.write(",searched");
output.write(attribute.getCamelCaseName());
output.write(')');
}
private void writeUniqueFinder(final JavaAttribute[] persistentAttributes)
throws IOException, InjectorParseException
{
int modifiers = -1;
for(int i=0; i<persistentAttributes.length; i++)
{
if(modifiers==-1)
modifiers = persistentAttributes[i].getMethodModifiers();
else
{
if(modifiers!=persistentAttributes[i].getMethodModifiers())
throw new InjectorParseException("Tried to write unique finder and found attribues with different modifiers");
}
}
final String methodModifiers = Modifier.toString(modifiers|Modifier.STATIC);
final String className = persistentAttributes[0].getParent().getName();
writeCommentHeader();
output.write("\t * Finds a ");
output.write(lowerCamelCase(className));
output.write(" by it's unique attributes");
for(int i=0; i<persistentAttributes.length; i++)
{
output.write(lineSeparator);
output.write("\t * @param searched");
output.write(persistentAttributes[i].getCamelCaseName());
output.write(" shall be equal to attribute {@link
output.write(persistentAttributes[i].getName());
output.write("}.");
}
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(' ');
output.write(className);
boolean first=true;
for(int i=0; i<persistentAttributes.length; i++)
{
if(first)
{
output.write(" findBy");
first = false;
}
else
output.write("And");
output.write(persistentAttributes[i].getCamelCaseName());
}
output.write('(');
final Set qualifiers = new HashSet();
for(int i=0; i<persistentAttributes.length; i++)
{
if(i>0)
output.write(',');
final JavaAttribute persistentAttribute = (JavaAttribute)persistentAttributes[i];
if(persistentAttribute.getQualifiers() != null)
qualifiers.addAll(persistentAttribute.getQualifiers());
output.write("final ");
output.write(persistentAttribute.getPersistentType());
output.write(" searched");
output.write(persistentAttribute.getCamelCaseName());
}
if(!qualifiers.isEmpty())
{
output.write(',');
writeParameterDeclarationList(qualifiers);
}
output.write(')');
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
output.write("\t\treturn (");
output.write(className);
output.write(")searchUnique(TYPE,");
if(persistentAttributes.length==1)
writeEquals(persistentAttributes[0]);
else
{
output.write("and(");
writeEquals(persistentAttributes[0]);
for(int i = 1; i<persistentAttributes.length; i++)
{
output.write(',');
writeEquals(persistentAttributes[i]);
}
output.write(')');
}
output.write(");");
output.write(lineSeparator);
output.write("\t}");
}
private final void writeType(final JavaClass javaClass)
throws IOException
{
writeCommentHeader();
output.write("\t * The persistent type information for ");
output.write(lowerCamelCase(javaClass.getName()));
output.write(".");
output.write(lineSeparator);
writeCommentFooter();
// the TYPE variable
output.write("public static final "+Type.class.getName()+" TYPE = ");
output.write(lineSeparator);
// open the constructor of type
output.write("\t\tnew "+Type.class.getName()+"(");
output.write(lineSeparator);
// the class itself
output.write("\t\t\t");
output.write(javaClass.getName());
output.write(".class,");
output.write(lineSeparator);
// the attributes of the class
output.write("\t\t\tnew "+Attribute.class.getName()+"[]{");
output.write(lineSeparator);
for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); )
{
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
output.write("\t\t\t\t");
output.write(persistentAttribute.getName());
output.write(',');
output.write(lineSeparator);
}
output.write("\t\t\t},");
output.write(lineSeparator);
// the unique contraints of the class
output.write("\t\t\tnew "+UniqueConstraint.class.getName()+"[]{");
output.write(lineSeparator);
for(Iterator i = javaClass.getUniqueConstraints().iterator(); i.hasNext(); )
{
final JavaAttribute[] uniqueConstraint = (JavaAttribute[])i.next();
if(uniqueConstraint.length==1)
{
// shorter notation, if unique contraint does not cover multive attributes
output.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+'(');
output.write(uniqueConstraint[0].getName());
output.write("),");
}
else
{
// longer notation otherwise
output.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+"(new "+Attribute.class.getName()+"[]{");
for(int j = 0; j<uniqueConstraint.length; j++)
{
output.write(uniqueConstraint[j].getName());
output.write(',');
}
output.write("}),");
}
output.write(lineSeparator);
}
output.write("\t\t\t},");
output.write(lineSeparator);
// the runnable initializing attributes
output.write("\t\t\tnew Runnable()");
output.write(lineSeparator);
output.write("\t\t\t{");
output.write(lineSeparator);
output.write("\t\t\t\tpublic void run()");
output.write(lineSeparator);
output.write("\t\t\t\t{");
output.write(lineSeparator);
for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); )
{
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
output.write("\t\t\t\t\t");
output.write(persistentAttribute.getName());
output.write(".initialize(\"");
output.write(persistentAttribute.getName());
output.write("\",");
output.write(persistentAttribute.isReadOnly() ? "true": "false");
output.write(',');
output.write(persistentAttribute.isNotNull() ? "true": "false");
//private List qualifiers = null;
output.write(");");
output.write(lineSeparator);
}
output.write("\t\t\t\t}");
output.write(lineSeparator);
output.write("\t\t\t}");
output.write(lineSeparator);
// close the constructor of Type
output.write("\t\t)");
output.write(lineSeparator);
output.write(";");
}
public void onClassEnd(JavaClass jc)
throws IOException, InjectorParseException
{
if(uniqueConstraints != null)
{
for( final Iterator i=uniqueConstraints.iterator(); i.hasNext(); )
{
final String uniqueConstraint=(String)i.next();
final List attributes = new ArrayList();
for(final StringTokenizer t=new StringTokenizer(uniqueConstraint, " "); t.hasMoreTokens(); )
{
final String attributeName = t.nextToken();
final JavaAttribute ja = jc.getPersistentAttribute(attributeName);
if(ja==null)
throw new InjectorParseException("Attribute with name "+attributeName+" does not exist!");
attributes.add(ja);
}
if(attributes.isEmpty())
throw new InjectorParseException("No attributes found in unique constraint "+uniqueConstraint);
jc.makeUnique((JavaAttribute[])attributes.toArray(new JavaAttribute[]{}));
}
}
//System.out.println("onClassEnd("+jc.getName()+")");
if(!jc.isInterface() && jc.isPersistent())
{
writeConstructor(jc);
for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); )
{
// write setter/getter methods
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
if(persistentAttribute.isMediaPersistentType())
writeMediaAccessMethods(persistentAttribute);
else
writeAccessMethods(persistentAttribute);
}
for(final Iterator i = jc.getUniqueConstraints().iterator(); i.hasNext(); )
{
// write unique finder methods
final JavaAttribute[] persistentAttributes = (JavaAttribute[])i.next();
writeUniqueFinder(persistentAttributes);
}
writeType(jc);
}
if(class_state!=jc)
throw new RuntimeException();
class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1));
}
public void onBehaviourHeader(JavaBehaviour jb)
throws java.io.IOException
{
output.write(jb.getLiteral());
}
public void onAttributeHeader(JavaAttribute ja)
{
}
public void onClassFeature(final JavaFeature jf, final String docComment)
throws IOException, InjectorParseException
{
//System.out.println("onClassFeature("+jf.getName()+" "+docComment+")");
if(!class_state.isInterface())
{
if(jf instanceof JavaAttribute &&
Modifier.isFinal(jf.getModifiers()) &&
Modifier.isStatic(jf.getModifiers()) &&
!discardnextfeature &&
containsTag(docComment, PERSISTENT_ATTRIBUTE))
{
final String type = jf.getType();
final JavaAttribute ja = (JavaAttribute)jf;
final String persistentType;
if("IntegerAttribute".equals(type))
persistentType = "Integer";
else if("BooleanAttribute".equals(type))
persistentType = "Boolean";
else if("StringAttribute".equals(type))
persistentType = "String";
else if("EnumerationAttribute".equals(type))
{
persistentType = ja.getCamelCaseName();
}
else if("ItemAttribute".equals(type))
{
persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE);
}
else if("MediaAttribute".equals(type))
{
persistentType = JavaAttribute.MEDIA_TYPE;
}
else
throw new RuntimeException();
ja.makePersistent(persistentType);
if(containsTag(docComment, UNIQUE_ATTRIBUTE))
ja.getParent().makeUnique(new JavaAttribute[]{ja});
if(containsTag(docComment, READ_ONLY_ATTRIBUTE))
ja.makeReadOnly();
if(containsTag(docComment, NOT_NULL_ATTRIBUTE))
ja.makeNotNull();
if(containsTag(docComment, MAPPED_ATTRIBUTE))
ja.makeMapped();
final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER);
if(qualifier!=null)
ja.makeQualified(Collections.singletonList(qualifier));
final String variant = Injector.findDocTag(docComment, VARIANT_MEDIA_ATTRIBUTE);
if(variant!=null)
ja.makeMediaVarianted(Collections.singletonList(variant));
final String mimeMajor = Injector.findDocTag(docComment, MIME_MAJOR);
final String mimeMinor = Injector.findDocTag(docComment, MIME_MINOR);
if(mimeMajor!=null || mimeMinor!=null)
ja.contrainMediaMime(mimeMajor, mimeMinor);
final String enumerationValue = Injector.findDocTag(docComment, ENUMERATION_VALUE);
if(enumerationValue!=null)
ja.makeEnumerationAttribute(Collections.singletonList(enumerationValue));
}
}
discardnextfeature=false;
}
public boolean onDocComment(String docComment)
throws IOException
{
//System.out.println("onDocComment("+docComment+")");
if(containsTag(docComment, GENERATED))
{
discardnextfeature=true;
return false;
}
else
{
output.write(docComment);
return true;
}
}
public void onFileDocComment(String docComment)
throws IOException
{
//System.out.println("onFileDocComment("+docComment+")");
output.write(docComment);
if (class_state != null)
{
// handle doccomment immediately
handleClassComment(class_state, docComment);
}
else
{
// remember to be handled as soon as we know what class we're talking about
lastFileDocComment = docComment;
}
}
public void onFileEnd()
{
if(!class_state_stack.isEmpty())
throw new RuntimeException();
}
private static final boolean containsTag(final String docComment, final String tagName)
{
return docComment!=null && docComment.indexOf('@'+tagName)>=0 ;
}
/**
* Identation contract:
* This methods is called, when output stream is immediatly after a line break,
* and it should return the output stream after immediatly after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeGetterBody(final Writer output, final JavaAttribute attribute)
throws IOException
{
output.write("\t\treturn ");
if(attribute.isBoxed())
output.write('(');
output.write('(');
output.write(attribute.getPersistentType());
output.write(")getAttribute(this.");
output.write(attribute.getName());
final List qualifiers = attribute.getQualifiers();
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(')');
if(attribute.isBoxed())
output.write(attribute.getUnBoxingCode());
output.write(';');
output.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when output stream is immediatly after a line break,
* and it should return the output stream after immediatly after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final Writer output, final JavaAttribute attribute)
throws IOException
{
final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter();
if(!exceptionsToCatch.isEmpty())
{
output.write("\t\ttry");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write('\t');
}
output.write("\t\tsetAttribute(this.");
output.write(attribute.getName());
final List qualifiers = attribute.getQualifiers();
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(',');
if(attribute.isBoxed())
output.write(attribute.getBoxingCode());
output.write(attribute.getName());
if(attribute.isBoxed())
output.write(')');
output.write(");");
output.write(lineSeparator);
if(!exceptionsToCatch.isEmpty())
{
output.write("\t\t}");
output.write(lineSeparator);
for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); )
writeViolationExceptionCatchClause(output, (Class)i.next());
}
}
private void writeViolationExceptionCatchClause(final Writer output, final Class exceptionClass)
throws IOException
{
output.write("\t\tcatch("+exceptionClass.getName()+" e)");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);");
output.write(lineSeparator);
output.write("\t\t}");
output.write(lineSeparator);
}
}
|
package fr.utc.assos.uvweb.io.base;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
/**
* A base UI-less fragment to easily manage async queries while being tight
* to the corresponding Activity or Fragment lifecycle.
* If the attached Activity or Fragment gets destroyed by a configuration
* change (like a rotation), the {@link Callbacks} reference needs to be updated
* using the {@code setCallCallbacks()} method.
*/
public abstract class BaseTaskFragment extends SherlockFragment {
public static final int THREAD_DEFAULT_POLICY = 0;
public static final int THREAD_POOL_EXECUTOR_POLICY = 1;
protected FragmentTask mTask;
private Callbacks mCallbacks;
private boolean mIsRunning;
public BaseTaskFragment() {
}
// Public API
public static <T extends BaseTaskFragment> T get(FragmentManager fm, Class<T> clazz) {
final String tag = clazz.getSimpleName();
T instance = clazz.cast(fm.findFragmentByTag(tag));
if (instance == null) {
try {
instance = clazz.newInstance();
fm.beginTransaction().add(instance, tag).commit();
} catch (java.lang.InstantiationException e) {
throw new IllegalArgumentException("Class must be instantiable");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Class must be accessible");
}
}
return instance;
}
public void startNewTask() {
startNewTask(THREAD_DEFAULT_POLICY);
}
public void startNewTask(final int threadMode) {
if (mTask != null) {
mTask.cancel(true);
mTask = null;
}
final Fragment target = getTargetFragment();
if (!(target instanceof Callbacks)) {
throw new IllegalStateException("Target fragment must implement Callbacks");
}
setCallbacks((Callbacks) target);
if (threadMode == THREAD_DEFAULT_POLICY) {
start();
} else if (threadMode == THREAD_POOL_EXECUTOR_POLICY) {
startOnThreadPoolExecutor();
} else {
throw new IllegalArgumentException("threadMode must be either THREAD_DEFAULT_POLICY" +
"or THREAD_POOL_EXECUTOR_POLICY");
}
}
public boolean isRunning() {
return mIsRunning;
}
// Lifecycle
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Callbacks) {
mCallbacks = (Callbacks) activity;
}
}
/**
* This method will only be called once when the retained
* Fragment is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
setUserVisibleHint(false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Fragment target = getTargetFragment();
if (target instanceof Callbacks) {
setCallbacks((Callbacks) target);
}
}
/**
* Set the callback to null so we don't accidentally leak the
* Fragment instance.
*/
@Override
public void onDetach() {
mCallbacks = null;
super.onDetach();
}
protected abstract void start();
protected abstract void startOnThreadPoolExecutor();
protected void setCallbacks(Callbacks callbacks) {
if (mTask != null && callbacks == null) {
mTask.cancel(true);
mTask = null;
}
mCallbacks = callbacks;
}
public interface Callbacks<Result> {
void onPreExecute();
void onPostExecute(Result result);
void onError();
}
public abstract class FragmentTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
protected static final String API_ENDPOINT = "http://192.168.0.15/Uvweb/web/app_dev.php/uv/app/";
@Override
protected void onPreExecute() {
if (mCallbacks != null) {
mCallbacks.onPreExecute();
}
mIsRunning = true;
}
@Override
@SuppressWarnings("unchecked")
protected void onPostExecute(Result result) {
mIsRunning = false;
if (mCallbacks != null) {
if (result == null) {
mCallbacks.onError();
} else {
mCallbacks.onPostExecute(result);
}
}
}
@Override
protected void onCancelled() {
mCallbacks = null;
mIsRunning = false;
}
}
}
|
package injection;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.lang.reflect.Modifier;
import persistence.SystemException;
import persistence.UniqueViolationException;
public final class Instrumentor implements InjectionConsumer
{
private final Writer output;
/**
* Holds several properties of the class currently
* worked on.
*/
private JavaClass class_state=null;
/**
* Collects the class states of outer classes,
* when operating on a inner class.
* @see #class_state
* @element-type InstrumentorClass
*/
private ArrayList class_state_stack=new ArrayList();
protected final String lineSeparator;
/**
* The last file level doccomment that was read.
*/
private String lastFileDocComment = null;
public Instrumentor(Writer output)
{
this.output=output;
final String systemLineSeparator = System.getProperty("line.separator");
if(systemLineSeparator==null)
{
System.out.println("warning: property \"line.separator\" is null, using LF (unix style).");
lineSeparator = "\n";
}
else
lineSeparator = systemLineSeparator;
}
public void onPackage(JavaFile javafile)
throws InjectorParseException
{
}
public void onImport(String importname)
{
}
private boolean discardnextfeature=false;
/**
* Tag name for persistent classes.
*/
private static final String PERSISTENT_CLASS = "persistent";
/**
* Tag name for persistent attributes.
*/
private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS;
/**
* Tag name for unique attributes.
*/
private static final String UNIQUE_ATTRIBUTE = "unique";
/**
* Tag name for read-only attributes.
*/
private static final String READ_ONLY_ATTRIBUTE = "read-only";
/**
* Tag name for one qualifier of qualified attributes.
*/
private static final String ATTRIBUTE_QUALIFIER = "qualifier";
/**
* All generated class features get this doccomment tag.
*/
private static final String GENERATED = "generated";
private void handleClassComment(final JavaClass jc, final String docComment)
{
if(containsTag(docComment, PERSISTENT_CLASS))
jc.setPersistent();
}
public void onClass(final JavaClass jc)
{
//System.out.println("onClass("+jc.getName()+")");
discardnextfeature=false;
class_state_stack.add(class_state);
class_state=jc;
if(lastFileDocComment != null)
{
handleClassComment(jc, lastFileDocComment);
lastFileDocComment = null;
}
}
private static final String lowerCamelCase(final String s)
{
final char first = s.charAt(0);
if(Character.isLowerCase(first))
return s;
else
return Character.toLowerCase(first) + s.substring(1);
}
private void writeParameterDeclarationList(final Collection parameters)
throws IOException
{
if(parameters!=null)
{
boolean first = true;
for(Iterator i = parameters.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
final String parameter = (String)i.next();
output.write("final ");
output.write(parameter);
output.write(' ');
output.write(lowerCamelCase(parameter));
}
}
}
private void writeParameterCallList(final Collection parameters)
throws IOException
{
if(parameters!=null)
{
boolean first = true;
for(Iterator i = parameters.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
final String parameter = (String)i.next();
output.write(lowerCamelCase(parameter));
}
}
}
private void writeThrowsClause(final Collection exceptions)
throws IOException
{
if(!exceptions.isEmpty())
{
output.write(" throws ");
boolean first = true;
for(final Iterator i = exceptions.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
output.write(',');
output.write(((Class)i.next()).getName());
}
}
}
private final void writeCommentHeader()
throws IOException
{
output.write("/**");
output.write(lineSeparator);
output.write(lineSeparator);
output.write("\t **");
output.write(lineSeparator);
}
private final void writeCommentFooter()
throws IOException
{
output.write("\t * @"+GENERATED);
output.write(lineSeparator);
output.write("\t *");
output.write(lineSeparator);
output.write(" */");
}
public void writeConstructor(final JavaClass javaClass)
throws IOException
{
writeCommentHeader();
output.write("\t * This is a generated constructor.");
output.write(lineSeparator);
writeCommentFooter();
output.write(Modifier.toString(javaClass.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)));
output.write(' ');
output.write(javaClass.getName());
output.write('(');
boolean first = true;
final ArrayList readOnlyAttributes = new ArrayList();
final TreeSet setterExceptions = new TreeSet();
for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); )
{
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
if(persistentAttribute.isReadOnly())
{
readOnlyAttributes.add(persistentAttribute);
setterExceptions.addAll(persistentAttribute.getSetterExceptions());
if(first)
first = false;
else
output.write(',');
output.write("final ");
output.write(persistentAttribute.getPersistentType());
output.write(' ');
output.write(persistentAttribute.getName());
}
}
output.write(')');
writeThrowsClause(setterExceptions);
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
output.write("\t\tsuper(1.0);");
output.write(lineSeparator);
for(Iterator i = readOnlyAttributes.iterator(); i.hasNext(); )
{
final JavaAttribute readOnlyAttribute = (JavaAttribute)i.next();
output.write("\t\tset");
output.write(readOnlyAttribute.getCamelCaseName());
output.write('(');
output.write(readOnlyAttribute.getName());
output.write(");");
output.write(lineSeparator);
}
output.write("\t}");
}
private void writeAccessMethods(final JavaAttribute persistentAttribute)
throws IOException
{
final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers());
final String type = persistentAttribute.getPersistentType();
final List qualifiers = persistentAttribute.getQualifiers();
// getter
writeCommentHeader();
output.write("\t * This is a generated getter method.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(' ');
output.write(type);
output.write(" get");
output.write(persistentAttribute.getCamelCaseName());
output.write('(');
writeParameterDeclarationList(qualifiers);
output.write(')');
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
writeGetterBody(output, persistentAttribute);
output.write("\t}");
// setter
writeCommentHeader();
output.write("\t * This is a generated setter method.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(" void set");
output.write(persistentAttribute.getCamelCaseName());
output.write('(');
if(qualifiers!=null)
{
writeParameterDeclarationList(qualifiers);
output.write(',');
}
output.write("final ");
output.write(type);
output.write(' ');
output.write(persistentAttribute.getName());
output.write(')');
writeThrowsClause(persistentAttribute.getSetterExceptions());
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
writeSetterBody(output, persistentAttribute);
output.write("\t}");
}
private void writeUniqueFinder(final JavaAttribute[] persistentAttributes)
throws IOException
{
final JavaAttribute persistentAttribute = persistentAttributes[0];
final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()|Modifier.STATIC);
final String type = persistentAttribute.getPersistentType();
final List qualifiers = persistentAttribute.getQualifiers();
final String name = persistentAttribute.getCamelCaseName();
writeCommentHeader();
output.write("\t * This is a generated unique finder method.");
output.write(lineSeparator);
writeCommentFooter();
output.write(methodModifiers);
output.write(' ');
output.write(persistentAttribute.getParent().getName());
output.write(" findBy");
output.write(name);
output.write('(');
if(qualifiers!=null)
{
writeParameterDeclarationList(qualifiers);
output.write(',');
}
output.write("final ");
output.write(type);
output.write(' ');
output.write(persistentAttribute.getName());
output.write(')');
output.write(lineSeparator);
output.write("\t{");
output.write(lineSeparator);
output.write("\t\treturn null;");
output.write(lineSeparator);
output.write("\t}");
}
public void onClassEnd(JavaClass jc)
throws IOException, InjectorParseException
{
//System.out.println("onClassEnd("+jc.getName()+")");
if(!jc.isInterface() && jc.isPersistent())
{
writeConstructor(jc);
for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); )
{
// write setter/getter methods
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
writeAccessMethods(persistentAttribute);
}
for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); )
{
// write unique finder methods
final JavaAttribute persistentAttribute = (JavaAttribute)i.next();
if(persistentAttribute.isUnique())
writeUniqueFinder(new JavaAttribute[]{persistentAttribute});
}
}
if(class_state!=jc)
throw new RuntimeException();
class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1));
}
public void onBehaviourHeader(JavaBehaviour jb)
throws java.io.IOException
{
output.write(jb.getLiteral());
}
public void onAttributeHeader(JavaAttribute ja)
{
}
public void onClassFeature(final JavaFeature jf, final String docComment)
throws IOException, InjectorParseException
{
//System.out.println("onClassFeature("+jf.getName()+" "+docComment+")");
if(!class_state.isInterface())
{
if(jf instanceof JavaAttribute &&
Modifier.isFinal(jf.getModifiers()) &&
Modifier.isStatic(jf.getModifiers()) &&
!discardnextfeature &&
containsTag(docComment, PERSISTENT_ATTRIBUTE))
{
final String type = jf.getType();
final String persistentType;
if("IntegerAttribute".equals(type))
persistentType = "Integer";
else if("StringAttribute".equals(type))
persistentType = "String";
else if("ItemAttribute".equals(type))
{
persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE);
}
else
throw new RuntimeException();
final JavaAttribute ja = (JavaAttribute)jf;
ja.makePersistent(persistentType);
if(containsTag(docComment, UNIQUE_ATTRIBUTE))
ja.makeUnique();
if(containsTag(docComment, READ_ONLY_ATTRIBUTE))
ja.makeReadOnly();
final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER);
if(qualifier!=null)
ja.makeQualified(Collections.singletonList(qualifier));
}
}
discardnextfeature=false;
}
public boolean onDocComment(String docComment)
throws IOException
{
//System.out.println("onDocComment("+docComment+")");
if(containsTag(docComment, GENERATED))
{
discardnextfeature=true;
return false;
}
else
{
output.write(docComment);
return true;
}
}
public void onFileDocComment(String docComment)
throws IOException
{
//System.out.println("onFileDocComment("+docComment+")");
output.write(docComment);
if (class_state != null)
{
// handle doccomment immediately
handleClassComment(class_state, docComment);
}
else
{
// remember to be handled as soon as we know what class we're talking about
lastFileDocComment = docComment;
}
}
public void onFileEnd()
{
if(!class_state_stack.isEmpty())
throw new RuntimeException();
}
private static final boolean containsTag(final String docComment, final String tagName)
{
return docComment!=null && docComment.indexOf('@'+tagName)>=0 ;
}
/**
* Identation contract:
* This methods is called, when output stream is immediatly after a line break,
* and it should return the output stream after immediatly after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeGetterBody(final Writer output, final JavaAttribute attribute)
throws IOException
{
output.write("\t\treturn (");
output.write(attribute.getPersistentType());
output.write(")getAttribute(this.");
output.write(attribute.getName());
final List qualifiers = attribute.getQualifiers();
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(");");
output.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when output stream is immediatly after a line break,
* and it should return the output stream after immediatly after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final Writer output, final JavaAttribute attribute)
throws IOException
{
if(!attribute.isUnique())
{
output.write("\t\ttry");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write('\t');
}
output.write("\t\tsetAttribute(this.");
output.write(attribute.getName());
final List qualifiers = attribute.getQualifiers();
if(qualifiers!=null)
{
output.write(",new Object[]{");
writeParameterCallList(qualifiers);
output.write('}');
}
output.write(',');
output.write(attribute.getName());
output.write(");");
output.write(lineSeparator);
if(!attribute.isUnique())
{
output.write("\t\t}");
output.write(lineSeparator);
output.write("\t\tcatch("+UniqueViolationException.class.getName()+" e)");
output.write(lineSeparator);
output.write("\t\t{");
output.write(lineSeparator);
output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);");
output.write(lineSeparator);
output.write("\t\t}");
output.write(lineSeparator);
}
}
}
|
package free.giTorto.operations;
import com.google.refine.browsing.Engine;
import com.google.refine.browsing.FilteredRows;
import com.google.refine.browsing.RowVisitor;
import com.google.refine.expr.EvalError;
import com.google.refine.history.Change;
import com.google.refine.history.HistoryEntry;
import com.google.refine.model.*;
import com.google.refine.model.changes.*;
import com.google.refine.operations.EngineDependentOperation;
import com.google.refine.operations.OperationRegistry;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Pattern;
/**
* @author Giuliano Tortoreto
*/
public class CoordToWktOperation extends EngineDependentOperation {
final Project project;
final JSONObject engineConfig;
final String columnName;
final HashMap<String,Object> data;
final String newColumnName;
public CoordToWktOperation(final Project project, JSONObject engineConfig, String columnName, HashMap<String, Object> data, boolean updateRowContextDependencies) {
super(engineConfig);
this.columnName = columnName;
this.data = data;
this.engineConfig = engineConfig;
this.project = project;
this.newColumnName = "WktObject of "+(String)data.get("latitude")+ "_" + (String)data.get("longitude");
}
static public AbstractOperation reconstruct(Project project, JSONObject obj) throws Exception {
JSONObject engineConfig = obj.getJSONObject("engineConfig");
String columName = obj.getString("columnName");
String latitude = obj.getString("latitude");
String longitude = obj.getString("longitude");
HashMap<String,Object> dati = new HashMap<String, Object>();
dati.put("longitude",longitude);
dati.put("latitude",latitude);
return new CoordToWktOperation(project, engineConfig, columName, dati, true);
}
protected RowVisitor createRowVisitor(Project project, Vector<CellAtRow> newCells) throws Exception {
Column column = project.columnModel.getColumnByName(columnName);
int latCell = project.columnModel.getColumnIndexByName((String)data.get("latitude"));
int lngCell = project.columnModel.getColumnIndexByName((String)data.get("longitude"));
return new RowVisitor() {
int latCell;
int lngCell;
Cell cell;
Vector<CellAtRow> cellsAtRows;
Pattern pattern;
String latitude;
String longitude;
CellAtRow newCell;
public RowVisitor init(int latCell,int lngCell, Vector<CellAtRow> cellAtRows) {
this.latCell = latCell;
this.lngCell = lngCell;
this.cellsAtRows = cellAtRows;
pattern = Pattern.compile("([-]?[\\d]*([\\.,][\\d]+)?)");
return this;
}
@Override
public void start(Project project) {
// nothing to do
}
@Override
public void end(Project project) {
// nothing to do
}
@Override
public boolean visit(Project project, int rowIndex, Row row) {
cell = row.getCell(latCell);
Serializable cellValue = cell == null ? null : cell.value;
latitude = cellValue == null ? "" : cellValue.toString().trim();
latitude = latitude.replaceAll("[\\s\\+]","");
cell = row.getCell(lngCell);
cellValue = cell == null ? null : cell.value;
longitude = cellValue == null ? "" : cellValue.toString().trim();
longitude = longitude.replaceAll("[\\s\\+]","");
if (!latitude.equals("") && !longitude.equals("") &&
pattern.matcher(latitude).matches() && pattern.matcher(longitude).matches()) {
newCell = new CellAtRow(rowIndex, new Cell("POINT (" + longitude + " " + latitude + ")", null));
}else{
newCell = new CellAtRow(rowIndex, new Cell(new EvalError("The latitude or/and longitude given are not a valid number"), null));
}
cellsAtRows.add(rowIndex, newCell);
return false;
}
}.init(latCell,lngCell, newCells);
}
@Override
public void write(JSONWriter writer, Properties options) throws JSONException {
writer.object();
writer.key("op"); writer.value(OperationRegistry.s_opClassToName.get(this.getClass()));
writer.key("description"); writer.value(getBriefDescription(null));
writer.key("engineConfig"); writer.value(getEngineConfig());
writer.key("columnName"); writer.value(columnName);
writer.key("latitude"); writer.value(data.get("latitude"));
writer.key("longitude"); writer.value(data.get("longitude"));
writer.endObject();
}
@Override
protected String getBriefDescription(Project project) {
return "Create "+ newColumnName + " based on column " + data.get("latitude") +
" and column " + data.get("longitude");
}
@Override
protected HistoryEntry createHistoryEntry(Project project, long historyEntryID) throws Exception {
Engine engine = createEngine(project);
Column column = project.columnModel.getColumnByName(columnName);
if (project.columnModel.getColumnByName(newColumnName) != null) {
throw new Exception("Another columnName already named " + newColumnName);
}
Vector<CellAtRow> cellsAtRows = new Vector<CellAtRow>(project.rows.size());
FilteredRows filteredRows = engine.getAllFilteredRows();
filteredRows.accept(project, createRowVisitor(project, cellsAtRows));
String description = createDescription(columnName, cellsAtRows);
Change change = new ColumnAdditionChange(newColumnName, column.getCellIndex()+1, cellsAtRows);
return new HistoryEntry(
historyEntryID, project, description, this, change);
}
private String createDescription(String column, Vector<CellAtRow> cellsAtRows) {
return "Creating a WKT-point from column " + data.get("latitude") + " and from " + data.get("longitude");
}
}
|
package com.github.gtache.settings.gui;
import com.github.gtache.client.MessageDialog;
import com.github.gtache.client.languageserver.serverdefinition.*;
import com.github.gtache.settings.LSPState;
import com.github.gtache.utils.Utils;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* The GUI for the LSP settings
*/
public class LSPGUI {
private static final String EXT_LABEL = "Extension";
private static final String EXT_TOOLTIP = "e.g. scala, java, c, js, ...";
private static final String EXT = "ext";
private static final String MAINCLASS = "mainclass";
private static final String ARGS = "args";
private static final String PACKGE = "packge";
private static final String COMMAND = "command";
private static final String PATH = "path";
private static final Logger LOG = Logger.getInstance(LSPGUI.class);
private final LSPState state;
private final JPanel rootPanel;
private final List<LSPGUIRow> rows = new ArrayList<>();
private final Map<String, UserConfigurableServerDefinition> serverDefinitions = new LinkedHashMap<>();
public LSPGUI() {
state = LSPState.getInstance();
rootPanel = new JPanel();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.Y_AXIS));
rootPanel.add(createArtifactRow("", "", "", ""));
}
public JPanel getRootPanel() {
return rootPanel;
}
public Collection<LSPGUIRow> getRows() {
return rows;
}
public void clear() {
rows.clear();
serverDefinitions.clear();
rootPanel.removeAll();
rootPanel.validate();
rootPanel.repaint();
}
public void addServerDefinition(UserConfigurableServerDefinition serverDefinition) {
if (serverDefinition != null) {
serverDefinitions.put(serverDefinition.ext(), serverDefinition);
if (serverDefinition.getClass().equals(ArtifactLanguageServerDefinition.class)) {
final ArtifactLanguageServerDefinition def = (ArtifactLanguageServerDefinition) serverDefinition;
rootPanel.add(createArtifactRow(def.ext(), def.packge(), def.mainClass(), Utils.arrayToString(def.args(), " ")));
} else if (serverDefinition.getClass().equals(ExeLanguageServerDefinition.class)) {
final ExeLanguageServerDefinition def = (ExeLanguageServerDefinition) serverDefinition;
rootPanel.add(createExeRow(def.ext(), def.path(), Utils.arrayToString(def.args(), " ")));
} else if (serverDefinition.getClass().equals(RawCommandServerDefinition.class)) {
final RawCommandServerDefinition def = (RawCommandServerDefinition) serverDefinition;
rootPanel.add(createCommandRow(def.ext(), Utils.arrayToString(def.command(), " ")));
} else {
LOG.error("Unknown UserConfigurableServerDefinition : " + serverDefinition);
}
}
}
public void apply() {
MessageDialog.main("The changes will be applied after restarting the IDE.");
serverDefinitions.clear();
for (final LSPGUIRow row : rows) {
final String[] arr = row.toStringArray();
final String ext = row.getText(EXT);
final UserConfigurableServerDefinition serverDefinition = UserConfigurableServerDefinition$.MODULE$.fromArray(arr);
if (serverDefinition != null) {
serverDefinitions.put(ext, serverDefinition);
}
}
LSPState.getInstance().setExtToServ(serverDefinitions);
}
public boolean isModified() {
if (serverDefinitions.size() == rows.stream().filter(row -> Arrays.stream(row.toStringArray()).skip(1).anyMatch(s -> s != null && !s.isEmpty())).collect(Collectors.toList()).size()) {
for (final LSPGUIRow row : rows) {
final UserConfigurableServerDefinition stateDef = serverDefinitions.get(row.getText(EXT));
final UserConfigurableServerDefinition rowDef = UserConfigurableServerDefinition$.MODULE$.fromArray(row.toStringArray());
if (rowDef != null && !rowDef.equals(stateDef)) {
return true;
}
}
return false;
} else {
return true;
}
}
public void reset() {
this.clear();
if (state.getExtToServ() != null) {
for (UserConfigurableServerDefinition serverDefinition : state.getExtToServ().values()) {
addServerDefinition(serverDefinition);
}
}
}
private JComboBox<String> createComboBox(final JPanel panel, final String selected) {
final JComboBox<String> typeBox = new ComboBox<>();
final ConfigurableTypes[] types = ConfigurableTypes.values();
for (final ConfigurableTypes type : types) {
typeBox.addItem(type.getTyp());
}
typeBox.setSelectedItem(selected);
typeBox.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
final int idx = getComponentIndex(panel);
if (e.getItem().equals(ConfigurableTypes.ARTIFACT.getTyp())) {
rootPanel.add(createArtifactRow("", "", "", ""), idx);
rootPanel.remove(panel);
rows.remove(idx);
} else if (e.getItem().equals(ConfigurableTypes.RAWCOMMAND.getTyp())) {
rootPanel.add(createCommandRow("", ""), idx);
rootPanel.remove(panel);
rows.remove(idx);
} else if (e.getItem().equals(ConfigurableTypes.EXE.getTyp())) {
rootPanel.add(createExeRow("", "", ""), idx);
rootPanel.remove(panel);
rows.remove(idx);
} else {
LOG.error("Unknown type : " + e.getItem());
}
}
});
return typeBox;
}
private JButton createNewRowButton() {
final JButton newRowButton = new JButton();
newRowButton.setText("+");
newRowButton.addActionListener(e -> rootPanel.add(createArtifactRow("", "", "", "")));
return newRowButton;
}
private JButton createRemoveRowButton(final JPanel panel) {
final JButton removeRowButton = new JButton();
removeRowButton.setText("-");
removeRowButton.addActionListener(e -> {
final int idx = getComponentIndex(panel);
rootPanel.remove(panel);
rows.remove(idx);
});
return removeRowButton;
}
private JPanel createRow(final List<JComponent> labelFields, final String selectedItem) {
final JPanel panel = new JPanel();
int colIdx = 0;
panel.setLayout(new GridLayoutManager(2, 17, JBUI.emptyInsets(), -1, -1));
panel.add(new Spacer(), new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, 1, GridConstraints.SIZEPOLICY_FIXED, new Dimension(0, 10), new Dimension(0, 10), new Dimension(0, 10), 0, false));
final JComboBox<String> typeBox = createComboBox(panel, selectedItem);
panel.add(typeBox, new GridConstraints(0, colIdx++, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Iterator<JComponent> iterator = labelFields.iterator();
while (iterator.hasNext()) {
final JComponent label = iterator.next();
final JComponent field = iterator.next();
panel.add(new Spacer(), new GridConstraints(0, colIdx++, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
panel.add(label, new GridConstraints(0, colIdx++, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
panel.add(field, new GridConstraints(0, colIdx++, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
}
panel.add(new Spacer(), new GridConstraints(0, 14, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JButton newRowButton = createNewRowButton();
panel.add(newRowButton, new GridConstraints(0, 15, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
if (rows.isEmpty()) {
panel.add(new Spacer(), new GridConstraints(0, 16, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
} else {
final JButton removeRowButton = createRemoveRowButton(panel);
panel.add(removeRowButton, new GridConstraints(0, 16, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
return panel;
}
private JPanel createArtifactRow(final String ext, final String serv, final String mainClass, final String args) {
final JLabel extLabel = new JLabel(EXT_LABEL);
final JTextField extField = new JTextField();
extField.setToolTipText(EXT_TOOLTIP);
extField.setText(ext);
final JLabel packgeLabel = new JLabel("Artifact");
final JTextField packgeField = new JTextField();
packgeField.setToolTipText("e.g. ch.epfl.lamp:dotty-language-server_0.3:0.3.0-RC2");
packgeField.setText(serv);
final JLabel mainClassLabel = new JLabel("Main class");
final JTextField mainClassField = new JTextField();
mainClassField.setToolTipText("e.g. dotty.tools.languageserver.Main");
mainClassField.setText(mainClass);
final JLabel argsLabel = new JLabel("Args");
final JTextField argsField = new JTextField();
argsField.setToolTipText("e.g. -stdio");
argsField.setText(args);
final List<JComponent> components = Arrays.asList(extLabel, extField, packgeLabel, packgeField, mainClassLabel, mainClassField, argsLabel, argsField);
final JPanel panel = createRow(components, ArtifactLanguageServerDefinition$.MODULE$.getPresentableTyp());
final scala.collection.mutable.LinkedHashMap<String, JComponent> map = new scala.collection.mutable.LinkedHashMap<>();
map.put(EXT, extField);
map.put(PACKGE, packgeField);
map.put(MAINCLASS, mainClassField);
map.put(ARGS, argsField);
rows.add(new LSPGUIRow(panel, ArtifactLanguageServerDefinition$.MODULE$.typ(), map));
return panel;
}
private JPanel createExeRow(final String ext, final String path, final String args) {
final JLabel extLabel = new JLabel(EXT_LABEL);
final JTextField extField = new JTextField();
extField.setToolTipText(EXT_TOOLTIP);
extField.setText(ext);
final JLabel pathLabel = new JLabel("Path");
final JTextField pathField = new JTextField();
pathField.setToolTipText("e.g. C:\\rustLS\\rls.exe");
pathField.setText(path);
final JLabel argsLabel = new JLabel("Args");
final JTextField argsField = new JTextField();
argsField.setToolTipText("e.g. -stdio");
argsField.setText(args);
final List<JComponent> components = Arrays.asList(extLabel, extField, pathLabel, pathField, argsLabel, argsField);
final JPanel panel = createRow(components, ExeLanguageServerDefinition$.MODULE$.getPresentableTyp());
final scala.collection.mutable.LinkedHashMap<String, JComponent> map = new scala.collection.mutable.LinkedHashMap<>();
map.put(EXT, extField);
map.put(PATH, pathField);
map.put(ARGS, argsField);
rows.add(new LSPGUIRow(panel, ExeLanguageServerDefinition$.MODULE$.typ(), map));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
return panel;
}
private JPanel createCommandRow(final String ext, final String command) {
final JLabel extLabel = new JLabel(EXT_LABEL);
final JTextField extField = new JTextField();
extField.setToolTipText(EXT_TOOLTIP);
extField.setText(ext);
final JLabel commandLabel = new JLabel("Command");
final JTextField commandField = new JTextField();
commandField.setText(command);
commandField.setToolTipText("e.g. python.exe -m C:\\python-ls\\pyls");
final List<JComponent> components = Arrays.asList(extLabel, extField, commandLabel, commandField);
final JPanel panel = createRow(components, RawCommandServerDefinition$.MODULE$.getPresentableTyp());
final scala.collection.mutable.LinkedHashMap<String, JComponent> map = new scala.collection.mutable.LinkedHashMap<>();
map.put(EXT, extField);
map.put(COMMAND, commandField);
rows.add(new LSPGUIRow(panel, RawCommandServerDefinition$.MODULE$.typ(), map));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
return panel;
}
private int getComponentIndex(final JComponent component) {
for (int i = 0; i < rootPanel.getComponentCount(); ++i) {
if (rootPanel.getComponent(i).equals(component)) {
return i;
}
}
return -1;
}
}
|
package org.intermine.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.RAMDirectory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.MetadataManager;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreSummary;
import org.intermine.util.TypeUtil;
import org.intermine.web.config.WebConfig;
/**
* Initialiser for the InterMine web application
* Anything that needs global initialisation goes here.
*
* @author Andrew Varley
*/
public class InitialiserPlugin implements PlugIn
{
private static final Logger LOG = Logger.getLogger(InitialiserPlugin.class);
ProfileManager profileManager;
/**
* Init method called at Servlet initialisation
*
* @param servlet ActionServlet that is managing all the modules
* in this web application
* @param config ModuleConfig for the module with which this
* plug-in is associated
*
* @throws ServletException if this <code>PlugIn</code> cannot
* be successfully initialized
*/
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
ServletContext servletContext = servlet.getServletContext();
loadWebProperties(servletContext);
loadExampleQueries(servletContext);
ObjectStore os = null;
try {
os = ObjectStoreFactory.getObjectStore();
} catch (Exception e) {
throw new ServletException("Unable to instantiate ObjectStore", e);
}
servletContext.setAttribute(Constants.OBJECTSTORE, os);
loadWebConfig(servletContext, os);
loadClassCategories(servletContext, os);
loadClassDescriptions(servletContext, os);
summarizeObjectStore(servletContext, os);
createProfileManager(servletContext, os);
// Loading shared template queries requires profile manager
loadSuperUserDetails(servletContext);
// Load global template queries from superuser account
loadGlobalTemplateQueries(servletContext);
// Build lucene index
createTemplateIndex(servletContext);
}
/**
* Load the displayer configuration
*/
private void loadWebConfig(ServletContext servletContext, ObjectStore os)
throws ServletException {
InputStream is = servletContext.getResourceAsStream("/WEB-INF/webconfig-model.xml");
if (is == null) {
throw new ServletException("Unable to find webconfig-model.xml");
}
try {
servletContext.setAttribute(Constants.WEBCONFIG,
WebConfig.parse(is, os.getModel()));
} catch (Exception e) {
throw new ServletException("Unable to parse webconfig-model.xml", e);
}
}
/**
* Load the user-friendly class descriptions
*/
private void loadClassDescriptions(ServletContext servletContext, ObjectStore os)
throws ServletException {
Properties classDescriptions = null;
try {
classDescriptions = MetadataManager.loadClassDescriptions(os.getModel().getName());
} catch (Exception e) {
throw new ServletException("Error loading class descriptions", e);
}
servletContext.setAttribute("classDescriptions", classDescriptions);
}
/**
* Read the example queries into the EXAMPLE_QUERIES servlet context attribute.
*/
private void loadWebProperties(ServletContext servletContext) throws ServletException {
Properties webProperties = new Properties();
InputStream globalPropertiesStream =
servletContext.getResourceAsStream("/WEB-INF/global.web.properties");
try {
webProperties.load(globalPropertiesStream);
} catch (Exception e) {
throw new ServletException("Unable to find global.web.properties", e);
}
InputStream modelPropertiesStream =
servletContext.getResourceAsStream("/WEB-INF/web.properties");
if (modelPropertiesStream == null) {
// there are no model specific properties
} else {
try {
webProperties.load(modelPropertiesStream);
} catch (Exception e) {
throw new ServletException("Unable to find web.properties", e);
}
}
servletContext.setAttribute(Constants.WEB_PROPERTIES, webProperties);
}
/**
* Summarize the ObjectStore to get class counts
*/
private void summarizeObjectStore(ServletContext servletContext, ObjectStore os)
throws ServletException {
Properties objectStoreSummaryProperties = new Properties();
InputStream objectStoreSummaryPropertiesStream =
servletContext.getResourceAsStream("/WEB-INF/objectstoresummary.properties");
if (objectStoreSummaryPropertiesStream == null) {
// there are no model specific properties
} else {
try {
objectStoreSummaryProperties.load(objectStoreSummaryPropertiesStream);
} catch (Exception e) {
throw new ServletException("Unable to read objectstoresummary.properties", e);
}
}
ObjectStoreSummary oss = new ObjectStoreSummary(objectStoreSummaryProperties);
Model model = os.getModel();
Map classes = new LinkedHashMap();
Map classCounts = new LinkedHashMap();
for (Iterator i = new TreeSet(model.getClassNames()).iterator(); i.hasNext();) {
String className = (String) i.next();
classes.put(className, TypeUtil.unqualifiedName(className));
try {
//classCounts.put(className, new Integer(1));
classCounts.put(className, new Integer(oss.getClassCount(className)));
} catch (Exception e) {
throw new ServletException("Unable to get class count for " + className, e);
}
}
servletContext.setAttribute(Constants.OBJECT_STORE_SUMMARY, oss);
servletContext.setAttribute("classes", classes);
servletContext.setAttribute("classCounts", classCounts);
}
/**
* Read the example queries into the EXAMPLE_QUERIES servlet context attribute.
*/
private void loadExampleQueries(ServletContext servletContext) throws ServletException {
InputStream exampleQueriesStream =
servletContext.getResourceAsStream("/WEB-INF/example-queries.xml");
if (exampleQueriesStream == null) {
return;
}
Reader exampleQueriesReader = new InputStreamReader(exampleQueriesStream);
Map exampleQueries = null;
try {
exampleQueries = new PathQueryBinding().unmarshal(exampleQueriesReader);
} catch (Exception e) {
throw new ServletException("Unable to parse example-queries.xml", e);
}
servletContext.setAttribute(Constants.EXAMPLE_QUERIES, exampleQueries);
}
/**
* Loads the default template queries into the superuser's account.
*
* @param servletContext current servlet context
*/
private void loadDefaultGlobalTemplateQueries(ServletContext servletContext)
throws ServletException {
InputStream templateQueriesStream =
servletContext.getResourceAsStream("/WEB-INF/template-queries.xml");
if (templateQueriesStream == null) {
return;
}
Reader templateQueriesReader = new InputStreamReader(templateQueriesStream);
Map templateQueries = null;
try {
templateQueries = new TemplateQueryBinding().unmarshal(templateQueriesReader);
} catch (Exception e) {
throw new ServletException("Unable to parse template-queries.xml", e);
}
// Add them to superuser profile
String superuser = (String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT);
ProfileManager pm = (ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER);
if (superuser == null) {
LOG.warn("No superuser account specified");
return;
}
Profile profile = null;
if (!pm.hasProfile(superuser)) {
LOG.info("Creating profile for superuser " + superuser);
profile = new Profile(pm, superuser, new HashMap(), new HashMap(), new HashMap());
String password = RequestPasswordAction.generatePassword();
Map webProperties = (Map) servletContext.getAttribute(Constants.WEB_PROPERTIES);
pm.saveProfile(profile);
pm.setPassword(superuser, password);
} else {
profile = pm.getProfile(superuser, pm.getPassword(superuser));
}
if (profile.getSavedTemplates().size() == 0) {
Iterator iter = templateQueries.values().iterator();
while (iter.hasNext()) {
TemplateQuery template = (TemplateQuery) iter.next();
profile.saveTemplate(template.getName(), template);
}
}
}
/**
* Load superuser account name into servlet context attribute SUPERUSER_ACCOUNT
*
* @param servetContext servlet context in which to place attribute
*/
private void loadSuperUserDetails(ServletContext servletContext)
throws ServletException {
Properties properties = new Properties();
InputStream propertiesStream =
servletContext.getResourceAsStream("/WEB-INF/global.web.properties");
try {
properties.load(propertiesStream);
} catch (Exception e) {
throw new ServletException("Unable to find model.properties", e);
}
String superuser = properties.getProperty("superuser.account");
servletContext.setAttribute(Constants.SUPERUSER_ACCOUNT, superuser);
}
/**
* Create the lucene search index of all global template queries.
* @param servletContext the servlet context
* @throws ServletException if something goes wrong
*/
private static void createTemplateIndex(ServletContext servletContext)
throws ServletException {
long time = System.currentTimeMillis();
LOG.info("Indexing template queries");
RAMDirectory ram = new RAMDirectory();
IndexWriter writer;
try {
writer = new IndexWriter(ram, new StandardAnalyzer(), true);
} catch (IOException err) {
throw new ServletException("Failed to create lucene IndexWriter", err);
}
// step through global templates, indexing a Document for
// each template
Map templates = (Map) servletContext.getAttribute(Constants.GLOBAL_TEMPLATE_QUERIES);
Iterator iter = templates.values().iterator();
while (iter.hasNext()) {
TemplateQuery template = (TemplateQuery) iter.next();
Document doc = new Document();
doc.add(Field.Text("name", template.getName()));
doc.add(Field.Text("description", template.getDescription()));
doc.add(Field.Keyword("category", template.getCategory()));
// TODO
//doc.add(Field.Keyword("keywords", template.getKeywords()));
try {
writer.addDocument(doc);
} catch (IOException e) {
LOG.error("Failed to add template " + template.getName()
+ " to the index", e);
}
}
time = System.currentTimeMillis() - time;
LOG.info("Finished indexing templates (took " + time + " milliseconds)");
}
/**
* Read the template queries into the GLOBAL_TEMPLATE_QUERIES servlet context attribute and set
* CATEGORY_TEMPLATES and CLASS_CATEGORY_TEMPLATES.
* This is also called when the superuser updates his or her templates.
*
* @param servletContext servlet context in which to place template map
* @throws ServletException if something goes wrong
*/
public static void loadGlobalTemplateQueries(ServletContext servletContext)
throws ServletException {
Map templateMap = Collections.synchronizedMap(new HashMap());
ProfileManager pm = (ProfileManager) servletContext.getAttribute(Constants.PROFILE_MANAGER);
String superuser = (String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT);
if (superuser != null && pm.hasProfile(superuser)) {
Profile profile = pm.getProfile(superuser, pm.getPassword(superuser));
if (profile != null) {
templateMap = Collections.synchronizedMap(new TreeMap(profile.getSavedTemplates()));
} else {
LOG.warn("failed to getch profile for superuser " + superuser);
}
} else {
LOG.warn("superuser.account not specified");
}
servletContext.setAttribute(Constants.GLOBAL_TEMPLATE_QUERIES, templateMap);
// Sort into categories
Map categoryTemplates = new HashMap();
// a Map from class name to a Map from category to template
Map classCategoryTemplates = new HashMap();
// a Map from class name to a Map from template name to field name List - the field
// names/expressions are the ones that should be set when a template is linked to from the
// object details page eg. Gene.identifier
Map classTemplateExprs = new HashMap();
Iterator iter = templateMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
TemplateQuery template = (TemplateQuery) entry.getValue();
List list = (List) categoryTemplates.get(template.getCategory());
if (list == null) {
list = new ArrayList();
categoryTemplates.put(template.getCategory(), list);
}
list.add(template);
Object osObject = servletContext.getAttribute(Constants.OBJECTSTORE);
ObjectStore os = (ObjectStore) osObject;
setClassesForTemplate(os, template, classCategoryTemplates, classTemplateExprs);
}
servletContext.setAttribute(Constants.CATEGORY_TEMPLATES, categoryTemplates);
servletContext.setAttribute(Constants.CLASS_CATEGORY_TEMPLATES, classCategoryTemplates);
servletContext.setAttribute(Constants.CLASS_TEMPLATE_EXPRS, classTemplateExprs);
}
/**
* Return two Maps with information about the relations between classnames, a given template and
* its template categories.
* @param classCategoryTemplates a Map from class name to a Map from category to template
* @param classTemplateExprs a Map from class name to a Map from template name to field name
* List - the field names/expressions are the ones that should be set when a template is linked
* to from the object details page eg. Gene.identifier
*/
private static void setClassesForTemplate(ObjectStore os, TemplateQuery template,
Map classCategoryTemplates,
Map classTemplateExprs) {
List constraints = template.getAllConstraints();
Model model = os.getModel();
Iterator constraintIter = constraints.iterator();
// look for ClassName.fieldname (Gene.identifier)
// or ClassName.fieldname.fieldname.fieldname... (eg. Gene.organism.name)
while (constraintIter.hasNext()) {
Constraint c = (Constraint) constraintIter.next();
String constraintIdentifier = c.getIdentifier();
String[] bits = constraintIdentifier.split("\\.");
if (bits.length == 2) {
String className = model.getPackageName() + "." + bits[0];
String fieldName = bits[1];
String fieldExpr = TypeUtil.unqualifiedName(className) + "." + fieldName;
ClassDescriptor cd = model.getClassDescriptorByName(className);
if (cd != null && cd.getFieldDescriptorByName(fieldName) != null) {
Set subClasses = model.getAllSubs(cd);
Set thisAndSubClasses = new HashSet();
thisAndSubClasses.addAll(subClasses);
thisAndSubClasses.add(cd);
Iterator thisAndSubClassesIterator = thisAndSubClasses.iterator();
while (thisAndSubClassesIterator.hasNext()) {
ClassDescriptor thisCD = (ClassDescriptor) thisAndSubClassesIterator.next();
String thisClassName = thisCD.getName();
if (!classCategoryTemplates.containsKey(thisClassName)) {
classCategoryTemplates.put(thisClassName, new HashMap());
}
Map categoryTemplatesMap = (Map) classCategoryTemplates.get(thisClassName);
if (!categoryTemplatesMap.containsKey(template.getCategory())) {
categoryTemplatesMap.put(template.getCategory(), new ArrayList());
}
((List) categoryTemplatesMap.get(template.getCategory())).add(template);
if (!classTemplateExprs.containsKey(thisClassName)) {
classTemplateExprs.put(thisClassName, new HashMap());
}
Map fieldNameTemplatesMap = (Map) classTemplateExprs.get(thisClassName);
if (!fieldNameTemplatesMap.containsKey(template.getName())) {
fieldNameTemplatesMap.put(template.getName(), new ArrayList());
}
((List) fieldNameTemplatesMap.get(template.getName())).add(fieldExpr);
}
}
}
}
}
/**
* Load the CATEGORY_CLASSES and CATEGORIES servlet context attribute. Loads cateogires and
* subcateogires from roperties file /WEB-INF/classCategories.properties<p>
*
* The properties file should look something like:
* <pre>
* category.0.name = People
* category.0.subcategories = Employee Manager CEO Contractor Secretary
* category.1.name = Entities
* category.1.subcategories = Bank Address Department
* </pre>
*
* If a specified class cannot be found in the model, the class is ignored and not added to
* the category.
*
* @param servletContext the servlet context
* @param os the main object store
*/
private void loadClassCategories(ServletContext servletContext, ObjectStore os)
throws ServletException {
List categories = new ArrayList();
Map subcategories = new HashMap();
InputStream in = servletContext.getResourceAsStream("/WEB-INF/classCategories.properties");
if (in == null) {
return;
}
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException err) {
throw new ServletException(err);
}
int n = 0;
String catname;
while ((catname = properties.getProperty("category." + n + ".name")) != null) {
String sc = properties.getProperty("category." + n + ".classes");
String subcats[] = StringUtils.split(sc, ' ');
List subcatlist = new ArrayList();
subcats = StringUtils.stripAll(subcats);
for (int i = 0; subcats != null && i < subcats.length; i++) {
String className = os.getModel().getPackageName() + "." + subcats[i];
if (os.getModel().hasClassDescriptor(className)) {
subcatlist.add(subcats[i]);
} else {
LOG.warn("Category \"" + catname + "\" contains unknown class \"" + subcats[i]
+ "\"");
}
}
categories.add(catname);
subcategories.put(catname, subcatlist);
n++;
}
servletContext.setAttribute(Constants.CATEGORIES, categories);
servletContext.setAttribute(Constants.CATEGORY_CLASSES, subcategories);
}
/**
* Create the profile manager and place it into to the servlet context.
*/
private void createProfileManager(ServletContext servletContext, ObjectStore os)
throws ServletException {
try {
profileManager = new ProfileManager(os);
} catch (ObjectStoreException e) {
//throw new ServletException("Unable to create profile manager", e);
}
servletContext.setAttribute(Constants.PROFILE_MANAGER, profileManager);
}
/**
* Destroy method called at Servlet destroy
*/
public void destroy() {
try {
profileManager.close();
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
}
}
|
package gov.nih.nci.nautilus.test;
import gov.nih.nci.nautilus.criteria.ArrayPlatformCriteria;
import gov.nih.nci.nautilus.criteria.AssayPlatformCriteria;
import gov.nih.nci.nautilus.criteria.CloneOrProbeIDCriteria;
import gov.nih.nci.nautilus.criteria.Constants;
import gov.nih.nci.nautilus.criteria.CopyNumberCriteria;
import gov.nih.nci.nautilus.criteria.FoldChangeCriteria;
import gov.nih.nci.nautilus.criteria.GeneIDCriteria;
import gov.nih.nci.nautilus.de.ArrayPlatformDE;
import gov.nih.nci.nautilus.de.AssayPlatformDE;
import gov.nih.nci.nautilus.de.CloneIdentifierDE;
import gov.nih.nci.nautilus.de.CopyNumberDE;
import gov.nih.nci.nautilus.de.ExprFoldChangeDE;
import gov.nih.nci.nautilus.de.GeneIdentifierDE;
import gov.nih.nci.nautilus.query.ComparativeGenomicQuery;
import gov.nih.nci.nautilus.query.CompoundQuery;
import gov.nih.nci.nautilus.query.GeneExpressionQuery;
import gov.nih.nci.nautilus.query.OperatorType;
import gov.nih.nci.nautilus.query.Query;
import gov.nih.nci.nautilus.query.QueryManager;
import gov.nih.nci.nautilus.query.QueryType;
import gov.nih.nci.nautilus.queryprocessing.ge.GeneExpr;
import gov.nih.nci.nautilus.resultset.DimensionalViewContainer;
import gov.nih.nci.nautilus.resultset.ResultSet;
import gov.nih.nci.nautilus.resultset.Resultant;
import gov.nih.nci.nautilus.resultset.ResultsContainer;
import gov.nih.nci.nautilus.resultset.ResultsetManager;
import gov.nih.nci.nautilus.resultset.copynumber.CopyNumberSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.gene.GeneExprSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.sample.SampleResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleViewResultsContainer;
import gov.nih.nci.nautilus.view.ViewFactory;
import gov.nih.nci.nautilus.view.ViewType;
import gov.nih.nci.nautilus.view.Viewable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author Himanso
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class CompoundQueryTest extends TestCase {
ArrayPlatformCriteria allPlatformCrit;
ArrayPlatformCriteria affyOligoPlatformCrit;
ArrayPlatformCriteria cdnaPlatformCrit;
AssayPlatformCriteria snpPlatformCrit;
CloneOrProbeIDCriteria cloneCrit;
CloneOrProbeIDCriteria probeCrit;
GeneIDCriteria geneCrit;
FoldChangeCriteria foldCrit;
GeneExpressionQuery probeQuery;
GeneExpressionQuery cloneQuery;
GeneExpressionQuery geneQuery;
ComparativeGenomicQuery genomicQuery;
CopyNumberCriteria copyNumberCrit;
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
buildPlatformCrit();
buildFoldChangeCrit();
buildCloneCrit();
buildProbeCrit();
buildGeneIDCrit();
buildGeneExprCloneSingleViewQuery();
buildGeneExprProbeSetSingleViewQuery();
buildGeneExprGeneSingleViewQuery();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public void testSingleQueryInCompoundQueryProcessor() {
try {
//test Single Query
System.out.println("Testing Single Gene Query>>>>>>>>>>>>>>>>>>>>>>>");
CompoundQuery myCompoundQuery = new CompoundQuery(geneQuery);
Resultant resultant = ResultsetManager.executeQuery(myCompoundQuery);
System.out.println("SingleQuery:\n"+ myCompoundQuery.toString());
print(resultant);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testCompoundQueryANDProcessor() {
try {
//test CompoundQuery Query
System.out.println("Testing CompoundQuery GeneQuery AND ProbeQuery>>>>>>>>>>>>>>>>>>>>>>>");
CompoundQuery myCompoundQuery = new CompoundQuery(OperatorType.AND,geneQuery,probeQuery);
Resultant resultant = ResultsetManager.executeQuery(myCompoundQuery);
System.out.println("CompoundQuery:\n"+ myCompoundQuery.toString());
print(resultant);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testCompoundQueryNOTProcessor() {
try {
//test CompoundQuery Query
System.out.println("Testing CompoundQuery GeneQuery NOT ProbeQuery>>>>>>>>>>>>>>>>>>>>>>>");
CompoundQuery myCompoundQuery = new CompoundQuery(OperatorType.NOT,geneQuery,probeQuery);
Resultant resultant = ResultsetManager.executeQuery(myCompoundQuery);
System.out.println("CompoundQuery:\n"+ myCompoundQuery.toString());
print(resultant);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testCompoundQueryORProcessor() {
try {
//test CompoundQuery Query
System.out.println("Testing CompoundQuery CloneQuery OR ProbeQuery>>>>>>>>>>>>>>>>>>>>>>>");
CompoundQuery myCompoundQuery = new CompoundQuery(OperatorType.OR,cloneQuery,probeQuery);
Resultant resultant = ResultsetManager.executeQuery(myCompoundQuery);
System.out.println("CompoundQuery:\n"+ myCompoundQuery.toString());
print(resultant);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testGeneExprANDCopyNumberQuery() {
try {
//test CompoundQuery Query
System.out.println("Testing CompoundQuery GeneExprQuery AND GenomicQuery>>>>>>>>>>>>>>>>>>>>>>>");
CompoundQuery myCompoundQuery = new CompoundQuery(OperatorType.OR,geneQuery,genomicQuery);
Resultant resultant = ResultsetManager.executeQuery(myCompoundQuery);
System.out.println("CompoundQuery:\n"+ myCompoundQuery.toString());
print(resultant);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param geneExprObjects
*/
private void print(Resultant resultant) {
if(resultant != null){
ResultsContainer resultsContainer = resultant.getResultsContainer();
if (resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
GeneExprSingleViewResultsContainer geneViewContainer = dimensionalViewContainer.getGeneExprSingleViewContainer();
if (geneViewContainer != null){
displayGeneExprSingleView(geneViewContainer);
SampleViewResultsContainer sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
displaySampleView(sampleViewContainer);
}
}
else if (resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
CopyNumberSingleViewResultsContainer copyNumberContainer = dimensionalViewContainer.getCopyNumberSingleViewContainer();
if (copyNumberContainer != null){
displayCopyNumberSingleView(copyNumberContainer);
SampleViewResultsContainer sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
displaySampleView(sampleViewContainer);
}
}
else if (resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
GeneExprSingleViewResultsContainer geneViewContainer = dimensionalViewContainer.getGeneExprSingleViewContainer();
if (geneViewContainer != null){
displayGeneExprSingleView(geneViewContainer);
SampleViewResultsContainer sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
displaySampleView(sampleViewContainer);
}
}
}
}
private void displaySampleView(SampleViewResultsContainer sampleViewContainer){
System.out.println("Printing Sample View for the Query >>>>>>>>>>>>>>>>>>>>>>>");
Collection samples = sampleViewContainer.getBioSpecimenResultsets();
System.out.println("SAMPLE\tAGE\tGENDER\tSURVIVAL\tDISEASE");
StringBuffer stringBuffer = new StringBuffer();
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset)sampleIterator.next();
System.out.println(sampleResultset.getBiospecimen().getValue()+
"\t"+sampleResultset.getAgeGroup().getValue()+
"\t"+sampleResultset.getGenderCode().getValue()+
"\t"+sampleResultset.getSurvivalLengthRange().getValue()+
"\t"+sampleResultset.getDisease().getValue());
}
}
private void displayCopyNumberSingleView(CopyNumberSingleViewResultsContainer copyNumberContainer) {
final DecimalFormat resultFormat = new DecimalFormat("0.00");
Collection cytobands = copyNumberContainer.getCytobandResultsets();
Collection labels = copyNumberContainer.getGroupsLabels();
Collection sampleIds = null;
StringBuffer header = new StringBuffer();
StringBuffer sampleNames = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
//get group size (as Disease or Agegroup )from label.size
System.out.println("Printing Copy Number View>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println("GroupSize= "+labels.size());
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
System.out.println(label);
sampleIds = copyNumberContainer.getBiospecimenLabels(label);
//For each group get the number of samples in it from sampleIds.size()
System.out.println("SampleSize= "+sampleIds.size());
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
System.out.println(sampleIdIterator.next());
}
}
}
private void displayGeneExprSingleView(GeneExprSingleViewResultsContainer geneViewContainer){
final DecimalFormat resultFormat = new DecimalFormat("0.00");
Collection genes = geneViewContainer.getGeneResultsets();
Collection labels = geneViewContainer.getGroupsLabels();
Collection sampleIds = null;
StringBuffer header = new StringBuffer();
StringBuffer sampleNames = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
//get group size (as Disease or Agegroup )from label.size
System.out.println("Printing Gene Expr View>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println("GroupSize= "+labels.size());
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
System.out.println(label);
sampleIds = geneViewContainer.getBiospecimenLabels(label);
//For each group get the number of samples in it from sampleIds.size()
System.out.println("SampleSize= "+sampleIds.size());
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
System.out.println(sampleIdIterator.next());
}
}
}
public static Test suite() {
TestSuite suit = new TestSuite();
suit.addTest(new TestSuite(CompoundQueryTest.class));
return suit;
}
public static void main (String[] args) {
junit.textui.TestRunner.run(suite());
}
public void testExecute() {
}
private void buildProbeCrit() {
probeCrit = new CloneOrProbeIDCriteria();
//1555146_at is a probeSet for ATF2
probeCrit.setCloneIdentifier(new CloneIdentifierDE.ProbesetID("1555146_at"));
}
private void buildCloneCrit() {
cloneCrit = new CloneOrProbeIDCriteria();
//IMAGE:2014733 is a CloneID for AFT2
cloneCrit.setCloneIdentifier(new CloneIdentifierDE.IMAGEClone("IMAGE:2014733"));
}
private void buildGeneIDCrit() {
geneCrit = new GeneIDCriteria();
//Both IMAGE:2014733 and 1555146_at should be subsets of ATF2
geneCrit.setGeneIdentifier(new GeneIdentifierDE.GeneSymbol("ATF2"));
}
private void buildFoldChangeCrit() {
Float upRegExpected = new Float(2.0);
Float downRegExpected = new Float(1.0);
ExprFoldChangeDE.UpRegulation upRegObj = new ExprFoldChangeDE.UpRegulation(upRegExpected );
ExprFoldChangeDE.DownRegulation downRegObj = new ExprFoldChangeDE.DownRegulation(downRegExpected );
//ExprFoldChangeDE.UnChangedRegulationUpperLimit upUnChangedObj = new ExprFoldChangeDE.UnChangedRegulationUpperLimit(upperUnchangedExpected );
//ExprFoldChangeDE.UnChangedRegulationDownLimit downUnChangedRegObj = new ExprFoldChangeDE.UnChangedRegulationDownLimit(downUnChangedExpected );
foldCrit = new FoldChangeCriteria();
Collection objs = new ArrayList(4);
objs.add(upRegObj);
objs.add(downRegObj);
//objs.add(upUnChangedObj); objs.add(downUnChangedRegObj);
foldCrit.setFoldChangeObjects(objs);
}
private void buildCopyChangeCrit() {
Float amplification = new Float(2.0);
Float deletion = new Float(0.8);
CopyNumberDE.Amplification ampObj = new CopyNumberDE.Amplification(amplification );
CopyNumberDE.Deletion deletionObj = new CopyNumberDE.Deletion(deletion);
CopyNumberDE.UnChangedCopyNumberUpperLimit upCopyNumberObj = new CopyNumberDE.UnChangedCopyNumberUpperLimit(amplification);
CopyNumberDE.UnChangedCopyNumberDownLimit downCopyNumberObj = new CopyNumberDE.UnChangedCopyNumberDownLimit(deletion);
copyNumberCrit = new CopyNumberCriteria();
Collection objs = new ArrayList(4);
objs.add(ampObj);
//objs.add(deletionObj);
//objs.add(upCopyNumberObj); objs.add(downCopyNumberObj);
copyNumberCrit.setCopyNumbers(objs);
}
private void buildGeneExprProbeSetSingleViewQuery(){
probeQuery = (GeneExpressionQuery) QueryManager.createQuery(QueryType.GENE_EXPR_QUERY_TYPE);
probeQuery.setQueryName("ProbeSetQuery");
probeQuery.setAssociatedView(ViewFactory.newView(ViewType.GENE_SINGLE_SAMPLE_VIEW));
probeQuery.setCloneOrProbeIDCrit(probeCrit);
probeQuery.setArrayPlatformCrit(affyOligoPlatformCrit);
probeQuery.setFoldChgCrit(foldCrit);
}
private void buildGeneExprCloneSingleViewQuery(){
cloneQuery = (GeneExpressionQuery) QueryManager.createQuery(QueryType.GENE_EXPR_QUERY_TYPE);
cloneQuery.setQueryName("CloneQuery");
cloneQuery.setAssociatedView(ViewFactory.newView(ViewType.GENE_SINGLE_SAMPLE_VIEW));
cloneQuery.setCloneOrProbeIDCrit(cloneCrit);
cloneQuery.setArrayPlatformCrit(cdnaPlatformCrit);
cloneQuery.setFoldChgCrit(foldCrit);
}
private void buildGeneExprGeneSingleViewQuery(){
geneQuery = (GeneExpressionQuery) QueryManager.createQuery(QueryType.GENE_EXPR_QUERY_TYPE);
geneQuery.setQueryName("GeneQuery");
geneQuery.setAssociatedView(ViewFactory.newView(ViewType.GENE_SINGLE_SAMPLE_VIEW));
geneQuery.setGeneIDCrit(geneCrit);
geneQuery.setArrayPlatformCrit(allPlatformCrit);
geneQuery.setFoldChgCrit(foldCrit);
}
private void buildCopyNumberSingleViewQuery(){
genomicQuery = (ComparativeGenomicQuery) QueryManager.createQuery(QueryType.CGH_QUERY_TYPE);
genomicQuery.setQueryName("CopyNumberQuery");
genomicQuery.setAssociatedView(ViewFactory.newView(ViewType.COPYNUMBER_GROUP_SAMPLE_VIEW));
genomicQuery.setGeneIDCrit(geneCrit);
genomicQuery.setAssayPlatformCrit(snpPlatformCrit);
genomicQuery.setCopyNumberCrit(copyNumberCrit);
}
private void buildPlatformCrit() {
allPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.ALL_PLATFROM));
affyOligoPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.AFFY_OLIGO_PLATFORM));
cdnaPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.CDNA_ARRAY_PLATFORM));
snpPlatformCrit = new AssayPlatformCriteria();
snpPlatformCrit.setAssayPlatformDE(new AssayPlatformDE(Constants.AFFY_100K_SNP_ARRAY));
}
private void changeQueryView(Query query,Viewable view){
if(query !=null){
query.setAssociatedView(view);
}
}
}
|
package codeOrchestra.colt.as;
import codeOrchestra.colt.as.controller.COLTAsController;
import codeOrchestra.colt.as.logging.transport.LoggerServerSocketThread;
import codeOrchestra.colt.as.model.COLTAsProject;
import codeOrchestra.colt.as.model.ModelStorage;
import codeOrchestra.colt.as.model.util.ProjectImporter;
import codeOrchestra.colt.as.rpc.impl.COLTAsRemoteServiceImpl;
import codeOrchestra.colt.as.run.ASLiveLauncher;
import codeOrchestra.colt.as.session.sourcetracking.ASSourceFileFactory;
import codeOrchestra.colt.as.ui.TestMainApp;
import codeOrchestra.colt.as.util.ASPathUtils;
import codeOrchestra.colt.core.AbstractLiveCodingLanguageHandler;
import codeOrchestra.colt.core.LiveCodingManager;
import codeOrchestra.colt.core.ServiceProvider;
import codeOrchestra.colt.core.controller.COLTController;
import codeOrchestra.colt.core.launch.LiveLauncher;
import codeOrchestra.colt.core.logging.LoggerService;
import codeOrchestra.colt.core.rpc.COLTRemoteService;
import codeOrchestra.colt.core.session.sourcetracking.SourceFileFactory;
import codeOrchestra.colt.core.ui.components.COLTProgressIndicatorController;
import codeOrchestra.colt.core.ui.components.FxThreadCOLTProgressIndicatorWrapper;
import codeOrchestra.colt.core.ui.components.ICOLTProgressIndicator;
import codeOrchestra.colt.core.ui.components.sessionIndicator.SessionIndicatorController;
import codeOrchestra.util.StringUtils;
import groovy.util.slurpersupport.GPathResult;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import java.io.File;
/**
* @author Alexander Eliseyev
*/
public class ASLiveCodingLanguageHandler extends AbstractLiveCodingLanguageHandler<COLTAsProject> {
private LoggerServerSocketThread loggerServerSocketThread = new LoggerServerSocketThread();
private LoggerService loggerService;
@Override
public String getId() {
return "AS";
}
@Override
public String getName() {
return "ActionScript";
}
@Override
public COLTAsProject parseProject(GPathResult gPathResult, String projectPath) {
COLTAsProject project = ModelStorage.getInstance().getProject();
project.clear();
project.setPath(projectPath);
project.buildModel(gPathResult);
// Default settings
if (StringUtils.isEmpty(project.getProjectBuildSettings().sdkModel.getFlexSDKPath())) {
project.getProjectBuildSettings().sdkModel.setFlexSDKPath(ASPathUtils.getFlexSDKPath());
}
// Prepare dirs
project.initPaths();
return project;
}
@Override
public COLTAsProject createProject(String pName, File pFile) {
COLTAsProject project = ModelStorage.getInstance().getProject();
project.clear();
project.setName(pName);
project.setPath(pFile.getPath());
// Prepare dirs
project.initPaths();
return project;
}
@Override
public COLTAsProject importProject(File file) {
COLTAsProject project = ProjectImporter.importProject(file);
// Prepare dirs
project.initPaths();
return project;
}
@Override
public COLTAsProject getCurrentProject() {
return ModelStorage.getInstance().getProject();
}
@Override
public void initHandler() {
loggerServerSocketThread.openSocket();
ServiceProvider.get(LiveCodingManager.class).addListener(SessionIndicatorController.getInstance());
}
@Override
public void disposeHandler() {
loggerServerSocketThread.closeSocket();
ServiceProvider.get(LiveCodingManager.class).removeListener(SessionIndicatorController.getInstance());
}
@Override
public LoggerService getLoggerService() {
return loggerService;
}
public void setLoggerService(LoggerService loggerService) {
this.loggerService = loggerService;
}
@Override
public Node getPane() throws Exception {
return FXMLLoader.load(TestMainApp.class.getResource("main_app.fxml"));
}
@Override
public ICOLTProgressIndicator getProgressIndicator() {
return new FxThreadCOLTProgressIndicatorWrapper(COLTProgressIndicatorController.getInstance());
}
@Override
public COLTController<COLTAsProject> createCOLTController() {
return new COLTAsController();
}
@Override
public COLTRemoteService<COLTAsProject> createRPCService() {
return new COLTAsRemoteServiceImpl();
}
@Override
public LiveLauncher<COLTAsProject> createLauncher() {
return new ASLiveLauncher();
}
@Override
public LiveCodingManager<COLTAsProject> createLiveCodingManager() {
return new ASLiveCodingManager();
}
@Override
public SourceFileFactory createSourceFileFactory() {
return new ASSourceFileFactory();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.