diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/adsim/handler/FloodingReplayer.java b/src/main/java/adsim/handler/FloodingReplayer.java
index 3e73635..727b8c4 100644
--- a/src/main/java/adsim/handler/FloodingReplayer.java
+++ b/src/main/java/adsim/handler/FloodingReplayer.java
@@ -1,69 +1,69 @@
package adsim.handler;
import java.util.Collections;
import lombok.*;
import adsim.core.INodeHandler;
import adsim.core.Message;
import adsim.core.Message.TellNeighbors;
import adsim.core.Node;
import adsim.core.Session;
/**
* 定期的にバッファのメッセージを順番に送信します。
*/
public class FloodingReplayer extends NodeHandlerBase {
private int index;
public FloodingReplayer() {
this(0);
}
// Copy constructor
private FloodingReplayer(int index) {
this.index = index;
}
@Override
public void initialize(Node node) {
// Do nothing
}
@Override
public void interval(Session sess, Node node) {
for (val msg : node.getCreatedMessages()) {
node.pushMessage(msg);
}
node.getCreatedMessages().clear();
val buffer = node.getBuffer();
if (!buffer.isEmpty()) {
- val nextPointer = (index + 1) % buffer.size();
+ val nextPointer = (index++) % buffer.size();
node.broadcast(buffer.get(nextPointer));
}
}
private void onTellNeighbors(Node self, TellNeighbors msg) {
val buffer = self.getBuffer();
for (val nbEntry : msg.getEntries()) {
for (val bufMsg : buffer) {
if (bufMsg.getToId().equals(nbEntry.getSender())) {
self.broadcast(bufMsg);
}
}
}
}
@Override
public void onReceived(Node self, Message packet) {
if (packet.getType() == Message.TYPE_TELLNEIGHBORS) {
val tn = (TellNeighbors) packet;
onTellNeighbors(self, tn);
}
}
@Override
public INodeHandler clone() {
return new FloodingReplayer(index);
}
}
| true | true | public void interval(Session sess, Node node) {
for (val msg : node.getCreatedMessages()) {
node.pushMessage(msg);
}
node.getCreatedMessages().clear();
val buffer = node.getBuffer();
if (!buffer.isEmpty()) {
val nextPointer = (index + 1) % buffer.size();
node.broadcast(buffer.get(nextPointer));
}
}
| public void interval(Session sess, Node node) {
for (val msg : node.getCreatedMessages()) {
node.pushMessage(msg);
}
node.getCreatedMessages().clear();
val buffer = node.getBuffer();
if (!buffer.isEmpty()) {
val nextPointer = (index++) % buffer.size();
node.broadcast(buffer.get(nextPointer));
}
}
|
diff --git a/src/main/us/exultant/ahs/thread/WorkFuture.java b/src/main/us/exultant/ahs/thread/WorkFuture.java
index 325d59d..519235d 100644
--- a/src/main/us/exultant/ahs/thread/WorkFuture.java
+++ b/src/main/us/exultant/ahs/thread/WorkFuture.java
@@ -1,321 +1,324 @@
package us.exultant.ahs.thread;
import us.exultant.ahs.core.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
/**
* Produced internally by some WorkScheduler implementations for bookkeeping and return to
* the function that scheduled a task.
*
* Note that there is (currently) no hardcoded rule that a WorkTarget instance may only be
* submitted once to a single WorkScheduler and thus have exactly one paired WorkFuture
* object... but it's the only case the system is designed for, so sane results are not
* guaranteed if one does otherwise.
*
* @author hash
*
* @param <$V>
*/
class WorkFuture<$V> implements Future<$V> {
public WorkFuture(WorkTarget<$V> $wt, ScheduleParams $schedp) {
this.$work = $wt;
this.$schedp = $schedp;
this.$sync = new Sync();
}
final Sync $sync;
/** The underlying callable */
final WorkTarget<$V> $work;
/** The parameters with which the work target was scheduled. */
private final ScheduleParams $schedp;
/** Set to true when someone calls the cancel method. Never again becomes false. If there's currently a thread from the scheduler working on this, it must eventually notice this and deal with it; if there is no thread running this, the cancelling thread may act immediately. */
volatile boolean $cancelPlz = false;
/** The result to return from get(). Need not be volatile or synchronized since the value is only important when it is idempotent, which is once $state has made its own final idempotent transition. */
private $V $result = null;
/** The (already wrapped) exception to throw from get(). Need not be volatile or synchronized since the value is only important when it is idempotent, which is once $state has made its own final idempotent transition. */
private ExecutionException $exception = null;
/** Index into delay queue, to support faster updates. */
int $heapIndex = 0;
/** When nulled after set/cancel, this indicates that the results are accessible. */
volatile Thread $runner;
private volatile Listener<WorkFuture<$V>> $completionListener; //FIXME:AHS:THREAD: um, we need to be able to set this before the task starts or it's not very useful. Oh. Or we set it, then check for concurrent completion, then signal it. And forbid setting more than once?
WorkTarget<$V> getWorkTarget() { // this can't be public because giving out a WorkFuture to untrusted code isn't supposed to give that code the ability to call call() on the WT.
return $work;
}
public State getState() {
return $sync.getWFState();
}
public ScheduleParams getScheduleParams() {
return $schedp;
}
public boolean isCancelled() {
return getState() == State.CANCELLED;
}
public boolean isDone() {
switch (getState()) {
case FINISHED: return true;
case CANCELLED: return true;
default: return false;
}
}
public $V get() throws InterruptedException, ExecutionException, CancellationException {
$sync.waitForDone();
return $sync.get();
}
public $V get(long $timeout, TimeUnit $unit) throws InterruptedException, ExecutionException, TimeoutException, CancellationException {
$sync.waitForDone($unit.toNanos($timeout));
return $sync.get();
}
public boolean cancel(boolean $mayInterruptIfRunning) {
return $sync.cancel($mayInterruptIfRunning);
}
public static enum State {
/**
* the work has not identified itself as having things to do immediately,
* so it will not be scheduled.
*
* Note! This is <b>independent</b> of whether or not
* {@link WorkTarget#isReady()} returns true at any given time! The
* contract of the {@link WorkTarget#isReady()} method allows it to toggle
* at absolutely any time and with no synchronization whatsoever. This
* state enum refers only to what the {@link WorkScheduler} has most
* recently noticed (typically during invocation of the
* {@link WorkScheduler#update(WorkFuture)} method).
*/
WAITING, // this actually has to be ordinal zero due to the silliness in AQS
/**
* The {@link WorkScheduler} has found the WorkTarget of this Future to
* be ready, and has queued it for execution. The WorkFuture will be
* shifted to {@link #RUNNING} when it reaches the top of the
* WorkScheduler's queue of {@link #SCHEDULED} work (unless at that time
* {@link WorkTarget#isReady()} is no longer true, in which case this
* WorkFuture will be shifted back to {@link #WAITING}).
*/
SCHEDULED,
/**
* The {@link WorkScheduler} that produced this WorkFuture has put a
* thread onto the job and it has stack frames in the execution of the
* work.
*/
RUNNING,
///**
// * the work was running, but made a blocking call which returned thread
// * power to the scheduler. The thread that was running this WorkTarget
// * still has stack frames in the work, but the entire thread is paused in
// * a blocking call under the management of the WorkScheduler (which has
// * launched the activity of another thread to compensate for this thread's
// * inactivity, and will wake this thread and return it to RUNNING state as
// * soon as the task it is currently blocked on completes and any one of
// * the other then-RUNNING threads completes its task). not currently used.
// */
//PARKED,
/**
* The {@link WorkTarget#isDone()} method returned true after the last
* time a thread acting on behalf of this Future's {@link WorkScheduler}
* pushed the WorkTarget; the WorkTarget will no longer be scheduled for
* future activation, and the final result of the execution —
* whether it be a return value or an exception — is now available
* for immediate return via the {@link WorkFuture#get()} method. An
* exception thrown from the {@link WorkTarget#call()} method will also
* result in this Future becoming FINISHED, but the
* {@link WorkTarget#isDone()} method may still return false.
*/
FINISHED,
/**
* The work was cancelled via the {@link WorkFuture#cancel(boolean)}
* method before it could become {@link #FINISHED}. The work may have
* previously been {@link #RUNNING}, but will now no longer be scheduled
* for future activations. Since the cancellation was the result of an
* external operation rather than of the WorkTarget's own volition, the
* WorkTarget's {@link WorkTarget#isDone()} method may still return false.
*/
CANCELLED;
private final static State[] values = State.values();
}
/** Uses AQS sync state to represent run status. */
final class Sync extends AbstractQueuedSynchronizer {
Sync() {}
State getWFState() {
return State.values[getState()];
}
/** Implements AQS base acquire to succeed if finished or cancelled */
protected int tryAcquireShared(int $ignore) {
return isDone() ? 1 : -1;
}
/** Implements AQS base release to always signal after setting final done status by nulling runner thread. */
protected boolean tryReleaseShared(int $ignore) {
$runner = null;
// we don't call the completion listener here because this can be hit more than once; the thread nulling just works because it's essentially idempotent in this context
return true;
}
void waitForDone() throws InterruptedException {
acquireSharedInterruptibly(0);
}
void waitForDone(long $nanosTimeout) throws InterruptedException, TimeoutException {
if (!tryAcquireSharedNanos(0, $nanosTimeout)) throw new TimeoutException();
}
$V get() throws ExecutionException, CancellationException { // this could also be implemented in the outer class, but it's ever so slightly more efficient to use the int state here instead of go through the array lookup. probably. i dunno, maybe that even gets optimized out by a good enough jvm.
if (getState() == State.CANCELLED.ordinal()) throw new CancellationException(); // TODO:AHS:THREAD: consider what you want from your contract here. perhaps we should still return the last result? but then that complicates concurrency significantly, since that would mean we can only set the result field if we've locked out cancels. We could do it; use a higher-order bit of the state of the AQS perhaps, without actually changing the State we report to the rest of the program. Iono.
if ($exception != null) throw $exception;
return $result;
}
protected void hearDone() {} //TODO:AHS:THREAD: implement this later to punt off to a Listener
boolean cancel(boolean $mayInterruptIfRunning) {
for (;;) {
int $s = getState();
if ($s == State.FINISHED.ordinal()) return false;
if ($s == State.CANCELLED.ordinal()) return false;
if (compareAndSetState($s, State.CANCELLED.ordinal())) break;
}
if ($mayInterruptIfRunning) {
Thread $r = $runner;
if ($r != null) $r.interrupt();
}
releaseShared(0);
hearDone();
return true;
}
/**
* Checks the state of this WorkFuture. Changes only occur if the
* WorkFuture is currently WAITING and should become SCHEDULED. If the
* task is clock-based, only delay is checked; otherwise, only
* $work.isReady() is checked.
*
* If this method returns false, it may merely because the task isn't
* ready or is delayed, but it may also be because the task is FINISHED or
* CANCELLED, which is something the caller is advised to check.
*
* @return true if the scheduler must now remove the WF from the waiting
* pool (or delayed heap) and push it into the scheduled heap.
*/
//FIXME:AHS:THREAD: we have to notice doneness eventually even if no update was called and isReady is now returning false because it's done! it's a bit troublesome since we'll never bubble to the top of the scheduled heap. though really, the most straightforward fix isn't at all wrong: just run low-priority low-frequency fixed-rate task that calls update on all of the stuff in the waiting pool. only question with that is who decides exactly what priority and how rate that should be, since it's clearly one of those things we're really only want one of per vm.
boolean scheduler_shift() {
if ($schedp.isUnclocked() ? $work.isReady() : $schedp.getDelay() <= 0) return compareAndSetState(State.WAITING.ordinal(), State.SCHEDULED.ordinal());
// the CAS will occur if:
// - the task if delay-free (if clocked) or ready (if unclocked).
// if this is not the case, obviously we won't be switching out of waiting state.
// the CAS will fail and reture false if:
// - we're FINISHED (if this happened at the end of the task's last run, this task should have stayed in the scheduler to get to this call again. but it could have happened concurrently as a result of a thread outside the scheduler calling an update on a task that become done concurrently (close of a data source for example).)
// - we've been CANCELLED concurrently
return false;
}
/**
* Causes the current thread to take ownership of the task and power it.
*
* @return true if all went well and the task can be put back in a heap
* for more action later; false if there was a finish or
* concurrent cancel that the scheduler must respond to (by
* dropping the task).
*/
boolean scheduler_power() {
if (!compareAndSetState(State.SCHEDULED.ordinal(), State.RUNNING.ordinal())) {
// we were concurrently cancelled. weep.
return false;
}
$runner = Thread.currentThread();
if (getState() == State.RUNNING.ordinal()) { // recheck after setting thread
try {
$result = $work.call();
// the saved result here can be a little weird for any task that's not one-shot. we can't reliably differentiate between the run that made us done, or being already done when the run started, because we can't lock that... so we can't reliably ensure that what's returned by the last run before finishing isn't already something that's allowed to be insane according to the contract of WorkTarget.
} catch (Throwable $t) {
$exception = new ExecutionException($t);
tryFinish(true);
return false;
}
- boolean $waiting = compareAndSetState(State.RUNNING.ordinal(), State.WAITING.ordinal());
- if ($work.isDone()) tryFinish(true);
+ boolean $waiting = compareAndSetState(State.RUNNING.ordinal(), State.WAITING.ordinal()); // this has to be done before checking the work's doneness, because otherwise we could check doneness, get false... while another thread sends a doneness update and trys to finish us but is rejected because we're running... and then we, already having checked doneness, begin our CAS to WAITING. that'd be a fail.
+ if ($work.isDone()) {
+ tryFinish(true);
+ return false; // even if tryFinish failed and returned false, since we're the running thread, that still means the task is finished (just that we weren't the ones to make it happen).
+ }
if ($waiting) $schedp.setNextRunTime();
return $waiting;
} else {
releaseShared(0); // there was a concurrent cancel or finish. (note that this will result in null'ing $runner via tryReleaseShared(int).)
return false;
}
}
boolean tryFinish(final boolean $iAmTheRunner) {
// these come as a standard check whenever a shift returns false, or whenever an update call (from any thread!) noticed isDone was true. (whenever a scheduler completes a run of a task and notices doneness is ever so slightly separate because it transitions directly from RUNNING to FINISHED.)
// because this method is package-protected, we're going to assume that you've checked isDone before calling this, and that it was true. (Sure, most people's isDone method is pretty cheap, but we're going to shoot for savings/contention-avoidance here anyway.)
// WE MUST BLOCK CONCURRENT FINISHES IF WE'RE RUNNING. because that's insane. we have to set the answer of our current run. and things often become "done" as data sources when they give us their last thing, but that clearly doesn't mean we're finished yet and shouldn't report the results of that last data piece.
for (;;) {
int $s = getState();
if ($s == State.FINISHED.ordinal())
return false; // we're already done, obviously there's nothing to do here. (we notice this in particular since we don't want to double-sent the done notification to listeners, nor invoke ridiculous releases).
if ($s == State.CANCELLED.ordinal()) {
releaseShared(0); // aggressively release to set runner to null, in case we are racing with a cancel request that will try to interrupt runner
return false; // we're letting the cancel go though (though trying to dodge any interrupts the cancellation might have requested).
}
if ($s == State.RUNNING.ordinal())
if ($iAmTheRunner); // it's kay, we can continue to the finishing since this is our job.
else return false; // the working thread will deal with noticing doneness again when it's completed its cycle.
// $s is either SCHEDULED or WAITING
if (compareAndSetState($s, State.FINISHED.ordinal())) {
releaseShared(0);
hearDone();
return true;
}
}
}
}
public static class PriorityComparator implements Comparator<WorkFuture<?>> {
public static final PriorityComparator INSTANCE = new PriorityComparator();
public int compare(WorkFuture<?> $o1, WorkFuture<?> $o2) {
return $o1.$work.getPriority() - $o2.$work.getPriority();
}
}
public static class DelayComparator implements Comparator<WorkFuture<?>> {
public static final DelayComparator INSTANCE = new DelayComparator();
public int compare(WorkFuture<?> $o1, WorkFuture<?> $o2) {
long $diff = $o1.$schedp.getNextRunTime() - $o2.$schedp.getNextRunTime();
if ($diff < 0) return -1;
if ($diff > 0) return 1;
return 0;
}
}
}
| true | true | boolean scheduler_power() {
if (!compareAndSetState(State.SCHEDULED.ordinal(), State.RUNNING.ordinal())) {
// we were concurrently cancelled. weep.
return false;
}
$runner = Thread.currentThread();
if (getState() == State.RUNNING.ordinal()) { // recheck after setting thread
try {
$result = $work.call();
// the saved result here can be a little weird for any task that's not one-shot. we can't reliably differentiate between the run that made us done, or being already done when the run started, because we can't lock that... so we can't reliably ensure that what's returned by the last run before finishing isn't already something that's allowed to be insane according to the contract of WorkTarget.
} catch (Throwable $t) {
$exception = new ExecutionException($t);
tryFinish(true);
return false;
}
boolean $waiting = compareAndSetState(State.RUNNING.ordinal(), State.WAITING.ordinal());
if ($work.isDone()) tryFinish(true);
if ($waiting) $schedp.setNextRunTime();
return $waiting;
} else {
releaseShared(0); // there was a concurrent cancel or finish. (note that this will result in null'ing $runner via tryReleaseShared(int).)
return false;
}
}
| boolean scheduler_power() {
if (!compareAndSetState(State.SCHEDULED.ordinal(), State.RUNNING.ordinal())) {
// we were concurrently cancelled. weep.
return false;
}
$runner = Thread.currentThread();
if (getState() == State.RUNNING.ordinal()) { // recheck after setting thread
try {
$result = $work.call();
// the saved result here can be a little weird for any task that's not one-shot. we can't reliably differentiate between the run that made us done, or being already done when the run started, because we can't lock that... so we can't reliably ensure that what's returned by the last run before finishing isn't already something that's allowed to be insane according to the contract of WorkTarget.
} catch (Throwable $t) {
$exception = new ExecutionException($t);
tryFinish(true);
return false;
}
boolean $waiting = compareAndSetState(State.RUNNING.ordinal(), State.WAITING.ordinal()); // this has to be done before checking the work's doneness, because otherwise we could check doneness, get false... while another thread sends a doneness update and trys to finish us but is rejected because we're running... and then we, already having checked doneness, begin our CAS to WAITING. that'd be a fail.
if ($work.isDone()) {
tryFinish(true);
return false; // even if tryFinish failed and returned false, since we're the running thread, that still means the task is finished (just that we weren't the ones to make it happen).
}
if ($waiting) $schedp.setNextRunTime();
return $waiting;
} else {
releaseShared(0); // there was a concurrent cancel or finish. (note that this will result in null'ing $runner via tryReleaseShared(int).)
return false;
}
}
|
diff --git a/Evoting/src/com/rau/evoting/beans/MixNode.java b/Evoting/src/com/rau/evoting/beans/MixNode.java
index a7c3594..68fed9a 100644
--- a/Evoting/src/com/rau/evoting/beans/MixNode.java
+++ b/Evoting/src/com/rau/evoting/beans/MixNode.java
@@ -1,122 +1,122 @@
package com.rau.evoting.beans;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.mail.MessagingException;
import com.rau.evoting.ElGamal.ElGamalHelper;
import com.rau.evoting.data.ElectionDP;
import com.rau.evoting.data.ElectionTrusteeDP;
import com.rau.evoting.data.ElectionVoteDP;
import com.rau.evoting.models.CutVote;
import com.rau.evoting.models.Election;
import com.rau.evoting.models.Trustee;
import com.rau.evoting.utils.MailService;
import com.rau.evoting.utils.Util;
public class MixNode {
private Trustee trustee;
private boolean validToken;
private ArrayList<CutVote> votes;
private boolean showReEncrypt;
private boolean showThankYou;
public MixNode() {
Map<String, String> reqMap = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap();
validToken = true;
showReEncrypt = false;
showThankYou = false;
if (reqMap.containsKey("token")) {
int trId = Integer.valueOf(reqMap.get("trId"));
String token = reqMap.get("token");
trustee = ElectionTrusteeDP.getElectionTrustee(trId);
if (!trustee.getToken().equals(token)) {
validToken = false;
} else {
validToken = true;
votes = ElectionVoteDP.getCutVotes(trustee.getElectId(), trustee.getMixServer()-1);
}
}
}
public String shuffle() {
Util.shuffle(votes);
showReEncrypt = true;
return "";
}
public String reencrypt() {
Election election = ElectionDP.getElection(trustee.getElectId());
ElGamalHelper gamal = new ElGamalHelper(trustee.getPublicKey());
for (CutVote vote : votes) {
- vote.setAnswersSequence(gamal.encodeBigInt(vote
+ vote.setAnswersSequence(gamal.reEncodeBigInt(vote
.getAnswersSequence())); // change to reencrypt
}
ElectionVoteDP.updateCutVotes(votes, election.getId(), trustee.getMixServer()-1);
ElectionDP.setElectionMixStage(election.getId(), trustee.getMixServer());
Trustee tr = ElectionTrusteeDP.getTrusteeByMixServer(trustee.getElectId(), trustee.getMixServer()+1);
if(tr == null) {
ElectionDP.setElectionDecode(election.getId());
//send mail to all trustees make async!!!!!
List<Trustee> trustees = ElectionTrusteeDP.getElectionTrustees(election.getId());
String message = "Please follow this link to upload your private key and decode election votes: \n";
String title = "Trustee for " + election.getName() + " election";
String url = "http://localhost:8080/Evoting/DecodeVotes.xhtml?elId=" + election.getId();
for(Trustee t : trustees) {
url += "&trId=" + t.getId() + "&token=" + t.getToken();
message += url;
try {
MailService.sendMessage(t.getEmail(), title, message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} else {
String title = "Trustee for " + election.getName() + " election";
String message = "Please follow this link to open your mix node: \n";
String url ="http://localhost:8080/Evoting/MixNode.xhtml?trId=" + tr.getId() + "&token=" + tr.getToken();
message += url;
try {
MailService.sendMessage(tr.getEmail(), title, message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
showThankYou = true;
return "";
}
public boolean isValidToken() {
return validToken;
}
public void setValidToken(boolean validToken) {
this.validToken = validToken;
}
public boolean isShowReEncrypt() {
return showReEncrypt;
}
public void setShowReEncrypt(boolean showReEncrypt) {
this.showReEncrypt = showReEncrypt;
}
public boolean isShowThankYou() {
return showThankYou;
}
public void setShowThankYou(boolean showThankYou) {
this.showThankYou = showThankYou;
}
}
| true | true | public String reencrypt() {
Election election = ElectionDP.getElection(trustee.getElectId());
ElGamalHelper gamal = new ElGamalHelper(trustee.getPublicKey());
for (CutVote vote : votes) {
vote.setAnswersSequence(gamal.encodeBigInt(vote
.getAnswersSequence())); // change to reencrypt
}
ElectionVoteDP.updateCutVotes(votes, election.getId(), trustee.getMixServer()-1);
ElectionDP.setElectionMixStage(election.getId(), trustee.getMixServer());
Trustee tr = ElectionTrusteeDP.getTrusteeByMixServer(trustee.getElectId(), trustee.getMixServer()+1);
if(tr == null) {
ElectionDP.setElectionDecode(election.getId());
//send mail to all trustees make async!!!!!
List<Trustee> trustees = ElectionTrusteeDP.getElectionTrustees(election.getId());
String message = "Please follow this link to upload your private key and decode election votes: \n";
String title = "Trustee for " + election.getName() + " election";
String url = "http://localhost:8080/Evoting/DecodeVotes.xhtml?elId=" + election.getId();
for(Trustee t : trustees) {
url += "&trId=" + t.getId() + "&token=" + t.getToken();
message += url;
try {
MailService.sendMessage(t.getEmail(), title, message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} else {
String title = "Trustee for " + election.getName() + " election";
String message = "Please follow this link to open your mix node: \n";
String url ="http://localhost:8080/Evoting/MixNode.xhtml?trId=" + tr.getId() + "&token=" + tr.getToken();
message += url;
try {
MailService.sendMessage(tr.getEmail(), title, message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
showThankYou = true;
return "";
}
| public String reencrypt() {
Election election = ElectionDP.getElection(trustee.getElectId());
ElGamalHelper gamal = new ElGamalHelper(trustee.getPublicKey());
for (CutVote vote : votes) {
vote.setAnswersSequence(gamal.reEncodeBigInt(vote
.getAnswersSequence())); // change to reencrypt
}
ElectionVoteDP.updateCutVotes(votes, election.getId(), trustee.getMixServer()-1);
ElectionDP.setElectionMixStage(election.getId(), trustee.getMixServer());
Trustee tr = ElectionTrusteeDP.getTrusteeByMixServer(trustee.getElectId(), trustee.getMixServer()+1);
if(tr == null) {
ElectionDP.setElectionDecode(election.getId());
//send mail to all trustees make async!!!!!
List<Trustee> trustees = ElectionTrusteeDP.getElectionTrustees(election.getId());
String message = "Please follow this link to upload your private key and decode election votes: \n";
String title = "Trustee for " + election.getName() + " election";
String url = "http://localhost:8080/Evoting/DecodeVotes.xhtml?elId=" + election.getId();
for(Trustee t : trustees) {
url += "&trId=" + t.getId() + "&token=" + t.getToken();
message += url;
try {
MailService.sendMessage(t.getEmail(), title, message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} else {
String title = "Trustee for " + election.getName() + " election";
String message = "Please follow this link to open your mix node: \n";
String url ="http://localhost:8080/Evoting/MixNode.xhtml?trId=" + tr.getId() + "&token=" + tr.getToken();
message += url;
try {
MailService.sendMessage(tr.getEmail(), title, message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
showThankYou = true;
return "";
}
|
diff --git a/mini2Dx-dependency-injection/src/main/java/org/mini2Dx/context/Bean.java b/mini2Dx-dependency-injection/src/main/java/org/mini2Dx/context/Bean.java
index d174ca9aa..b5579d10d 100644
--- a/mini2Dx-dependency-injection/src/main/java/org/mini2Dx/context/Bean.java
+++ b/mini2Dx-dependency-injection/src/main/java/org/mini2Dx/context/Bean.java
@@ -1,30 +1,30 @@
/**
* Copyright (c) 2013, mini2Dx Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.context;
/**
* A base class to bean facades during dependency injection
*
* @author Thomas Cashman
*/
public abstract class Bean {
public abstract Object getInstance();
/**
* Returns the key to be used for a given {@link Class}
* @param clazz The {@link Class} to get the key for
* @return The {@link Class} unique key
*/
public static <T> String getClassKey(Class<T> clazz) {
- return clazz.getPackage().getName() + clazz.getSimpleName();
+ return clazz.getName();
}
}
| true | true | public static <T> String getClassKey(Class<T> clazz) {
return clazz.getPackage().getName() + clazz.getSimpleName();
}
| public static <T> String getClassKey(Class<T> clazz) {
return clazz.getName();
}
|
diff --git a/impl/src/main/java/org/jboss/weld/servlet/ServletHelper.java b/impl/src/main/java/org/jboss/weld/servlet/ServletHelper.java
index ec47f013e..9e2a7e7dc 100644
--- a/impl/src/main/java/org/jboss/weld/servlet/ServletHelper.java
+++ b/impl/src/main/java/org/jboss/weld/servlet/ServletHelper.java
@@ -1,43 +1,49 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet;
import javax.servlet.ServletContext;
import org.jboss.weld.BeanManagerImpl;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.servlet.api.ServletServices;
/**
* @author pmuir
*
*/
public class ServletHelper
{
public static BeanManagerImpl getModuleBeanManager(ServletContext ctx)
{
if (ctx == null)
{
- throw new IllegalArgumentException("Must provide the Servlet Context");
+ throw new IllegalArgumentException("ServletContext is null");
}
BeanDeploymentArchive beanDeploymentArchive = Container.instance().deploymentServices().get(ServletServices.class).getBeanDeploymentArchive(ctx);
- return Container.instance().beanDeploymentArchives().get(beanDeploymentArchive).getCurrent();
+ BeanManagerImpl beanManagerImpl = Container.instance().beanDeploymentArchives().get(beanDeploymentArchive);
+ if (beanManagerImpl == null)
+ {
+ throw new IllegalArgumentException("Unable to find BeanManager. BeanDeploymentArchive: " + beanDeploymentArchive + "; ServletContext: " + ctx);
+ }
+ // Actually we need the manager for the current activity
+ return beanManagerImpl.getCurrent();
}
}
| false | true | public static BeanManagerImpl getModuleBeanManager(ServletContext ctx)
{
if (ctx == null)
{
throw new IllegalArgumentException("Must provide the Servlet Context");
}
BeanDeploymentArchive beanDeploymentArchive = Container.instance().deploymentServices().get(ServletServices.class).getBeanDeploymentArchive(ctx);
return Container.instance().beanDeploymentArchives().get(beanDeploymentArchive).getCurrent();
}
| public static BeanManagerImpl getModuleBeanManager(ServletContext ctx)
{
if (ctx == null)
{
throw new IllegalArgumentException("ServletContext is null");
}
BeanDeploymentArchive beanDeploymentArchive = Container.instance().deploymentServices().get(ServletServices.class).getBeanDeploymentArchive(ctx);
BeanManagerImpl beanManagerImpl = Container.instance().beanDeploymentArchives().get(beanDeploymentArchive);
if (beanManagerImpl == null)
{
throw new IllegalArgumentException("Unable to find BeanManager. BeanDeploymentArchive: " + beanDeploymentArchive + "; ServletContext: " + ctx);
}
// Actually we need the manager for the current activity
return beanManagerImpl.getCurrent();
}
|
diff --git a/src/de/todesbaum/jsite/application/ProjectInserter.java b/src/de/todesbaum/jsite/application/ProjectInserter.java
index b14dadb..1859393 100644
--- a/src/de/todesbaum/jsite/application/ProjectInserter.java
+++ b/src/de/todesbaum/jsite/application/ProjectInserter.java
@@ -1,736 +1,736 @@
/*
* jSite - ProjectInserter.java - Copyright © 2006–2011 David Roden
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package de.todesbaum.jsite.application;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import de.todesbaum.jsite.gui.FileScanner;
import de.todesbaum.jsite.gui.FileScannerListener;
import de.todesbaum.util.freenet.fcp2.Client;
import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
import de.todesbaum.util.freenet.fcp2.Connection;
import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
import de.todesbaum.util.freenet.fcp2.FileEntry;
import de.todesbaum.util.freenet.fcp2.Message;
import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
import de.todesbaum.util.freenet.fcp2.Verbosity;
import de.todesbaum.util.io.Closer;
import de.todesbaum.util.io.ReplacingOutputStream;
import de.todesbaum.util.io.StreamCopier;
import de.todesbaum.util.io.StreamCopier.ProgressListener;
/**
* Manages project inserts.
*
* @author David ‘Bombe’ Roden <[email protected]>
*/
public class ProjectInserter implements FileScannerListener, Runnable {
/** The logger. */
private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
/** Random number for FCP instances. */
private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
/** Counter for FCP connection identifier. */
private static int counter = 0;
/** The list of insert listeners. */
private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
/** The freenet interface. */
protected Freenet7Interface freenetInterface;
/** The project to insert. */
protected Project project;
/** The file scanner. */
private FileScanner fileScanner;
/** Object used for synchronization. */
protected final Object lockObject = new Object();
/** The temp directory. */
private String tempDirectory;
/** The current connection. */
private Connection connection;
/** Whether the insert is cancelled. */
private volatile boolean cancelled = false;
/** Progress listener for payload transfers. */
private ProgressListener progressListener;
/**
* Adds a listener to the list of registered listeners.
*
* @param insertListener
* The listener to add
*/
public void addInsertListener(InsertListener insertListener) {
insertListeners.add(insertListener);
}
/**
* Removes a listener from the list of registered listeners.
*
* @param insertListener
* The listener to remove
*/
public void removeInsertListener(InsertListener insertListener) {
insertListeners.remove(insertListener);
}
/**
* Notifies all listeners that the project insert has started.
*
* @see InsertListener#projectInsertStarted(Project)
*/
protected void fireProjectInsertStarted() {
for (InsertListener insertListener : insertListeners) {
insertListener.projectInsertStarted(project);
}
}
/**
* Notifies all listeners that the insert has generated a URI.
*
* @see InsertListener#projectURIGenerated(Project, String)
* @param uri
* The generated URI
*/
protected void fireProjectURIGenerated(String uri) {
for (InsertListener insertListener : insertListeners) {
insertListener.projectURIGenerated(project, uri);
}
}
/**
* Notifies all listeners that the insert has made some progress.
*
* @see InsertListener#projectUploadFinished(Project)
*/
protected void fireProjectUploadFinished() {
for (InsertListener insertListener : insertListeners) {
insertListener.projectUploadFinished(project);
}
}
/**
* Notifies all listeners that the insert has made some progress.
*
* @see InsertListener#projectInsertProgress(Project, int, int, int, int,
* boolean)
* @param succeeded
* The number of succeeded blocks
* @param failed
* The number of failed blocks
* @param fatal
* The number of fatally failed blocks
* @param total
* The total number of blocks
* @param finalized
* <code>true</code> if the total number of blocks has already
* been finalized, <code>false</code> otherwise
*/
protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
for (InsertListener insertListener : insertListeners) {
insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
}
}
/**
* Notifies all listeners the project insert has finished.
*
* @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
* @param success
* <code>true</code> if the project was inserted successfully,
* <code>false</code> if it failed
* @param cause
* The cause of the failure, if any
*/
protected void fireProjectInsertFinished(boolean success, Throwable cause) {
for (InsertListener insertListener : insertListeners) {
insertListener.projectInsertFinished(project, success, cause);
}
}
/**
* Sets the project to insert.
*
* @param project
* The project to insert
*/
public void setProject(Project project) {
this.project = project;
}
/**
* Sets the freenet interface to use.
*
* @param freenetInterface
* The freenet interface to use
*/
public void setFreenetInterface(Freenet7Interface freenetInterface) {
this.freenetInterface = freenetInterface;
}
/**
* Sets the temp directory to use.
*
* @param tempDirectory
* The temp directory to use, or {@code null} to use the system
* default
*/
public void setTempDirectory(String tempDirectory) {
this.tempDirectory = tempDirectory;
}
/**
* Starts the insert.
*
* @param progressListener
* Listener to notify on progress events
*/
public void start(ProgressListener progressListener) {
cancelled = false;
this.progressListener = progressListener;
fileScanner = new FileScanner(project);
fileScanner.addFileScannerListener(this);
new Thread(fileScanner).start();
}
/**
* Stops the current insert.
*/
public void stop() {
cancelled = true;
synchronized (lockObject) {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Creates an input stream that delivers the given file, replacing edition
* tokens in the file’s content, if necessary.
*
* @param filename
* The name of the file
* @param fileOption
* The file options
* @param edition
* The current edition
* @param length
* An array containing a single long which is used to
* <em>return</em> the final length of the file, after all
* replacements
* @return The input stream for the file
* @throws IOException
* if an I/O error occurs
*/
private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
File file = new File(project.getLocalPath(), filename);
length[0] = file.length();
if (!fileOption.getReplaceEdition()) {
return new FileInputStream(file);
}
ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
FileInputStream fileInput = new FileInputStream(file);
try {
outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
for (int index = 1; index <= fileOption.getEditionRange(); index++) {
outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
}
StreamCopier.copy(fileInput, outputStream, length[0]);
} finally {
Closer.close(fileInput);
Closer.close(outputStream);
Closer.close(filteredByteOutputStream);
}
byte[] filteredBytes = filteredByteOutputStream.toByteArray();
length[0] = filteredBytes.length;
return new ByteArrayInputStream(filteredBytes);
}
/**
* Creates an input stream for a container.
*
* @param containerFiles
* All container definitions
* @param containerName
* The name of the container to create
* @param edition
* The current edition
* @param containerLength
* An array containing a single long which is used to
* <em>return</em> the final length of the container stream,
* after all replacements
* @return The input stream for the container
* @throws IOException
* if an I/O error occurs
*/
private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
tempFile.deleteOnExit();
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
try {
for (String filename : containerFiles.get(containerName)) {
File dataFile = new File(project.getLocalPath(), filename);
if (dataFile.exists()) {
ZipEntry zipEntry = new ZipEntry(filename);
long[] fileLength = new long[1];
InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
try {
zipOutputStream.putNextEntry(zipEntry);
StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
} finally {
zipOutputStream.closeEntry();
wrappedInputStream.close();
}
}
}
} finally {
zipOutputStream.closeEntry();
Closer.close(zipOutputStream);
Closer.close(fileOutputStream);
}
containerLength[0] = tempFile.length();
return new FileInputStream(tempFile);
}
/**
* Creates a file entry suitable for handing in to
* {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
*
* @param filename
* The name of the file to insert
* @param edition
* The current edition
* @param containerFiles
* The container definitions
* @return A file entry for the given file
*/
private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
FileEntry fileEntry = null;
FileOption fileOption = project.getFileOption(filename);
if (filename.startsWith("/container/:")) {
String containerName = filename.substring("/container/:".length());
try {
long[] containerLength = new long[1];
InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
} catch (IOException ioe1) {
/* ignore, null is returned. */
}
} else {
if (fileOption.isInsert()) {
try {
long[] fileLength = new long[1];
InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
} catch (IOException ioe1) {
/* ignore, null is returned. */
}
} else {
if (fileOption.isInsertRedirect()) {
fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
}
}
}
return fileEntry;
}
/**
* Creates container definitions.
*
* @param files
* The list of all files
* @param containers
* The list of all containers
* @param containerFiles
* Empty map that will be filled with container definitions
*/
private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
for (String filename : new ArrayList<String>(files)) {
FileOption fileOption = project.getFileOption(filename);
String containerName = fileOption.getContainer();
if (!containerName.equals("")) {
if (!containers.contains(containerName)) {
containers.add(containerName);
containerFiles.put(containerName, new ArrayList<String>());
/* hmm. looks like a hack to me. */
files.add("/container/:" + containerName);
}
containerFiles.get(containerName).add(filename);
files.remove(filename);
}
}
}
/**
* Validates the given project. The project will be checked for any invalid
* conditions, such as invalid insert or request keys, missing path names,
* missing default file, and so on.
*
* @param project
* The project to check
* @return The encountered warnings and errors
*/
public static CheckReport validateProject(Project project) {
CheckReport checkReport = new CheckReport();
if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
checkReport.addIssue("error.no-local-path", true);
}
if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
checkReport.addIssue("error.no-path", true);
}
if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
checkReport.addIssue("warning.empty-index", false);
} else {
File indexFile = new File(project.getLocalPath(), project.getIndexFile());
if (!indexFile.exists()) {
checkReport.addIssue("error.index-missing", true);
}
}
String indexFile = project.getIndexFile();
boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
checkReport.addIssue("warning.container-index", false);
}
List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
checkReport.addIssue("warning.index-not-html", false);
}
Map<String, FileOption> fileOptions = project.getFileOptions();
Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
boolean insert = fileOptionEntries.isEmpty();
for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
String fileName = fileOptionEntry.getKey();
FileOption fileOption = fileOptionEntry.getValue();
insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
checkReport.addIssue("error.index-not-inserted", true);
}
if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
checkReport.addIssue("error.no-custom-key", true, fileName);
}
}
if (!insert) {
checkReport.addIssue("error.no-files-to-insert", true);
}
Set<String> fileNames = new HashSet<String>();
for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
FileOption fileOption = fileOptionEntry.getValue();
if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
continue;
}
String fileName = fileOptionEntry.getKey();
if (fileOption.hasChangedName()) {
fileName = fileOption.getChangedName();
}
logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
if (!fileNames.add(fileName)) {
checkReport.addIssue("error.duplicate-file", true, fileName);
}
}
return checkReport;
}
/**
* {@inheritDoc}
*/
public void run() {
fireProjectInsertStarted();
List<String> files = fileScanner.getFiles();
/* create connection to node */
synchronized (lockObject) {
connection = freenetInterface.getConnection("project-insert-" + random + counter++);
}
connection.setTempDirectory(tempDirectory);
boolean connected = false;
Throwable cause = null;
try {
connected = connection.connect();
} catch (IOException e1) {
cause = e1;
}
if (!connected || cancelled) {
fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
return;
}
Client client = new Client(connection);
/* create containers */
final List<String> containers = new ArrayList<String>();
final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
createContainers(files, containers, containerFiles);
/* collect files */
int edition = project.getEdition();
String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
putDir.setDefaultName(project.getIndexFile());
}
putDir.setVerbosity(Verbosity.ALL);
putDir.setMaxRetries(-1);
putDir.setEarlyEncode(false);
for (String filename : files) {
FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
if (fileEntry != null) {
try {
putDir.addFileEntry(fileEntry);
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
}
}
/* start request */
try {
client.execute(putDir, progressListener);
fireProjectUploadFinished();
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
/* parse progress and success messages */
String finalURI = null;
boolean success = false;
boolean finished = false;
boolean disconnected = false;
while (!finished && !cancelled) {
Message message = client.readMessage();
finished = (message == null) || (disconnected = client.isDisconnected());
logger.log(Level.FINE, "Received message: " + message);
if (!finished) {
@SuppressWarnings("null")
String messageName = message.getName();
if ("URIGenerated".equals(messageName)) {
finalURI = message.get("URI");
fireProjectURIGenerated(finalURI);
}
if ("SimpleProgress".equals(messageName)) {
int total = Integer.parseInt(message.get("Total"));
int succeeded = Integer.parseInt(message.get("Succeeded"));
int fatal = Integer.parseInt(message.get("FatallyFailed"));
int failed = Integer.parseInt(message.get("Failed"));
boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
}
- success = "PutSuccessful".equals(messageName);
- finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
+ success |= "PutSuccessful".equals(messageName);
+ finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
}
}
/* post-insert work */
if (success) {
@SuppressWarnings("null")
String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
int newEdition = Integer.parseInt(editionPart);
project.setEdition(newEdition);
project.setLastInsertionTime(System.currentTimeMillis());
}
fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
}
//
// INTERFACE FileScannerListener
//
/**
* {@inheritDoc}
*/
public void fileScannerFinished(FileScanner fileScanner) {
if (!fileScanner.isError()) {
new Thread(this).start();
} else {
fireProjectInsertFinished(false, null);
}
fileScanner.removeFileScannerListener(this);
}
/**
* Container class that collects all warnings and errors that occured during
* {@link ProjectInserter#validateProject(Project) project validation}.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public static class CheckReport implements Iterable<Issue> {
/** The issures that occured. */
private final List<Issue> issues = new ArrayList<Issue>();
/**
* Adds an issue.
*
* @param issue
* The issue to add
*/
public void addIssue(Issue issue) {
issues.add(issue);
}
/**
* Creates an {@link Issue} from the given error key and fatality flag
* and {@link #addIssue(Issue) adds} it.
*
* @param errorKey
* The error key
* @param fatal
* {@code true} if the error is fatal, {@code false} if only
* a warning should be generated
* @param parameters
* Any additional parameters
*/
public void addIssue(String errorKey, boolean fatal, String... parameters) {
addIssue(new Issue(errorKey, fatal, parameters));
}
/**
* {@inheritDoc}
*/
public Iterator<Issue> iterator() {
return issues.iterator();
}
/**
* Returns whether this check report does not contain any errors.
*
* @return {@code true} if this check report does not contain any
* errors, {@code false} if this check report does contain
* errors
*/
public boolean isEmpty() {
return issues.isEmpty();
}
/**
* Returns the number of issues in this check report.
*
* @return The number of issues
*/
public int size() {
return issues.size();
}
}
/**
* Container class for a single issue. An issue contains an error key
* that describes the error, and a fatality flag that determines whether
* the insert has to be aborted (if the flag is {@code true}) or if it
* can still be performed and only a warning should be generated (if the
* flag is {@code false}).
*
* @author <a href="mailto:[email protected]">David ‘Bombe’
* Roden</a>
*/
public static class Issue {
/** The error key. */
private final String errorKey;
/** The fatality flag. */
private final boolean fatal;
/** Additional parameters. */
private String[] parameters;
/**
* Creates a new issue.
*
* @param errorKey
* The error key
* @param fatal
* The fatality flag
* @param parameters
* Any additional parameters
*/
protected Issue(String errorKey, boolean fatal, String... parameters) {
this.errorKey = errorKey;
this.fatal = fatal;
this.parameters = parameters;
}
/**
* Returns the key of the encountered error.
*
* @return The error key
*/
public String getErrorKey() {
return errorKey;
}
/**
* Returns whether the issue is fatal and the insert has to be
* aborted. Otherwise only a warning should be shown.
*
* @return {@code true} if the insert needs to be aborted, {@code
* false} otherwise
*/
public boolean isFatal() {
return fatal;
}
/**
* Returns any additional parameters.
*
* @return The additional parameters
*/
public String[] getParameters() {
return parameters;
}
}
}
| true | true | public void run() {
fireProjectInsertStarted();
List<String> files = fileScanner.getFiles();
/* create connection to node */
synchronized (lockObject) {
connection = freenetInterface.getConnection("project-insert-" + random + counter++);
}
connection.setTempDirectory(tempDirectory);
boolean connected = false;
Throwable cause = null;
try {
connected = connection.connect();
} catch (IOException e1) {
cause = e1;
}
if (!connected || cancelled) {
fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
return;
}
Client client = new Client(connection);
/* create containers */
final List<String> containers = new ArrayList<String>();
final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
createContainers(files, containers, containerFiles);
/* collect files */
int edition = project.getEdition();
String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
putDir.setDefaultName(project.getIndexFile());
}
putDir.setVerbosity(Verbosity.ALL);
putDir.setMaxRetries(-1);
putDir.setEarlyEncode(false);
for (String filename : files) {
FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
if (fileEntry != null) {
try {
putDir.addFileEntry(fileEntry);
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
}
}
/* start request */
try {
client.execute(putDir, progressListener);
fireProjectUploadFinished();
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
/* parse progress and success messages */
String finalURI = null;
boolean success = false;
boolean finished = false;
boolean disconnected = false;
while (!finished && !cancelled) {
Message message = client.readMessage();
finished = (message == null) || (disconnected = client.isDisconnected());
logger.log(Level.FINE, "Received message: " + message);
if (!finished) {
@SuppressWarnings("null")
String messageName = message.getName();
if ("URIGenerated".equals(messageName)) {
finalURI = message.get("URI");
fireProjectURIGenerated(finalURI);
}
if ("SimpleProgress".equals(messageName)) {
int total = Integer.parseInt(message.get("Total"));
int succeeded = Integer.parseInt(message.get("Succeeded"));
int fatal = Integer.parseInt(message.get("FatallyFailed"));
int failed = Integer.parseInt(message.get("Failed"));
boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
}
success = "PutSuccessful".equals(messageName);
finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
}
}
/* post-insert work */
if (success) {
@SuppressWarnings("null")
String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
int newEdition = Integer.parseInt(editionPart);
project.setEdition(newEdition);
project.setLastInsertionTime(System.currentTimeMillis());
}
fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
}
| public void run() {
fireProjectInsertStarted();
List<String> files = fileScanner.getFiles();
/* create connection to node */
synchronized (lockObject) {
connection = freenetInterface.getConnection("project-insert-" + random + counter++);
}
connection.setTempDirectory(tempDirectory);
boolean connected = false;
Throwable cause = null;
try {
connected = connection.connect();
} catch (IOException e1) {
cause = e1;
}
if (!connected || cancelled) {
fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
return;
}
Client client = new Client(connection);
/* create containers */
final List<String> containers = new ArrayList<String>();
final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
createContainers(files, containers, containerFiles);
/* collect files */
int edition = project.getEdition();
String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
putDir.setDefaultName(project.getIndexFile());
}
putDir.setVerbosity(Verbosity.ALL);
putDir.setMaxRetries(-1);
putDir.setEarlyEncode(false);
for (String filename : files) {
FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
if (fileEntry != null) {
try {
putDir.addFileEntry(fileEntry);
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
}
}
/* start request */
try {
client.execute(putDir, progressListener);
fireProjectUploadFinished();
} catch (IOException ioe1) {
fireProjectInsertFinished(false, ioe1);
return;
}
/* parse progress and success messages */
String finalURI = null;
boolean success = false;
boolean finished = false;
boolean disconnected = false;
while (!finished && !cancelled) {
Message message = client.readMessage();
finished = (message == null) || (disconnected = client.isDisconnected());
logger.log(Level.FINE, "Received message: " + message);
if (!finished) {
@SuppressWarnings("null")
String messageName = message.getName();
if ("URIGenerated".equals(messageName)) {
finalURI = message.get("URI");
fireProjectURIGenerated(finalURI);
}
if ("SimpleProgress".equals(messageName)) {
int total = Integer.parseInt(message.get("Total"));
int succeeded = Integer.parseInt(message.get("Succeeded"));
int fatal = Integer.parseInt(message.get("FatallyFailed"));
int failed = Integer.parseInt(message.get("Failed"));
boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
}
success |= "PutSuccessful".equals(messageName);
finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
}
}
/* post-insert work */
if (success) {
@SuppressWarnings("null")
String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
int newEdition = Integer.parseInt(editionPart);
project.setEdition(newEdition);
project.setLastInsertionTime(System.currentTimeMillis());
}
fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
}
|
diff --git a/src/gov/nih/nci/nautilus/struts/form/BaseForm.java b/src/gov/nih/nci/nautilus/struts/form/BaseForm.java
index bbfcada6..a3c24744 100755
--- a/src/gov/nih/nci/nautilus/struts/form/BaseForm.java
+++ b/src/gov/nih/nci/nautilus/struts/form/BaseForm.java
@@ -1,90 +1,90 @@
// Created by Xslt generator for Eclipse.
// XSL : not found (java.io.FileNotFoundException: (Bad file descriptor))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl
package gov.nih.nci.nautilus.struts.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
import java.util.*;
/**
* GeneExpressionForm.java created by EasyStruts - XsltGen.
* http://easystruts.sf.net
* created on 08-11-2004
*
* XDoclet definition:
* @struts:form name="geneExpressionForm"
*/
public class BaseForm extends ActionForm {
// Collections used for Lookup values.
private ArrayList diseaseType;
private ArrayList geneTypeColl;
// --------------------------------------------------------- Methods
public BaseForm(){
// Create Lookups for Gene Expression screens
setLookups();
}
protected boolean isBasePairValid(String basePairStart, String basePairEnd) {
int intBasePairStart;
int intBasePairEnd;
System.out.println("Start "+basePairStart+" End "+basePairEnd);
try {
intBasePairStart = Integer.parseInt(basePairStart);
intBasePairEnd = Integer.parseInt(basePairEnd);
}
catch (NumberFormatException e) {
return false;
}
if (intBasePairStart >= intBasePairEnd) return false;
return true;
}
public void setLookups() {
diseaseType = new ArrayList();
geneTypeColl = new ArrayList();
// These are hardcoded but will come from DB
- diseaseType.add( new LabelValueBean( "Astrocytic", "astro" ) );
- diseaseType.add( new LabelValueBean( "Oligodendroglial", "oligo" ) );
- diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal cell" ) );
- diseaseType.add( new LabelValueBean( "Mixed gliomas", "Mixed gliomas" ) );
- diseaseType.add( new LabelValueBean( "Neuroepithelial", "Neuroepithelial" ) );
- diseaseType.add( new LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
- diseaseType.add( new LabelValueBean( "Neuronal and mixed neuronal-glial", "neuronal-glial" ) );
- diseaseType.add( new LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
- diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
- diseaseType.add( new LabelValueBean( "Glioblastoma", "Glioblastoma" ));
+ diseaseType.add( new LabelValueBean( "Astrocytic", "ASTROCYTOMA" ) );
+ diseaseType.add( new LabelValueBean( "Oligodendroglial", "OLIG" ) );
+ //diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal cell" ) );
+ diseaseType.add( new LabelValueBean( "Mixed gliomas", "MIXED" ) );
+ //diseaseType.add( new LabelValueBean( "Neuroepithelial", "Neuroepithelial" ) );
+ //diseaseType.add( new LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
+ //diseaseType.add( new LabelValueBean( "Neuronal and mixed neuronal-glial", "neuronal-glial" ) );
+ //diseaseType.add( new LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
+ //diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
+ diseaseType.add( new LabelValueBean( "Glioblastoma", "GBM" ));
- geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" ) );
+ //geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" ) );
geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" ) );
geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" ) );
geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" ) );
}
// Getter methods for Gene Expression Lookup
public ArrayList getDiseaseType()
{ return diseaseType; }
public ArrayList getGeneTypeColl()
{ return geneTypeColl; }
}
| false | true | public void setLookups() {
diseaseType = new ArrayList();
geneTypeColl = new ArrayList();
// These are hardcoded but will come from DB
diseaseType.add( new LabelValueBean( "Astrocytic", "astro" ) );
diseaseType.add( new LabelValueBean( "Oligodendroglial", "oligo" ) );
diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal cell" ) );
diseaseType.add( new LabelValueBean( "Mixed gliomas", "Mixed gliomas" ) );
diseaseType.add( new LabelValueBean( "Neuroepithelial", "Neuroepithelial" ) );
diseaseType.add( new LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
diseaseType.add( new LabelValueBean( "Neuronal and mixed neuronal-glial", "neuronal-glial" ) );
diseaseType.add( new LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
diseaseType.add( new LabelValueBean( "Glioblastoma", "Glioblastoma" ));
geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" ) );
geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" ) );
geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" ) );
geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" ) );
}
| public void setLookups() {
diseaseType = new ArrayList();
geneTypeColl = new ArrayList();
// These are hardcoded but will come from DB
diseaseType.add( new LabelValueBean( "Astrocytic", "ASTROCYTOMA" ) );
diseaseType.add( new LabelValueBean( "Oligodendroglial", "OLIG" ) );
//diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal cell" ) );
diseaseType.add( new LabelValueBean( "Mixed gliomas", "MIXED" ) );
//diseaseType.add( new LabelValueBean( "Neuroepithelial", "Neuroepithelial" ) );
//diseaseType.add( new LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
//diseaseType.add( new LabelValueBean( "Neuronal and mixed neuronal-glial", "neuronal-glial" ) );
//diseaseType.add( new LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
//diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
diseaseType.add( new LabelValueBean( "Glioblastoma", "GBM" ));
//geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" ) );
geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" ) );
geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" ) );
geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" ) );
}
|
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/TimesheetApp.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/TimesheetApp.java
index 9ca7d91..969e6b9 100644
--- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/TimesheetApp.java
+++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/TimesheetApp.java
@@ -1,137 +1,139 @@
package com.uwusoft.timesheet;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import com.uwusoft.timesheet.dialog.TimeDialog;
import com.uwusoft.timesheet.extensionpoint.StorageService;
import com.uwusoft.timesheet.util.ExtensionManager;
import com.uwusoft.timesheet.util.MessageBox;
/**
* This class controls all aspects of the application's execution
*/
public class TimesheetApp implements IApplication {
public static SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
public static final String WORKING_HOURS = "weekly.workinghours";
public static final String DEFAULT_TASK = "task.default";
public static final String DAILY_TASK = "task.daily";
public static final String DAILY_TASK_TOTAL = "task.daily.total";
public static final String LAST_TASK = "task.last";
private static final String SYSTEM_SHUTDOWN = "system.shutdown";
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
if (!PlatformUI.isWorkbenchRunning()) return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
- display.syncExec(new Runnable() {
- public void run() {
- if (!display.isDisposed()) {
- preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
- workbench.close();
+ if (!display.isDisposed()) {
+ display.syncExec(new Runnable() {
+ public void run() {
+ if (!display.isDisposed()) {
+ preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
+ workbench.close();
+ }
}
- }
- });
+ });
+ }
}
});
try {
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
String startTime = formatter.format(mx.getStartTime());
String shutdownTime = preferenceStore.getString(SYSTEM_SHUTDOWN);
if (shutdownTime == "") shutdownTime = startTime;
else shutdownTime = formatter.format(formatter.parse(shutdownTime));
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
Date startDate = formatter.parse(startTime);
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
Date shutdownDate = formatter.parse(shutdownTime);
calDay.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
if (startDay != shutdownDay) { // don't automatically check in/out if computer is rebooted
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
calWeek.setTime(shutdownDate);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
if (preferenceStore.getString(LAST_TASK) != "") { // last task will be set to empty if a manual check out has occurred
// automatic check out
if (storageService == null) return IApplication.EXIT_OK;
TimeDialog timeDialog = new TimeDialog(display, "Check out at " + DateFormat.getDateInstance(DateFormat.SHORT).format(shutdownDate),
preferenceStore.getString(LAST_TASK), shutdownDate);
if (timeDialog.open() == Dialog.OK) {
storageService.createTaskEntry(timeDialog.getTime(), preferenceStore.getString(LAST_TASK));
storageService.storeLastDailyTotal();
if (preferenceStore.getString(DAILY_TASK) != "")
storageService.createTaskEntry(
timeDialog.getTime(), preferenceStore.getString(DAILY_TASK), preferenceStore.getString(DAILY_TASK_TOTAL));
}
}
// automatic check in
TimeDialog timeDialog = new TimeDialog(display, "Check in at " + DateFormat.getDateInstance(DateFormat.SHORT).format(startDate),
StorageService.CHECK_IN, startDate);
if (timeDialog.open() == Dialog.OK) {
if (startWeek != shutdownWeek)
storageService.storeLastWeekTotal(preferenceStore.getString(WORKING_HOURS)); // store Week and Overtime
storageService.createTaskEntry(timeDialog.getTime(), StorageService.CHECK_IN);
preferenceStore.setValue(LAST_TASK, preferenceStore.getString(DEFAULT_TASK));
}
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
} catch (Exception e) {
MessageBox.setMessage("Timesheet notification", e.getLocalizedMessage());
} finally {
display.dispose();
}
return IApplication.EXIT_OK;
}
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
if (!PlatformUI.isWorkbenchRunning())
return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed())
workbench.close();
}
});
}
}
| false | true | public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
if (!PlatformUI.isWorkbenchRunning()) return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed()) {
preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
workbench.close();
}
}
});
}
});
try {
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
String startTime = formatter.format(mx.getStartTime());
String shutdownTime = preferenceStore.getString(SYSTEM_SHUTDOWN);
if (shutdownTime == "") shutdownTime = startTime;
else shutdownTime = formatter.format(formatter.parse(shutdownTime));
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
Date startDate = formatter.parse(startTime);
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
Date shutdownDate = formatter.parse(shutdownTime);
calDay.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
if (startDay != shutdownDay) { // don't automatically check in/out if computer is rebooted
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
calWeek.setTime(shutdownDate);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
if (preferenceStore.getString(LAST_TASK) != "") { // last task will be set to empty if a manual check out has occurred
// automatic check out
if (storageService == null) return IApplication.EXIT_OK;
TimeDialog timeDialog = new TimeDialog(display, "Check out at " + DateFormat.getDateInstance(DateFormat.SHORT).format(shutdownDate),
preferenceStore.getString(LAST_TASK), shutdownDate);
if (timeDialog.open() == Dialog.OK) {
storageService.createTaskEntry(timeDialog.getTime(), preferenceStore.getString(LAST_TASK));
storageService.storeLastDailyTotal();
if (preferenceStore.getString(DAILY_TASK) != "")
storageService.createTaskEntry(
timeDialog.getTime(), preferenceStore.getString(DAILY_TASK), preferenceStore.getString(DAILY_TASK_TOTAL));
}
}
// automatic check in
TimeDialog timeDialog = new TimeDialog(display, "Check in at " + DateFormat.getDateInstance(DateFormat.SHORT).format(startDate),
StorageService.CHECK_IN, startDate);
if (timeDialog.open() == Dialog.OK) {
if (startWeek != shutdownWeek)
storageService.storeLastWeekTotal(preferenceStore.getString(WORKING_HOURS)); // store Week and Overtime
storageService.createTaskEntry(timeDialog.getTime(), StorageService.CHECK_IN);
preferenceStore.setValue(LAST_TASK, preferenceStore.getString(DEFAULT_TASK));
}
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
} catch (Exception e) {
MessageBox.setMessage("Timesheet notification", e.getLocalizedMessage());
} finally {
display.dispose();
}
return IApplication.EXIT_OK;
}
| public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
if (!PlatformUI.isWorkbenchRunning()) return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
if (!display.isDisposed()) {
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed()) {
preferenceStore.setValue(SYSTEM_SHUTDOWN, formatter.format(System.currentTimeMillis()));
workbench.close();
}
}
});
}
}
});
try {
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
String startTime = formatter.format(mx.getStartTime());
String shutdownTime = preferenceStore.getString(SYSTEM_SHUTDOWN);
if (shutdownTime == "") shutdownTime = startTime;
else shutdownTime = formatter.format(formatter.parse(shutdownTime));
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
Date startDate = formatter.parse(startTime);
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
Date shutdownDate = formatter.parse(shutdownTime);
calDay.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
if (startDay != shutdownDay) { // don't automatically check in/out if computer is rebooted
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
calWeek.setTime(shutdownDate);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
if (preferenceStore.getString(LAST_TASK) != "") { // last task will be set to empty if a manual check out has occurred
// automatic check out
if (storageService == null) return IApplication.EXIT_OK;
TimeDialog timeDialog = new TimeDialog(display, "Check out at " + DateFormat.getDateInstance(DateFormat.SHORT).format(shutdownDate),
preferenceStore.getString(LAST_TASK), shutdownDate);
if (timeDialog.open() == Dialog.OK) {
storageService.createTaskEntry(timeDialog.getTime(), preferenceStore.getString(LAST_TASK));
storageService.storeLastDailyTotal();
if (preferenceStore.getString(DAILY_TASK) != "")
storageService.createTaskEntry(
timeDialog.getTime(), preferenceStore.getString(DAILY_TASK), preferenceStore.getString(DAILY_TASK_TOTAL));
}
}
// automatic check in
TimeDialog timeDialog = new TimeDialog(display, "Check in at " + DateFormat.getDateInstance(DateFormat.SHORT).format(startDate),
StorageService.CHECK_IN, startDate);
if (timeDialog.open() == Dialog.OK) {
if (startWeek != shutdownWeek)
storageService.storeLastWeekTotal(preferenceStore.getString(WORKING_HOURS)); // store Week and Overtime
storageService.createTaskEntry(timeDialog.getTime(), StorageService.CHECK_IN);
preferenceStore.setValue(LAST_TASK, preferenceStore.getString(DEFAULT_TASK));
}
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
} catch (Exception e) {
MessageBox.setMessage("Timesheet notification", e.getLocalizedMessage());
} finally {
display.dispose();
}
return IApplication.EXIT_OK;
}
|
diff --git a/src/com/cloud4all/minimatchmaker/MiniMatchMakerService.java b/src/com/cloud4all/minimatchmaker/MiniMatchMakerService.java
index e4e241c..28faab6 100644
--- a/src/com/cloud4all/minimatchmaker/MiniMatchMakerService.java
+++ b/src/com/cloud4all/minimatchmaker/MiniMatchMakerService.java
@@ -1,204 +1,204 @@
package com.cloud4all.minimatchmaker;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONObject;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/*
MiniMatchMakerService
This class is a communication layout between Flow manager and Mini match maker's kernel.
Copyright (c) 2013, Technosite R&D
All rights reserved.
The research leading to these results has received funding from the European Union's Seventh Framework Programme (FP7/2007-2013) under grant agreement n� 289016
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
�* Redistributions of source code must retain the above copyright notice, this�list of conditions and the following disclaimer.
�* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
�* Neither the name of Technosite R&D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class MiniMatchMakerService extends Service {
public interface MiniMatchMakerListener {
void MiniMatchMakerResponse(JSONObject data);
}
private final IBinder mBinder = new MyBinder();
private MiniMatchMakerEngine engine = null;
private MiniMatchMakerListener listener = null;
@Override
public void onCreate() {
super.onCreate();
engine = new MiniMatchMakerEngine(this);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
HashMap<String,String> list = new HashMap<String,String>();
CloudIntent cloudinfo = CloudIntent.intentToCloudIntent(intent);
int event = cloudinfo.getIdEvent();
int id_action = cloudinfo.getIdAction();
manageArgumentsInPetition(cloudinfo );
switch (event) {
case CommunicationPersistence.EVENT_ARE_REPORTER :
engine.addDeviceInfo(arguments.get("device_reporter").toString() );
engine.makeLogin(arguments.get("user").toString());
list.put("message","yes");
sendCommunication(CommunicationPersistence.EVENT_ARE_REPORTER_RESPONSE,list, id_action );
break;
case CommunicationPersistence.EVENT_STORAGE_REPORTER :
list.put("message","OK");
sendCommunication(CommunicationPersistence.EVENT_STORAGE_REPORTER_RESPONSE ,list, id_action );
break;
case CommunicationPersistence.EVENT_GET_CONFIGURATION :
if (engine.makeLogin(arguments.get("user").toString())) {
// the user is logged
// nothing to do yet in this version
}
list.put("features_category","root");
list.put("brightness_mode","1");
list.put("brightness","250");
list.put("sound_effects","1");
list.put("music_volume","15");
list.put("alarm_volume","7");
list.put("dtmf_volume","15");
list.put("notification_volume","7");
list.put("ring_volume","7");
list.put("system_volume","7");
list.put("voice_call_volume","5");
list.put("notification_sound","http://www.fundacionvf.es/prueba.ogg");
list.put("font_scale","1.5");
list.put("show_window","1");
- list.put("windows_width",engine.getDeviceInfoForKey("screenWidth"));
- list.put("windows_height",engine.getDeviceInfoForKey("screenHeight"));
+ list.put("windows_width",engine.getDeviceInfoForKey("Screen width"));
+ list.put("windows_height",engine.getDeviceInfoForKey("Screen height"));
list.put("text_color_notification","#FFFF00");
list.put("background_color_notification","#0000FF");
list.put("notification_vibrate ","1");
list.put("vibrate_pattern","2");
sendCommunication(CommunicationPersistence.EVENT_GET_CONFIGURATION_RESPONSE ,list, id_action );
break;
default :
break;
}
// reset arguments from petition
arguments = null;
} catch (Exception e) {
Log.e("MiniMatchMakerService error in onStartCommand", "Error managing the intent.\n"+e);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
public class MyBinder extends Binder {
MiniMatchMakerService getService() {
return MiniMatchMakerService.this;
}
}
public MiniMatchMakerEngine getEngine() {
return engine;
}
// ** Listener
public void registerListener(MiniMatchMakerListener listenerObject) {
listener = listenerObject;
Log.i("MiniMatchMakerService", "Object registered as listener of the service");
}
// ** Input method
public void insertData(JSONObject data) {
if (engine == null) engine = new MiniMatchMakerEngine(this);
Log.i("MiniMatchMakerService", "Sending data to the engine.");
engine.receiveData(data);
}
// ** Output method
public void ResponseData(JSONObject data) {
if (listener!=null) {
Log.i("MiniMatchMakerService", "Sending data to the listener.");
listener.MiniMatchMakerResponse(data);
}
}
// ** Methods for communication with Orquestator
private HashMap<String,String> arguments = null;
private void manageArgumentsInPetition(CloudIntent intent) {
String[] args;
try {
arguments = new HashMap<String,String>();
args = intent.getArrayIds();
for (int i = 0; i < args.length; i++){
String paramName = args[i];
String paramValue = intent.getValue(args[i]);
arguments.put(paramName, paramValue);
}
} catch (Exception e) {
Log.e("MiniMatchMakerService error in ManagePettition", "Error in Intent management.\n" +e);
}
}
private void sendCommunication(int CloudEvent, Map<String, String> params, int idAction) {
try {
CloudIntent intent = new CloudIntent(CommunicationPersistence.ACTION_ORCHESTRATOR, CloudEvent,idAction);
// manage params
Iterator<Map.Entry<String,String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
intent.setParams(e.getKey(), e.getValue());
}
Context ct = getApplicationContext();
ct.sendBroadcast(intent);
} catch (Exception e) {
Log.e("MiniMatchMakerBroadcastManager error in sendCommunication", "Error sending broadcast.\n" +e);
}
}
}
| true | true | public int onStartCommand(Intent intent, int flags, int startId) {
try {
HashMap<String,String> list = new HashMap<String,String>();
CloudIntent cloudinfo = CloudIntent.intentToCloudIntent(intent);
int event = cloudinfo.getIdEvent();
int id_action = cloudinfo.getIdAction();
manageArgumentsInPetition(cloudinfo );
switch (event) {
case CommunicationPersistence.EVENT_ARE_REPORTER :
engine.addDeviceInfo(arguments.get("device_reporter").toString() );
engine.makeLogin(arguments.get("user").toString());
list.put("message","yes");
sendCommunication(CommunicationPersistence.EVENT_ARE_REPORTER_RESPONSE,list, id_action );
break;
case CommunicationPersistence.EVENT_STORAGE_REPORTER :
list.put("message","OK");
sendCommunication(CommunicationPersistence.EVENT_STORAGE_REPORTER_RESPONSE ,list, id_action );
break;
case CommunicationPersistence.EVENT_GET_CONFIGURATION :
if (engine.makeLogin(arguments.get("user").toString())) {
// the user is logged
// nothing to do yet in this version
}
list.put("features_category","root");
list.put("brightness_mode","1");
list.put("brightness","250");
list.put("sound_effects","1");
list.put("music_volume","15");
list.put("alarm_volume","7");
list.put("dtmf_volume","15");
list.put("notification_volume","7");
list.put("ring_volume","7");
list.put("system_volume","7");
list.put("voice_call_volume","5");
list.put("notification_sound","http://www.fundacionvf.es/prueba.ogg");
list.put("font_scale","1.5");
list.put("show_window","1");
list.put("windows_width",engine.getDeviceInfoForKey("screenWidth"));
list.put("windows_height",engine.getDeviceInfoForKey("screenHeight"));
list.put("text_color_notification","#FFFF00");
list.put("background_color_notification","#0000FF");
list.put("notification_vibrate ","1");
list.put("vibrate_pattern","2");
sendCommunication(CommunicationPersistence.EVENT_GET_CONFIGURATION_RESPONSE ,list, id_action );
break;
default :
break;
}
// reset arguments from petition
arguments = null;
} catch (Exception e) {
Log.e("MiniMatchMakerService error in onStartCommand", "Error managing the intent.\n"+e);
}
return super.onStartCommand(intent, flags, startId);
}
| public int onStartCommand(Intent intent, int flags, int startId) {
try {
HashMap<String,String> list = new HashMap<String,String>();
CloudIntent cloudinfo = CloudIntent.intentToCloudIntent(intent);
int event = cloudinfo.getIdEvent();
int id_action = cloudinfo.getIdAction();
manageArgumentsInPetition(cloudinfo );
switch (event) {
case CommunicationPersistence.EVENT_ARE_REPORTER :
engine.addDeviceInfo(arguments.get("device_reporter").toString() );
engine.makeLogin(arguments.get("user").toString());
list.put("message","yes");
sendCommunication(CommunicationPersistence.EVENT_ARE_REPORTER_RESPONSE,list, id_action );
break;
case CommunicationPersistence.EVENT_STORAGE_REPORTER :
list.put("message","OK");
sendCommunication(CommunicationPersistence.EVENT_STORAGE_REPORTER_RESPONSE ,list, id_action );
break;
case CommunicationPersistence.EVENT_GET_CONFIGURATION :
if (engine.makeLogin(arguments.get("user").toString())) {
// the user is logged
// nothing to do yet in this version
}
list.put("features_category","root");
list.put("brightness_mode","1");
list.put("brightness","250");
list.put("sound_effects","1");
list.put("music_volume","15");
list.put("alarm_volume","7");
list.put("dtmf_volume","15");
list.put("notification_volume","7");
list.put("ring_volume","7");
list.put("system_volume","7");
list.put("voice_call_volume","5");
list.put("notification_sound","http://www.fundacionvf.es/prueba.ogg");
list.put("font_scale","1.5");
list.put("show_window","1");
list.put("windows_width",engine.getDeviceInfoForKey("Screen width"));
list.put("windows_height",engine.getDeviceInfoForKey("Screen height"));
list.put("text_color_notification","#FFFF00");
list.put("background_color_notification","#0000FF");
list.put("notification_vibrate ","1");
list.put("vibrate_pattern","2");
sendCommunication(CommunicationPersistence.EVENT_GET_CONFIGURATION_RESPONSE ,list, id_action );
break;
default :
break;
}
// reset arguments from petition
arguments = null;
} catch (Exception e) {
Log.e("MiniMatchMakerService error in onStartCommand", "Error managing the intent.\n"+e);
}
return super.onStartCommand(intent, flags, startId);
}
|
diff --git a/org.eclipse.jdt.core/compiler/org/jmlspecs/jml4/boogie/Boogie.java b/org.eclipse.jdt.core/compiler/org/jmlspecs/jml4/boogie/Boogie.java
index b1b5f306..0539d716 100644
--- a/org.eclipse.jdt.core/compiler/org/jmlspecs/jml4/boogie/Boogie.java
+++ b/org.eclipse.jdt.core/compiler/org/jmlspecs/jml4/boogie/Boogie.java
@@ -1,71 +1,76 @@
package org.jmlspecs.jml4.boogie;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.jmlspecs.jml4.compiler.DefaultCompilerExtension;
import org.jmlspecs.jml4.util.Logger;
/**
* A compiler extension that enables Java code to be passed through
* Microsoft Boogie in order to formally verify JML DbC annotations.
*/
public class Boogie extends DefaultCompilerExtension {
private static final boolean DEBUG = true;
/**
* The name of the compiler extension
*
* @return the compiler extension's name
*/
public String name() { return "JML4BOOGIE"; } //$NON-NLS-1$
/**
* Called by Eclipse's compilation mechanism before Java bytecode is generated for output.
*
* @param compiler the compiler object
* @param unit the root AST node of a Java source file to parse
*/
public void preCodeGeneration(Compiler compiler, CompilationUnitDeclaration unit) {
if (DEBUG) {
Logger.println(this + " - compiler.options.jmlEnabled: "+compiler.options.jmlEnabled); //$NON-NLS-1$
Logger.println(this + " - compiler.options.jmlBoogieEnabled: "+compiler.options.jmlBoogieEnabled); //$NON-NLS-1$
Logger.println(this + " - compiler.options.jmlBoogieOutputOnly: "+compiler.options.jmlBoogieOutputOnly); //$NON-NLS-1$
}
if (compiler.options.jmlEnabled && compiler.options.jmlDbcEnabled && compiler.options.jmlBoogieEnabled) {
process(compiler, unit);
}
}
/**
* Processes the AST, converts it to Boogie code and passes it to a Boogie runtime.
*
* @param compiler the compiler object passed by Eclipse
* @param unit the root ASTNode object
*/
private void process(Compiler compiler, CompilationUnitDeclaration unit) {
if (compiler.options.jmlBoogieOutputOnly) {
// debugging / testing
BoogieSource source = BoogieVisitor.visit(unit);
String results = source.getResults();
String[] resultsArray = results.split("/\\*!BOOGIESTART!\\*/"); //$NON-NLS-1$
- compiler.problemReporter.jmlEsc2Error(resultsArray[1], 0, 0);
+ if (resultsArray.length >= 2) {
+ compiler.problemReporter.jmlEsc2Error(resultsArray[1], 0, 0);
+ }
+ else {
+ compiler.problemReporter.jmlEsc2Error("Invalid or missing boogie:\n'" + results + "'", 0, 0); //$NON-NLS-1$ //$NON-NLS-2$
+ }
}
else {
BoogieAdapter adapter = new BoogieAdapter(compiler);
adapter.prove(unit);
}
}
/**
* Debugging method to print any compiler options relevant to this extension.
*
* @param options the compiler options to check
* @param buf the output buffer to add debugging info to
*/
public void optionsToBuffer(CompilerOptions options, StringBuffer buf) {
buf.append("\n\t\t- BOOGIE: ").append(options.jmlBoogieEnabled ? //$NON-NLS-1$
CompilerOptions.ENABLED : CompilerOptions.DISABLED);
}
}
| true | true | private void process(Compiler compiler, CompilationUnitDeclaration unit) {
if (compiler.options.jmlBoogieOutputOnly) {
// debugging / testing
BoogieSource source = BoogieVisitor.visit(unit);
String results = source.getResults();
String[] resultsArray = results.split("/\\*!BOOGIESTART!\\*/"); //$NON-NLS-1$
compiler.problemReporter.jmlEsc2Error(resultsArray[1], 0, 0);
}
else {
BoogieAdapter adapter = new BoogieAdapter(compiler);
adapter.prove(unit);
}
}
| private void process(Compiler compiler, CompilationUnitDeclaration unit) {
if (compiler.options.jmlBoogieOutputOnly) {
// debugging / testing
BoogieSource source = BoogieVisitor.visit(unit);
String results = source.getResults();
String[] resultsArray = results.split("/\\*!BOOGIESTART!\\*/"); //$NON-NLS-1$
if (resultsArray.length >= 2) {
compiler.problemReporter.jmlEsc2Error(resultsArray[1], 0, 0);
}
else {
compiler.problemReporter.jmlEsc2Error("Invalid or missing boogie:\n'" + results + "'", 0, 0); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else {
BoogieAdapter adapter = new BoogieAdapter(compiler);
adapter.prove(unit);
}
}
|
diff --git a/src/be/ibridge/kettle/repository/dialog/RepositoryImportProgressDialog.java b/src/be/ibridge/kettle/repository/dialog/RepositoryImportProgressDialog.java
index 742f2105..319dce32 100644
--- a/src/be/ibridge/kettle/repository/dialog/RepositoryImportProgressDialog.java
+++ b/src/be/ibridge/kettle/repository/dialog/RepositoryImportProgressDialog.java
@@ -1,428 +1,428 @@
/*
*
*
*/
package be.ibridge.kettle.repository.dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.dialog.ErrorDialog;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.repository.RepositoryDirectory;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
* Takes care of displaying a dialog that will handle the wait while we are importing a backup file from XML...
*
* @author Matt
* @since 03-jun-2005
*/
public class RepositoryImportProgressDialog extends Dialog
{
private LogWriter log;
private Shell shell, parent;
private Display display;
private Props props;
private Repository rep;
private String filename;
private RepositoryDirectory baseDirectory;
private ProgressBar wBar;
private Label wLabel;
private Text wLogging;
private Button wClose;
/**
* @deprecated
*/
public RepositoryImportProgressDialog(Shell parent, int style, LogWriter log, Props props, Repository rep, String filename, RepositoryDirectory baseDirectory)
{
super(parent, style);
this.log = log;
this.props = props;
this.parent = parent;
this.rep = rep;
this.filename = filename;
this.baseDirectory = baseDirectory;
}
public RepositoryImportProgressDialog(Shell parent, int style, Repository rep, String filename, RepositoryDirectory baseDirectory)
{
super(parent, style);
this.log = LogWriter.getInstance();
this.props = Props.getInstance();
this.parent = parent;
this.rep = rep;
this.filename = filename;
this.baseDirectory = baseDirectory;
}
public void open()
{
display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook(shell);
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setText("Import repository objects from XML");
shell.setLayout (formLayout);
//
// The progress bar on top...
////////////////////////////////////////////////////////////////////
wBar = new ProgressBar(shell, SWT.HORIZONTAL);
props.setLook(wBar);
FormData fdBar = new FormData();
fdBar.left = new FormAttachment(0,0);
fdBar.top = new FormAttachment(0,0);
fdBar.right = new FormAttachment(100,0);
wBar.setLayoutData(fdBar);
//
// Then the task line...
////////////////////////////////////////////////////////////////////
wLabel = new Label(shell, SWT.LEFT);
props.setLook(wLabel);
FormData fdLabel = new FormData();
fdLabel.left = new FormAttachment(0,0);
fdLabel.top = new FormAttachment(wBar, Const.MARGIN);
fdLabel.right = new FormAttachment(100,0);
wLabel.setLayoutData(fdLabel);
//
// The close button...
////////////////////////////////////////////////////////////////////
// Buttons
wClose = new Button(shell, SWT.PUSH);
wClose.setText(" &Close ");
BaseStepDialog.positionBottomButtons(shell, new Button[] { wClose }, Const.MARGIN, (Control)null);
wClose.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dispose(); } });
//
// Then the logging...
////////////////////////////////////////////////////////////////////
wLogging = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wLabel);
FormData fdLogging = new FormData();
fdLogging.left = new FormAttachment(0,0);
fdLogging.top = new FormAttachment(wLabel, Const.MARGIN);
fdLogging.right = new FormAttachment(100,0);
fdLogging.bottom = new FormAttachment(wClose, -Const.MARGIN);
wLogging.setLayoutData(fdLogging);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { dispose(); } } );
WindowProperty winprop = props.getScreen(shell.getText());
if (winprop!=null) winprop.setShell(shell, 640, 480); else shell.pack();
shell.open();
display.asyncExec(
new Runnable()
{
public void run()
{
importAll();
}
}
);
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
private void addLog(String line)
{
String rest = wLogging.getText();
wLogging.setText(rest+line+Const.CR);
wLogging.setSelection(wLogging.getText().length()); // make it scroll
}
private void importAll()
{
wLabel.setText("Importing repository objects from an XML file");
try
{
boolean overwrite = false;
boolean askOverwrite = true;
boolean makeDirectory = false;
boolean askDirectory = true;
addLog("Import objects from file ["+filename+"]");
// To where?
wLabel.setText("Asking in which directory to put the objects...");
Document doc = XMLHandler.loadXMLFile(filename);
if (doc!=null)
{
//
// HERE WE START
//
Node repnode = XMLHandler.getSubNode(doc, "repository");
Node transsnode = XMLHandler.getSubNode(repnode, "transformations");
if (transsnode!=null) // Load transformations...
{
int nrtrans = XMLHandler.countNodes(transsnode, "transformation");
wBar.setMinimum(0);
wBar.setMaximum(nrtrans);
for (int i=0;i<nrtrans;i++)
{
wBar.setSelection(i+1);
Node transnode = XMLHandler.getSubNodeByNr(transsnode, "transformation", i);
//
// Load transformation from XML into a directory, possibly created!
//
TransMeta ti = new TransMeta(transnode);
wLabel.setText("Importing transformation "+(i+1)+"/"+nrtrans+" : "+ti.getName());
// What's the directory path?
String directoryPath = XMLHandler.getTagValue(transnode, "info", "directory");
// remove the leading root, we never don't need it.
directoryPath = directoryPath.substring(1);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the transformation from XML and all went well...
// See if the transformation already existed!
long id = rep.getTransformationID(ti.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ti.getName()+"]",
null,
"The transformation ["+ti.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the transformation?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
askOverwrite = !md.getToggleState();
}
if (id<=0 || overwrite)
{
ti.setDirectory( targetDirectory ) ;
try
{
ti.saveRep(rep);
addLog("Saved transformation #"+i+" in the repository: ["+ti.getName()+"]");
}
catch(Exception e)
{
addLog("Unable to save transformation #"+i+" : ["+ti.getName()+") in the repository because of an error :"+e.toString());
addLog(Const.getStackTracker(e));
}
}
else
{
addLog("We didn't save transformation ["+ti.getName()+"]");
}
}
}
// Ask again for the jobs...
overwrite = false;
askOverwrite = true;
Node jobsnode = XMLHandler.getSubNode(repnode, "jobs");
if (jobsnode!=null) // Load jobs...
{
int nrjobs = XMLHandler.countNodes(jobsnode, "job");
wBar.setMinimum(0);
wBar.setMaximum(nrjobs);
for (int i=0;i<nrjobs;i++)
{
wBar.setSelection(i+1);
Node jobnode = XMLHandler.getSubNodeByNr(jobsnode, "job", i);
// Load the job from the XML node.
JobMeta ji = new JobMeta(log, jobnode, rep);
wLabel.setText("Importing job "+(i+1)+"/"+nrjobs+" : "+ji.getName());
// What's the directory path?
String directoryPath = Const.NVL(XMLHandler.getTagValue(jobnode, "directory"), Const.FILE_SEPARATOR);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the job from XML and all went well...
// See if the job already exists!
long id = rep.getJobID(ji.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ji.getName()+"]",
null,
"The job ["+ji.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the job?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
- askOverwrite = md.getToggleState();
+ askOverwrite = !md.getToggleState();
}
if (id<=0 || overwrite)
{
ji.setDirectory(targetDirectory);
ji.saveRep(rep);
addLog("Saved job #"+i+" in the repository: ["+ji.getName()+"]");
}
else
{
addLog("We didn't save job ["+ji.getName()+"]");
}
}
}
addLog("Finished importing.");
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage("Sorry, this is not a valid XML file."+Const.CR+"Please check the log for more information.");
mb.setText("ERROR");
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error importing repository objects", "There was an error while importing repository objects from an XML file", e);
}
}
}
| true | true | private void importAll()
{
wLabel.setText("Importing repository objects from an XML file");
try
{
boolean overwrite = false;
boolean askOverwrite = true;
boolean makeDirectory = false;
boolean askDirectory = true;
addLog("Import objects from file ["+filename+"]");
// To where?
wLabel.setText("Asking in which directory to put the objects...");
Document doc = XMLHandler.loadXMLFile(filename);
if (doc!=null)
{
//
// HERE WE START
//
Node repnode = XMLHandler.getSubNode(doc, "repository");
Node transsnode = XMLHandler.getSubNode(repnode, "transformations");
if (transsnode!=null) // Load transformations...
{
int nrtrans = XMLHandler.countNodes(transsnode, "transformation");
wBar.setMinimum(0);
wBar.setMaximum(nrtrans);
for (int i=0;i<nrtrans;i++)
{
wBar.setSelection(i+1);
Node transnode = XMLHandler.getSubNodeByNr(transsnode, "transformation", i);
//
// Load transformation from XML into a directory, possibly created!
//
TransMeta ti = new TransMeta(transnode);
wLabel.setText("Importing transformation "+(i+1)+"/"+nrtrans+" : "+ti.getName());
// What's the directory path?
String directoryPath = XMLHandler.getTagValue(transnode, "info", "directory");
// remove the leading root, we never don't need it.
directoryPath = directoryPath.substring(1);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the transformation from XML and all went well...
// See if the transformation already existed!
long id = rep.getTransformationID(ti.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ti.getName()+"]",
null,
"The transformation ["+ti.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the transformation?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
askOverwrite = !md.getToggleState();
}
if (id<=0 || overwrite)
{
ti.setDirectory( targetDirectory ) ;
try
{
ti.saveRep(rep);
addLog("Saved transformation #"+i+" in the repository: ["+ti.getName()+"]");
}
catch(Exception e)
{
addLog("Unable to save transformation #"+i+" : ["+ti.getName()+") in the repository because of an error :"+e.toString());
addLog(Const.getStackTracker(e));
}
}
else
{
addLog("We didn't save transformation ["+ti.getName()+"]");
}
}
}
// Ask again for the jobs...
overwrite = false;
askOverwrite = true;
Node jobsnode = XMLHandler.getSubNode(repnode, "jobs");
if (jobsnode!=null) // Load jobs...
{
int nrjobs = XMLHandler.countNodes(jobsnode, "job");
wBar.setMinimum(0);
wBar.setMaximum(nrjobs);
for (int i=0;i<nrjobs;i++)
{
wBar.setSelection(i+1);
Node jobnode = XMLHandler.getSubNodeByNr(jobsnode, "job", i);
// Load the job from the XML node.
JobMeta ji = new JobMeta(log, jobnode, rep);
wLabel.setText("Importing job "+(i+1)+"/"+nrjobs+" : "+ji.getName());
// What's the directory path?
String directoryPath = Const.NVL(XMLHandler.getTagValue(jobnode, "directory"), Const.FILE_SEPARATOR);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the job from XML and all went well...
// See if the job already exists!
long id = rep.getJobID(ji.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ji.getName()+"]",
null,
"The job ["+ji.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the job?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
askOverwrite = md.getToggleState();
}
if (id<=0 || overwrite)
{
ji.setDirectory(targetDirectory);
ji.saveRep(rep);
addLog("Saved job #"+i+" in the repository: ["+ji.getName()+"]");
}
else
{
addLog("We didn't save job ["+ji.getName()+"]");
}
}
}
addLog("Finished importing.");
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage("Sorry, this is not a valid XML file."+Const.CR+"Please check the log for more information.");
mb.setText("ERROR");
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error importing repository objects", "There was an error while importing repository objects from an XML file", e);
}
}
| private void importAll()
{
wLabel.setText("Importing repository objects from an XML file");
try
{
boolean overwrite = false;
boolean askOverwrite = true;
boolean makeDirectory = false;
boolean askDirectory = true;
addLog("Import objects from file ["+filename+"]");
// To where?
wLabel.setText("Asking in which directory to put the objects...");
Document doc = XMLHandler.loadXMLFile(filename);
if (doc!=null)
{
//
// HERE WE START
//
Node repnode = XMLHandler.getSubNode(doc, "repository");
Node transsnode = XMLHandler.getSubNode(repnode, "transformations");
if (transsnode!=null) // Load transformations...
{
int nrtrans = XMLHandler.countNodes(transsnode, "transformation");
wBar.setMinimum(0);
wBar.setMaximum(nrtrans);
for (int i=0;i<nrtrans;i++)
{
wBar.setSelection(i+1);
Node transnode = XMLHandler.getSubNodeByNr(transsnode, "transformation", i);
//
// Load transformation from XML into a directory, possibly created!
//
TransMeta ti = new TransMeta(transnode);
wLabel.setText("Importing transformation "+(i+1)+"/"+nrtrans+" : "+ti.getName());
// What's the directory path?
String directoryPath = XMLHandler.getTagValue(transnode, "info", "directory");
// remove the leading root, we never don't need it.
directoryPath = directoryPath.substring(1);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the transformation from XML and all went well...
// See if the transformation already existed!
long id = rep.getTransformationID(ti.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ti.getName()+"]",
null,
"The transformation ["+ti.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the transformation?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
askOverwrite = !md.getToggleState();
}
if (id<=0 || overwrite)
{
ti.setDirectory( targetDirectory ) ;
try
{
ti.saveRep(rep);
addLog("Saved transformation #"+i+" in the repository: ["+ti.getName()+"]");
}
catch(Exception e)
{
addLog("Unable to save transformation #"+i+" : ["+ti.getName()+") in the repository because of an error :"+e.toString());
addLog(Const.getStackTracker(e));
}
}
else
{
addLog("We didn't save transformation ["+ti.getName()+"]");
}
}
}
// Ask again for the jobs...
overwrite = false;
askOverwrite = true;
Node jobsnode = XMLHandler.getSubNode(repnode, "jobs");
if (jobsnode!=null) // Load jobs...
{
int nrjobs = XMLHandler.countNodes(jobsnode, "job");
wBar.setMinimum(0);
wBar.setMaximum(nrjobs);
for (int i=0;i<nrjobs;i++)
{
wBar.setSelection(i+1);
Node jobnode = XMLHandler.getSubNodeByNr(jobsnode, "job", i);
// Load the job from the XML node.
JobMeta ji = new JobMeta(log, jobnode, rep);
wLabel.setText("Importing job "+(i+1)+"/"+nrjobs+" : "+ji.getName());
// What's the directory path?
String directoryPath = Const.NVL(XMLHandler.getTagValue(jobnode, "directory"), Const.FILE_SEPARATOR);
RepositoryDirectory targetDirectory = baseDirectory.findDirectory(directoryPath);
if (targetDirectory==null)
{
if (askDirectory)
{
MessageDialogWithToggle mb = new MessageDialogWithToggle(shell,
"Create directory?",
null,
"The Directory ["+directoryPath+"] doesn't exists."+Const.CR+"Do you want me to create this directory?",
MessageDialog.QUESTION,
new String[] { "Yes", "No", "Cancel" },
1,
"Don't ask me again.",
!askDirectory
);
int answer = mb.open();
makeDirectory = answer==0;
askDirectory = !mb.getToggleState();
// Cancel?
if (answer==2) return;
}
if (makeDirectory)
{
addLog("Creating directory ["+directoryPath+"] in directory ["+baseDirectory+"]");
targetDirectory = baseDirectory.createDirectory(rep, directoryPath);
}
else
{
targetDirectory = baseDirectory;
}
}
// OK, we loaded the job from XML and all went well...
// See if the job already exists!
long id = rep.getJobID(ji.getName(), targetDirectory.getID());
if (id>0 && askOverwrite)
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
"["+ji.getName()+"]",
null,
"The job ["+ji.getName()+"] already exists in the repository."+Const.CR+"Do you want to overwrite the job?"+Const.CR,
MessageDialog.QUESTION,
new String[] { "Yes", "No" },
1,
"Don't ask me again.",
!askOverwrite
);
int answer = md.open();
overwrite = answer==0;
askOverwrite = !md.getToggleState();
}
if (id<=0 || overwrite)
{
ji.setDirectory(targetDirectory);
ji.saveRep(rep);
addLog("Saved job #"+i+" in the repository: ["+ji.getName()+"]");
}
else
{
addLog("We didn't save job ["+ji.getName()+"]");
}
}
}
addLog("Finished importing.");
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage("Sorry, this is not a valid XML file."+Const.CR+"Please check the log for more information.");
mb.setText("ERROR");
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, props, "Error importing repository objects", "There was an error while importing repository objects from an XML file", e);
}
}
|
diff --git a/src/common/basiccomponents/tile/TileEntityBatteryBox.java b/src/common/basiccomponents/tile/TileEntityBatteryBox.java
index 16a7c8a..793aeb4 100644
--- a/src/common/basiccomponents/tile/TileEntityBatteryBox.java
+++ b/src/common/basiccomponents/tile/TileEntityBatteryBox.java
@@ -1,673 +1,673 @@
package basiccomponents.tile;
import ic2.api.Direction;
import ic2.api.ElectricItem;
import ic2.api.EnergyNet;
import ic2.api.IElectricItem;
import ic2.api.IEnergySink;
import ic2.api.IEnergySource;
import ic2.api.IEnergyStorage;
import java.util.List;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.INetworkManager;
import net.minecraft.src.ItemStack;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet250CustomPayload;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.ISidedInventory;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.electricity.ElectricInfo;
import universalelectricity.core.electricity.ElectricityManager;
import universalelectricity.core.implement.IConductor;
import universalelectricity.core.implement.IElectricityReceiver;
import universalelectricity.core.implement.IItemElectric;
import universalelectricity.core.implement.IJouleStorage;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.implement.IRedstoneProvider;
import universalelectricity.prefab.network.IPacketReceiver;
import universalelectricity.prefab.network.PacketManager;
import universalelectricity.prefab.tile.TileEntityElectricityReceiver;
import basiccomponents.BCLoader;
import basiccomponents.block.BlockBasicMachine;
import buildcraft.api.power.IPowerProvider;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerFramework;
import buildcraft.api.power.PowerProvider;
import com.google.common.io.ByteArrayDataInput;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.LanguageRegistry;
import dan200.computer.api.IComputerAccess;
import dan200.computer.api.IPeripheral;
public class TileEntityBatteryBox extends TileEntityElectricityReceiver implements IEnergySink, IEnergySource, IEnergyStorage, IPowerReceptor, IJouleStorage, IPacketReceiver, IRedstoneProvider, IInventory, ISidedInventory, IPeripheral
{
private double joules = 0;
private ItemStack[] containingItems = new ItemStack[2];
private boolean isFull = false;
private int playersUsing = 0;
public IPowerProvider powerProvider;
public TileEntityBatteryBox()
{
super();
this.setPowerProvider(null);
}
@Override
public double wattRequest()
{
if (!this.isDisabled()) { return ElectricInfo.getWatts(this.getMaxJoules()) - ElectricInfo.getWatts(this.joules); }
return 0;
}
@Override
public boolean canReceiveFromSide(ForgeDirection side)
{
return side == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite();
}
@Override
public boolean canConnect(ForgeDirection side)
{
return canReceiveFromSide(side) || side == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
}
@Override
public void onReceive(Object sender, double amps, double voltage, ForgeDirection side)
{
if (!this.isDisabled())
{
this.setJoules(this.joules + ElectricInfo.getJoules(amps, voltage, 1));
}
}
@Override
public void initiate()
{
if (Loader.isModLoaded("IC2"))
{
try
{
if (Class.forName("ic2.common.EnergyNet").getMethod("getForWorld", World.class) != null)
{
EnergyNet.getForWorld(worldObj).addTileEntity(this);
FMLLog.fine("Added battery box to IC2 energy net.");
}
else
{
FMLLog.severe("Failed to register battery box to IC2 energy net.");
}
}
catch (Exception e)
{
FMLLog.severe("Failed to register battery box to IC2 energy net.");
}
}
}
@Override
public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
- double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules() * 0.005, this.getVoltage()), this.joules);
+ double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules(this.containingItems[0]) * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
- double joulesReceived = electricItem.onUse(electricItem.getMaxJoules() * 0.005, this.containingItems[1]);
+ double joulesReceived = electricItem.onUse(electricItem.getMaxJoules(this.containingItems[1]) * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
@Override
public Packet getDescriptionPacket()
{
return PacketManager.getPacket(BCLoader.CHANNEL, this, this.joules, this.disabledTicks);
}
@Override
public void handlePacketData(INetworkManager network, int type, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
try
{
this.joules = dataStream.readDouble();
this.disabledTicks = dataStream.readInt();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void openChest()
{
this.playersUsing++;
}
@Override
public void closeChest()
{
this.playersUsing--;
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound)
{
super.readFromNBT(par1NBTTagCompound);
this.joules = par1NBTTagCompound.getDouble("electricityStored");
NBTTagList var2 = par1NBTTagCompound.getTagList("Items");
this.containingItems = new ItemStack[this.getSizeInventory()];
for (int var3 = 0; var3 < var2.tagCount(); ++var3)
{
NBTTagCompound var4 = (NBTTagCompound) var2.tagAt(var3);
byte var5 = var4.getByte("Slot");
if (var5 >= 0 && var5 < this.containingItems.length)
{
this.containingItems[var5] = ItemStack.loadItemStackFromNBT(var4);
}
}
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound)
{
super.writeToNBT(par1NBTTagCompound);
par1NBTTagCompound.setDouble("electricityStored", this.joules);
NBTTagList var2 = new NBTTagList();
for (int var3 = 0; var3 < this.containingItems.length; ++var3)
{
if (this.containingItems[var3] != null)
{
NBTTagCompound var4 = new NBTTagCompound();
var4.setByte("Slot", (byte) var3);
this.containingItems[var3].writeToNBT(var4);
var2.appendTag(var4);
}
}
par1NBTTagCompound.setTag("Items", var2);
}
@Override
public int getStartInventorySide(ForgeDirection side)
{
if (side == side.DOWN) { return 1; }
if (side == side.UP) { return 1; }
return 0;
}
@Override
public int getSizeInventorySide(ForgeDirection side)
{
return 1;
}
@Override
public int getSizeInventory()
{
return this.containingItems.length;
}
@Override
public ItemStack getStackInSlot(int par1)
{
return this.containingItems[par1];
}
@Override
public ItemStack decrStackSize(int par1, int par2)
{
if (this.containingItems[par1] != null)
{
ItemStack var3;
if (this.containingItems[par1].stackSize <= par2)
{
var3 = this.containingItems[par1];
this.containingItems[par1] = null;
return var3;
}
else
{
var3 = this.containingItems[par1].splitStack(par2);
if (this.containingItems[par1].stackSize == 0)
{
this.containingItems[par1] = null;
}
return var3;
}
}
else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int par1)
{
if (this.containingItems[par1] != null)
{
ItemStack var2 = this.containingItems[par1];
this.containingItems[par1] = null;
return var2;
}
else
{
return null;
}
}
@Override
public void setInventorySlotContents(int par1, ItemStack par2ItemStack)
{
this.containingItems[par1] = par2ItemStack;
if (par2ItemStack != null && par2ItemStack.stackSize > this.getInventoryStackLimit())
{
par2ItemStack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public String getInvName()
{
return LanguageRegistry.instance().getStringLocalization("tile.bcMachine.1.name");
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer par1EntityPlayer)
{
return this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : par1EntityPlayer.getDistanceSq(this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D) <= 64.0D;
}
@Override
public boolean isPoweringTo(ForgeDirection side)
{
return this.isFull;
}
@Override
public boolean isIndirectlyPoweringTo(ForgeDirection side)
{
return isPoweringTo(side);
}
@Override
public double getJoules(Object... data)
{
return this.joules;
}
@Override
public void setJoules(double joules, Object... data)
{
this.joules = Math.max(Math.min(joules, this.getMaxJoules()), 0);
}
@Override
public double getMaxJoules(Object... data)
{
return 3000000;
}
/**
* BUILDCRAFT FUNCTIONS
*/
/**
* Is this tile entity a BC tile?
*/
public boolean isPoweredTile(TileEntity tileEntity)
{
if (tileEntity instanceof IPowerReceptor)
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
IPowerProvider provider = receptor.getPowerProvider();
return provider != null && provider.getClass().getSuperclass().equals(PowerProvider.class);
}
return false;
}
@Override
public void setPowerProvider(IPowerProvider provider)
{
if (provider == null)
{
if (PowerFramework.currentFramework != null)
{
powerProvider = PowerFramework.currentFramework.createPowerProvider();
powerProvider.configure(20, 25, 25, 25, (int) (this.getMaxJoules() * UniversalElectricity.BC3_RATIO));
}
}
else
{
this.powerProvider = provider;
}
}
@Override
public IPowerProvider getPowerProvider()
{
return this.powerProvider;
}
@Override
public void doWork()
{
}
@Override
public int powerRequest()
{
return (int) Math.ceil((this.getMaxJoules() - this.joules) * UniversalElectricity.BC3_RATIO);
}
/**
* INDUSTRIALCRAFT FUNCTIONS
*/
public int getStored()
{
return (int) (this.joules * UniversalElectricity.IC2_RATIO);
}
@Override
public boolean isAddedToEnergyNet()
{
return this.ticks > 0;
}
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, Direction direction)
{
return canReceiveFromSide(direction.toForgeDirection());
}
@Override
public boolean emitsEnergyTo(TileEntity receiver, Direction direction)
{
return direction.toForgeDirection() == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
}
@Override
public int getCapacity()
{
return (int) (this.getMaxJoules() / UniversalElectricity.IC2_RATIO);
}
@Override
public int getOutput()
{
return 32;
}
@Override
public int getMaxEnergyOutput()
{
return 32;
}
@Override
public boolean demandsEnergy()
{
if (!this.isDisabled() && UniversalElectricity.IC2_RATIO > 0) { return this.joules < getMaxJoules(); }
return false;
}
@Override
public int injectEnergy(Direction directionFrom, int euAmount)
{
if (!this.isDisabled())
{
double inputElectricity = euAmount * UniversalElectricity.IC2_RATIO;
double rejectedElectricity = Math.max(inputElectricity - (this.getMaxJoules() - this.joules), 0);
this.setJoules(joules + inputElectricity);
return (int) (rejectedElectricity * UniversalElectricity.TO_IC2_RATIO);
}
return euAmount;
}
/**
* COMPUTERCRAFT FUNCTIONS
*/
@Override
public String getType()
{
return "BatteryBox";
}
@Override
public String[] getMethodNames()
{
return new String[]
{ "getVoltage", "getWattage", "isFull" };
}
@Override
public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception
{
final int getVoltage = 0;
final int getWattage = 1;
final int isFull = 2;
switch (method)
{
case getVoltage:
return new Object[]
{ getVoltage() };
case getWattage:
return new Object[]
{ ElectricInfo.getWatts(joules) };
case isFull:
return new Object[]
{ isFull };
default:
throw new Exception("Function unimplemented");
}
}
@Override
public boolean canAttachToSide(int side)
{
return true;
}
@Override
public void attach(IComputerAccess computer, String computerSide)
{
}
@Override
public void detach(IComputerAccess computer)
{
}
}
| false | true | public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules() * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
double joulesReceived = electricItem.onUse(electricItem.getMaxJoules() * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
| public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules(this.containingItems[0]) * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
double joulesReceived = electricItem.onUse(electricItem.getMaxJoules(this.containingItems[1]) * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
|
diff --git a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java
index 46e166ea4..4c8e5b916 100644
--- a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java
+++ b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java
@@ -1,1528 +1,1528 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.nephele.executiongraph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.nephele.execution.Environment;
import eu.stratosphere.nephele.execution.ExecutionListener;
import eu.stratosphere.nephele.execution.ExecutionSignature;
import eu.stratosphere.nephele.execution.ExecutionState;
import eu.stratosphere.nephele.instance.AllocatedResource;
import eu.stratosphere.nephele.instance.DummyInstance;
import eu.stratosphere.nephele.instance.InstanceManager;
import eu.stratosphere.nephele.instance.InstanceType;
import eu.stratosphere.nephele.io.InputGate;
import eu.stratosphere.nephele.io.OutputGate;
import eu.stratosphere.nephele.io.channels.AbstractInputChannel;
import eu.stratosphere.nephele.io.channels.AbstractOutputChannel;
import eu.stratosphere.nephele.io.channels.ChannelID;
import eu.stratosphere.nephele.io.channels.ChannelSetupException;
import eu.stratosphere.nephele.io.channels.ChannelType;
import eu.stratosphere.nephele.io.channels.bytebuffered.NetworkOutputChannel;
import eu.stratosphere.nephele.io.compression.CompressionLevel;
import eu.stratosphere.nephele.jobgraph.AbstractJobVertex;
import eu.stratosphere.nephele.jobgraph.JobEdge;
import eu.stratosphere.nephele.jobgraph.JobFileOutputVertex;
import eu.stratosphere.nephele.jobgraph.JobGraph;
import eu.stratosphere.nephele.jobgraph.JobID;
import eu.stratosphere.nephele.jobgraph.JobInputVertex;
import eu.stratosphere.nephele.template.AbstractInputTask;
import eu.stratosphere.nephele.template.AbstractInvokable;
import eu.stratosphere.nephele.template.IllegalConfigurationException;
import eu.stratosphere.nephele.template.InputSplit;
import eu.stratosphere.nephele.types.Record;
import eu.stratosphere.nephele.util.StringUtils;
/**
* In Nephele an execution graph is the main data structure for scheduling, executing and
* observing a job. An execution graph is created from an job graph. In contrast to a job graph
* it can contain communication edges of specific types, sub groups of vertices and information on
* when and where (on which instance) to run particular tasks.
*
* @author warneke
*/
public class ExecutionGraph implements ExecutionListener {
/**
* The log object used for debugging.
*/
private static final Log LOG = LogFactory.getLog(ExecutionGraph.class);
/**
* The ID of the job this graph has been built for.
*/
private final JobID jobID;
/**
* The name of the original job graph.
*/
private final String jobName;
/**
* Mapping of channel IDs to execution vertices.
*/
private final Map<ChannelID, ExecutionVertex> channelToVertexMap = new HashMap<ChannelID, ExecutionVertex>();
/**
* Mapping of channel IDs to input channels.
*/
private final Map<ChannelID, AbstractInputChannel<? extends Record>> inputChannelMap = new HashMap<ChannelID, AbstractInputChannel<? extends Record>>();
/**
* Mapping of channel IDs to output channels.
*/
private final Map<ChannelID, AbstractOutputChannel<? extends Record>> outputChannelMap = new HashMap<ChannelID, AbstractOutputChannel<? extends Record>>();
/**
* List of stages in the graph.
*/
private final List<ExecutionStage> stages = new ArrayList<ExecutionStage>();
/**
* Index to the current execution stage.
*/
private int indexToCurrentExecutionStage = 0;
/**
* The job configuration that was originally attached to the JobGraph.
*/
private Configuration jobConfiguration;
/**
* The current status of the job which is represented by this execution graph.
*/
private InternalJobStatus jobStatus = InternalJobStatus.CREATED;
/**
* The error description of the first task which causes this job to fail.
*/
private volatile String errorDescription = null;
/**
* List of listeners which are notified in case the status of this job has changed.
*/
private List<JobStatusListener> jobStatusListeners = new ArrayList<JobStatusListener>();
/**
* List of listeners which are notified in case the execution stage of a job has changed.
*/
private List<ExecutionStageListener> executionStageListeners = new ArrayList<ExecutionStageListener>();
/**
* Private constructor used for duplicating execution vertices.
*
* @param jobID
* the ID of the duplicated execution graph
* @param jobName
* the name of the original job graph
*/
private ExecutionGraph(JobID jobID, String jobName) {
this.jobID = jobID;
this.jobName = jobName;
}
/**
* Creates a new execution graph from a job graph.
*
* @param job
* the user's job graph
* @param instanceManager
* the instance manager
* @throws GraphConversionException
* thrown if the job graph is not valid and no execution graph can be constructed from it
*/
public ExecutionGraph(JobGraph job, InstanceManager instanceManager) throws GraphConversionException {
this(job.getJobID(), job.getName());
// Start constructing the new execution graph from given job graph
try {
constructExecutionGraph(job, instanceManager);
} catch (Exception e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
}
/**
* Applies the user defined settings to the execution graph.
*
* @param temporaryGroupVertexMap
* mapping between job vertices and the corresponding group vertices.
* @throws GraphConversionException
* thrown if an error occurs while applying the user settings.
*/
private void applyUserDefinedSettings(HashMap<AbstractJobVertex, ExecutionGroupVertex> temporaryGroupVertexMap)
throws GraphConversionException {
// The check for cycles in the dependency chain for instance sharing is already checked in
// <code>submitJob</code> method of the job manager
// If there is no cycle, apply the settings to the corresponding group vertices
final Iterator<Map.Entry<AbstractJobVertex, ExecutionGroupVertex>> it = temporaryGroupVertexMap.entrySet()
.iterator();
while (it.hasNext()) {
final Map.Entry<AbstractJobVertex, ExecutionGroupVertex> entry = it.next();
final AbstractJobVertex jobVertex = entry.getKey();
if (jobVertex.getVertexToShareInstancesWith() != null) {
final AbstractJobVertex vertexToShareInstancesWith = jobVertex.getVertexToShareInstancesWith();
final ExecutionGroupVertex groupVertex = entry.getValue();
final ExecutionGroupVertex groupVertexToShareInstancesWith = temporaryGroupVertexMap
.get(vertexToShareInstancesWith);
groupVertex.shareInstancesWith(groupVertexToShareInstancesWith);
}
}
// Second, we create the number of members each group vertex is supposed to have
Iterator<ExecutionGroupVertex> it2 = new ExecutionGroupVertexIterator(this, true, -1);
while (it2.hasNext()) {
final ExecutionGroupVertex groupVertex = it2.next();
if (groupVertex.isNumberOfMembersUserDefined()) {
groupVertex.changeNumberOfGroupMembers(groupVertex.getUserDefinedNumberOfMembers());
}
}
repairInstanceAssignment();
// Finally, apply the channel settings channel settings
it2 = new ExecutionGroupVertexIterator(this, true, -1);
while (it2.hasNext()) {
final ExecutionGroupVertex groupVertex = it2.next();
for (int i = 0; i < groupVertex.getNumberOfForwardLinks(); i++) {
final ExecutionGroupEdge edge = groupVertex.getForwardEdge(i);
if (edge.isChannelTypeUserDefined()) {
edge.changeChannelType(edge.getChannelType());
}
if (edge.isCompressionLevelUserDefined()) {
edge.changeCompressionLevel(edge.getCompressionLevel());
}
}
}
// TODO: Check if calling this is really necessary, if not set visibility of reassignInstances back to protected
it2 = new ExecutionGroupVertexIterator(this, true, -1);
while (it2.hasNext()) {
final ExecutionGroupVertex groupVertex = it2.next();
if (groupVertex.getVertexToShareInstancesWith() == null) {
groupVertex.reassignInstances();
this.repairInstanceAssignment();
}
}
}
/**
* Sets up an execution graph from a job graph.
*
* @param jobGraph
* the job graph to create the execution graph from
* @param instanceManager
* the instance manager
* @throws GraphConversionException
* thrown if the job graph is not valid and no execution graph can be constructed from it
*/
private void constructExecutionGraph(JobGraph jobGraph, InstanceManager instanceManager)
throws GraphConversionException {
// Clean up temporary data structures
final HashMap<AbstractJobVertex, ExecutionVertex> temporaryVertexMap = new HashMap<AbstractJobVertex, ExecutionVertex>();
final HashMap<AbstractJobVertex, ExecutionGroupVertex> temporaryGroupVertexMap = new HashMap<AbstractJobVertex, ExecutionGroupVertex>();
// First, store job configuration
this.jobConfiguration = jobGraph.getJobConfiguration();
// Initially, create only one execution stage that contains all group vertices
final ExecutionStage initialExecutionStage = new ExecutionStage(this, 0);
this.stages.add(initialExecutionStage);
// Convert job vertices to execution vertices and initialize them
final AbstractJobVertex[] all = jobGraph.getAllJobVertices();
for (int i = 0; i < all.length; i++) {
final ExecutionVertex createdVertex = createVertex(all[i], instanceManager, initialExecutionStage);
temporaryVertexMap.put(all[i], createdVertex);
temporaryGroupVertexMap.put(all[i], createdVertex.getGroupVertex());
}
// Create initial network channel for every vertex
for (int i = 0; i < all.length; i++) {
createInitialChannels(all[i], temporaryVertexMap);
}
// Now that an initial graph is built, apply the user settings
applyUserDefinedSettings(temporaryGroupVertexMap);
}
/**
* Creates the initial channels between all connected job vertices.
*
* @param jobVertex
* the job vertex from which the wiring is determined
* @param vertexMap
* a temporary vertex map
* @throws GraphConversionException
* if the initial wiring cannot be created
*/
private void createInitialChannels(AbstractJobVertex jobVertex,
HashMap<AbstractJobVertex, ExecutionVertex> vertexMap) throws GraphConversionException {
ExecutionVertex ev;
if (!vertexMap.containsKey(jobVertex)) {
throw new GraphConversionException("Cannot find mapping for vertex " + jobVertex.getName());
}
ev = vertexMap.get(jobVertex);
// First compare number of output gates
if (jobVertex.getNumberOfForwardConnections() != ev.getEnvironment().getNumberOfOutputGates()) {
throw new GraphConversionException("Job and execution vertex " + jobVertex.getName()
+ " have different number of outputs");
}
if (jobVertex.getNumberOfBackwardConnections() != ev.getEnvironment().getNumberOfInputGates()) {
throw new GraphConversionException("Job and execution vertex " + jobVertex.getName()
+ " have different number of inputs");
}
// Now assign identifiers to gates and check type
for (int j = 0; j < jobVertex.getNumberOfForwardConnections(); j++) {
final JobEdge edge = jobVertex.getForwardConnection(j);
final AbstractJobVertex target = edge.getConnectedVertex();
// find output gate of execution vertex
final OutputGate<? extends Record> eog = ev.getEnvironment().getOutputGate(j);
if (eog == null) {
throw new GraphConversionException("Cannot retrieve output gate " + j + " from vertex "
+ jobVertex.getName());
}
final ExecutionVertex executionTarget = vertexMap.get(target);
if (executionTarget == null) {
throw new GraphConversionException("Cannot find mapping for vertex " + target.getName());
}
final InputGate<? extends Record> eig = executionTarget.getEnvironment().getInputGate(
edge.getIndexOfInputGate());
if (eig == null) {
throw new GraphConversionException("Cannot retrieve input gate " + edge.getIndexOfInputGate()
+ " from vertex " + target.getName());
}
ChannelType channelType = ChannelType.NETWORK;
CompressionLevel compressionLevel = CompressionLevel.NO_COMPRESSION;
boolean userDefinedChannelType = false;
boolean userDefinedCompressionLevel = false;
// Create a network channel with no compression by default, user settings will be applied later on
createChannel(ev, eog, executionTarget, eig, channelType, compressionLevel);
if (edge.getChannelType() != null) {
channelType = edge.getChannelType();
userDefinedChannelType = true;
}
if (edge.getCompressionLevel() != null) {
compressionLevel = edge.getCompressionLevel();
userDefinedCompressionLevel = true;
}
// Connect the corresponding group vertices and copy the user settings from the job edge
ev.getGroupVertex().wireTo(executionTarget.getGroupVertex(), edge.getIndexOfInputGate(), j, channelType,
userDefinedChannelType, compressionLevel, userDefinedCompressionLevel);
}
}
/**
* Destroys all the channels originating from the source vertex at the given output gate and arriving at the target
* vertex at the given
* input gate. All destroyed channels are completely unregistered with the {@link ExecutionGraph}.
*
* @param source
* the source vertex the channels to be removed originate from
* @param indexOfOutputGate
* the index of the output gate the channels to be removed are assigned to
* @param target
* the target vertex the channels to be removed arrive
* @param indexOfInputGate
* the index of the input gate the channels to be removed are assigned to
* @throws GraphConversionException
* thrown if an inconsistency during the unwiring process occurs
*/
public void unwire(ExecutionGroupVertex source, int indexOfOutputGate, ExecutionGroupVertex target,
int indexOfInputGate) throws GraphConversionException {
// Unwire the respective gate of the source vertices
for (int i = 0; i < source.getCurrentNumberOfGroupMembers(); i++) {
final ExecutionVertex sourceVertex = source.getGroupMember(i);
final OutputGate<? extends Record> outputGate = sourceVertex.getEnvironment().getOutputGate(
indexOfOutputGate);
if (outputGate == null) {
throw new GraphConversionException("unwire: " + sourceVertex.getName()
+ " has no output gate with index " + indexOfOutputGate);
}
for (int j = 0; j < outputGate.getNumberOfOutputChannels(); j++) {
final AbstractOutputChannel<? extends Record> outputChannel = outputGate.getOutputChannel(j);
this.outputChannelMap.remove(outputChannel.getID());
this.channelToVertexMap.remove(outputChannel.getID());
}
outputGate.removeAllOutputChannels();
}
// Unwire the respective gate of the target vertices
for (int i = 0; i < target.getCurrentNumberOfGroupMembers(); i++) {
final ExecutionVertex targetVertex = target.getGroupMember(i);
final InputGate<? extends Record> inputGate = targetVertex.getEnvironment().getInputGate(indexOfInputGate);
if (inputGate == null) {
throw new GraphConversionException("unwire: " + targetVertex.getName()
+ " has no input gate with index " + indexOfInputGate);
}
for (int j = 0; j < inputGate.getNumberOfInputChannels(); j++) {
final AbstractInputChannel<? extends Record> inputChannel = inputGate.getInputChannel(j);
this.inputChannelMap.remove(inputChannel.getID());
this.channelToVertexMap.remove(inputChannel.getID());
}
inputGate.removeAllInputChannels();
}
}
public void wire(ExecutionGroupVertex source, int indexOfOutputGate, ExecutionGroupVertex target,
int indexOfInputGate, ChannelType channelType, CompressionLevel compressionLevel)
throws GraphConversionException {
// Unwire the respective gate of the source vertices
for (int i = 0; i < source.getCurrentNumberOfGroupMembers(); i++) {
final ExecutionVertex sourceVertex = source.getGroupMember(i);
final OutputGate<? extends Record> outputGate = sourceVertex.getEnvironment().getOutputGate(
indexOfOutputGate);
if (outputGate == null) {
throw new GraphConversionException("wire: " + sourceVertex.getName()
+ " has no output gate with index " + indexOfOutputGate);
}
if (outputGate.getNumberOfOutputChannels() > 0) {
throw new GraphConversionException("wire: wire called on source " + sourceVertex.getName() + " (" + i
+ "), but number of output channels is " + outputGate.getNumberOfOutputChannels() + "!");
}
for (int j = 0; j < target.getCurrentNumberOfGroupMembers(); j++) {
final ExecutionVertex targetVertex = target.getGroupMember(j);
final InputGate<? extends Record> inputGate = targetVertex.getEnvironment().getInputGate(
indexOfInputGate);
if (inputGate == null) {
throw new GraphConversionException("wire: " + targetVertex.getName()
+ " has no input gate with index " + indexOfInputGate);
}
if (inputGate.getNumberOfInputChannels() > 0 && i == 0) {
throw new GraphConversionException("wire: wire called on target " + targetVertex.getName() + " ("
+ j + "), but number of input channels is " + inputGate.getNumberOfInputChannels() + "!");
}
// Check if a wire is supposed to be created
if (inputGate.getDistributionPattern().createWire(i, j, source.getCurrentNumberOfGroupMembers(),
target.getCurrentNumberOfGroupMembers())) {
createChannel(sourceVertex, outputGate, targetVertex, inputGate, channelType, compressionLevel);
}
}
}
}
private void createChannel(ExecutionVertex source, OutputGate<? extends Record> outputGate, ExecutionVertex target,
InputGate<? extends Record> inputGate, ChannelType channelType, CompressionLevel compressionLevel)
throws GraphConversionException {
AbstractOutputChannel<? extends Record> outputChannel;
AbstractInputChannel<? extends Record> inputChannel;
switch (channelType) {
case NETWORK:
outputChannel = outputGate.createNetworkOutputChannel(null, compressionLevel);
inputChannel = inputGate.createNetworkInputChannel(null, compressionLevel);
break;
case INMEMORY:
outputChannel = outputGate.createInMemoryOutputChannel(null, compressionLevel);
inputChannel = inputGate.createInMemoryInputChannel(null, compressionLevel);
break;
case FILE:
outputChannel = outputGate.createFileOutputChannel(null, compressionLevel);
inputChannel = inputGate.createFileInputChannel(null, compressionLevel);
break;
default:
throw new GraphConversionException("Cannot create channel: unknown type");
}
// Copy the number of the opposite channel
inputChannel.setConnectedChannelID(outputChannel.getID());
outputChannel.setConnectedChannelID(inputChannel.getID());
this.outputChannelMap.put(outputChannel.getID(), outputChannel);
this.inputChannelMap.put(inputChannel.getID(), inputChannel);
this.channelToVertexMap.put(outputChannel.getID(), source);
this.channelToVertexMap.put(inputChannel.getID(), target);
}
/**
* Creates an execution vertex from a job vertex.
*
* @param jobVertex
* the job vertex to create the execution vertex from
* @param instanceManager
* the instanceManager
* @param initialExecutionStage
* the initial execution stage all group vertices are added to
* @return the new execution vertex
* @throws GraphConversionException
* thrown if the job vertex is of an unknown subclass
*/
private ExecutionVertex createVertex(AbstractJobVertex jobVertex, InstanceManager instanceManager,
ExecutionStage initialExecutionStage) throws GraphConversionException {
// If the user has requested instance type, check if the type is known by the current instance manager
InstanceType instanceType = null;
boolean userDefinedInstanceType = false;
if (jobVertex.getInstanceType() != null) {
userDefinedInstanceType = true;
instanceType = instanceManager.getInstanceTypeByName(jobVertex.getInstanceType());
if (instanceType == null) {
throw new GraphConversionException("Requested instance type " + jobVertex.getInstanceType()
+ " is not known to the instance manager");
}
}
if (instanceType == null) {
instanceType = instanceManager.getDefaultInstanceType();
}
// Calculate the cryptographic signature of this vertex
final ExecutionSignature signature = ExecutionSignature.createSignature(jobVertex.getInvokableClass(),
jobVertex.getJobGraph().getJobID());
// Create a group vertex for the job vertex
final ExecutionGroupVertex groupVertex = new ExecutionGroupVertex(jobVertex.getName(), jobVertex.getID(), this,
jobVertex.getNumberOfSubtasks(), instanceType, userDefinedInstanceType, jobVertex
.getNumberOfSubtasksPerInstance(), jobVertex.getVertexToShareInstancesWith() != null ? true : false,
jobVertex.getConfiguration(), signature);
// Create an initial execution vertex for the job vertex
final Class<? extends AbstractInvokable> invokableClass = jobVertex.getInvokableClass();
if (invokableClass == null) {
throw new GraphConversionException("JobVertex " + jobVertex.getID() + " (" + jobVertex.getName()
+ ") does not specify a task");
}
// Add group vertex to initial execution stage
initialExecutionStage.addStageMember(groupVertex);
ExecutionVertex ev = null;
try {
ev = new ExecutionVertex(jobVertex.getJobGraph().getJobID(), invokableClass, this,
groupVertex);
} catch (Exception e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Run the configuration check the user has provided for the vertex
try {
jobVertex.checkConfiguration(ev.getEnvironment().getInvokable());
} catch (IllegalConfigurationException e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Check if the user's specifications for the number of subtasks are valid
final int minimumNumberOfSubtasks = jobVertex.getMinimumNumberOfSubtasks(ev.getEnvironment().getInvokable());
final int maximumNumberOfSubtasks = jobVertex.getMaximumNumberOfSubtasks(ev.getEnvironment().getInvokable());
if (jobVertex.getNumberOfSubtasks() != -1) {
if (jobVertex.getNumberOfSubtasks() < 1) {
throw new GraphConversionException("Cannot split task " + jobVertex.getName() + " into "
+ jobVertex.getNumberOfSubtasks() + " subtasks");
}
if (jobVertex.getNumberOfSubtasks() < minimumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks must be at least " + minimumNumberOfSubtasks);
}
if (maximumNumberOfSubtasks != -1) {
if (jobVertex.getNumberOfSubtasks() > maximumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks for vertex " + jobVertex.getName()
+ " can be at most " + maximumNumberOfSubtasks);
}
}
}
// Check number of subtasks per instance
if (jobVertex.getNumberOfSubtasksPerInstance() != -1 && jobVertex.getNumberOfSubtasksPerInstance() < 1) {
throw new GraphConversionException("Cannot set number of subtasks per instance to "
+ jobVertex.getNumberOfSubtasksPerInstance() + " for vertex " + jobVertex.getName());
}
// Assign min/max to the group vertex (settings are actually applied in applyUserDefinedSettings)
groupVertex.setMinMemberSize(minimumNumberOfSubtasks);
groupVertex.setMaxMemberSize(maximumNumberOfSubtasks);
// Assign initial instance to vertex (may be overwritten later on when user settings are applied)
ev.setAllocatedResource(new AllocatedResource(DummyInstance.createDummyInstance(instanceType), instanceType,
null));
// Register input and output vertices separately
if (jobVertex instanceof JobInputVertex) {
final InputSplit[] inputSplits;
// let the task code compute the input splits
if (ev.getEnvironment().getInvokable() instanceof AbstractInputTask) {
try {
- inputSplits = ((AbstractInputTask) ev.getEnvironment().getInvokable()).
+ inputSplits = ((AbstractInputTask<?>) ev.getEnvironment().getInvokable()).
computeInputSplits(jobVertex.getNumberOfSubtasks());
}
catch (Exception e) {
throw new GraphConversionException("Cannot compute input splits for " + groupVertex.getName() + ": "
+ StringUtils.stringifyException(e));
}
}
else {
throw new GraphConversionException(
"BUG: JobInputVertex contained a task class which was not an input task.");
}
// assign input splits
groupVertex.setInputSplits(inputSplits);
}
// TODO: This is a quick workaround, problem can be solved in a more generic way
if (jobVertex instanceof JobFileOutputVertex) {
final JobFileOutputVertex jbov = (JobFileOutputVertex) jobVertex;
jobVertex.getConfiguration().setString("outputPath", jbov.getFilePath().toString());
}
return ev;
}
/**
* Returns the number of input vertices registered with this execution graph.
*
* @return the number of input vertices registered with this execution graph
*/
public int getNumberOfInputVertices() {
return this.stages.get(0).getNumberOfInputExecutionVertices();
}
/**
* Returns the number of input vertices for the given stage.
*
* @param stage
* the index of the execution stage
* @return the number of input vertices for the given stage
*/
public int getNumberOfInputVertices(int stage) {
if (stage >= this.stages.size()) {
return 0;
}
return this.stages.get(stage).getNumberOfInputExecutionVertices();
}
/**
* Returns the number of output vertices registered with this execution graph.
*
* @return the number of output vertices registered with this execution graph
*/
public int getNumberOfOutputVertices() {
return this.stages.get(0).getNumberOfOutputExecutionVertices();
}
/**
* Returns the number of output vertices for the given stage.
*
* @param stage
* the index of the execution stage
* @return the number of input vertices for the given stage
*/
public int getNumberOfOutputVertices(int stage) {
if (stage >= this.stages.size()) {
return 0;
}
return this.stages.get(stage).getNumberOfOutputExecutionVertices();
}
/**
* Returns the input vertex with the specified index.
*
* @param index
* the index of the input vertex to return
* @return the input vertex with the specified index or <code>null</code> if no input vertex with such an index
* exists
*/
public ExecutionVertex getInputVertex(int index) {
return this.stages.get(0).getInputExecutionVertex(index);
}
/**
* Returns the output vertex with the specified index.
*
* @param index
* the index of the output vertex to return
* @return the output vertex with the specified index or <code>null</code> if no output vertex with such an index
* exists
*/
public ExecutionVertex getOutputVertex(int index) {
return this.stages.get(0).getOutputExecutionVertex(index);
}
/**
* Returns the input vertex with the specified index for the given stage
*
* @param stage
* the index of the stage
* @param index
* the index of the input vertex to return
* @return the input vertex with the specified index or <code>null</code> if no input vertex with such an index
* exists in that stage
*/
public ExecutionVertex getInputVertex(int stage, int index) {
if (stage >= this.stages.size()) {
return null;
}
return this.stages.get(stage).getInputExecutionVertex(index);
}
/**
* Returns the output vertex with the specified index for the given stage.
*
* @param stage
* the index of the stage
* @param index
* the index of the output vertex to return
* @return the output vertex with the specified index or <code>null</code> if no output vertex with such an index
* exists in that stage
*/
public ExecutionVertex getOutputVertex(int stage, int index) {
if (stage >= this.stages.size()) {
return null;
}
return this.stages.get(stage).getOutputExecutionVertex(index);
}
/**
* Returns the execution stage with number <code>num</code>.
*
* @param num
* the number of the execution stage to be returned
* @return the execution stage with number <code>num</code> or <code>null</code> if no such execution stage exists
*/
public ExecutionStage getStage(int num) {
if (num < this.stages.size()) {
return this.stages.get(num);
}
return null;
}
/**
* Returns the number of execution stages in the execution graph.
*
* @return the number of execution stages in the execution graph
*/
public int getNumberOfStages() {
return this.stages.size();
}
/**
* Identifies an execution by the specified channel ID and returns it.
*
* @param id
* the channel ID to identify the vertex with
* @return the execution vertex which has a channel with ID <code>id</code> or <code>null</code> if no such vertex
* exists in the execution graph
*/
public ExecutionVertex getVertexByChannelID(ChannelID id) {
if (!this.channelToVertexMap.containsKey(id)) {
return null;
}
return this.channelToVertexMap.get(id);
}
/**
* Finds an input channel by its ID and returns it.
*
* @param id
* the channel ID to identify the input channel
* @return the input channel whose ID matches <code>id</code> or <code>null</code> if no such channel is known
*/
public AbstractInputChannel<? extends Record> getInputChannelByID(ChannelID id) {
if (!this.inputChannelMap.containsKey(id)) {
return null;
}
return this.inputChannelMap.get(id);
}
/**
* Finds an output channel by its ID and returns it.
*
* @param id
* the channel ID to identify the output channel
* @return the output channel whose ID matches <code>id</code> or <code>null</code> if no such channel is known
*/
public AbstractOutputChannel<? extends Record> getOutputChannelByID(ChannelID id) {
if (!this.outputChannelMap.containsKey(id)) {
return null;
}
return this.outputChannelMap.get(id);
}
/**
* Returns a (possibly empty) list of execution vertices which are currently assigned to the
* given allocated resource. The vertices in that list may have an arbitrary execution state.
*
* @param allocatedResource
* the allocated resource to check the assignment for
* @return a (possibly empty) list of execution vertices which are currently assigned to the given instance
*/
public synchronized List<ExecutionVertex> getVerticesAssignedToResource(AllocatedResource allocatedResource) {
final List<ExecutionVertex> list = new ArrayList<ExecutionVertex>();
if (allocatedResource == null) {
return list;
}
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
if (allocatedResource.equals(vertex.getAllocatedResource())) {
list.add(vertex);
}
}
return list;
}
public ExecutionVertex getVertexByID(ExecutionVertexID id) {
if (id == null) {
return null;
}
final ExecutionGraphIterator it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
if (vertex.getID().equals(id)) {
return vertex;
}
}
return null;
}
public ExecutionVertex getVertexByEnvironment(Environment environment) {
if (environment == null) {
return null;
}
final ExecutionGraphIterator it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
if (vertex.getEnvironment() == environment) {
return vertex;
}
}
return null;
}
/**
* Checks if the current execution stage has been successfully completed, i.e.
* all vertices in this stage have successfully finished their execution.
*
* @return <code>true</code> if stage is completed, <code>false</code> otherwise
*/
private boolean isCurrentStageCompleted() {
if (this.indexToCurrentExecutionStage >= this.stages.size()) {
return true;
}
final ExecutionGraphIterator it = new ExecutionGraphIterator(this, this.indexToCurrentExecutionStage, true,
true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
if (vertex.getExecutionState() != ExecutionState.FINISHED) {
return false;
}
}
return true;
}
/**
* Checks if the execution of execution graph is finished.
*
* @return <code>true</code> if the execution of the graph is finished, <code>false</code> otherwise
*/
public boolean isExecutionFinished() {
return (getJobStatus() == InternalJobStatus.FINISHED);
}
public void prepareChannelsForExecution(ExecutionVertex executionVertex) throws ChannelSetupException {
// Prepare channels
for (int k = 0; k < executionVertex.getEnvironment().getNumberOfOutputGates(); k++) {
final OutputGate<? extends Record> outputGate = executionVertex.getEnvironment().getOutputGate(k);
for (int l = 0; l < outputGate.getNumberOfOutputChannels(); l++) {
final AbstractOutputChannel<? extends Record> outputChannel = outputGate.getOutputChannel(l);
final AbstractInputChannel<? extends Record> inputChannel = this.inputChannelMap.get(outputChannel
.getConnectedChannelID());
if (inputChannel == null) {
throw new ChannelSetupException("Cannot find input channel to output channel "
+ outputChannel.getID());
}
final ExecutionVertex targetVertex = this.channelToVertexMap.get(inputChannel.getID());
final AllocatedResource targetResources = targetVertex.getAllocatedResource();
if (targetResources == null) {
throw new ChannelSetupException("Cannot find allocated resources for target vertex "
+ targetVertex.getID() + " in instance map");
}
if (targetResources.getInstance() instanceof DummyInstance) {
throw new ChannelSetupException("Allocated instance for " + targetVertex.getID()
+ " is a dummy vertex!");
}
}
}
}
/**
* Returns the job ID of the job configuration this execution graph was originally constructed from.
*
* @return the job ID of the job configuration this execution graph was originally constructed from
*/
public JobID getJobID() {
return this.jobID;
}
public void removeUnnecessaryNetworkChannels(int stageNumber) {
if (stageNumber >= this.stages.size()) {
throw new IllegalArgumentException("removeUnnecessaryNetworkChannels called on an illegal stage ("
+ stageNumber + ")");
}
final ExecutionStage executionStage = this.stages.get(stageNumber);
for (int i = 0; i < executionStage.getNumberOfStageMembers(); i++) {
final ExecutionGroupVertex groupVertex = executionStage.getStageMember(i);
for (int j = 0; j < groupVertex.getCurrentNumberOfGroupMembers(); j++) {
final ExecutionVertex sourceVertex = groupVertex.getGroupMember(j);
for (int k = 0; k < sourceVertex.getEnvironment().getNumberOfOutputGates(); k++) {
final OutputGate<? extends Record> outputGate = sourceVertex.getEnvironment().getOutputGate(k);
for (int l = 0; l < outputGate.getNumberOfOutputChannels(); l++) {
final AbstractOutputChannel<? extends Record> oldOutputChannel = outputGate.getOutputChannel(l);
// Skip if not a network channel
if (!(oldOutputChannel instanceof NetworkOutputChannel<?>)) {
continue;
}
// Get matching input channel
final ExecutionVertex targetVertex = this.channelToVertexMap.get(oldOutputChannel
.getConnectedChannelID());
if (targetVertex == null) {
throw new RuntimeException("Cannot find target vertex: Inconsistency...");
}
// Run on the same instance?
if (!targetVertex.getAllocatedResource().getInstance().equals(
sourceVertex.getAllocatedResource().getInstance())) {
continue;
}
final AbstractInputChannel<? extends Record> oldInputChannel = getInputChannelByID(oldOutputChannel
.getConnectedChannelID());
final InputGate<? extends Record> inputGate = oldInputChannel.getInputGate();
// Replace channels
final AbstractOutputChannel<? extends Record> newOutputChannel = outputGate.replaceChannel(
oldOutputChannel.getID(), ChannelType.INMEMORY);
final AbstractInputChannel<? extends Record> newInputChannel = inputGate.replaceChannel(
oldInputChannel.getID(), ChannelType.INMEMORY);
// The new channels reuse the IDs of the old channels, so only the channel maps must be updated
this.outputChannelMap.put(newOutputChannel.getID(), newOutputChannel);
this.inputChannelMap.put(newInputChannel.getID(), newInputChannel);
}
}
}
}
}
/**
* Returns the index of the current execution stage.
*
* @return the index of the current execution stage
*/
public int getIndexOfCurrentExecutionStage() {
return this.indexToCurrentExecutionStage;
}
/**
* Returns the stage which is currently executed.
*
* @return the currently executed stage or <code>null</code> if the job execution is already completed
*/
public ExecutionStage getCurrentExecutionStage() {
if (this.indexToCurrentExecutionStage >= this.stages.size()) {
return null;
}
return this.stages.get(this.indexToCurrentExecutionStage);
}
public void repairStages() {
final Map<ExecutionGroupVertex, Integer> stageNumbers = new HashMap<ExecutionGroupVertex, Integer>();
ExecutionGroupVertexIterator it = new ExecutionGroupVertexIterator(this, true, -1);
while (it.hasNext()) {
final ExecutionGroupVertex groupVertex = it.next();
int precedingNumber = 0;
if (stageNumbers.containsKey(groupVertex)) {
precedingNumber = stageNumbers.get(groupVertex).intValue();
} else {
stageNumbers.put(groupVertex, Integer.valueOf(precedingNumber));
}
for (int i = 0; i < groupVertex.getNumberOfForwardLinks(); i++) {
final ExecutionGroupEdge edge = groupVertex.getForwardEdge(i);
if (!stageNumbers.containsKey(edge.getTargetVertex())) {
// Target vertex has not yet been discovered
if (edge.getChannelType() != ChannelType.FILE) {
// Same stage as preceding vertex
stageNumbers.put(edge.getTargetVertex(), Integer.valueOf(precedingNumber));
} else {
// File channel, increase stage of target vertex by one
stageNumbers.put(edge.getTargetVertex(), Integer.valueOf(precedingNumber + 1));
}
} else {
final int stageNumber = stageNumbers.get(edge.getTargetVertex()).intValue();
if (edge.getChannelType() != ChannelType.FILE) {
if (stageNumber != precedingNumber) {
stageNumbers.put(edge.getTargetVertex(), (int) Math.max(precedingNumber, stageNumber));
}
} else {
// File channel, increase stage of target vertex by one
if (stageNumber != (precedingNumber + 1)) {
stageNumbers.put(edge.getTargetVertex(), (int) Math.max(precedingNumber + 1, stageNumber));
}
}
}
}
}
// Traverse the graph backwards (starting from the output vertices) to make sure vertices are allocated in a
// stage as high as possible
it = new ExecutionGroupVertexIterator(this, false, -1);
while (it.hasNext()) {
final ExecutionGroupVertex groupVertex = it.next();
final int succeedingNumber = stageNumbers.get(groupVertex);
for (int i = 0; i < groupVertex.getNumberOfBackwardLinks(); i++) {
final ExecutionGroupEdge edge = groupVertex.getBackwardEdge(i);
final int stageNumber = stageNumbers.get(edge.getSourceVertex());
if (edge.getChannelType() == ChannelType.FILE) {
if (stageNumber < (succeedingNumber - 1)) {
stageNumbers.put(edge.getSourceVertex(), Integer.valueOf(succeedingNumber - 1));
}
} else {
if (stageNumber != succeedingNumber) {
LOG.error(edge.getSourceVertex() + " and " + edge.getTargetVertex()
+ " are assigned to different stages although not connected by a file channel");
}
}
}
}
// Finally, assign the new stage numbers
this.stages.clear();
final Iterator<Map.Entry<ExecutionGroupVertex, Integer>> it2 = stageNumbers.entrySet().iterator();
while (it2.hasNext()) {
final Map.Entry<ExecutionGroupVertex, Integer> entry = it2.next();
final ExecutionGroupVertex groupVertex = entry.getKey();
final int stageNumber = entry.getValue().intValue();
// Prevent out of bounds exceptions
while (this.stages.size() <= stageNumber) {
this.stages.add(null);
}
ExecutionStage executionStage = this.stages.get(stageNumber);
// If the stage not yet exists,
if (executionStage == null) {
executionStage = new ExecutionStage(this, stageNumber);
this.stages.set(stageNumber, executionStage);
}
executionStage.addStageMember(groupVertex);
groupVertex.setExecutionStage(executionStage);
}
}
public void repairInstanceAssignment() {
Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionVertex sourceVertex = it.next();
for (int i = 0; i < sourceVertex.getEnvironment().getNumberOfOutputGates(); i++) {
final OutputGate<? extends Record> outputGate = sourceVertex.getEnvironment().getOutputGate(i);
for (int j = 0; j < outputGate.getNumberOfOutputChannels(); j++) {
final AbstractOutputChannel<? extends Record> outputChannel = outputGate.getOutputChannel(j);
final ChannelType channelType = outputChannel.getType();
if (channelType == ChannelType.FILE || channelType == ChannelType.INMEMORY) {
final ExecutionVertex targetVertex = getVertexByChannelID(outputChannel.getConnectedChannelID());
targetVertex.setAllocatedResource(sourceVertex.getAllocatedResource());
}
}
}
}
it = new ExecutionGraphIterator(this, false);
while (it.hasNext()) {
final ExecutionVertex targetVertex = it.next();
for (int i = 0; i < targetVertex.getEnvironment().getNumberOfInputGates(); i++) {
final InputGate<? extends Record> inputGate = targetVertex.getEnvironment().getInputGate(i);
for (int j = 0; j < inputGate.getNumberOfInputChannels(); j++) {
final AbstractInputChannel<? extends Record> inputChannel = inputGate.getInputChannel(j);
final ChannelType channelType = inputChannel.getType();
if (channelType == ChannelType.FILE || channelType == ChannelType.INMEMORY) {
final ExecutionVertex sourceVertex = getVertexByChannelID(inputChannel.getConnectedChannelID());
sourceVertex.setAllocatedResource(targetVertex.getAllocatedResource());
}
}
}
}
}
public ChannelType getChannelType(ExecutionVertex sourceVertex, ExecutionVertex targetVertex) {
final ExecutionGroupVertex sourceGroupVertex = sourceVertex.getGroupVertex();
final ExecutionGroupVertex targetGroupVertex = targetVertex.getGroupVertex();
final List<ExecutionGroupEdge> edges = sourceGroupVertex.getForwardEdges(targetGroupVertex);
if (edges.size() == 0) {
return null;
}
// On a task level, the two vertices are connected
final ExecutionGroupEdge edge = edges.get(0);
// Now lets see if these two concrete subtasks are connected
final OutputGate<? extends Record> outputGate = sourceVertex.getEnvironment().getOutputGate(
edge.getIndexOfOutputGate());
for (int i = 0; i < outputGate.getNumberOfOutputChannels(); i++) {
final AbstractOutputChannel<? extends Record> outputChannel = outputGate.getOutputChannel(i);
final ChannelID inputChannelID = outputChannel.getConnectedChannelID();
if (targetVertex == this.channelToVertexMap.get(inputChannelID)) {
return edge.getChannelType();
}
}
return null;
}
/**
* Returns the job configuration that was originally attached to the job graph.
*
* @return the job configuration that was originally attached to the job graph
*/
public Configuration getJobConfiguration() {
return this.jobConfiguration;
}
/**
* Checks whether the job represented by the execution graph has the status <code>FINISHED</code>.
*
* @return <code>true</code> if the job has the status <code>CREATED</code>, <code>false</code> otherwise
*/
private boolean jobHasFinishedStatus() {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
if (it.next().getExecutionState() != ExecutionState.FINISHED) {
return false;
}
}
return true;
}
/**
* Checks whether the job represented by the execution graph has the status <code>SCHEDULED</code>.
*
* @return <code>true</code> if the job has the status <code>SCHEDULED</code>, <code>false</code> otherwise
*/
private boolean jobHasScheduledStatus() {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionState s = it.next().getExecutionState();
if (s != ExecutionState.CREATED && s != ExecutionState.SCHEDULED && s != ExecutionState.ASSIGNING
&& s != ExecutionState.ASSIGNED && s != ExecutionState.READY) {
return false;
}
}
return true;
}
/**
* Checks whether the job represented by the execution graph has the status <code>CANCELED</code> or
* <code>FAILED</code>.
*
* @return <code>true</code> if the job has the status <code>CANCELED</code> or <code>FAILED</code>,
* <code>false</code> otherwise
*/
private boolean jobHasFailedOrCanceledStatus() {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionState state = it.next().getExecutionState();
if (state != ExecutionState.CANCELED && state != ExecutionState.FAILED && state != ExecutionState.FINISHED) {
return false;
}
}
return true;
}
/**
* Checks and updates the current execution status of the
* job which is represented by this execution graph.
*
* @param latestStateChange
* the latest execution state change which occurred
*/
public synchronized void checkAndUpdateJobStatus(final ExecutionState latestStateChange) {
switch (this.jobStatus) {
case CREATED:
if (jobHasScheduledStatus()) {
this.jobStatus = InternalJobStatus.SCHEDULED;
} else if (latestStateChange == ExecutionState.CANCELED) {
if (jobHasFailedOrCanceledStatus()) {
this.jobStatus = InternalJobStatus.CANCELED;
}
}
break;
case SCHEDULED:
if (latestStateChange == ExecutionState.RUNNING) {
this.jobStatus = InternalJobStatus.RUNNING;
return;
} else if (latestStateChange == ExecutionState.CANCELED) {
if (jobHasFailedOrCanceledStatus()) {
this.jobStatus = InternalJobStatus.CANCELED;
}
}
break;
case RUNNING:
if (latestStateChange == ExecutionState.CANCELING || latestStateChange == ExecutionState.CANCELED) {
this.jobStatus = InternalJobStatus.CANCELING;
return;
}
if (latestStateChange == ExecutionState.FAILED) {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
if (vertex.getExecutionState() == ExecutionState.FAILED && !vertex.hasRetriesLeft()) {
this.jobStatus = InternalJobStatus.FAILING;
return;
}
}
}
if (jobHasFinishedStatus()) {
this.jobStatus = InternalJobStatus.FINISHED;
}
break;
case FAILING:
if (jobHasFailedOrCanceledStatus()) {
this.jobStatus = InternalJobStatus.FAILED;
}
break;
case FAILED:
LOG.error("Received update of execute state in job status FAILED");
break;
case CANCELING:
if (jobHasFailedOrCanceledStatus()) {
this.jobStatus = InternalJobStatus.CANCELED;
}
break;
case CANCELED:
LOG.error("Received update of execute state in job status CANCELED");
break;
case FINISHED:
LOG.error("Received update of execute state in job status FINISHED");
break;
}
}
/**
* Returns the current status of the job
* represented by this execution graph.
*
* @return the current status of the job
*/
public synchronized InternalJobStatus getJobStatus() {
return this.jobStatus;
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void executionStateChanged(Environment ee, ExecutionState newExecutionState,
String optionalMessage) {
final InternalJobStatus oldStatus = this.jobStatus;
checkAndUpdateJobStatus(newExecutionState);
if (newExecutionState == ExecutionState.FINISHED) {
// It is worth checking if the current stage has complete
if (this.isCurrentStageCompleted()) {
// Increase current execution stage
++this.indexToCurrentExecutionStage;
if (this.indexToCurrentExecutionStage < this.stages.size()) {
final Iterator<ExecutionStageListener> it = this.executionStageListeners.iterator();
final ExecutionStage nextExecutionStage = getCurrentExecutionStage();
while (it.hasNext()) {
it.next().nextExecutionStageEntered(ee.getJobID(), nextExecutionStage);
}
}
}
}
if (this.jobStatus != oldStatus) {
// The task caused the entire job to fail, save the error description
if (this.jobStatus == InternalJobStatus.FAILING) {
this.errorDescription = optionalMessage;
}
// If this is the final failure state change, reuse the saved error description
if (this.jobStatus == InternalJobStatus.FAILED) {
optionalMessage = this.errorDescription;
}
final Iterator<JobStatusListener> it = this.jobStatusListeners.iterator();
while (it.hasNext()) {
it.next().jobStatusHasChanged(this, this.jobStatus, optionalMessage);
}
}
}
/**
* Registers a new {@link JobStatusListener} object with this execution graph.
* After being registered the object will receive notifications about changes
* of the job status. It is not possible to register the same listener object
* twice.
*
* @param jobStatusListener
* the listener object to register
*/
public synchronized void registerJobStatusListener(final JobStatusListener jobStatusListener) {
if (jobStatusListener == null) {
return;
}
if (!this.jobStatusListeners.contains(jobStatusListener)) {
this.jobStatusListeners.add(jobStatusListener);
}
}
/**
* Unregisters the given {@link JobStatusListener} object. After having called this
* method, the object will no longer receive notifications about changes of the job
* status.
*
* @param jobStatusListener
* the listener object to unregister
*/
public synchronized void unregisterJobStatusListener(final JobStatusListener jobStatusListener) {
if (jobStatusListener == null) {
return;
}
this.jobStatusListeners.remove(jobStatusListener);
}
/**
* Registers a new {@link ExecutionStageListener} object with this execution graph. After being registered the
* object will receive a notification whenever the job has entered its next execution stage. Note that a
* notification is not sent when the job has entered its initial execution stage.
*
* @param executionStageListener
* the listener object to register
*/
public synchronized void registerExecutionStageListener(final ExecutionStageListener executionStageListener) {
if (executionStageListener == null) {
return;
}
if (!this.executionStageListeners.contains(executionStageListener)) {
this.executionStageListeners.add(executionStageListener);
}
}
/**
* Unregisters the given {@link ExecutionStageListener} object. After having called this method, the object will no
* longer receiver notifications about the execution stage progress.
*
* @param executionStageListener
* the listener object to unregister
*/
public synchronized void unregisterExecutionStageListener(final ExecutionStageListener executionStageListener) {
if (executionStageListener == null) {
return;
}
this.executionStageListeners.remove(executionStageListener);
}
/**
* Returns the name of the original job graph.
*
* @return the name of the original job graph, possibly <code>null</code>
*/
public String getJobName() {
return this.jobName;
}
/**
* {@inheritDoc}
*/
@Override
public void userThreadFinished(Environment ee, Thread userThread) {
// Nothing to do here
}
/**
* {@inheritDoc}
*/
@Override
public void userThreadStarted(Environment ee, Thread userThread) {
// Nothing to do here
}
/**
* Returns a list of vertices which are contained in this execution graph and have a finished checkpoint.
*
* @return list of vertices which are contained in this execution graph and have a finished checkpoint
*/
public List<ExecutionVertex> getVerticesWithCheckpoints() {
final List<ExecutionVertex> list = new ArrayList<ExecutionVertex>();
final Iterator<ExecutionGroupVertex> it = new ExecutionGroupVertexIterator(this, true, -1);
// In the current implementation we just look for vertices which have outgoing file channels
while (it.hasNext()) {
final ExecutionGroupVertex groupVertex = it.next();
for (int i = 0; i < groupVertex.getNumberOfForwardLinks(); i++) {
if (groupVertex.getForwardEdge(i).getChannelType() == ChannelType.FILE) {
for (int j = 0; j < groupVertex.getCurrentNumberOfGroupMembers(); j++) {
list.add(groupVertex.getGroupMember(j));
}
break;
}
}
}
return list;
}
}
| true | true | private ExecutionVertex createVertex(AbstractJobVertex jobVertex, InstanceManager instanceManager,
ExecutionStage initialExecutionStage) throws GraphConversionException {
// If the user has requested instance type, check if the type is known by the current instance manager
InstanceType instanceType = null;
boolean userDefinedInstanceType = false;
if (jobVertex.getInstanceType() != null) {
userDefinedInstanceType = true;
instanceType = instanceManager.getInstanceTypeByName(jobVertex.getInstanceType());
if (instanceType == null) {
throw new GraphConversionException("Requested instance type " + jobVertex.getInstanceType()
+ " is not known to the instance manager");
}
}
if (instanceType == null) {
instanceType = instanceManager.getDefaultInstanceType();
}
// Calculate the cryptographic signature of this vertex
final ExecutionSignature signature = ExecutionSignature.createSignature(jobVertex.getInvokableClass(),
jobVertex.getJobGraph().getJobID());
// Create a group vertex for the job vertex
final ExecutionGroupVertex groupVertex = new ExecutionGroupVertex(jobVertex.getName(), jobVertex.getID(), this,
jobVertex.getNumberOfSubtasks(), instanceType, userDefinedInstanceType, jobVertex
.getNumberOfSubtasksPerInstance(), jobVertex.getVertexToShareInstancesWith() != null ? true : false,
jobVertex.getConfiguration(), signature);
// Create an initial execution vertex for the job vertex
final Class<? extends AbstractInvokable> invokableClass = jobVertex.getInvokableClass();
if (invokableClass == null) {
throw new GraphConversionException("JobVertex " + jobVertex.getID() + " (" + jobVertex.getName()
+ ") does not specify a task");
}
// Add group vertex to initial execution stage
initialExecutionStage.addStageMember(groupVertex);
ExecutionVertex ev = null;
try {
ev = new ExecutionVertex(jobVertex.getJobGraph().getJobID(), invokableClass, this,
groupVertex);
} catch (Exception e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Run the configuration check the user has provided for the vertex
try {
jobVertex.checkConfiguration(ev.getEnvironment().getInvokable());
} catch (IllegalConfigurationException e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Check if the user's specifications for the number of subtasks are valid
final int minimumNumberOfSubtasks = jobVertex.getMinimumNumberOfSubtasks(ev.getEnvironment().getInvokable());
final int maximumNumberOfSubtasks = jobVertex.getMaximumNumberOfSubtasks(ev.getEnvironment().getInvokable());
if (jobVertex.getNumberOfSubtasks() != -1) {
if (jobVertex.getNumberOfSubtasks() < 1) {
throw new GraphConversionException("Cannot split task " + jobVertex.getName() + " into "
+ jobVertex.getNumberOfSubtasks() + " subtasks");
}
if (jobVertex.getNumberOfSubtasks() < minimumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks must be at least " + minimumNumberOfSubtasks);
}
if (maximumNumberOfSubtasks != -1) {
if (jobVertex.getNumberOfSubtasks() > maximumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks for vertex " + jobVertex.getName()
+ " can be at most " + maximumNumberOfSubtasks);
}
}
}
// Check number of subtasks per instance
if (jobVertex.getNumberOfSubtasksPerInstance() != -1 && jobVertex.getNumberOfSubtasksPerInstance() < 1) {
throw new GraphConversionException("Cannot set number of subtasks per instance to "
+ jobVertex.getNumberOfSubtasksPerInstance() + " for vertex " + jobVertex.getName());
}
// Assign min/max to the group vertex (settings are actually applied in applyUserDefinedSettings)
groupVertex.setMinMemberSize(minimumNumberOfSubtasks);
groupVertex.setMaxMemberSize(maximumNumberOfSubtasks);
// Assign initial instance to vertex (may be overwritten later on when user settings are applied)
ev.setAllocatedResource(new AllocatedResource(DummyInstance.createDummyInstance(instanceType), instanceType,
null));
// Register input and output vertices separately
if (jobVertex instanceof JobInputVertex) {
final InputSplit[] inputSplits;
// let the task code compute the input splits
if (ev.getEnvironment().getInvokable() instanceof AbstractInputTask) {
try {
inputSplits = ((AbstractInputTask) ev.getEnvironment().getInvokable()).
computeInputSplits(jobVertex.getNumberOfSubtasks());
}
catch (Exception e) {
throw new GraphConversionException("Cannot compute input splits for " + groupVertex.getName() + ": "
+ StringUtils.stringifyException(e));
}
}
else {
throw new GraphConversionException(
"BUG: JobInputVertex contained a task class which was not an input task.");
}
// assign input splits
groupVertex.setInputSplits(inputSplits);
}
// TODO: This is a quick workaround, problem can be solved in a more generic way
if (jobVertex instanceof JobFileOutputVertex) {
final JobFileOutputVertex jbov = (JobFileOutputVertex) jobVertex;
jobVertex.getConfiguration().setString("outputPath", jbov.getFilePath().toString());
}
return ev;
}
| private ExecutionVertex createVertex(AbstractJobVertex jobVertex, InstanceManager instanceManager,
ExecutionStage initialExecutionStage) throws GraphConversionException {
// If the user has requested instance type, check if the type is known by the current instance manager
InstanceType instanceType = null;
boolean userDefinedInstanceType = false;
if (jobVertex.getInstanceType() != null) {
userDefinedInstanceType = true;
instanceType = instanceManager.getInstanceTypeByName(jobVertex.getInstanceType());
if (instanceType == null) {
throw new GraphConversionException("Requested instance type " + jobVertex.getInstanceType()
+ " is not known to the instance manager");
}
}
if (instanceType == null) {
instanceType = instanceManager.getDefaultInstanceType();
}
// Calculate the cryptographic signature of this vertex
final ExecutionSignature signature = ExecutionSignature.createSignature(jobVertex.getInvokableClass(),
jobVertex.getJobGraph().getJobID());
// Create a group vertex for the job vertex
final ExecutionGroupVertex groupVertex = new ExecutionGroupVertex(jobVertex.getName(), jobVertex.getID(), this,
jobVertex.getNumberOfSubtasks(), instanceType, userDefinedInstanceType, jobVertex
.getNumberOfSubtasksPerInstance(), jobVertex.getVertexToShareInstancesWith() != null ? true : false,
jobVertex.getConfiguration(), signature);
// Create an initial execution vertex for the job vertex
final Class<? extends AbstractInvokable> invokableClass = jobVertex.getInvokableClass();
if (invokableClass == null) {
throw new GraphConversionException("JobVertex " + jobVertex.getID() + " (" + jobVertex.getName()
+ ") does not specify a task");
}
// Add group vertex to initial execution stage
initialExecutionStage.addStageMember(groupVertex);
ExecutionVertex ev = null;
try {
ev = new ExecutionVertex(jobVertex.getJobGraph().getJobID(), invokableClass, this,
groupVertex);
} catch (Exception e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Run the configuration check the user has provided for the vertex
try {
jobVertex.checkConfiguration(ev.getEnvironment().getInvokable());
} catch (IllegalConfigurationException e) {
throw new GraphConversionException(StringUtils.stringifyException(e));
}
// Check if the user's specifications for the number of subtasks are valid
final int minimumNumberOfSubtasks = jobVertex.getMinimumNumberOfSubtasks(ev.getEnvironment().getInvokable());
final int maximumNumberOfSubtasks = jobVertex.getMaximumNumberOfSubtasks(ev.getEnvironment().getInvokable());
if (jobVertex.getNumberOfSubtasks() != -1) {
if (jobVertex.getNumberOfSubtasks() < 1) {
throw new GraphConversionException("Cannot split task " + jobVertex.getName() + " into "
+ jobVertex.getNumberOfSubtasks() + " subtasks");
}
if (jobVertex.getNumberOfSubtasks() < minimumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks must be at least " + minimumNumberOfSubtasks);
}
if (maximumNumberOfSubtasks != -1) {
if (jobVertex.getNumberOfSubtasks() > maximumNumberOfSubtasks) {
throw new GraphConversionException("Number of subtasks for vertex " + jobVertex.getName()
+ " can be at most " + maximumNumberOfSubtasks);
}
}
}
// Check number of subtasks per instance
if (jobVertex.getNumberOfSubtasksPerInstance() != -1 && jobVertex.getNumberOfSubtasksPerInstance() < 1) {
throw new GraphConversionException("Cannot set number of subtasks per instance to "
+ jobVertex.getNumberOfSubtasksPerInstance() + " for vertex " + jobVertex.getName());
}
// Assign min/max to the group vertex (settings are actually applied in applyUserDefinedSettings)
groupVertex.setMinMemberSize(minimumNumberOfSubtasks);
groupVertex.setMaxMemberSize(maximumNumberOfSubtasks);
// Assign initial instance to vertex (may be overwritten later on when user settings are applied)
ev.setAllocatedResource(new AllocatedResource(DummyInstance.createDummyInstance(instanceType), instanceType,
null));
// Register input and output vertices separately
if (jobVertex instanceof JobInputVertex) {
final InputSplit[] inputSplits;
// let the task code compute the input splits
if (ev.getEnvironment().getInvokable() instanceof AbstractInputTask) {
try {
inputSplits = ((AbstractInputTask<?>) ev.getEnvironment().getInvokable()).
computeInputSplits(jobVertex.getNumberOfSubtasks());
}
catch (Exception e) {
throw new GraphConversionException("Cannot compute input splits for " + groupVertex.getName() + ": "
+ StringUtils.stringifyException(e));
}
}
else {
throw new GraphConversionException(
"BUG: JobInputVertex contained a task class which was not an input task.");
}
// assign input splits
groupVertex.setInputSplits(inputSplits);
}
// TODO: This is a quick workaround, problem can be solved in a more generic way
if (jobVertex instanceof JobFileOutputVertex) {
final JobFileOutputVertex jbov = (JobFileOutputVertex) jobVertex;
jobVertex.getConfiguration().setString("outputPath", jbov.getFilePath().toString());
}
return ev;
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java
index a9814fa6..9caebc48 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java
@@ -1,160 +1,166 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity.core.services;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import us.nineworlds.plex.rest.model.impl.Directory;
import us.nineworlds.plex.rest.model.impl.Genre;
import us.nineworlds.plex.rest.model.impl.MediaContainer;
import us.nineworlds.serenity.core.model.impl.TVShowSeriesInfo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
/**
* @author dcarver
*
*/
public class ShowRetrievalIntentService extends AbstractPlexRESTIntentService {
private List<TVShowSeriesInfo> tvShowList = null;
protected String key;
protected String category;
public ShowRetrievalIntentService() {
super("ShowRetrievalIntentService");
tvShowList = new ArrayList<TVShowSeriesInfo>();
}
@Override
public void sendMessageResults(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.obj = tvShowList;
try {
messenger.send(msg);
} catch (RemoteException ex) {
Log.e(getClass().getName(), "Unable to send message", ex);
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
key = intent.getExtras().getString("key");
category = intent.getExtras().getString("category");
createBanners();
sendMessageResults(intent);
}
protected void createBanners() {
MediaContainer mc = null;
String baseUrl = null;
try {
mc = retrieveVideos();
baseUrl = factory.baseURL();
} catch (IOException ex) {
Log.e(getClass().getName(), "Unable to talk to server: ", ex);
} catch (Exception e) {
Log.e(getClass().getName(), "Oops.", e);
}
if (mc != null && mc.getSize() > 0) {
List<Directory> shows = mc.getDirectories();
if (shows != null) {
for (Directory show : shows) {
TVShowSeriesInfo mpi = new TVShowSeriesInfo();
if (show.getSummary() != null) {
mpi.setPlotSummary(show.getSummary());
}
String burl = factory.baseURL()
+ ":/resources/show-fanart.jpg";
if (show.getArt() != null) {
burl = baseUrl + show.getArt().replaceFirst("/", "");
}
mpi.setBackgroundURL(burl);
String turl = "";
if (show.getBanner() != null) {
turl = baseUrl + show.getBanner().replaceFirst("/", "");
}
mpi.setPosterURL(turl);
String thumbURL = "";
if (show.getThumb() != null) {
thumbURL = baseUrl
+ show.getThumb().replaceFirst("/", "");
}
mpi.setThumbNailURL(thumbURL);
mpi.setTitle(show.getTitle());
mpi.setContentRating(show.getContentRating());
List<String> genres = processGeneres(show);
mpi.setGeneres(genres);
mpi.setShowsWatched(show.getViewedLeafCount());
- int totalEpisodes = Integer.parseInt(show.getLeafCount());
- int unwatched = totalEpisodes
- - Integer.parseInt(show.getViewedLeafCount());
+ int totalEpisodes = 0;
+ int viewedEpisodes = 0;
+ if (show.getLeafCount() != null) {
+ totalEpisodes = Integer.parseInt(show.getLeafCount());
+ }
+ if (show.getViewedLeafCount() != null) {
+ viewedEpisodes = Integer.parseInt(show.getViewedLeafCount());
+ }
+ int unwatched = totalEpisodes - viewedEpisodes;
mpi.setShowsUnwatched(Integer.toString(unwatched));
mpi.setKey(show.getKey());
tvShowList.add(mpi);
}
}
}
}
protected MediaContainer retrieveVideos() throws Exception {
if (category == null) {
category = "all";
}
return factory.retrieveSections(key, category);
}
protected List<String> processGeneres(Directory show) {
ArrayList<String> genres = new ArrayList<String>();
if (show.getGenres() != null) {
for (Genre genre : show.getGenres()) {
genres.add(genre.getTag());
}
}
return genres;
}
}
| true | true | protected void createBanners() {
MediaContainer mc = null;
String baseUrl = null;
try {
mc = retrieveVideos();
baseUrl = factory.baseURL();
} catch (IOException ex) {
Log.e(getClass().getName(), "Unable to talk to server: ", ex);
} catch (Exception e) {
Log.e(getClass().getName(), "Oops.", e);
}
if (mc != null && mc.getSize() > 0) {
List<Directory> shows = mc.getDirectories();
if (shows != null) {
for (Directory show : shows) {
TVShowSeriesInfo mpi = new TVShowSeriesInfo();
if (show.getSummary() != null) {
mpi.setPlotSummary(show.getSummary());
}
String burl = factory.baseURL()
+ ":/resources/show-fanart.jpg";
if (show.getArt() != null) {
burl = baseUrl + show.getArt().replaceFirst("/", "");
}
mpi.setBackgroundURL(burl);
String turl = "";
if (show.getBanner() != null) {
turl = baseUrl + show.getBanner().replaceFirst("/", "");
}
mpi.setPosterURL(turl);
String thumbURL = "";
if (show.getThumb() != null) {
thumbURL = baseUrl
+ show.getThumb().replaceFirst("/", "");
}
mpi.setThumbNailURL(thumbURL);
mpi.setTitle(show.getTitle());
mpi.setContentRating(show.getContentRating());
List<String> genres = processGeneres(show);
mpi.setGeneres(genres);
mpi.setShowsWatched(show.getViewedLeafCount());
int totalEpisodes = Integer.parseInt(show.getLeafCount());
int unwatched = totalEpisodes
- Integer.parseInt(show.getViewedLeafCount());
mpi.setShowsUnwatched(Integer.toString(unwatched));
mpi.setKey(show.getKey());
tvShowList.add(mpi);
}
}
}
}
| protected void createBanners() {
MediaContainer mc = null;
String baseUrl = null;
try {
mc = retrieveVideos();
baseUrl = factory.baseURL();
} catch (IOException ex) {
Log.e(getClass().getName(), "Unable to talk to server: ", ex);
} catch (Exception e) {
Log.e(getClass().getName(), "Oops.", e);
}
if (mc != null && mc.getSize() > 0) {
List<Directory> shows = mc.getDirectories();
if (shows != null) {
for (Directory show : shows) {
TVShowSeriesInfo mpi = new TVShowSeriesInfo();
if (show.getSummary() != null) {
mpi.setPlotSummary(show.getSummary());
}
String burl = factory.baseURL()
+ ":/resources/show-fanart.jpg";
if (show.getArt() != null) {
burl = baseUrl + show.getArt().replaceFirst("/", "");
}
mpi.setBackgroundURL(burl);
String turl = "";
if (show.getBanner() != null) {
turl = baseUrl + show.getBanner().replaceFirst("/", "");
}
mpi.setPosterURL(turl);
String thumbURL = "";
if (show.getThumb() != null) {
thumbURL = baseUrl
+ show.getThumb().replaceFirst("/", "");
}
mpi.setThumbNailURL(thumbURL);
mpi.setTitle(show.getTitle());
mpi.setContentRating(show.getContentRating());
List<String> genres = processGeneres(show);
mpi.setGeneres(genres);
mpi.setShowsWatched(show.getViewedLeafCount());
int totalEpisodes = 0;
int viewedEpisodes = 0;
if (show.getLeafCount() != null) {
totalEpisodes = Integer.parseInt(show.getLeafCount());
}
if (show.getViewedLeafCount() != null) {
viewedEpisodes = Integer.parseInt(show.getViewedLeafCount());
}
int unwatched = totalEpisodes - viewedEpisodes;
mpi.setShowsUnwatched(Integer.toString(unwatched));
mpi.setKey(show.getKey());
tvShowList.add(mpi);
}
}
}
}
|
diff --git a/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java b/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java
index 033f0cc8..84aa71d5 100644
--- a/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java
+++ b/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java
@@ -1,871 +1,882 @@
package org.red5.server.net.rtmp.codec;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2007 by respective authors (see below). All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.ByteBuffer;
import org.red5.io.amf.AMF;
import org.red5.io.object.Deserializer;
import org.red5.io.object.Input;
import org.red5.io.utils.BufferUtils;
import org.red5.server.api.IConnection;
import org.red5.server.api.IContext;
import org.red5.server.api.IScope;
import org.red5.server.api.Red5;
import org.red5.server.api.IConnection.Encoding;
import org.red5.server.net.protocol.HandshakeFailedException;
import org.red5.server.net.protocol.ProtocolException;
import org.red5.server.net.protocol.ProtocolState;
import org.red5.server.net.protocol.SimpleProtocolDecoder;
import org.red5.server.net.rtmp.RTMPUtils;
import org.red5.server.net.rtmp.event.AudioData;
import org.red5.server.net.rtmp.event.BytesRead;
import org.red5.server.net.rtmp.event.ChunkSize;
import org.red5.server.net.rtmp.event.ClientBW;
import org.red5.server.net.rtmp.event.FlexMessage;
import org.red5.server.net.rtmp.event.IRTMPEvent;
import org.red5.server.net.rtmp.event.Invoke;
import org.red5.server.net.rtmp.event.Notify;
import org.red5.server.net.rtmp.event.Ping;
import org.red5.server.net.rtmp.event.ServerBW;
import org.red5.server.net.rtmp.event.Unknown;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.net.rtmp.message.Constants;
import org.red5.server.net.rtmp.message.Header;
import org.red5.server.net.rtmp.message.Packet;
import org.red5.server.net.rtmp.message.SharedObjectTypeMapping;
import org.red5.server.service.Call;
import org.red5.server.service.PendingCall;
import org.red5.server.so.FlexSharedObjectMessage;
import org.red5.server.so.ISharedObjectEvent;
import org.red5.server.so.ISharedObjectMessage;
import org.red5.server.so.SharedObjectMessage;
/**
* RTMP protocol decoder
*/
public class RTMPProtocolDecoder implements Constants, SimpleProtocolDecoder,
IEventDecoder {
/**
* Logger
*/
protected static Log log = LogFactory.getLog(RTMPProtocolDecoder.class
.getName());
/**
* I/O logger
*/
protected static Log ioLog = LogFactory.getLog(RTMPProtocolDecoder.class
.getName()
+ ".in");
/**
* Deserializer
*/
private Deserializer deserializer;
/** Constructs a new RTMPProtocolDecoder. */
public RTMPProtocolDecoder() {
}
/**
* Setter for deserializer
*
* @param deserializer Deserializer
*/
public void setDeserializer(Deserializer deserializer) {
this.deserializer = deserializer;
}
/** {@inheritDoc} */
public List decodeBuffer(ProtocolState state, ByteBuffer buffer) {
final List<Object> result = new LinkedList<Object>();
try {
while (true) {
final int remaining = buffer.remaining();
if (state.canStartDecoding(remaining)) {
state.startDecoding();
} else {
break;
}
final Object decodedObject = decode(state, buffer);
if (state.hasDecodedObject()) {
result.add(decodedObject);
} else if (state.canContinueDecoding()) {
continue;
} else {
break;
}
if (!buffer.hasRemaining()) {
break;
}
}
} catch (HandshakeFailedException hfe) {
IConnection conn = Red5.getConnectionLocal();
if (conn != null) {
conn.close();
} else {
log.error("Handshake validation failed but no current connection!?");
}
return null;
} catch (ProtocolException pvx) {
log.error("Error decoding buffer", pvx);
} catch (Exception ex) {
log.error("Error decoding buffer", ex);
} finally {
buffer.compact();
}
return result;
}
/**
* Setup the classloader to use when deserializing custom objects.
*/
protected void setupClassLoader() {
IConnection conn = Red5.getConnectionLocal();
if (conn == null) {
return;
}
IScope scope = conn.getScope();
if (scope == null) {
return;
}
IContext context = scope.getContext();
if (context != null) {
Thread.currentThread().setContextClassLoader(context.getApplicationContext().getClassLoader());
}
}
/**
* Decodes byte buffer
* @param state Protocol state
* @param in Input byte buffer
* @return Decoded object
* @throws ProtocolException Exception during decoding
*/
public Object decode(ProtocolState state, ByteBuffer in)
throws ProtocolException {
int start = in.position();
try {
final RTMP rtmp = (RTMP) state;
switch (rtmp.getState()) {
case RTMP.STATE_CONNECTED:
return decodePacket(rtmp, in);
case RTMP.STATE_ERROR:
// attempt to correct error
return null;
case RTMP.STATE_CONNECT:
case RTMP.STATE_HANDSHAKE:
return decodeHandshake(rtmp, in);
default:
return null;
}
} catch (ProtocolException pe) {
// Raise to caller unmodified
throw pe;
} catch (RuntimeException e) {
log.error("Error in packet at " + start, e);
throw new ProtocolException("Error during decoding");
}
}
/**
* Decodes handshake message
* @param rtmp RTMP protocol state
* @param in Byte buffer
* @return Byte buffer
*/
public ByteBuffer decodeHandshake(RTMP rtmp, ByteBuffer in) {
final int remaining = in.remaining();
if (rtmp.getMode() == RTMP.MODE_SERVER) {
if (rtmp.getState() == RTMP.STATE_CONNECT) {
if (remaining < HANDSHAKE_SIZE + 1) {
if (log.isDebugEnabled()) {
log.debug("Handshake init too small, buffering. remaining: " + remaining);
}
rtmp.bufferDecoding(HANDSHAKE_SIZE + 1);
return null;
} else {
final ByteBuffer hs = ByteBuffer.allocate(HANDSHAKE_SIZE);
in.get(); // skip the header byte
BufferUtils.put(hs, in, HANDSHAKE_SIZE);
hs.flip();
rtmp.setState(RTMP.STATE_HANDSHAKE);
return hs;
}
}
if (rtmp.getState() == RTMP.STATE_HANDSHAKE) {
if (log.isDebugEnabled()) {
log.debug("Handshake reply");
}
if (remaining < HANDSHAKE_SIZE) {
if (log.isDebugEnabled()) {
log.debug("Handshake reply too small, buffering. remaining: " + remaining);
}
rtmp.bufferDecoding(HANDSHAKE_SIZE);
return null;
} else {
// Skip first 8 bytes when comparing the handshake, they seem to
// be changed when connecting from a Mac client.
if (!rtmp.validateHandshakeReply(in, 8, HANDSHAKE_SIZE-8)) {
if (log.isDebugEnabled()) {
log.debug("Handshake reply validation failed, disconnecting client.");
}
in.skip(HANDSHAKE_SIZE);
rtmp.setState(RTMP.STATE_ERROR);
throw new HandshakeFailedException("Handshake validation failed");
}
in.skip(HANDSHAKE_SIZE);
rtmp.setState(RTMP.STATE_CONNECTED);
rtmp.continueDecoding();
return null;
}
}
} else {
// else, this is client mode.
if (rtmp.getState() == RTMP.STATE_CONNECT) {
final int size = (2 * HANDSHAKE_SIZE) + 1;
if (remaining < size) {
if (log.isDebugEnabled()) {
log.debug("Handshake init too small, buffering. remaining: " + remaining);
}
rtmp.bufferDecoding(size);
return null;
} else {
final ByteBuffer hs = ByteBuffer.allocate(size);
BufferUtils.put(hs, in, size);
hs.flip();
rtmp.setState(RTMP.STATE_CONNECTED);
return hs;
}
}
}
return null;
}
/**
* Decodes packet
* @param rtmp RTMP protocol state
* @param in Byte buffer
* @return Byte buffer
*/
public Packet decodePacket(RTMP rtmp, ByteBuffer in) {
final int remaining = in.remaining();
// We need at least one byte
if (remaining < 1) {
rtmp.bufferDecoding(1);
return null;
}
final int position = in.position();
byte headerByte = in.get();
int headerValue;
int byteCount;
if ((headerByte & 0x3f) == 0) {
// Two byte header
+ if (remaining < 2) {
+ in.position(position);
+ rtmp.bufferDecoding(2);
+ return null;
+ }
headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 2;
} else if ((headerByte & 0x3f) == 1) {
// Three byte header
+ if (remaining < 3) {
+ in.position(position);
+ rtmp.bufferDecoding(3);
+ return null;
+ }
headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 3;
} else {
// Single byte header
headerValue = (int) headerByte & 0xff;
byteCount = 1;
}
final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount);
if (channelId < 0) {
throw new ProtocolException("Bad channel id: " + channelId);
}
// Get the header size and length
int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount));
+ headerLength += byteCount - 1;
if (headerLength > remaining) {
if (log.isDebugEnabled()) {
log.debug("Header too small, buffering. remaining: " + remaining);
}
in.position(position);
rtmp.bufferDecoding(headerLength);
return null;
}
// Move the position back to the start
in.position(position);
final Header header = decodeHeader(in, rtmp
.getLastReadHeader(channelId));
if (header == null) {
throw new ProtocolException("Header is null, check for error");
}
// Save the header
rtmp.setLastReadHeader(channelId, header);
// Check to see if this is a new packets or continue decoding an
// existing one.
Packet packet = rtmp.getLastReadPacket(channelId);
if (packet == null) {
packet = new Packet(header);
rtmp.setLastReadPacket(channelId, packet);
}
final ByteBuffer buf = packet.getData();
final int addSize = (header.getTimer() == 0xffffff ? 4 : 0);
final int readRemaining = header.getSize() + addSize - buf.position();
final int chunkSize = rtmp.getReadChunkSize();
final int readAmount = (readRemaining > chunkSize) ? chunkSize
: readRemaining;
if (in.remaining() < readAmount) {
if (log.isDebugEnabled()) {
log.debug("Chunk too small, buffering (" + in.remaining() + ','
+ readAmount);
}
// skip the position back to the start
in.position(position);
rtmp.bufferDecoding(headerLength + readAmount);
return null;
}
BufferUtils.put(buf, in, readAmount);
if (buf.position() < header.getSize() + addSize) {
rtmp.continueDecoding();
return null;
}
buf.flip();
final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf);
packet.setMessage(message);
if (message instanceof ChunkSize) {
ChunkSize chunkSizeMsg = (ChunkSize) message;
rtmp.setReadChunkSize(chunkSizeMsg.getSize());
}
rtmp.setLastReadPacket(channelId, null);
return packet;
}
/**
* Decides packet header
* @param in Input byte buffer
* @param lastHeader Previous header
* @return Decoded header
*/
public Header decodeHeader(ByteBuffer in, Header lastHeader) {
byte headerByte = in.get();
int headerValue;
int byteCount = 1;
if ((headerByte & 0x3f) == 0) {
// Two byte header
headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 2;
} else if ((headerByte & 0x3f) == 1) {
// Three byte header
headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 3;
} else {
// Single byte header
headerValue = (int) headerByte & 0xff;
byteCount = 1;
}
final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount);
final int headerSize = RTMPUtils.decodeHeaderSize(headerValue, byteCount);
Header header = new Header();
header.setChannelId(channelId);
header.setTimerRelative(headerSize != HEADER_NEW);
switch (headerSize) {
case HEADER_NEW:
header.setTimer(RTMPUtils.readUnsignedMediumInt(in));
header.setSize(RTMPUtils.readMediumInt(in));
header.setDataType(in.get());
header.setStreamId(RTMPUtils.readReverseInt(in));
break;
case HEADER_SAME_SOURCE:
header.setTimer(RTMPUtils.readUnsignedMediumInt(in));
header.setSize(RTMPUtils.readMediumInt(in));
header.setDataType(in.get());
header.setStreamId(lastHeader.getStreamId());
break;
case HEADER_TIMER_CHANGE:
header.setTimer(RTMPUtils.readUnsignedMediumInt(in));
header.setSize(lastHeader.getSize());
header.setDataType(lastHeader.getDataType());
header.setStreamId(lastHeader.getStreamId());
break;
case HEADER_CONTINUE:
header.setTimer(lastHeader.getTimer());
header.setSize(lastHeader.getSize());
header.setDataType(lastHeader.getDataType());
header.setStreamId(lastHeader.getStreamId());
break;
default:
log.error("Unexpected header size: " + headerSize);
return null;
}
return header;
}
/**
* Decodes RTMP message event
* @param rtmp RTMP protocol state
* @param header RTMP header
* @param in Input byte buffer
* @return RTMP event
*/
public IRTMPEvent decodeMessage(RTMP rtmp, Header header, ByteBuffer in) {
IRTMPEvent message;
if (header.getTimer() == 0xffffff) {
// Skip first four bytes
int unknown = in.getInt();
if (log.isDebugEnabled()) {
log.debug("Unknown 4 bytes: " + unknown);
}
}
switch (header.getDataType()) {
case TYPE_CHUNK_SIZE:
message = decodeChunkSize(in);
break;
case TYPE_INVOKE:
message = decodeInvoke(in, rtmp);
break;
case TYPE_NOTIFY:
if (header.getStreamId() == 0)
message = decodeNotify(in, header, rtmp);
else
message = decodeStreamMetadata(in);
break;
case TYPE_PING:
message = decodePing(in);
break;
case TYPE_BYTES_READ:
message = decodeBytesRead(in);
break;
case TYPE_AUDIO_DATA:
message = decodeAudioData(in);
break;
case TYPE_VIDEO_DATA:
message = decodeVideoData(in);
break;
case TYPE_FLEX_SHARED_OBJECT:
message = decodeFlexSharedObject(in, rtmp);
break;
case TYPE_SHARED_OBJECT:
message = decodeSharedObject(in, rtmp);
break;
case TYPE_SERVER_BANDWIDTH:
message = decodeServerBW(in);
break;
case TYPE_CLIENT_BANDWIDTH:
message = decodeClientBW(in);
break;
case TYPE_FLEX_MESSAGE:
message = decodeFlexMessage(in, rtmp);
break;
default:
log.warn("Unknown object type: " + header.getDataType());
message = decodeUnknown(header.getDataType(), in);
break;
}
message.setHeader(header);
message.setTimestamp(header.getTimer());
return message;
}
/**
* Decodes server bandwidth
* @param in Byte buffer
* @return RTMP event
*/
private IRTMPEvent decodeServerBW(ByteBuffer in) {
return new ServerBW(in.getInt());
}
/**
* Decodes client bandwidth
* @param in Byte buffer
* @return RTMP event
*/
private IRTMPEvent decodeClientBW(ByteBuffer in) {
return new ClientBW(in.getInt(), in.get());
}
/** {@inheritDoc} */
public Unknown decodeUnknown(byte dataType, ByteBuffer in) {
return new Unknown(dataType, in.asReadOnlyBuffer());
}
/** {@inheritDoc} */
public ChunkSize decodeChunkSize(ByteBuffer in) {
return new ChunkSize(in.getInt());
}
/** {@inheritDoc} */
public ISharedObjectMessage decodeFlexSharedObject(ByteBuffer in, RTMP rtmp) {
// Unknown byte, always 0?
in.skip(1);
final Input input = new org.red5.io.amf.Input(in);
String name = input.getString();
// Read version of SO to modify
int version = in.getInt();
// Read persistence informations
boolean persistent = in.getInt() == 2;
// Skip unknown bytes
in.skip(4);
final SharedObjectMessage so = new FlexSharedObjectMessage(null, name,
version, persistent);
doDecodeSharedObject(so, in, input);
return so;
}
/** {@inheritDoc} */
public ISharedObjectMessage decodeSharedObject(ByteBuffer in, RTMP rtmp) {
final Input input = new org.red5.io.amf.Input(in);
String name = input.getString();
// Read version of SO to modify
int version = in.getInt();
// Read persistence informations
boolean persistent = in.getInt() == 2;
// Skip unknown bytes
in.skip(4);
final SharedObjectMessage so = new FlexSharedObjectMessage(null, name,
version, persistent);
doDecodeSharedObject(so, in, input);
return so;
}
/**
* Perform the actual decoding of the shared object contents.
*
* @param so
* @param in
* @param rtmp
*/
protected void doDecodeSharedObject(SharedObjectMessage so, ByteBuffer in, Input input) {
// Parse request body
setupClassLoader();
while (in.hasRemaining()) {
final ISharedObjectEvent.Type type = SharedObjectTypeMapping
.toType(in.get());
String key = null;
Object value = null;
//if(log.isDebugEnabled())
// log.debug("type: "+SharedObjectTypeMapping.toString(type));
//SharedObjectEvent event = new SharedObjectEvent(,null,null);
final int length = in.getInt();
if (type == ISharedObjectEvent.Type.CLIENT_STATUS) {
// Status code
key = input.getString();
// Status level
value = input.getString();
} else if (type == ISharedObjectEvent.Type.CLIENT_UPDATE_DATA) {
key = null;
// Map containing new attribute values
final Map<String, Object> map = new HashMap<String, Object>();
final int start = in.position();
while (in.position() - start < length) {
String tmp = input.getString();
map.put(tmp, deserializer.deserialize(input));
}
value = map;
} else if (type != ISharedObjectEvent.Type.SERVER_SEND_MESSAGE
&& type != ISharedObjectEvent.Type.CLIENT_SEND_MESSAGE) {
if (length > 0) {
key = input.getString();
if (length > key.length() + 2) {
value = deserializer.deserialize(input);
}
}
} else {
final int start = in.position();
// the "send" event seems to encode the handler name
// as complete AMF string including the string type byte
key = (String) deserializer.deserialize(input);
// read parameters
final List<Object> list = new LinkedList<Object>();
while (in.position() - start < length) {
Object tmp = deserializer.deserialize(input);
list.add(tmp);
}
value = list;
}
so.addEvent(type, key, value);
}
}
/** {@inheritDoc} */
public Notify decodeNotify(ByteBuffer in, RTMP rtmp) {
return decodeNotify(in, null, rtmp);
}
public Notify decodeNotify(ByteBuffer in, Header header, RTMP rtmp) {
return decodeNotifyOrInvoke(new Notify(), in, header, rtmp);
}
/** {@inheritDoc} */
public Invoke decodeInvoke(ByteBuffer in, RTMP rtmp) {
return (Invoke) decodeNotifyOrInvoke(new Invoke(), in, null, rtmp);
}
/**
* Checks if the passed action is a reserved stream method.
*
* @param action Action to check
* @return <code>true</code> if passed action is a reserved stream method, <code>false</code> otherwise
*/
private boolean isStreamCommand(String action) {
return (ACTION_CREATE_STREAM.equals(action)
|| ACTION_DELETE_STREAM.equals(action)
|| ACTION_PUBLISH.equals(action) || ACTION_PLAY.equals(action)
|| ACTION_SEEK.equals(action) || ACTION_PAUSE.equals(action)
|| ACTION_CLOSE_STREAM.equals(action)
|| ACTION_RECEIVE_VIDEO.equals(action) || ACTION_RECEIVE_AUDIO
.equals(action));
}
/**
* Decodes notification event
* @param notify Notify event
* @param in Byte buffer
* @param header Header
* @param rtmp RTMP protocol state
* @return Notification event
*/
protected Notify decodeNotifyOrInvoke(Notify notify, ByteBuffer in, Header header, RTMP rtmp) {
// TODO: we should use different code depending on server or client mode
int start = in.position();
Input input;
if (rtmp.getEncoding() == Encoding.AMF3)
input = new org.red5.io.amf3.Input(in);
else
input = new org.red5.io.amf.Input(in);
String action = (String) deserializer.deserialize(input);
if (!(notify instanceof Invoke) && rtmp != null
&& rtmp.getMode() == RTMP.MODE_SERVER && header != null
&& header.getStreamId() != 0 && !isStreamCommand(action)) {
// Don't decode "NetStream.send" requests
in.position(start);
notify.setData(in.asReadOnlyBuffer());
return notify;
}
if (log.isDebugEnabled()) {
log.debug("Action " + action);
}
if (header == null || header.getStreamId() == 0) {
int invokeId = ((Number) deserializer.deserialize(input)).intValue();
notify.setInvokeId(invokeId);
}
Object[] params = new Object[] {};
if (in.hasRemaining()) {
setupClassLoader();
List<Object> paramList = new ArrayList<Object>();
final Object obj = deserializer.deserialize(input);
if (obj instanceof Map) {
// Before the actual parameters we sometimes (connect) get a map
// of parameters, this is usually null, but if set should be
// passed to the connection object.
final Map connParams = (Map) obj;
notify.setConnectionParams(connParams);
} else if (obj != null) {
paramList.add(obj);
}
while (in.hasRemaining()) {
paramList.add(deserializer.deserialize(input));
}
params = paramList.toArray();
if (log.isDebugEnabled()) {
log.debug("Num params: " + paramList.size());
for (int i = 0; i < params.length; i++) {
log.debug(" > " + i + ": " + params[i]);
}
}
}
final int dotIndex = action.lastIndexOf('.');
String serviceName = (dotIndex == -1) ? null : action.substring(0,
dotIndex);
String serviceMethod = (dotIndex == -1) ? action : action.substring(
dotIndex + 1, action.length());
if (notify instanceof Invoke) {
PendingCall call = new PendingCall(serviceName, serviceMethod,
params);
((Invoke) notify).setCall(call);
} else {
Call call = new Call(serviceName, serviceMethod, params);
notify.setCall(call);
}
return notify;
}
/**
* Decodes ping event
* @param in Byte buffer
* @return Ping event
*/
public Ping decodePing(ByteBuffer in) {
final Ping ping = new Ping();
ping.setDebug(in.getHexDump());
ping.setValue1(in.getShort());
ping.setValue2(in.getInt());
if (in.hasRemaining()) {
ping.setValue3(in.getInt());
}
if (in.hasRemaining()) {
ping.setValue4(in.getInt());
}
return ping;
}
/** {@inheritDoc} */
public BytesRead decodeBytesRead(ByteBuffer in) {
return new BytesRead(in.getInt());
}
/** {@inheritDoc} */
public AudioData decodeAudioData(ByteBuffer in) {
return new AudioData(in.asReadOnlyBuffer());
}
/** {@inheritDoc} */
public VideoData decodeVideoData(ByteBuffer in) {
return new VideoData(in.asReadOnlyBuffer());
}
public Notify decodeStreamMetadata(ByteBuffer in) {
return new Notify(in.asReadOnlyBuffer());
}
/**
* Decodes FlexMessage event
* @param in Byte buffer
* @param rtmp RTMP protocol state
* @return FlexMessage event
*/
public FlexMessage decodeFlexMessage(ByteBuffer in, RTMP rtmp) {
// Unknown byte, always 0?
in.skip(1);
Input input = new org.red5.io.amf.Input(in);
String action = (String) deserializer.deserialize(input);
int invokeId = ((Number) deserializer.deserialize(input)).intValue();
FlexMessage msg = new FlexMessage();
msg.setInvokeId(invokeId);
Object[] params = new Object[] {};
if (in.hasRemaining()) {
setupClassLoader();
ArrayList<Object> paramList = new ArrayList<Object>();
final Object obj = deserializer.deserialize(input);
if (obj != null) {
paramList.add(obj);
}
while (in.hasRemaining()) {
// Check for AMF3 encoding of parameters
byte tmp = in.get();
in.position(in.position()-1);
if (tmp == AMF.TYPE_AMF3_OBJECT) {
// The next parameter is encoded using AMF3
input = new org.red5.io.amf3.Input(in);
} else {
// The next parameter is encoded using AMF0
input = new org.red5.io.amf.Input(in);
}
paramList.add(deserializer.deserialize(input));
}
params = paramList.toArray();
if (log.isDebugEnabled()) {
log.debug("Num params: " + paramList.size());
for (int i = 0; i < params.length; i++) {
log.debug(" > " + i + ": " + params[i]);
}
}
}
final int dotIndex = action.lastIndexOf('.');
String serviceName = (dotIndex == -1) ? null : action.substring(0,
dotIndex);
String serviceMethod = (dotIndex == -1) ? action : action.substring(
dotIndex + 1, action.length());
PendingCall call = new PendingCall(serviceName, serviceMethod, params);
msg.setCall(call);
return msg;
}
}
| false | true | public Packet decodePacket(RTMP rtmp, ByteBuffer in) {
final int remaining = in.remaining();
// We need at least one byte
if (remaining < 1) {
rtmp.bufferDecoding(1);
return null;
}
final int position = in.position();
byte headerByte = in.get();
int headerValue;
int byteCount;
if ((headerByte & 0x3f) == 0) {
// Two byte header
headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 2;
} else if ((headerByte & 0x3f) == 1) {
// Three byte header
headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 3;
} else {
// Single byte header
headerValue = (int) headerByte & 0xff;
byteCount = 1;
}
final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount);
if (channelId < 0) {
throw new ProtocolException("Bad channel id: " + channelId);
}
// Get the header size and length
int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount));
if (headerLength > remaining) {
if (log.isDebugEnabled()) {
log.debug("Header too small, buffering. remaining: " + remaining);
}
in.position(position);
rtmp.bufferDecoding(headerLength);
return null;
}
// Move the position back to the start
in.position(position);
final Header header = decodeHeader(in, rtmp
.getLastReadHeader(channelId));
if (header == null) {
throw new ProtocolException("Header is null, check for error");
}
// Save the header
rtmp.setLastReadHeader(channelId, header);
// Check to see if this is a new packets or continue decoding an
// existing one.
Packet packet = rtmp.getLastReadPacket(channelId);
if (packet == null) {
packet = new Packet(header);
rtmp.setLastReadPacket(channelId, packet);
}
final ByteBuffer buf = packet.getData();
final int addSize = (header.getTimer() == 0xffffff ? 4 : 0);
final int readRemaining = header.getSize() + addSize - buf.position();
final int chunkSize = rtmp.getReadChunkSize();
final int readAmount = (readRemaining > chunkSize) ? chunkSize
: readRemaining;
if (in.remaining() < readAmount) {
if (log.isDebugEnabled()) {
log.debug("Chunk too small, buffering (" + in.remaining() + ','
+ readAmount);
}
// skip the position back to the start
in.position(position);
rtmp.bufferDecoding(headerLength + readAmount);
return null;
}
BufferUtils.put(buf, in, readAmount);
if (buf.position() < header.getSize() + addSize) {
rtmp.continueDecoding();
return null;
}
buf.flip();
final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf);
packet.setMessage(message);
if (message instanceof ChunkSize) {
ChunkSize chunkSizeMsg = (ChunkSize) message;
rtmp.setReadChunkSize(chunkSizeMsg.getSize());
}
rtmp.setLastReadPacket(channelId, null);
return packet;
}
| public Packet decodePacket(RTMP rtmp, ByteBuffer in) {
final int remaining = in.remaining();
// We need at least one byte
if (remaining < 1) {
rtmp.bufferDecoding(1);
return null;
}
final int position = in.position();
byte headerByte = in.get();
int headerValue;
int byteCount;
if ((headerByte & 0x3f) == 0) {
// Two byte header
if (remaining < 2) {
in.position(position);
rtmp.bufferDecoding(2);
return null;
}
headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 2;
} else if ((headerByte & 0x3f) == 1) {
// Three byte header
if (remaining < 3) {
in.position(position);
rtmp.bufferDecoding(3);
return null;
}
headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff);
byteCount = 3;
} else {
// Single byte header
headerValue = (int) headerByte & 0xff;
byteCount = 1;
}
final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount);
if (channelId < 0) {
throw new ProtocolException("Bad channel id: " + channelId);
}
// Get the header size and length
int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount));
headerLength += byteCount - 1;
if (headerLength > remaining) {
if (log.isDebugEnabled()) {
log.debug("Header too small, buffering. remaining: " + remaining);
}
in.position(position);
rtmp.bufferDecoding(headerLength);
return null;
}
// Move the position back to the start
in.position(position);
final Header header = decodeHeader(in, rtmp
.getLastReadHeader(channelId));
if (header == null) {
throw new ProtocolException("Header is null, check for error");
}
// Save the header
rtmp.setLastReadHeader(channelId, header);
// Check to see if this is a new packets or continue decoding an
// existing one.
Packet packet = rtmp.getLastReadPacket(channelId);
if (packet == null) {
packet = new Packet(header);
rtmp.setLastReadPacket(channelId, packet);
}
final ByteBuffer buf = packet.getData();
final int addSize = (header.getTimer() == 0xffffff ? 4 : 0);
final int readRemaining = header.getSize() + addSize - buf.position();
final int chunkSize = rtmp.getReadChunkSize();
final int readAmount = (readRemaining > chunkSize) ? chunkSize
: readRemaining;
if (in.remaining() < readAmount) {
if (log.isDebugEnabled()) {
log.debug("Chunk too small, buffering (" + in.remaining() + ','
+ readAmount);
}
// skip the position back to the start
in.position(position);
rtmp.bufferDecoding(headerLength + readAmount);
return null;
}
BufferUtils.put(buf, in, readAmount);
if (buf.position() < header.getSize() + addSize) {
rtmp.continueDecoding();
return null;
}
buf.flip();
final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf);
packet.setMessage(message);
if (message instanceof ChunkSize) {
ChunkSize chunkSizeMsg = (ChunkSize) message;
rtmp.setReadChunkSize(chunkSizeMsg.getSize());
}
rtmp.setLastReadPacket(channelId, null);
return packet;
}
|
diff --git a/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultContinuumReleaseManager.java b/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultContinuumReleaseManager.java
index d233ecffc..ae9d4b56f 100644
--- a/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultContinuumReleaseManager.java
+++ b/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultContinuumReleaseManager.java
@@ -1,320 +1,321 @@
package org.apache.maven.continuum.release;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.lang.BooleanUtils;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.release.config.ContinuumReleaseDescriptor;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.release.tasks.PerformReleaseProjectTask;
import org.apache.maven.continuum.release.tasks.PrepareReleaseProjectTask;
import org.apache.maven.continuum.release.tasks.RollbackReleaseProjectTask;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.provider.ScmProvider;
import org.apache.maven.scm.repository.ScmRepository;
import org.apache.maven.shared.release.ReleaseManagerListener;
import org.apache.maven.shared.release.config.ReleaseDescriptor;
import org.apache.maven.shared.release.config.ReleaseDescriptorStore;
import org.apache.maven.shared.release.config.ReleaseDescriptorStoreException;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.codehaus.plexus.taskqueue.TaskQueueException;
import java.io.File;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
/**
* @author Jason van Zyl
* @author Edwin Punzalan
* @version $Id$
*/
public class DefaultContinuumReleaseManager
implements ContinuumReleaseManager
{
/**
* @plexus.requirement
*/
private ReleaseDescriptorStore releaseStore;
/**
* @plexus.requirement
*/
private TaskQueue prepareReleaseQueue;
/**
* @plexus.requirement
*/
private TaskQueue performReleaseQueue;
/**
* @plexus.requirement
*/
private TaskQueue rollbackReleaseQueue;
/**
* @plexus.requirement
*/
private ScmManager scmManager;
private Map<String, ContinuumReleaseManagerListener> listeners;
/**
* contains previous release:prepare descriptors; one per project
*
* @todo remove static when singleton strategy is working
*/
private static Map preparedReleases;
/**
* contains results
*
* @todo remove static when singleton strategy is working
*/
private static Map releaseResults;
public String prepare( Project project, Properties releaseProperties, Map<String, String> relVersions,
Map<String, String> devVersions, ContinuumReleaseManagerListener listener,
String workingDirectory )
throws ContinuumReleaseException
{
return prepare( project, releaseProperties, relVersions, devVersions, listener, workingDirectory, null, null );
}
public String prepare( Project project, Properties releaseProperties, Map<String, String> relVersions,
Map<String, String> devVersions, ContinuumReleaseManagerListener listener,
String workingDirectory, Map<String, String> environments, String executable )
throws ContinuumReleaseException
{
String releaseId = project.getGroupId() + ":" + project.getArtifactId();
ReleaseDescriptor descriptor =
getReleaseDescriptor( project, releaseProperties, relVersions, devVersions, environments, workingDirectory, executable );
getListeners().put( releaseId, listener );
try
{
prepareReleaseQueue.put(
new PrepareReleaseProjectTask( releaseId, descriptor, (ReleaseManagerListener) listener ) );
}
catch ( TaskQueueException e )
{
throw new ContinuumReleaseException( "Failed to add prepare release task in queue.", e );
}
return releaseId;
}
public void perform( String releaseId, File buildDirectory, String goals, String arguments,
boolean useReleaseProfile, ContinuumReleaseManagerListener listener )
throws ContinuumReleaseException
{
perform( releaseId, buildDirectory, goals, arguments, useReleaseProfile, listener, null );
}
public void perform( String releaseId, File buildDirectory, String goals, String arguments,
boolean useReleaseProfile, ContinuumReleaseManagerListener listener,
LocalRepository repository )
throws ContinuumReleaseException
{
ReleaseDescriptor descriptor = (ReleaseDescriptor) getPreparedReleases().get( releaseId );
if ( descriptor != null )
{
perform( releaseId, descriptor, buildDirectory, goals, arguments, useReleaseProfile, listener, repository );
}
}
public void perform( String releaseId, String workingDirectory, File buildDirectory, String goals, String arguments,
boolean useReleaseProfile, ContinuumReleaseManagerListener listener )
throws ContinuumReleaseException
{
ReleaseDescriptor descriptor = readReleaseDescriptor( workingDirectory );
perform( releaseId, descriptor, buildDirectory, goals, arguments, useReleaseProfile, listener, null );
}
private void perform( String releaseId, ReleaseDescriptor descriptor, File buildDirectory, String goals,
String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener,
LocalRepository repository )
throws ContinuumReleaseException
{
if ( descriptor != null )
{
descriptor.setAdditionalArguments( arguments );
}
try
{
getListeners().put( releaseId, listener );
performReleaseQueue.put(
new PerformReleaseProjectTask( releaseId, descriptor, buildDirectory, goals, useReleaseProfile,
(ReleaseManagerListener) listener, repository ) );
}
catch ( TaskQueueException e )
{
throw new ContinuumReleaseException( "Failed to add perform release task in queue.", e );
}
}
public void rollback( String releaseId, String workingDirectory, ContinuumReleaseManagerListener listener )
throws ContinuumReleaseException
{
ReleaseDescriptor descriptor = readReleaseDescriptor( workingDirectory );
rollback( releaseId, descriptor, listener );
}
private void rollback( String releaseId, ReleaseDescriptor descriptor, ContinuumReleaseManagerListener listener )
throws ContinuumReleaseException
{
Task releaseTask = new RollbackReleaseProjectTask( releaseId, descriptor, (ReleaseManagerListener) listener );
try
{
rollbackReleaseQueue.put( releaseTask );
}
catch ( TaskQueueException e )
{
throw new ContinuumReleaseException( "Failed to rollback release.", e );
}
}
public Map getPreparedReleases()
{
if ( preparedReleases == null )
{
preparedReleases = new Hashtable();
}
return preparedReleases;
}
public Map getReleaseResults()
{
if ( releaseResults == null )
{
releaseResults = new Hashtable();
}
return releaseResults;
}
private ReleaseDescriptor getReleaseDescriptor( Project project, Properties releaseProperties,
Map<String, String> relVersions, Map<String, String> devVersions,
Map<String, String> environments, String workingDirectory,
String executable )
{
ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor();
//release properties from the project
descriptor.setWorkingDirectory( workingDirectory );
descriptor.setScmSourceUrl( project.getScmUrl() );
//required properties
descriptor.setScmReleaseLabel( releaseProperties.getProperty( "tag" ) );
descriptor.setScmTagBase( releaseProperties.getProperty( "tagBase" ) );
descriptor.setReleaseVersions( relVersions );
descriptor.setDevelopmentVersions( devVersions );
descriptor.setPreparationGoals( releaseProperties.getProperty( "prepareGoals" ) );
descriptor.setAdditionalArguments( releaseProperties.getProperty( "arguments" ) );
descriptor.setAddSchema( Boolean.valueOf( releaseProperties.getProperty( "addSchema" ) ) );
descriptor.setAutoVersionSubmodules(
Boolean.valueOf( releaseProperties.getProperty( "autoVersionSubmodules" ) ) );
String useEditMode = releaseProperties.getProperty( "useEditMode" );
if ( BooleanUtils.toBoolean( useEditMode ) )
{
descriptor.setScmUseEditMode( Boolean.valueOf( useEditMode ) );
}
LocalRepository repository = project.getProjectGroup().getLocalRepository();
if ( repository != null )
{
- descriptor.setAdditionalArguments( "\"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
+ descriptor.setAdditionalArguments( descriptor.getAdditionalArguments() + " \"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
+ //descriptor.setAdditionalArguments( "\"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
}
//other properties
if ( releaseProperties.containsKey( "username" ) )
{
descriptor.setScmUsername( releaseProperties.getProperty( "username" ) );
}
if ( releaseProperties.containsKey( "password" ) )
{
descriptor.setScmPassword( releaseProperties.getProperty( "password" ) );
}
if ( releaseProperties.containsKey( "commentPrefix" ) )
{
descriptor.setScmCommentPrefix( releaseProperties.getProperty( "commentPrefix" ) );
}
if ( releaseProperties.containsKey( "useReleaseProfile" ) )
{
descriptor.setUseReleaseProfile( Boolean.valueOf( releaseProperties.getProperty( "useReleaseProfile" ) ) );
}
//forced properties
descriptor.setInteractive( false );
//set environments
descriptor.setEnvironments( environments );
descriptor.setExecutable( executable );
return descriptor;
}
private ReleaseDescriptor readReleaseDescriptor( String workingDirectory )
throws ContinuumReleaseException
{
ReleaseDescriptor descriptor = new ContinuumReleaseDescriptor();
descriptor.setWorkingDirectory( workingDirectory );
try
{
descriptor = releaseStore.read( descriptor );
}
catch ( ReleaseDescriptorStoreException e )
{
throw new ContinuumReleaseException( "Failed to parse descriptor file.", e );
}
return descriptor;
}
public Map<String, ContinuumReleaseManagerListener> getListeners()
{
if ( listeners == null )
{
listeners = new Hashtable<String, ContinuumReleaseManagerListener>();
}
return listeners;
}
public String sanitizeTagName( String scmUrl, String tagName )
throws Exception
{
ScmRepository scmRepo = scmManager.makeScmRepository( scmUrl );
ScmProvider scmProvider = scmManager.getProviderByRepository( scmRepo );
return scmProvider.sanitizeTagName( tagName );
}
}
| true | true | private ReleaseDescriptor getReleaseDescriptor( Project project, Properties releaseProperties,
Map<String, String> relVersions, Map<String, String> devVersions,
Map<String, String> environments, String workingDirectory,
String executable )
{
ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor();
//release properties from the project
descriptor.setWorkingDirectory( workingDirectory );
descriptor.setScmSourceUrl( project.getScmUrl() );
//required properties
descriptor.setScmReleaseLabel( releaseProperties.getProperty( "tag" ) );
descriptor.setScmTagBase( releaseProperties.getProperty( "tagBase" ) );
descriptor.setReleaseVersions( relVersions );
descriptor.setDevelopmentVersions( devVersions );
descriptor.setPreparationGoals( releaseProperties.getProperty( "prepareGoals" ) );
descriptor.setAdditionalArguments( releaseProperties.getProperty( "arguments" ) );
descriptor.setAddSchema( Boolean.valueOf( releaseProperties.getProperty( "addSchema" ) ) );
descriptor.setAutoVersionSubmodules(
Boolean.valueOf( releaseProperties.getProperty( "autoVersionSubmodules" ) ) );
String useEditMode = releaseProperties.getProperty( "useEditMode" );
if ( BooleanUtils.toBoolean( useEditMode ) )
{
descriptor.setScmUseEditMode( Boolean.valueOf( useEditMode ) );
}
LocalRepository repository = project.getProjectGroup().getLocalRepository();
if ( repository != null )
{
descriptor.setAdditionalArguments( "\"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
}
//other properties
if ( releaseProperties.containsKey( "username" ) )
{
descriptor.setScmUsername( releaseProperties.getProperty( "username" ) );
}
if ( releaseProperties.containsKey( "password" ) )
{
descriptor.setScmPassword( releaseProperties.getProperty( "password" ) );
}
if ( releaseProperties.containsKey( "commentPrefix" ) )
{
descriptor.setScmCommentPrefix( releaseProperties.getProperty( "commentPrefix" ) );
}
if ( releaseProperties.containsKey( "useReleaseProfile" ) )
{
descriptor.setUseReleaseProfile( Boolean.valueOf( releaseProperties.getProperty( "useReleaseProfile" ) ) );
}
//forced properties
descriptor.setInteractive( false );
//set environments
descriptor.setEnvironments( environments );
descriptor.setExecutable( executable );
return descriptor;
}
| private ReleaseDescriptor getReleaseDescriptor( Project project, Properties releaseProperties,
Map<String, String> relVersions, Map<String, String> devVersions,
Map<String, String> environments, String workingDirectory,
String executable )
{
ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor();
//release properties from the project
descriptor.setWorkingDirectory( workingDirectory );
descriptor.setScmSourceUrl( project.getScmUrl() );
//required properties
descriptor.setScmReleaseLabel( releaseProperties.getProperty( "tag" ) );
descriptor.setScmTagBase( releaseProperties.getProperty( "tagBase" ) );
descriptor.setReleaseVersions( relVersions );
descriptor.setDevelopmentVersions( devVersions );
descriptor.setPreparationGoals( releaseProperties.getProperty( "prepareGoals" ) );
descriptor.setAdditionalArguments( releaseProperties.getProperty( "arguments" ) );
descriptor.setAddSchema( Boolean.valueOf( releaseProperties.getProperty( "addSchema" ) ) );
descriptor.setAutoVersionSubmodules(
Boolean.valueOf( releaseProperties.getProperty( "autoVersionSubmodules" ) ) );
String useEditMode = releaseProperties.getProperty( "useEditMode" );
if ( BooleanUtils.toBoolean( useEditMode ) )
{
descriptor.setScmUseEditMode( Boolean.valueOf( useEditMode ) );
}
LocalRepository repository = project.getProjectGroup().getLocalRepository();
if ( repository != null )
{
descriptor.setAdditionalArguments( descriptor.getAdditionalArguments() + " \"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
//descriptor.setAdditionalArguments( "\"-Dmaven.repo.local=" + repository.getLocation() + "\"" );
}
//other properties
if ( releaseProperties.containsKey( "username" ) )
{
descriptor.setScmUsername( releaseProperties.getProperty( "username" ) );
}
if ( releaseProperties.containsKey( "password" ) )
{
descriptor.setScmPassword( releaseProperties.getProperty( "password" ) );
}
if ( releaseProperties.containsKey( "commentPrefix" ) )
{
descriptor.setScmCommentPrefix( releaseProperties.getProperty( "commentPrefix" ) );
}
if ( releaseProperties.containsKey( "useReleaseProfile" ) )
{
descriptor.setUseReleaseProfile( Boolean.valueOf( releaseProperties.getProperty( "useReleaseProfile" ) ) );
}
//forced properties
descriptor.setInteractive( false );
//set environments
descriptor.setEnvironments( environments );
descriptor.setExecutable( executable );
return descriptor;
}
|
diff --git a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
index c04ce4e..ac02cc0 100644
--- a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
+++ b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
@@ -1,168 +1,173 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.tasks;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.logic.GlobalConstants;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung ([email protected])
*
*/
public class InstanceUploaderTask extends AsyncTask<String, Integer, ArrayList<String>> {
private static String t = "InstanceUploaderTask";
InstanceUploaderListener mStateListener;
String mUrl;
public void setUploadServer(String newServer) {
mUrl = newServer;
}
@Override
protected ArrayList<String> doInBackground(String... values) {
ArrayList<String> uploadedIntances = new ArrayList<String>();
int instanceCount = values.length;
for (int i = 0; i < instanceCount; i++) {
publishProgress(i + 1, instanceCount);
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpClientParams.setRedirecting(params, false);
// setup client
DefaultHttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(mUrl);
// get instance file
File file = new File(values[i]);
// find all files in parent directory
File[] files = file.getParentFile().listFiles();
if (files == null) {
+ Log.e(t, "no files to upload");
cancel(true);
}
// mime post
MultipartEntity entity = new MultipartEntity();
- for (int j = 0; j < 1; j++) {
+ for (int j = 0; j < files.length; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
// uploading xml file
entity.addPart("xml_submission_file", new FileBody(f));
+ Log.i(t, "added xml file " + f.getName());
} else if (f.getName().endsWith(".png") || f.getName().endsWith(".jpg")) {
// upload image file
entity.addPart(f.getName(), new FileBody(f));
+ Log.i(t, "added image file" + f.getName());
+ } else {
+ Log.e(t, "unsupported file type, not adding file: " + f.getName());
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IOException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IllegalStateException e) {
e.printStackTrace();
return uploadedIntances;
}
// check response.
// TODO: This isn't handled correctly.
String serverLocation = null;
Header[] h = response.getHeaders("Location");
if (h != null && h.length > 0) {
serverLocation = h[0].getValue();
} else {
// something should be done here...
Log.e(t, "Location header was absent");
}
int responseCode = response.getStatusLine().getStatusCode();
Log.e(t, "Response code:" + responseCode);
// verify that your response came from a known server
if (serverLocation != null && mUrl.contains(serverLocation) && responseCode == 201) {
uploadedIntances.add(values[i]);
}
}
return uploadedIntances;
}
@Override
protected void onPostExecute(ArrayList<String> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.uploadingComplete(value);
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| false | true | protected ArrayList<String> doInBackground(String... values) {
ArrayList<String> uploadedIntances = new ArrayList<String>();
int instanceCount = values.length;
for (int i = 0; i < instanceCount; i++) {
publishProgress(i + 1, instanceCount);
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpClientParams.setRedirecting(params, false);
// setup client
DefaultHttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(mUrl);
// get instance file
File file = new File(values[i]);
// find all files in parent directory
File[] files = file.getParentFile().listFiles();
if (files == null) {
cancel(true);
}
// mime post
MultipartEntity entity = new MultipartEntity();
for (int j = 0; j < 1; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
// uploading xml file
entity.addPart("xml_submission_file", new FileBody(f));
} else if (f.getName().endsWith(".png") || f.getName().endsWith(".jpg")) {
// upload image file
entity.addPart(f.getName(), new FileBody(f));
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IOException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IllegalStateException e) {
e.printStackTrace();
return uploadedIntances;
}
// check response.
// TODO: This isn't handled correctly.
String serverLocation = null;
Header[] h = response.getHeaders("Location");
if (h != null && h.length > 0) {
serverLocation = h[0].getValue();
} else {
// something should be done here...
Log.e(t, "Location header was absent");
}
int responseCode = response.getStatusLine().getStatusCode();
Log.e(t, "Response code:" + responseCode);
// verify that your response came from a known server
if (serverLocation != null && mUrl.contains(serverLocation) && responseCode == 201) {
uploadedIntances.add(values[i]);
}
}
return uploadedIntances;
}
| protected ArrayList<String> doInBackground(String... values) {
ArrayList<String> uploadedIntances = new ArrayList<String>();
int instanceCount = values.length;
for (int i = 0; i < instanceCount; i++) {
publishProgress(i + 1, instanceCount);
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, GlobalConstants.CONNECTION_TIMEOUT);
HttpClientParams.setRedirecting(params, false);
// setup client
DefaultHttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(mUrl);
// get instance file
File file = new File(values[i]);
// find all files in parent directory
File[] files = file.getParentFile().listFiles();
if (files == null) {
Log.e(t, "no files to upload");
cancel(true);
}
// mime post
MultipartEntity entity = new MultipartEntity();
for (int j = 0; j < files.length; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
// uploading xml file
entity.addPart("xml_submission_file", new FileBody(f));
Log.i(t, "added xml file " + f.getName());
} else if (f.getName().endsWith(".png") || f.getName().endsWith(".jpg")) {
// upload image file
entity.addPart(f.getName(), new FileBody(f));
Log.i(t, "added image file" + f.getName());
} else {
Log.e(t, "unsupported file type, not adding file: " + f.getName());
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IOException e) {
e.printStackTrace();
return uploadedIntances;
} catch (IllegalStateException e) {
e.printStackTrace();
return uploadedIntances;
}
// check response.
// TODO: This isn't handled correctly.
String serverLocation = null;
Header[] h = response.getHeaders("Location");
if (h != null && h.length > 0) {
serverLocation = h[0].getValue();
} else {
// something should be done here...
Log.e(t, "Location header was absent");
}
int responseCode = response.getStatusLine().getStatusCode();
Log.e(t, "Response code:" + responseCode);
// verify that your response came from a known server
if (serverLocation != null && mUrl.contains(serverLocation) && responseCode == 201) {
uploadedIntances.add(values[i]);
}
}
return uploadedIntances;
}
|
diff --git a/dojo-server/src/main/java/org/automation/dojo/GameLogService.java b/dojo-server/src/main/java/org/automation/dojo/GameLogService.java
index f791387..ca95bac 100644
--- a/dojo-server/src/main/java/org/automation/dojo/GameLogService.java
+++ b/dojo-server/src/main/java/org/automation/dojo/GameLogService.java
@@ -1,172 +1,172 @@
package org.automation.dojo;
import org.automation.dojo.web.controllers.ReleaseLogView;
import org.automation.dojo.web.scenario.BasicScenario;
import org.automation.dojo.web.scenario.Release;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author serhiy.zelenin
*/
public class GameLogService implements LogService {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private ReleaseLog currentRelease;
private ArrayList<ReleaseLog> releases = new ArrayList<ReleaseLog>();
private final Set<String> registeredPlayers = new HashSet<String>();
@Autowired
private TimeService timeService;
public GameLogService(TimeService timeService) {
this.timeService = timeService;
}
public GameLogService() {
}
public void playerLog(PlayerRecord record) {
lock.writeLock().lock();
try {
if (!registeredPlayers.contains(record.getPlayerName())) {
throw new IllegalArgumentException("Player " + record.getPlayerName() + " does not exist!");
}
record.setLogTime(timeService.now());
currentRelease.putRecord(record);
} finally {
lock.writeLock().unlock();
}
}
public List<GameLog> getGameLogs(final String player, final BasicScenario scenario) {
lock.readLock().lock();
try {
ArrayList<GameLog> result = new ArrayList<GameLog>();
for (ReleaseLog release : releases) {
GameLog gameLog = new GameLog(scenario, release.getReleaseDate());
gameLog.addAll(release.getRecordsFor(player, scenario));
result.add(gameLog);
}
return result;
} finally {
lock.readLock().unlock();
}
}
public Collection<String> getRegisteredPlayers() {
lock.readLock().lock();
try {
return Collections.unmodifiableCollection(registeredPlayers);
} finally {
lock.readLock().unlock();
}
}
public void createGameLog(Release release) {
lock.writeLock().lock();
try {
currentRelease = new ReleaseLog(release, timeService.now());
releases.add(currentRelease);
} finally {
lock.writeLock().unlock();
}
}
public List<ReleaseLog> getReleaseLogs() {
lock.readLock().lock();
try {
return Collections.unmodifiableList(releases);
} finally {
lock.readLock().unlock();
}
}
public boolean registerPlayer(String name) {
lock.writeLock().lock();
try {
if (registeredPlayers.contains(name)) {
return false;
}
registeredPlayers.add(name);
return true;
} finally {
lock.writeLock().unlock();
}
}
public List<BoardRecord> getBoardRecords() {
lock.readLock().lock();
try {
- if (releases.isEmpty()) {
- return createBoardRecordsWithZeroScores();
- }
Map<String, Integer> gameScores = new HashMap<String, Integer>();
for (ReleaseLog release : releases) {
addReleaseScoresToGameScores(release, gameScores);
}
+ if (gameScores.isEmpty()) {
+ return createBoardRecordsWithZeroScores();
+ }
ArrayList<BoardRecord> result = convertGameScores(gameScores);
Collections.sort(result);
return result;
} finally {
lock.readLock().unlock();
}
}
private List<BoardRecord> createBoardRecordsWithZeroScores() {
LinkedList<BoardRecord> boardRecords = new LinkedList<BoardRecord>();
for (String player : registeredPlayers) {
boardRecords.add(new BoardRecord(player, 0));
}
return boardRecords;
}
public ReleaseLog getCurrentReleaseLog() {
return currentRelease;
}
private ArrayList<BoardRecord> convertGameScores(Map<String, Integer> gameScores) {
ArrayList<BoardRecord> result = new ArrayList<BoardRecord>();
for (Map.Entry<String, Integer> entry : gameScores.entrySet()) {
result.add(new BoardRecord(entry.getKey(), entry.getValue()));
}
return result;
}
private void addReleaseScoresToGameScores(ReleaseLog release, Map<String, Integer> gameScores) {
Map<String, Integer> releaseBoard = release.getBoardRecords();
for (Map.Entry<String, Integer> releaseEntry : releaseBoard.entrySet()) {
int total = totalForRelease(gameScores, releaseEntry);
gameScores.put(releaseEntry.getKey(), total);
}
}
private int totalForRelease(Map<String, Integer> board, Map.Entry<String, Integer> releaseEntry) {
int total = releaseEntry.getValue();
String playerName = releaseEntry.getKey();
if (board.containsKey(playerName)) {
total += board.get(playerName);
}
return total;
}
@Override
public List<ReleaseLogView> getLastReleaseLogsForPlayer(String playerName, int maxLogRecordsAmount) {
lock.readLock().lock();
try {
LinkedList<ReleaseLogView> playerLogs = new LinkedList<ReleaseLogView>();
int recordsToShow = maxLogRecordsAmount >= 0 ? maxLogRecordsAmount : Integer.MAX_VALUE;
for (int i = releases.size() - 1; i >= 0 && recordsToShow > 0; i--) {
List<PlayerRecord> releaseLogs = releases.get(i)
.getLastRecordsForPlayer(playerName, recordsToShow);
playerLogs.add(0, new ReleaseLogView(releaseLogs, i + 1));
recordsToShow -= releaseLogs.size();
}
return playerLogs;
} finally {
lock.readLock().unlock();
}
}
}
| false | true | public List<BoardRecord> getBoardRecords() {
lock.readLock().lock();
try {
if (releases.isEmpty()) {
return createBoardRecordsWithZeroScores();
}
Map<String, Integer> gameScores = new HashMap<String, Integer>();
for (ReleaseLog release : releases) {
addReleaseScoresToGameScores(release, gameScores);
}
ArrayList<BoardRecord> result = convertGameScores(gameScores);
Collections.sort(result);
return result;
} finally {
lock.readLock().unlock();
}
}
| public List<BoardRecord> getBoardRecords() {
lock.readLock().lock();
try {
Map<String, Integer> gameScores = new HashMap<String, Integer>();
for (ReleaseLog release : releases) {
addReleaseScoresToGameScores(release, gameScores);
}
if (gameScores.isEmpty()) {
return createBoardRecordsWithZeroScores();
}
ArrayList<BoardRecord> result = convertGameScores(gameScores);
Collections.sort(result);
return result;
} finally {
lock.readLock().unlock();
}
}
|
diff --git a/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/IndexFileManageServiceImpl.java b/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/IndexFileManageServiceImpl.java
index 6d14f3b..6432fcd 100644
--- a/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/IndexFileManageServiceImpl.java
+++ b/crescent_core_web/src/main/java/com/tistory/devyongsik/admin/IndexFileManageServiceImpl.java
@@ -1,313 +1,313 @@
package com.tistory.devyongsik.admin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.tistory.devyongsik.config.CrescentCollectionHandler;
import com.tistory.devyongsik.config.SpringApplicationContext;
import com.tistory.devyongsik.domain.CrescentCollection;
import com.tistory.devyongsik.domain.CrescentCollectionField;
import com.tistory.devyongsik.utils.RankingTerm;
import com.tistory.devyongsik.utils.TopRankingQueue;
import com.tistory.devyongsik.utils.decoder.Decoder;
import com.tistory.devyongsik.utils.decoder.LongDecoder;
import com.tistory.devyongsik.utils.decoder.MockDecoder;
@Service("indexFileManageService")
public class IndexFileManageServiceImpl implements IndexFileManageService {
//TODO 호출할때마다 계산하는게 아니라, 색인시간 체크해서 보여주도록
private Logger logger = LoggerFactory.getLogger(IndexFileManageServiceImpl.class);
private Map<String, Integer>fieldTermCount = new HashMap<String, Integer>();
private RankingTerm[] topRankingTerms = null;
Map<String, Object> result = new HashMap<String, Object>();
public enum View { Overview, Document };
private final static int DEFAULT_TOPRANKING_TERM = 20;
String[] resultField1 = {"collectionName", "indexName", "numOfField", "numOfDoc", "numOfTerm",
"hasDel", "isOptimize", "indexVersion", "lastModify", "termCount", "topRanking"};
@Override
public boolean reload(String collectionName, String topRankingField) throws Exception {
if (collectionName == null) {
return false;
}
CrescentCollectionHandler collectionHandler
= SpringApplicationContext.getBean("crescentCollectionHandler", CrescentCollectionHandler.class);
CrescentCollection collection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Decoder decoder = null;
if (collection == null) {
logger.debug("doesn't Collection Info => {}", collectionName);
init(View.Overview);
return false;
}
if (!StringUtils.hasText(topRankingField)) {
if (collection.getDefaultSearchFields().get(0) != null) {
topRankingField = collection.getDefaultSearchFields().get(0).getName();
} else {
logger.debug("doesn't defaultSearchField => {}", collectionName);
init(View.Overview);
return false;
}
}
for (CrescentCollectionField field :collection.getFields()) {
if (field.getName().equals(topRankingField)) {
if (StringUtils.capitalize(field.getType()).equals("Long")) {
decoder = new LongDecoder();
} else {
decoder = new MockDecoder();
}
}
}
List<String> fieldName = new ArrayList<String>();
for (CrescentCollectionField field : collection.getFields())
fieldName.add(field.getName());
TopRankingQueue topRankingQueue = new TopRankingQueue(DEFAULT_TOPRANKING_TERM, new RankingTermComparator());
try {
Directory directory = FSDirectory.open(new File(collection.getIndexingDirectory()));
IndexReader reader = IndexReader.open(directory);
TermEnum terms = reader.terms();
int termFreq = 0;
int termCount = 0;
Term beforeTerm = null;
//init term count
fieldTermCount.clear();
for (CrescentCollectionField field : collection.getFields())
fieldTermCount.put(field.getName(), 0);
topRankingQueue.clear();
while(terms.next()) {
Term currTerm = terms.term();
if (beforeTerm == null) {
beforeTerm = currTerm;
}
if (beforeTerm.field() == currTerm.field()) {
termCount++;
} else {
fieldTermCount.put(beforeTerm.field(), termCount);
termCount = 1;
beforeTerm = currTerm;
}
TermDocs termDocs = reader.termDocs(currTerm);
if (currTerm.field().equals(topRankingField)) {
while (termDocs.next()) {
- RankingTerm e = new RankingTerm(decoder.decodeTerm(currTerm.text()), currTerm.field(), terms.docFreq());
+ RankingTerm e = new RankingTerm(
+ decoder.decodeTerm(currTerm.text()), currTerm.field(), terms.docFreq());
topRankingQueue.add(e);
- termDocs.skipTo(terms.docFreq());
}
}
termFreq++;
}
if (beforeTerm != null)
fieldTermCount.put(beforeTerm.field(), termCount);
terms.close();
result.put("numOfTerm", termFreq);
result.put("numOfDoc", reader.numDocs());
result.put("hasDel", reader.hasDeletions());
result.put("isOptimize", reader.isOptimized());
result.put("indexVersion", reader.getVersion());
result.put("lastModify", new Date(IndexReader.lastModified(directory)));
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (topRankingQueue.size() != 0) {
topRankingTerms = topRankingQueue.toArray();
Arrays.sort(topRankingTerms, Collections.reverseOrder());
}
result.put("collectionName", collectionName);
result.put("indexName", collection.getIndexingDirectory());
result.put("numOfField", collection.getFields().size());
result.put("termCount", fieldTermCount);
result.put("topRanking", topRankingTerms);
result.put("topRankingCount", DEFAULT_TOPRANKING_TERM);
result.put("fieldName", fieldName);
return true;
}
@Override
public boolean reload(String collectionName, int docNum) {
if (collectionName == null)
return false;
CrescentCollectionHandler collectionHandler
= SpringApplicationContext.getBean("crescentCollectionHandler", CrescentCollectionHandler.class);
CrescentCollection collection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
if (collection == null) {
logger.debug("doesn't Collection Info => {}", collectionName);
return false;
}
List<String> fieldName = new ArrayList<String>();
List<String> flag = new ArrayList<String>();
List<String> norm = new ArrayList<String>();
List<String> value = new ArrayList<String>();
try {
Directory directory = FSDirectory.open(new File(collection.getIndexingDirectory()));
IndexReader reader = IndexReader.open(directory);
Document document = null;
try {
document = reader.document(docNum);
} catch(IllegalArgumentException e) {
e.printStackTrace();
return false;
}
String fName = null;
for (Fieldable field : document.getFields()) {
fName = field.name();
fieldName.add(fName);
flag.add(fieldFlag(field));
if (reader.hasNorms(fName)) {
norm.add(String.valueOf(Similarity.decodeNorm(reader.norms(fName)[docNum])));
} else {
norm.add("---");
}
value.add(field.stringValue());
}
} catch(IOException e) {
e.printStackTrace();
return false;
}
result.put("collection", collectionName);
result.put("docNum", docNum);
result.put("fieldName", fieldName);
result.put("flag", flag);
result.put("norm", norm);
result.put("value", value);
return true;
}
@Override
public boolean reload(String collectionName, String field,
String query) {
// TODO Auto-generated method stub
return true;
}
private void init(View view) {
if (view == View.Overview) {
for (String field : resultField1) {
result.put(field, "?????");
}
} else if (view == View.Document) {
}
}
// org source => Luke:Util.java
private static String fieldFlag(Fieldable f) {
if (f == null) {
return "--------------";
}
StringBuffer flags = new StringBuffer();
if (f.isIndexed()) flags.append("I");
else flags.append("-");
IndexOptions opts = f.getIndexOptions();
if (f.isIndexed() && opts != null) {
switch (opts) {
case DOCS_ONLY:
flags.append("d--");
break;
case DOCS_AND_FREQS:
flags.append("df-");
break;
case DOCS_AND_FREQS_AND_POSITIONS:
flags.append("dfp");
}
} else {
flags.append("---");
}
if (f.isTokenized()) flags.append("T");
else flags.append("-");
if (f.isStored()) flags.append("S");
else flags.append("-");
if (f.isTermVectorStored()) flags.append("V");
else flags.append("-");
if (f.isStoreOffsetWithTermVector()) flags.append("o");
else flags.append("-");
if (f.isStorePositionWithTermVector()) flags.append("p");
else flags.append("-");
if (f.getOmitNorms()) flags.append("-");
else flags.append("N");
if (f.isLazy()) flags.append("L");
else flags.append("-");
if (f.isBinary()) flags.append("B");
else flags.append("-");
if (f instanceof NumericField) flags.append("#");
else flags.append("-");
return flags.toString();
}
@Override
public Map<String, Object> getResult() {
return result;
}
}
class RankingTermComparator implements Comparator<RankingTerm>
{
@Override
public int compare(RankingTerm x, RankingTerm y)
{
// Assume neither string is null. Real code should
// probably be more robust
if (x.getCount() < y.getCount())
{
return -1;
}
if (x.getCount() > y.getCount())
{
return 1;
}
return 0;
}
}
| false | true | public boolean reload(String collectionName, String topRankingField) throws Exception {
if (collectionName == null) {
return false;
}
CrescentCollectionHandler collectionHandler
= SpringApplicationContext.getBean("crescentCollectionHandler", CrescentCollectionHandler.class);
CrescentCollection collection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Decoder decoder = null;
if (collection == null) {
logger.debug("doesn't Collection Info => {}", collectionName);
init(View.Overview);
return false;
}
if (!StringUtils.hasText(topRankingField)) {
if (collection.getDefaultSearchFields().get(0) != null) {
topRankingField = collection.getDefaultSearchFields().get(0).getName();
} else {
logger.debug("doesn't defaultSearchField => {}", collectionName);
init(View.Overview);
return false;
}
}
for (CrescentCollectionField field :collection.getFields()) {
if (field.getName().equals(topRankingField)) {
if (StringUtils.capitalize(field.getType()).equals("Long")) {
decoder = new LongDecoder();
} else {
decoder = new MockDecoder();
}
}
}
List<String> fieldName = new ArrayList<String>();
for (CrescentCollectionField field : collection.getFields())
fieldName.add(field.getName());
TopRankingQueue topRankingQueue = new TopRankingQueue(DEFAULT_TOPRANKING_TERM, new RankingTermComparator());
try {
Directory directory = FSDirectory.open(new File(collection.getIndexingDirectory()));
IndexReader reader = IndexReader.open(directory);
TermEnum terms = reader.terms();
int termFreq = 0;
int termCount = 0;
Term beforeTerm = null;
//init term count
fieldTermCount.clear();
for (CrescentCollectionField field : collection.getFields())
fieldTermCount.put(field.getName(), 0);
topRankingQueue.clear();
while(terms.next()) {
Term currTerm = terms.term();
if (beforeTerm == null) {
beforeTerm = currTerm;
}
if (beforeTerm.field() == currTerm.field()) {
termCount++;
} else {
fieldTermCount.put(beforeTerm.field(), termCount);
termCount = 1;
beforeTerm = currTerm;
}
TermDocs termDocs = reader.termDocs(currTerm);
if (currTerm.field().equals(topRankingField)) {
while (termDocs.next()) {
RankingTerm e = new RankingTerm(decoder.decodeTerm(currTerm.text()), currTerm.field(), terms.docFreq());
topRankingQueue.add(e);
termDocs.skipTo(terms.docFreq());
}
}
termFreq++;
}
if (beforeTerm != null)
fieldTermCount.put(beforeTerm.field(), termCount);
terms.close();
result.put("numOfTerm", termFreq);
result.put("numOfDoc", reader.numDocs());
result.put("hasDel", reader.hasDeletions());
result.put("isOptimize", reader.isOptimized());
result.put("indexVersion", reader.getVersion());
result.put("lastModify", new Date(IndexReader.lastModified(directory)));
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (topRankingQueue.size() != 0) {
topRankingTerms = topRankingQueue.toArray();
Arrays.sort(topRankingTerms, Collections.reverseOrder());
}
result.put("collectionName", collectionName);
result.put("indexName", collection.getIndexingDirectory());
result.put("numOfField", collection.getFields().size());
result.put("termCount", fieldTermCount);
result.put("topRanking", topRankingTerms);
result.put("topRankingCount", DEFAULT_TOPRANKING_TERM);
result.put("fieldName", fieldName);
return true;
}
| public boolean reload(String collectionName, String topRankingField) throws Exception {
if (collectionName == null) {
return false;
}
CrescentCollectionHandler collectionHandler
= SpringApplicationContext.getBean("crescentCollectionHandler", CrescentCollectionHandler.class);
CrescentCollection collection = collectionHandler.getCrescentCollections().getCrescentCollection(collectionName);
Decoder decoder = null;
if (collection == null) {
logger.debug("doesn't Collection Info => {}", collectionName);
init(View.Overview);
return false;
}
if (!StringUtils.hasText(topRankingField)) {
if (collection.getDefaultSearchFields().get(0) != null) {
topRankingField = collection.getDefaultSearchFields().get(0).getName();
} else {
logger.debug("doesn't defaultSearchField => {}", collectionName);
init(View.Overview);
return false;
}
}
for (CrescentCollectionField field :collection.getFields()) {
if (field.getName().equals(topRankingField)) {
if (StringUtils.capitalize(field.getType()).equals("Long")) {
decoder = new LongDecoder();
} else {
decoder = new MockDecoder();
}
}
}
List<String> fieldName = new ArrayList<String>();
for (CrescentCollectionField field : collection.getFields())
fieldName.add(field.getName());
TopRankingQueue topRankingQueue = new TopRankingQueue(DEFAULT_TOPRANKING_TERM, new RankingTermComparator());
try {
Directory directory = FSDirectory.open(new File(collection.getIndexingDirectory()));
IndexReader reader = IndexReader.open(directory);
TermEnum terms = reader.terms();
int termFreq = 0;
int termCount = 0;
Term beforeTerm = null;
//init term count
fieldTermCount.clear();
for (CrescentCollectionField field : collection.getFields())
fieldTermCount.put(field.getName(), 0);
topRankingQueue.clear();
while(terms.next()) {
Term currTerm = terms.term();
if (beforeTerm == null) {
beforeTerm = currTerm;
}
if (beforeTerm.field() == currTerm.field()) {
termCount++;
} else {
fieldTermCount.put(beforeTerm.field(), termCount);
termCount = 1;
beforeTerm = currTerm;
}
TermDocs termDocs = reader.termDocs(currTerm);
if (currTerm.field().equals(topRankingField)) {
while (termDocs.next()) {
RankingTerm e = new RankingTerm(
decoder.decodeTerm(currTerm.text()), currTerm.field(), terms.docFreq());
topRankingQueue.add(e);
}
}
termFreq++;
}
if (beforeTerm != null)
fieldTermCount.put(beforeTerm.field(), termCount);
terms.close();
result.put("numOfTerm", termFreq);
result.put("numOfDoc", reader.numDocs());
result.put("hasDel", reader.hasDeletions());
result.put("isOptimize", reader.isOptimized());
result.put("indexVersion", reader.getVersion());
result.put("lastModify", new Date(IndexReader.lastModified(directory)));
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (topRankingQueue.size() != 0) {
topRankingTerms = topRankingQueue.toArray();
Arrays.sort(topRankingTerms, Collections.reverseOrder());
}
result.put("collectionName", collectionName);
result.put("indexName", collection.getIndexingDirectory());
result.put("numOfField", collection.getFields().size());
result.put("termCount", fieldTermCount);
result.put("topRanking", topRankingTerms);
result.put("topRankingCount", DEFAULT_TOPRANKING_TERM);
result.put("fieldName", fieldName);
return true;
}
|
diff --git a/src/main/java/net/frontlinesms/ui/handler/contacts/ContactsTabHandler.java b/src/main/java/net/frontlinesms/ui/handler/contacts/ContactsTabHandler.java
index d515dea..ede8261 100644
--- a/src/main/java/net/frontlinesms/ui/handler/contacts/ContactsTabHandler.java
+++ b/src/main/java/net/frontlinesms/ui/handler/contacts/ContactsTabHandler.java
@@ -1,624 +1,624 @@
/**
*
*/
package net.frontlinesms.ui.handler.contacts;
// TODO remove static imports
import static net.frontlinesms.FrontlineSMSConstants.ACTION_ADD_TO_GROUP;
import static net.frontlinesms.FrontlineSMSConstants.COMMON_CONTACTS_IN_GROUP;
import static net.frontlinesms.FrontlineSMSConstants.COMMON_E_MAIL_ADDRESS;
import static net.frontlinesms.FrontlineSMSConstants.COMMON_GROUP;
import static net.frontlinesms.FrontlineSMSConstants.COMMON_NAME;
import static net.frontlinesms.FrontlineSMSConstants.COMMON_PHONE_NUMBER;
import static net.frontlinesms.FrontlineSMSConstants.MESSAGE_CONTACTS_DELETED;
import static net.frontlinesms.FrontlineSMSConstants.MESSAGE_GROUPS_AND_CONTACTS_DELETED;
import static net.frontlinesms.FrontlineSMSConstants.MESSAGE_GROUP_ALREADY_EXISTS;
import static net.frontlinesms.FrontlineSMSConstants.MESSAGE_REMOVING_CONTACTS;
import static net.frontlinesms.FrontlineSMSConstants.PROPERTY_FIELD;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_BUTTON_YES;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_CONTACT_MANAGER_CONTACT_LIST;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_DELETE_NEW_CONTACT;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_GROUPS_MENU;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_MENU_ITEM_MSG_HISTORY;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_MENU_ITEM_VIEW_CONTACT;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_MI_DELETE;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_MI_SEND_SMS;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_NEW_GROUP;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_PN_CONTACTS;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_SEND_SMS_BUTTON;
import static net.frontlinesms.ui.UiGeneratorControllerConstants.COMPONENT_VIEW_CONTACT_BUTTON;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import net.frontlinesms.data.DuplicateKeyException;
import net.frontlinesms.data.Order;
import net.frontlinesms.data.domain.Contact;
import net.frontlinesms.data.domain.Group;
import net.frontlinesms.data.domain.Message;
import net.frontlinesms.data.repository.ContactDao;
import net.frontlinesms.data.repository.GroupDao;
import net.frontlinesms.data.repository.GroupMembershipDao;
import net.frontlinesms.ui.Icon;
import net.frontlinesms.ui.UiGeneratorController;
import net.frontlinesms.ui.handler.BaseTabHandler;
import net.frontlinesms.ui.handler.ComponentPagingHandler;
import net.frontlinesms.ui.handler.PagedComponentItemProvider;
import net.frontlinesms.ui.handler.PagedListDetails;
import net.frontlinesms.ui.i18n.InternationalisationUtils;
import thinlet.Thinlet;
import thinlet.ThinletText;
/**
* Event handler for the Contacts tab and associated dialogs.
* @author Alex [email protected]
*/
public class ContactsTabHandler extends BaseTabHandler implements PagedComponentItemProvider, SingleGroupSelecterPanelOwner, ContactEditorOwner {
//> STATIC CONSTANTS
/** UI XML File Path: the Home Tab itself */
private static final String UI_FILE_CONTACTS_TAB = "/ui/core/contacts/contactsTab.xml";
private static final String UI_FILE_DELETE_OPTION_DIALOG_FORM = "/ui/dialog/deleteOptionDialogForm.xml"; // TODO move this to the correct path
private static final String UI_FILE_NEW_GROUP_FORM = "/ui/dialog/newGroupForm.xml"; // TODO move this to the correct path
private static final String COMPONENT_GROUP_SELECTER_CONTAINER = "pnGroupsContainer";
private static final String COMPONENT_BUTTON_OK = "btOk";
private static final String COMPONENT_CONTACTS_PANEL = "pnContacts";
private static final String COMPONENT_DELETE_BUTTON = "deleteButton";
private static final String COMPONENT_SEND_SMS_BUTTON_GROUP_SIDE = "sendSMSButtonGroupSide";
//> INSTANCE PROPERTIES
//> DATA ACCESS OBJECTS
/** Data access object for {@link Group}s */
private final GroupDao groupDao;
/** Data access object for {@link Contact}s */
private final ContactDao contactDao;
private final GroupMembershipDao groupMembershipDao;
//> CACHED THINLET UI COMPONENTS
/** UI Component component: contact list. This is cached here to save searching for it later. */
private Object contactListComponent;
/** Handler for paging of {@link #contactListComponent} */
private ComponentPagingHandler contactListPager;
/** String to filter the contacts by */
private String contactFilter;
private final GroupSelecterPanel groupSelecter;
/** The selected group in the left panel */
private Group selectedGroup;
private Object newGroupForm;
//> CONSTRUCTORS
/**
* Create a new instance of this class.
* @param ui value for {@link #ui}
* @param contactDao {@link #contactDao}
* @param groupDao {@link #groupDao}
*/
public ContactsTabHandler(UiGeneratorController ui) {
super(ui);
this.contactDao = ui.getFrontlineController().getContactDao();
this.groupDao = ui.getFrontlineController().getGroupDao();
this.groupMembershipDao = ui.getFrontlineController().getGroupMembershipDao();
this.groupSelecter = new GroupSelecterPanel(ui, this);
}
@Override
public void init() {
super.init();
this.groupSelecter.init(ui.getRootGroup());
ui.add(find(COMPONENT_GROUP_SELECTER_CONTAINER), this.groupSelecter.getPanelComponent(), 0);
}
//> ACCESSORS
/** Refreshes the data displayed in the tab. */
public void refresh() {
updateGroupList();
}
//> GROUP SELECTION METHODS
/**
* Method invoked when the group/contacts tree selection changes.
* This method updated the contact list according to the new selection.
*/
public void groupSelectionChanged(Group selectedGroup) {
if(log.isTraceEnabled()) log.trace("Group selected: " + selectedGroup);
this.selectedGroup = selectedGroup;
String contactsPanelTitle;
boolean enableDeleteButton;
if(selectedGroup == null) {
contactsPanelTitle = "";
enableDeleteButton = false;
} else {
contactsPanelTitle = InternationalisationUtils.getI18NString(COMMON_CONTACTS_IN_GROUP, selectedGroup.getName());
enableDeleteButton = !this.ui.isDefaultGroup(selectedGroup);
}
this.ui.setText(find(COMPONENT_CONTACTS_PANEL), contactsPanelTitle);
Object buttonPanelContainer = find(COMPONENT_GROUP_SELECTER_CONTAINER);
Object deleteButton = this.ui.find(buttonPanelContainer, COMPONENT_DELETE_BUTTON);
this.ui.setEnabled(deleteButton, enableDeleteButton);
Object btSendSmsToGroup = this.ui.find(buttonPanelContainer, COMPONENT_SEND_SMS_BUTTON_GROUP_SIDE);
this.ui.setEnabled(btSendSmsToGroup, selectedGroup != null);
updateContactList();
}
public void groupNameChanged (String groupName) {
boolean shouldEnableOKButton = (groupName != null && !groupName.equals(""));
if (this.newGroupForm != null) {
Object okButton = this.ui.find(this.newGroupForm, COMPONENT_BUTTON_OK);
this.ui.setEnabled(okButton, shouldEnableOKButton);
}
}
//> CONTACT EDITING METHODS
/** @see ContactEditorOwner#contactCreationComplete(Contact) */
public void contactCreationComplete(Contact contact) {
// Refresh the Contacts tab, and make sure that the group and contact who were previously selected are still selected
updateContactList();
};
/** @see ContactEditorOwner#contactEditingComplete(Contact) */
public void contactEditingComplete(Contact contact) {
contactCreationComplete(contact);
}
//> PAGING METHODS
public PagedListDetails getListDetails(Object list, int startIndex, int limit) {
if(list == this.contactListComponent) {
return getContactListDetails(startIndex, limit);
} else throw new IllegalStateException();
}
private PagedListDetails getContactListDetails(int startIndex, int limit) {
Group selectedGroup = this.groupSelecter.getSelectedGroup();
if(selectedGroup == null) {
return PagedListDetails.EMPTY;
} else {
int totalItemCount = groupMembershipDao.getFilteredMemberCount(selectedGroup, this.contactFilter);
List<Contact> contacts = groupMembershipDao.getFilteredMembersSorted(selectedGroup, contactFilter, Contact.Field.NAME, Order.ASCENDING, startIndex, limit);
Object[] listItems = toThinletComponents(contacts);
return new PagedListDetails(totalItemCount, listItems);
}
}
private Object[] toThinletComponents(List<Contact> contacts) {
Object[] components = new Object[contacts.size()];
for (int i = 0; i < components.length; i++) {
Contact c = contacts.get(i);
components[i] = ui.getRow(c);
}
return components;
}
//> UI METHODS
/** Show editor for new contact. */
public void showNewContactDialog() {
ContactEditor editor = new ContactEditor(ui, this);
Group selectedGroup = this.groupSelecter.getSelectedGroup();
editor.show(selectedGroup);
}
/**
* Shows the delete option dialog
* If the group contains contacts, it asks the user if he/she wants to remove the selected contacts from database.
* Otherwise, it only shows a confirmation dialog
*/
public void showDeleteOptionDialog() {
Group g = this.groupSelecter.getSelectedGroup();
if (!this.ui.isDefaultGroup(g)) {
if (groupMembershipDao.getMemberCount(g) > 0) {
// If the group is not empty, we ask if the user also wants to delete the contacts
Object deleteDialog = ui.loadComponentFromFile(UI_FILE_DELETE_OPTION_DIALOG_FORM, this);
ui.add(deleteDialog);
} else {
// Otherwise, the
showConfirmationDialog("deleteSelectedGroup");
}
}
}
/**
* Launches the deletion of the selected group
* if the user confirmed it in the confirm dialog
*/
public void deleteSelectedGroup () {
this.ui.removeConfirmationDialog();
removeSelectedFromGroupList(null, null);
}
/**
* Shows contact dialog to allow edition of the selected contact.
* <br>This method affects the advanced mode.
* @param list
*/
public void showContactDetails(Object list) {
Object selected = this.ui.getSelectedItem(list);
if(selected != null) {
ContactEditor editor = new ContactEditor(ui, this);
editor.show(this.ui.getAttachedObject(selected, Contact.class));
}
}
/**
* Populates the pop up menu with all groups create by users.
*
* @param popUp
* @param list
*/
public void populateGroups(Object popUp, Object list) {
Object[] selectedItems = this.ui.getSelectedItems(list);
this.ui.setVisible(popUp, this.ui.getSelectedItems(list).length > 0);
if (selectedItems.length == 0) {
//Nothing selected
boolean none = true;
for (Object o : this.ui.getItems(popUp)) {
if (this.ui.getName(o).equals(COMPONENT_NEW_GROUP)
|| this.ui.getName(o).equals("miNewContact")) {
this.ui.setVisible(o, true);
none = false;
} else {
this.ui.setVisible(o, false);
}
}
this.ui.setVisible(popUp, !none);
} else if (this.ui.getAttachedObject(selectedItems[0]) instanceof Contact) {
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (name.equals(COMPONENT_MENU_ITEM_MSG_HISTORY)
|| name.equals(COMPONENT_MENU_ITEM_VIEW_CONTACT)) {
this.ui.setVisible(o, this.ui.getSelectedItems(list).length == 1);
} else if (!name.equals(COMPONENT_GROUPS_MENU)) {
this.ui.setVisible(o, true);
}
}
Object menu = this.ui.find(popUp, COMPONENT_GROUPS_MENU);
this.ui.removeAll(menu);
List<Group> allGroups = this.groupDao.getAllGroups();
for (Group g : allGroups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
- this.ui.setText(menuItem, InternationalisationUtils.getI18NString(COMMON_GROUP) + "'" + g.getName() + "'");
+ this.ui.setText(menuItem, InternationalisationUtils.getI18NString(COMMON_GROUP) + " '" + g.getName() + "'");
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "addToGroup(this)", menu, this);
this.ui.add(menu, menuItem);
}
this.ui.setVisible(menu, allGroups.size() != 0);
String menuName = InternationalisationUtils.getI18NString(ACTION_ADD_TO_GROUP);
this.ui.setText(menu, menuName);
Object menuRemove = this.ui.find(popUp, "groupsMenuRemove");
if (menuRemove != null) {
Contact c = this.ui.getContact(this.ui.getSelectedItem(list));
this.ui.removeAll(menuRemove);
List<Group> groups = this.groupMembershipDao.getGroups(c);
for (Group g : groups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
this.ui.setText(menuItem, g.getName());
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "removeFromGroup(this)", menuRemove, this);
this.ui.add(menuRemove, menuItem);
}
this.ui.setEnabled(menuRemove, groups.size() != 0);
}
} else {
Group g = this.ui.getGroup(this.ui.getSelectedItem(list));
//GROUPS OR BOTH
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (COMPONENT_NEW_GROUP.equals(name)
|| COMPONENT_MI_SEND_SMS.equals(name)
|| COMPONENT_MI_DELETE.equals(name)
|| COMPONENT_MENU_ITEM_MSG_HISTORY.equals(name)
|| "miNewContact".equals(name)) {
this.ui.setVisible(o, true);
} else {
this.ui.setVisible(o, false);
}
if (COMPONENT_MI_DELETE.equals(name)) {
this.ui.setVisible(o, !this.ui.isDefaultGroup(g));
}
// FIXME this is superfluous - always sets vis to true
if (COMPONENT_NEW_GROUP.equals(name)) {
this.ui.setVisible(o, true);
}
}
}
}
/**
* Shows the new group dialog.
* @param groupList
*/
public void showNewGroupDialog() {
newGroupForm = this.ui.loadComponentFromFile(UI_FILE_NEW_GROUP_FORM, this);
ui.setAttachedObject(newGroupForm, this.groupSelecter.getSelectedGroup());
this.ui.add(newGroupForm);
}
/** Updates the list of contacts with the new filter. */
public void filterContacts() {
updateContactList();
}
/**
* Applies a text filter to the contact list. The list is not updated until {@link #filterContacts()}
* is called.
* @param contactFilter The new filter.
*/
public void setContactFilter(String contactFilter) {
this.contactFilter = contactFilter;
}
/**
* Enables or disables the buttons on the Contacts tab (advanced mode).
* @param contactList
*/
public void enabledButtonsAfterSelection(Object contactList) {
boolean enabled = this.ui.getSelectedItems(contactList).length > 0;
this.ui.setEnabled(find(COMPONENT_DELETE_NEW_CONTACT), enabled);
this.ui.setEnabled(find(COMPONENT_VIEW_CONTACT_BUTTON), enabled);
this.ui.setEnabled(find(COMPONENT_SEND_SMS_BUTTON), enabled);
}
/**
* Adds selected contacts to group.
*
* @param item The item holding the destination group.
*/
public void addToGroup(Object item) {
log.trace("ENTER");
Object[] selected = null;
selected = this.ui.getSelectedItems(contactListComponent);
// Add to the selected groups...
Group destination = this.ui.getGroup(item);
// Let's check all the selected items. Any that are groups should be added to!
for (Object component : selected) {
if (this.ui.isAttachment(component, Contact.class)) {
Contact contact = this.ui.getContact(component);
log.debug("Adding Contact [" + contact.getName() + "] to [" + destination + "]");
if(this.groupMembershipDao.addMember(destination, contact)) {
groupDao.updateGroup(destination);
}
}
}
updateGroupList();
log.trace("EXIT");
}
/**
* Remove selected groups and contacts.
*
* @param button
* @param dialog
*/
public void removeSelectedFromGroupList(final Object button, Object dialog) {
log.trace("ENTER");
if (dialog != null) {
this.ui.removeDialog(dialog);
}
Group selectedGroup = this.groupSelecter.getSelectedGroup();
if(!ui.isDefaultGroup(selectedGroup)) {
boolean removeContactsAlso = false;
if (button != null) {
removeContactsAlso = ui.getName(button).equals(COMPONENT_BUTTON_YES);
}
log.debug("Selected Group [" + selectedGroup.getName() + "]");
log.debug("Remove Contacts from database [" + removeContactsAlso + "]");
if (!ui.isDefaultGroup(selectedGroup)) {
log.debug("Removing group [" + selectedGroup.getName() + "] from database");
groupDao.deleteGroup(selectedGroup, removeContactsAlso);
this.groupSelecter.selectGroup(groupSelecter.getRootGroup());
} else {
// Inside a default group
throw new IllegalStateException();
}
}
Object sms = ui.find(find(COMPONENT_GROUP_SELECTER_CONTAINER), COMPONENT_SEND_SMS_BUTTON_GROUP_SIDE);
ui.setEnabled(sms, selectedGroup != null);
ui.alert(InternationalisationUtils.getI18NString(MESSAGE_GROUPS_AND_CONTACTS_DELETED));
refresh();
log.trace("EXIT");
}
/**
* Removes the contacts selected in the contacts list from the group which is selected in the groups tree.
* @param selectedGroup A set of thinlet components with group members attached to them.
*/
public void removeFromGroup(Object selectedGroup) {
Group g = this.ui.getGroup(selectedGroup);
Contact c = this.ui.getContact(this.ui.getSelectedItem(contactListComponent));
if(this.groupMembershipDao.removeMember(g, c)) {
this.refresh();
}
}
/** Removes the selected contacts of the supplied contact list component. */
public void deleteSelectedContacts() {
log.trace("ENTER");
Group selectedGroup = this.groupSelecter.getSelectedGroup();
this.ui.removeConfirmationDialog();
this.ui.setStatus(InternationalisationUtils.getI18NString(MESSAGE_REMOVING_CONTACTS));
final Object[] selected = this.ui.getSelectedItems(contactListComponent);
for (Object o : selected) {
Contact contact = ui.getContact(o);
log.debug("Deleting contact [" + contact.getName() + "]");
contactDao.deleteContact(contact);
}
ui.alert(InternationalisationUtils.getI18NString(MESSAGE_CONTACTS_DELETED));
refresh();
this.groupSelecter.selectGroup(selectedGroup);
log.trace("EXIT");
}
/**
* Creates a new group with the supplied name.
*
* @param newGroupName The desired group name.
* @param dialog the dialog holding the information to where we should create this new group.
*/
public void createNewGroup(String newGroupName, Object dialog) {
// The selected parent group should be attached to this dialog. Get it,
// create the new group, update the group list and then remove the dialog.
Group selectedParentGroup = this.ui.getGroup(dialog);
doGroupCreation(newGroupName, dialog, selectedParentGroup);
}
//> PRIVATE UI HELPER METHODS
/**
* Creates a group with the supplied name and inside the supplied parent .
* @param newGroupName The desired group name.
* @param dialog The dialog to be removed after the operation.
* @param selectedParentGroup
*/
private void doGroupCreation(String newGroupName, Object dialog, Group selectedParentGroup) {
log.trace("ENTER");
if(log.isDebugEnabled()) {
String parentGroupName = selectedParentGroup == null ? "null" : selectedParentGroup.getName();
log.debug("Parent group [" + parentGroupName + "]");
}
if(selectedParentGroup == null) {
selectedParentGroup = ui.getRootGroup();
}
log.debug("Group Name [" + newGroupName + "]");
try {
if(log.isDebugEnabled()) log.debug("Creating group with name: " + newGroupName + " and parent: " + selectedParentGroup);
Group g = new Group(selectedParentGroup, newGroupName);
this.groupDao.saveGroup(g);
this.groupSelecter.addGroup(g);
if (dialog != null) this.ui.remove(dialog);
this.selectedGroup = g;
this.updateGroupList();
log.debug("Group created successfully!");
} catch (DuplicateKeyException e) {
log.debug("A group with this name already exists.", e);
this.ui.alert(InternationalisationUtils.getI18NString(MESSAGE_GROUP_ALREADY_EXISTS));
}
log.trace("EXIT");
}
/** Repopulates the contact list according to the current filter. */
public void updateContactList() {
this.contactListPager.setCurrentPage(0);
this.contactListPager.refresh();
enabledButtonsAfterSelection(contactListComponent);
}
/** Updates the group tree. */
private void updateGroupList() {
this.groupSelecter.refresh(true);
this.groupSelecter.selectGroup(selectedGroup);
Object btSendSmsToGroup = ui.find(find(COMPONENT_GROUP_SELECTER_CONTAINER), COMPONENT_SEND_SMS_BUTTON_GROUP_SIDE);
this.ui.setEnabled(btSendSmsToGroup, this.groupSelecter.getSelectedGroup() != null);
updateContactList();
}
//> EVENT HANDLER METHODS
public void addToContactList(Contact contact, Group group) {
List<Group> selectedGroupsFromTree = new ArrayList<Group>();
Group g = this.groupSelecter.getSelectedGroup();
selectedGroupsFromTree.add(g);
if (selectedGroupsFromTree.contains(group)) {
int limit = this.contactListPager.getMaxItemsPerPage();
//Adding
if (this.ui.getItems(contactListComponent).length < limit) {
this.ui.add(contactListComponent, this.ui.getRow(contact));
}
}
this.groupSelecter.refresh(true);
// updateTree(group);
}
//> UI PASS-THROUGH METHODS TO UiGC
/** @see UiGeneratorController#groupList_expansionChanged(Object) */
public void groupList_expansionChanged(Object groupList) {
this.ui.groupList_expansionChanged(groupList);
}
/** Shows the compose message dialog for all members of the selected group. */
public void sendSmsToGroup() {
this.ui.show_composeMessageForm(this.groupSelecter.getSelectedGroup());
}
/** Shows the compose message dialog for all selected contacts. */
public void sendSmsToContacts() {
Object[] selectedItems = ui.getSelectedItems(contactListComponent);
if(selectedItems.length > 0) {
HashSet<Object> contacts = new HashSet<Object>(); // Must be Objects because of stupid method sig of show_comp...
for(Object selectedItem : selectedItems) {
contacts.add(ui.getAttachedObject(selectedItem, Contact.class));
}
this.ui.show_composeMessageForm(contacts);
}
}
/**
* Shows the export wizard dialog for exporting contacts.
* @param list The list to get selected items from.
* @param type the name of the type to export
*/
public void showExportWizard(Object list) {
this.ui.showExportWizard(list, "contacts");
}
//> INSTANCE HELPER METHODS
/** Initialise dynamic contents of the tab component. */
protected Object initialiseTab() {
Object tabComponent = ui.loadComponentFromFile(UI_FILE_CONTACTS_TAB, this);
// Cache Thinlet UI components
contactListComponent = this.ui.find(tabComponent, COMPONENT_CONTACT_MANAGER_CONTACT_LIST);
this.contactListPager = new ComponentPagingHandler(this.ui, this, contactListComponent);
Object pnContacts = this.ui.find(tabComponent, COMPONENT_PN_CONTACTS);
this.ui.add(pnContacts, this.contactListPager.getPanel());
//initContactTableForSorting();
return tabComponent;
}
/** Initialise the message table's HEADER component for sorting the table. */
private void initContactTableForSorting() {
Object header = Thinlet.get(contactListComponent, ThinletText.HEADER);
for (Object o : ui.getItems(header)) {
String text = ui.getString(o, Thinlet.TEXT);
// Here, the FIELD property is set on each column of the message table. These field objects are
// then used for easy sorting of the message table.
if(text != null) {
if (text.equalsIgnoreCase(InternationalisationUtils.getI18NString(COMMON_NAME))) ui.putProperty(o, PROPERTY_FIELD, Message.Field.STATUS);
else if(text.equalsIgnoreCase(InternationalisationUtils.getI18NString(COMMON_PHONE_NUMBER))) ui.putProperty(o, PROPERTY_FIELD, Message.Field.DATE);
else if(text.equalsIgnoreCase(InternationalisationUtils.getI18NString(COMMON_E_MAIL_ADDRESS))) ui.putProperty(o, PROPERTY_FIELD, Message.Field.SENDER_MSISDN);
}
}
}
//> STATIC FACTORIES
//> STATIC HELPER METHODS
}
| true | true | public void populateGroups(Object popUp, Object list) {
Object[] selectedItems = this.ui.getSelectedItems(list);
this.ui.setVisible(popUp, this.ui.getSelectedItems(list).length > 0);
if (selectedItems.length == 0) {
//Nothing selected
boolean none = true;
for (Object o : this.ui.getItems(popUp)) {
if (this.ui.getName(o).equals(COMPONENT_NEW_GROUP)
|| this.ui.getName(o).equals("miNewContact")) {
this.ui.setVisible(o, true);
none = false;
} else {
this.ui.setVisible(o, false);
}
}
this.ui.setVisible(popUp, !none);
} else if (this.ui.getAttachedObject(selectedItems[0]) instanceof Contact) {
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (name.equals(COMPONENT_MENU_ITEM_MSG_HISTORY)
|| name.equals(COMPONENT_MENU_ITEM_VIEW_CONTACT)) {
this.ui.setVisible(o, this.ui.getSelectedItems(list).length == 1);
} else if (!name.equals(COMPONENT_GROUPS_MENU)) {
this.ui.setVisible(o, true);
}
}
Object menu = this.ui.find(popUp, COMPONENT_GROUPS_MENU);
this.ui.removeAll(menu);
List<Group> allGroups = this.groupDao.getAllGroups();
for (Group g : allGroups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
this.ui.setText(menuItem, InternationalisationUtils.getI18NString(COMMON_GROUP) + "'" + g.getName() + "'");
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "addToGroup(this)", menu, this);
this.ui.add(menu, menuItem);
}
this.ui.setVisible(menu, allGroups.size() != 0);
String menuName = InternationalisationUtils.getI18NString(ACTION_ADD_TO_GROUP);
this.ui.setText(menu, menuName);
Object menuRemove = this.ui.find(popUp, "groupsMenuRemove");
if (menuRemove != null) {
Contact c = this.ui.getContact(this.ui.getSelectedItem(list));
this.ui.removeAll(menuRemove);
List<Group> groups = this.groupMembershipDao.getGroups(c);
for (Group g : groups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
this.ui.setText(menuItem, g.getName());
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "removeFromGroup(this)", menuRemove, this);
this.ui.add(menuRemove, menuItem);
}
this.ui.setEnabled(menuRemove, groups.size() != 0);
}
} else {
Group g = this.ui.getGroup(this.ui.getSelectedItem(list));
//GROUPS OR BOTH
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (COMPONENT_NEW_GROUP.equals(name)
|| COMPONENT_MI_SEND_SMS.equals(name)
|| COMPONENT_MI_DELETE.equals(name)
|| COMPONENT_MENU_ITEM_MSG_HISTORY.equals(name)
|| "miNewContact".equals(name)) {
this.ui.setVisible(o, true);
} else {
this.ui.setVisible(o, false);
}
if (COMPONENT_MI_DELETE.equals(name)) {
this.ui.setVisible(o, !this.ui.isDefaultGroup(g));
}
// FIXME this is superfluous - always sets vis to true
if (COMPONENT_NEW_GROUP.equals(name)) {
this.ui.setVisible(o, true);
}
}
}
}
| public void populateGroups(Object popUp, Object list) {
Object[] selectedItems = this.ui.getSelectedItems(list);
this.ui.setVisible(popUp, this.ui.getSelectedItems(list).length > 0);
if (selectedItems.length == 0) {
//Nothing selected
boolean none = true;
for (Object o : this.ui.getItems(popUp)) {
if (this.ui.getName(o).equals(COMPONENT_NEW_GROUP)
|| this.ui.getName(o).equals("miNewContact")) {
this.ui.setVisible(o, true);
none = false;
} else {
this.ui.setVisible(o, false);
}
}
this.ui.setVisible(popUp, !none);
} else if (this.ui.getAttachedObject(selectedItems[0]) instanceof Contact) {
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (name.equals(COMPONENT_MENU_ITEM_MSG_HISTORY)
|| name.equals(COMPONENT_MENU_ITEM_VIEW_CONTACT)) {
this.ui.setVisible(o, this.ui.getSelectedItems(list).length == 1);
} else if (!name.equals(COMPONENT_GROUPS_MENU)) {
this.ui.setVisible(o, true);
}
}
Object menu = this.ui.find(popUp, COMPONENT_GROUPS_MENU);
this.ui.removeAll(menu);
List<Group> allGroups = this.groupDao.getAllGroups();
for (Group g : allGroups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
this.ui.setText(menuItem, InternationalisationUtils.getI18NString(COMMON_GROUP) + " '" + g.getName() + "'");
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "addToGroup(this)", menu, this);
this.ui.add(menu, menuItem);
}
this.ui.setVisible(menu, allGroups.size() != 0);
String menuName = InternationalisationUtils.getI18NString(ACTION_ADD_TO_GROUP);
this.ui.setText(menu, menuName);
Object menuRemove = this.ui.find(popUp, "groupsMenuRemove");
if (menuRemove != null) {
Contact c = this.ui.getContact(this.ui.getSelectedItem(list));
this.ui.removeAll(menuRemove);
List<Group> groups = this.groupMembershipDao.getGroups(c);
for (Group g : groups) {
Object menuItem = Thinlet.create(Thinlet.MENUITEM);
this.ui.setText(menuItem, g.getName());
this.ui.setIcon(menuItem, Icon.GROUP);
this.ui.setAttachedObject(menuItem, g);
this.ui.setAction(menuItem, "removeFromGroup(this)", menuRemove, this);
this.ui.add(menuRemove, menuItem);
}
this.ui.setEnabled(menuRemove, groups.size() != 0);
}
} else {
Group g = this.ui.getGroup(this.ui.getSelectedItem(list));
//GROUPS OR BOTH
for (Object o : this.ui.getItems(popUp)) {
String name = this.ui.getName(o);
if (COMPONENT_NEW_GROUP.equals(name)
|| COMPONENT_MI_SEND_SMS.equals(name)
|| COMPONENT_MI_DELETE.equals(name)
|| COMPONENT_MENU_ITEM_MSG_HISTORY.equals(name)
|| "miNewContact".equals(name)) {
this.ui.setVisible(o, true);
} else {
this.ui.setVisible(o, false);
}
if (COMPONENT_MI_DELETE.equals(name)) {
this.ui.setVisible(o, !this.ui.isDefaultGroup(g));
}
// FIXME this is superfluous - always sets vis to true
if (COMPONENT_NEW_GROUP.equals(name)) {
this.ui.setVisible(o, true);
}
}
}
}
|
diff --git a/src/net/sourceforge/dvb/projectx/xinput/ftp/FtpServer.java b/src/net/sourceforge/dvb/projectx/xinput/ftp/FtpServer.java
index 4521d9e..8b78b05 100644
--- a/src/net/sourceforge/dvb/projectx/xinput/ftp/FtpServer.java
+++ b/src/net/sourceforge/dvb/projectx/xinput/ftp/FtpServer.java
@@ -1,217 +1,215 @@
package net.sourceforge.dvb.projectx.xinput.ftp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import net.sourceforge.dvb.projectx.xinput.XInputFile;
public class FtpServer {
private FtpVO ftpVO;
private StringCommandListener scl;
private FTPClient ftpClient;
private boolean isOpen;
private String testMsg;
private FtpServer() {
throw new UnsupportedOperationException();
}
public FtpServer(FtpVO aFtpVO) {
if (aFtpVO == null) { throw new IllegalArgumentException("aFtpVO mustn't be null!"); }
ftpVO = aFtpVO;
scl = new StringCommandListener();
ftpClient = new FTPClient();
ftpClient.addProtocolCommandListener(scl);
isOpen = false;
}
public boolean open() {
boolean isSuccessful = false;
if (isOpen) { throw new IllegalStateException("Is already open, must be closed before!"); }
try {
int reply;
ftpClient.connect(ftpVO.getServer());
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("Can't connect!");
}
if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
ftpClient.logout();
throw new IOException("Can't login!");
}
if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
ftpClient.logout();
throw new IOException("Can't change directory!");
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
isSuccessful = true;
} catch (Exception e) {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
// do nothing
}
}
isSuccessful = false;
}
isOpen = isSuccessful;
return isSuccessful;
}
public XInputFile[] listFiles() {
FTPFile[] ftpFiles = null;
XInputFile[] ftpInputFiles = null;
try {
ftpFiles = ftpClient.listFiles();
ftpInputFiles = new XInputFile[ftpFiles.length];
for (int i = 0; i < ftpFiles.length; i++) {
FtpVO tempFtpVO = (FtpVO) ftpVO.clone();
tempFtpVO.setFtpFile(ftpFiles[i]);
ftpInputFiles[i] = new XInputFile(tempFtpVO);
}
} catch (Exception e) {
ftpInputFiles = new XInputFile[0];
}
return ftpInputFiles;
}
public InputStream retrieveFileStream(String aFileName) throws IOException {
return ftpClient.retrieveFileStream(aFileName);
}
public void close() {
if (!isOpen) {
throw new IllegalStateException("Is already closed, must be opened before!");
} else {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (Exception e) {
// do nothing
}
isOpen = false;
}
}
public boolean test() {
int base = 0;
boolean error = false;
FTPFile[] ftpFiles;
testMsg = null;
try {
int reply;
ftpClient.connect(ftpVO.getServer());
// Check connection
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
testMsg = "Can't connect.";
- error = true;
return false;
}
// Login
if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
ftpClient.logout();
testMsg = "Can't login.";
- error = true;
return false;
}
// Change directory
if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
testMsg = "Can't change to directory";
- error = true;
return false;
}
testMsg = "Everything is fine.";
ftpClient.logout();
} catch (IOException ex) {
testMsg = ex.getLocalizedMessage();
+ error = true;
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
}
}
}
- return true;
+ return !error;
}
public String getTestMsg() {
return testMsg;
}
public String getLog() {
return scl.getMessages();
}
}
/*
* int base = 0; boolean storeFile = false, binaryTransfer = false, error =
* false; String server, username, password, remote, local, remoteDir; FTPClient
* ftp; FTPFile[] ftpFiles;
*
* server = "192.168.0.5"; username = "root"; password = "dreambox"; remote =
* ""; local = ""; remoteDir = "/hdd/movie";
*
* ftp = new FTPClient(); ftp.addProtocolCommandListener( new
* PrintCommandListener(new PrintWriter(System.out)));
*
*
* try { if (!ftp.login(username, password)) { ftp.logout(); error = true; }
* else { System.out.println("Remote system is " + ftp.getSystemName());
*
* ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode();
*
* ftp.changeWorkingDirectory(remoteDir); ftpFiles = ftp.listFiles(); for (int i =
* 0; i < ftpFiles.length; i++) { FTPFile file = ftpFiles[i];
* System.out.println("Listing of " + remoteDir + ": " + file.getName()); }
*
*
* if (storeFile) { InputStream input;
*
* input = new FileInputStream(local); ftp.storeFile(remote, input); } else {
* OutputStream output;
*
* output = new FileOutputStream(local); ftp.retrieveFile(remote, output); }
*
*
* ftp.logout(); } } catch (FTPConnectionClosedException e) { error = true;
* System.err.println("Server closed connection."); e.printStackTrace(); } catch
* (IOException e) { error = true; e.printStackTrace(); } finally { if
* (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do
* nothing } } }
*/
| false | true | public boolean test() {
int base = 0;
boolean error = false;
FTPFile[] ftpFiles;
testMsg = null;
try {
int reply;
ftpClient.connect(ftpVO.getServer());
// Check connection
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
testMsg = "Can't connect.";
error = true;
return false;
}
// Login
if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
ftpClient.logout();
testMsg = "Can't login.";
error = true;
return false;
}
// Change directory
if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
testMsg = "Can't change to directory";
error = true;
return false;
}
testMsg = "Everything is fine.";
ftpClient.logout();
} catch (IOException ex) {
testMsg = ex.getLocalizedMessage();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
}
}
}
return true;
}
| public boolean test() {
int base = 0;
boolean error = false;
FTPFile[] ftpFiles;
testMsg = null;
try {
int reply;
ftpClient.connect(ftpVO.getServer());
// Check connection
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
testMsg = "Can't connect.";
return false;
}
// Login
if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
ftpClient.logout();
testMsg = "Can't login.";
return false;
}
// Change directory
if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
testMsg = "Can't change to directory";
return false;
}
testMsg = "Everything is fine.";
ftpClient.logout();
} catch (IOException ex) {
testMsg = ex.getLocalizedMessage();
error = true;
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
}
}
}
return !error;
}
|
diff --git a/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java b/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java
index cb27fc2..e93f8f2 100644
--- a/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java
+++ b/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java
@@ -1,115 +1,115 @@
package org.osmdroid.google.sample;
import org.osmdroid.api.IMapView;
import org.osmdroid.api.IMyLocationOverlay;
import org.osmdroid.util.GeoPoint;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.maps.MapActivity;
public class GoogleWrapperSample extends MapActivity {
private static final int GOOGLE_MAP_VIEW_ID = 1;
private static final int OSM_MAP_VIEW_ID = 2;
private static final int ENABLE_MY_LOCATION_ID = 3;
private static final int DISABLE_MY_LOCATION_ID = 4;
private MenuItem mGoogleMenuItem;
private MenuItem mOsmMenuItem;
private MenuItem mEnableMyLocationOverlayMenuItem;
private MenuItem mDisableMyLocationOverlayMenuItem;
private MapViewSelection mMapViewSelection = MapViewSelection.OSM;
private IMapView mMapView;
private IMyLocationOverlay mMyLocationOverlay;
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
protected void onResume() {
super.onResume();
setMapView();
}
@Override
protected void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
}
@Override
public boolean onCreateOptionsMenu(final Menu pMenu) {
mGoogleMenuItem = pMenu.add(0, GOOGLE_MAP_VIEW_ID, Menu.NONE, R.string.map_view_google);
mOsmMenuItem = pMenu.add(0, OSM_MAP_VIEW_ID, Menu.NONE, R.string.map_view_osm);
mEnableMyLocationOverlayMenuItem = pMenu.add(0, ENABLE_MY_LOCATION_ID, Menu.NONE, R.string.enable_my_location);
mDisableMyLocationOverlayMenuItem = pMenu.add(0, DISABLE_MY_LOCATION_ID, Menu.NONE, R.string.disable_my_location);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu pMenu) {
mGoogleMenuItem.setVisible(mMapViewSelection == MapViewSelection.OSM);
mOsmMenuItem.setVisible(mMapViewSelection == MapViewSelection.Google);
mEnableMyLocationOverlayMenuItem.setVisible(!mMyLocationOverlay.isMyLocationEnabled());
mDisableMyLocationOverlayMenuItem.setVisible(mMyLocationOverlay.isMyLocationEnabled());
return super.onPrepareOptionsMenu(pMenu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem pItem) {
if (pItem == mGoogleMenuItem) {
// switch to google
mMapViewSelection = MapViewSelection.Google;
setMapView();
return true;
}
if (pItem == mOsmMenuItem) {
// switch to osm
mMapViewSelection = MapViewSelection.OSM;
setMapView();
return true;
}
if (pItem == mEnableMyLocationOverlayMenuItem) {
mMyLocationOverlay.enableMyLocation();
}
if (pItem == mDisableMyLocationOverlayMenuItem) {
mMyLocationOverlay.disableMyLocation();
}
return false;
}
private void setMapView() {
if (mMapViewSelection == MapViewSelection.OSM) {
final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256);
setContentView(mapView);
mMapView = mapView;
final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
if (mMapViewSelection == MapViewSelection.Google) {
final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key));
setContentView(mapView);
- mMapView = new org.osmdroid.google.MapView(mapView);
+ mMapView = new org.osmdroid.google.wrapper.MapView(mapView);
- final org.osmdroid.google.MyLocationOverlay mlo = new org.osmdroid.google.MyLocationOverlay(this, mapView);
+ final org.osmdroid.google.wrapper.MyLocationOverlay mlo = new org.osmdroid.google.wrapper.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
mMapView.getController().setZoom(14);
mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover
mMyLocationOverlay.disableMyLocation();
}
private enum MapViewSelection { Google, OSM };
}
| false | true | private void setMapView() {
if (mMapViewSelection == MapViewSelection.OSM) {
final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256);
setContentView(mapView);
mMapView = mapView;
final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
if (mMapViewSelection == MapViewSelection.Google) {
final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key));
setContentView(mapView);
mMapView = new org.osmdroid.google.MapView(mapView);
final org.osmdroid.google.MyLocationOverlay mlo = new org.osmdroid.google.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
mMapView.getController().setZoom(14);
mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover
mMyLocationOverlay.disableMyLocation();
}
| private void setMapView() {
if (mMapViewSelection == MapViewSelection.OSM) {
final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256);
setContentView(mapView);
mMapView = mapView;
final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
if (mMapViewSelection == MapViewSelection.Google) {
final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key));
setContentView(mapView);
mMapView = new org.osmdroid.google.wrapper.MapView(mapView);
final org.osmdroid.google.wrapper.MyLocationOverlay mlo = new org.osmdroid.google.wrapper.MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mlo);
mMyLocationOverlay = mlo;
}
mMapView.getController().setZoom(14);
mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover
mMyLocationOverlay.disableMyLocation();
}
|
diff --git a/src/com/tzachsolomon/spendingtracker/ViewEntriesSpent.java b/src/com/tzachsolomon/spendingtracker/ViewEntriesSpent.java
index 17bef0a..326be79 100644
--- a/src/com/tzachsolomon/spendingtracker/ViewEntriesSpent.java
+++ b/src/com/tzachsolomon/spendingtracker/ViewEntriesSpent.java
@@ -1,675 +1,675 @@
package com.tzachsolomon.spendingtracker;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ViewEntriesSpent extends Activity implements OnGestureListener,
OnDoubleTapListener {
private final static String TAG = ViewEntriesSpent.class.getSimpleName();
public final static int TYPE_MONTH = 0;
public final static int TYPE_WEEK = 1;
public final static int TYPE_TODAY = 2;
private GestureDetector m_Detector;
private final static String XMLFILE = "spendingTracker.xml";
private TableLayout tlEntries;
private TextView textViewSpendingRefrenceDate;
private SpendingTrackerDbEngine m_SpendingTrackerDbEngine;
private int m_Type;
private Calendar m_Calendar;
private String[][] m_Data;
@Override
protected void onCreate(Bundle savedInstanceState) {
//
super.onCreate(savedInstanceState);
setContentView(R.layout.spending_entries);
initializeVariables();
try {
Bundle extras = getIntent().getExtras();
m_Type = extras.getInt("TYPE");
//
} catch (SQLException e) {
Toast.makeText(this,
"Could not populate rows due to " + e.toString(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
m_Detector = new GestureDetector(this, this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//
this.m_Detector.onTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
@Override
protected void onResume() {
//
super.onResume();
updateTableLayout();
}
private void updateTableLayout() {
switch (m_Type) {
case TYPE_TODAY:
m_Data = m_SpendingTrackerDbEngine.getSpentDailyEntries(m_Calendar);
break;
case TYPE_WEEK:
m_Data = m_SpendingTrackerDbEngine.getSpentThisWeekEnteries(1,
m_Calendar);
break;
case TYPE_MONTH:
m_Data = m_SpendingTrackerDbEngine
.getSpentThisMonthEnteries(m_Calendar);
break;
default:
break;
}
PopulateRows(m_Data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_spent, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//
MenuItem menuItemSpentExport = menu.findItem(R.id.menuItemSpentExport);
MenuItem menuItemSpentImport = menu.findItem(R.id.menuItemSpentImport);
MenuItem menuItemSpentDatabase = menu
.findItem(R.id.menuItemSpentDatabase);
if (m_Type == TYPE_MONTH) {
menuItemSpentExport.setVisible(true);
menuItemSpentImport.setVisible(true);
menuItemSpentDatabase.setVisible(true);
} else {
menuItemSpentExport.setVisible(false);
menuItemSpentImport.setVisible(false);
menuItemSpentDatabase.setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//
boolean ret = false;
switch (item.getItemId()) {
case R.id.menuItemSpentStatistics:
menuItemSpentStatistics_Clicked();
break;
case R.id.menuItemSpentSortAmount:
menuItemSpentSortAmount_Clicked();
break;
case R.id.menuItemSpentSortCategory:
menuItemSpentSortCategory_Clicked();
break;
case R.id.menuItemSpentSortDate:
menuItemSpentSortDate_Clicked();
break;
case R.id.menuItemSpentSortId:
menuItemSpentSortId_Clicked();
break;
case R.id.menuItemSpentDelete:
menuItemSpentDelete_Clicked();
ret = true;
break;
case R.id.menuItemSpentEdit:
menuItemSpentEdit_Clicked();
ret = true;
break;
case R.id.menuItemSpentExport:
menuItemSpentExport_Clicked();
ret = true;
break;
case R.id.menuItemSpentImport:
menuItemSpentImport_Clicked();
ret = true;
break;
default:
ret = super.onOptionsItemSelected(item);
break;
}
return ret;
}
private void menuItemSpentStatistics_Clicked() {
//
int rowIndex = m_Data.length - 1;
HashMap<String, Float> stats = new HashMap<String, Float>();
HashMap<String, Integer> statsCounter = new HashMap<String, Integer>();
StringBuilder stringBuilder = new StringBuilder();
Log.i(TAG, "number of rows: " + rowIndex);
while (rowIndex >= 0) {
// column 2 in m_Data is the category
String key = m_Data[rowIndex][2];
if (stats.containsKey(key)) {
float value = stats.get(key);
Log.i(TAG, "value " + value);
value += Float.parseFloat(m_Data[rowIndex][1]);
stats.put(key, value);
statsCounter.put(key, statsCounter.get(key) + 1);
} else {
stats.put(key,
Float.parseFloat(m_Data[rowIndex][1]));
- statsCounter.put(key, 0);
+ statsCounter.put(key, 1);
}
rowIndex--;
}
Iterator<String> a = stats.keySet().iterator();
while ( a.hasNext() ){
String key = (String)a.next();
float value = (stats.get(key));
- stringBuilder.append("Category " + key);
+ stringBuilder.append("\nCategory " + key);
stringBuilder.append("\n\tTotal Spent: " + value);
stringBuilder.append("\n\tAverage Spent: " + value / (float)statsCounter.get(key));
stringBuilder.append("\n\t# of entries: " + statsCounter.get(key));
}
Dialog d = new Dialog(this);
d.setTitle(getString(R.string.dialogTitleSpentStatistics));
TextView message = new TextView(this);
message.setText(stringBuilder.toString());
d.setContentView(message);
d.show();
}
private void menuItemSpentSortCategory_Clicked() {
//
m_SpendingTrackerDbEngine
.setSortBy(SpendingTrackerDbEngine.KEY_CATEGORY);
updateTableLayout();
}
private void menuItemSpentSortAmount_Clicked() {
//
m_SpendingTrackerDbEngine.setSortBy(SpendingTrackerDbEngine.KEY_AMOUNT);
updateTableLayout();
}
private void menuItemSpentSortDate_Clicked() {
//
m_SpendingTrackerDbEngine.setSortBy(SpendingTrackerDbEngine.KEY_DATE);
updateTableLayout();
}
private void menuItemSpentSortId_Clicked() {
//
m_SpendingTrackerDbEngine.setSortBy(SpendingTrackerDbEngine.KEY_ROWID);
updateTableLayout();
}
private void menuItemSpentImport_Clicked() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog
.setTitle(getString(R.string.alertDialogImportDatabaseTitle));
alertDialog
.setMessage(getString(R.string.alertDialogImportDatabaseMessage));
alertDialog.setPositiveButton(
getString(R.string.alertDialogImportDatabasePositive),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
importDatabase();
}
});
alertDialog.setNegativeButton(
getString(R.string.alertDialogImportDatabaseNegative),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
alertDialog.show();
}
private void importDatabase() {
String result = "";
try {
result = m_SpendingTrackerDbEngine.importFromXMLFile(XMLFILE);
updateTableLayout();
} catch (Exception e) {
//
result = e.getMessage();
e.printStackTrace();
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
private void exportDatabase() {
String result = "";
try {
result = m_SpendingTrackerDbEngine.exportToXMLFile(XMLFILE);
} catch (Exception e) {
//
result = e.getMessage();
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
private void menuItemSpentExport_Clicked() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog
.setTitle(getString(R.string.alertDialogExportDatabaseTitle));
alertDialog
.setMessage(getString(R.string.alertDialogExportDatabaseMessage));
alertDialog.setPositiveButton(
getString(R.string.alertDialogExportDatabasePositive),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
exportDatabase();
}
});
alertDialog.setNegativeButton(
getString(R.string.alertDialogExportDatabaseNegative),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
alertDialog.show();
}
private void menuItemSpentDelete_Clicked() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText editTextRowId = new EditText(this);
editTextRowId.setInputType(InputType.TYPE_CLASS_NUMBER);
editTextRowId.setHint(getString(R.string.editTextRowIdHint));
alertDialog.setView(editTextRowId);
alertDialog
.setTitle(getString(R.string.alertDialogViewEntriesSpentTitleDelete));
alertDialog.setPositiveButton(
getString(R.string.alertDialogViewEntriesSpentPositiveDelete),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
String rowId = editTextRowId.getText().toString();
m_SpendingTrackerDbEngine
.deleteSpentEntryByRowId(rowId);
Toast.makeText(ViewEntriesSpent.this,
getString(R.string.entryDeleted),
Toast.LENGTH_SHORT).show();
updateTableLayout();
}
});
alertDialog.setNegativeButton(
getString(R.string.alertDialogViewEntriesSpentNegative),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
alertDialog.show();
}
private void menuItemSpentEdit_Clicked() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText editTextRowId = new EditText(this);
editTextRowId.setInputType(InputType.TYPE_CLASS_NUMBER);
editTextRowId.setHint(getString(R.string.editTextRowIdHint));
alertDialog.setView(editTextRowId);
alertDialog
.setTitle(getString(R.string.alertDialogViewEntriesSpentTitleEdit));
alertDialog.setPositiveButton(
getString(R.string.alertDialogViewEntriesSpentPositiveEdit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
Intent intent = new Intent(ViewEntriesSpent.this,
EditEntrySpent.class);
intent.putExtra("RowId", editTextRowId.getText()
.toString());
startActivity(intent);
}
});
alertDialog.setNegativeButton(
getString(R.string.alertDialogViewEntriesSpentNegative),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
alertDialog.show();
}
private void PopulateRows(String[][] i_Data) {
int rows = i_Data.length;
int i;
try {
int howMuchRowsToRemove = tlEntries.getChildCount() - 1;
// removing all entries except the headers
tlEntries.removeViews(1, howMuchRowsToRemove);
for (i = 0; i < rows; i++) {
AddRowToTable(i_Data[i]);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
private void AddRowToTable(String[] i_Row) {
int columns = i_Row.length;
int i;
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView[] textViews = new TextView[columns];
// taken from the todays_entries.xml
int[] layout_weight = new int[] { 10, 20, 60, 10 };
for (i = 0; i < columns; i++) {
textViews[i] = new TextView(this);
textViews[i].setText(i_Row[i]);
textViews[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
layout_weight[i]));
tr.addView(textViews[i]);
}
tlEntries.addView(tr);
}
private void initializeVariables() {
// initialize members
m_Calendar = Calendar.getInstance();
m_Calendar.setTimeInMillis(System.currentTimeMillis());
tlEntries = (TableLayout) findViewById(R.id.tableLayoutEnteriesSpent);
textViewSpendingRefrenceDate = (TextView) findViewById(R.id.textViewSpendingRefrenceDate);
showRefrenceDate();
m_SpendingTrackerDbEngine = new SpendingTrackerDbEngine(this);
m_SpendingTrackerDbEngine.setSortBy(SpendingTrackerDbEngine.KEY_DATE);
}
@Override
public boolean onDown(MotionEvent e) {
//
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
//
float direction = e1.getX() - e2.getX();
float distance = Math.abs(direction);
Log.d(TAG, "velocityX " + velocityX);
Log.d(TAG, "distance " + distance);
// checking if the user swipe from left to right or right to left
if (Math.abs(velocityX) > 100 && distance > 100) {
if (direction > 0) {
// move right
screenSlide(1);
} else {
// move left
screenSlide(-1);
}
}
return true;
}
/**
* Function will add according to m_Type it is currently displaying
*
* @param i_Add
* - 1 add 1 day / week / month, -1 subtract 1 day / week / month
*/
private void screenSlide(int i_Add) {
//
switch (m_Type) {
case TYPE_TODAY:
m_Calendar.add(Calendar.DAY_OF_YEAR, i_Add);
break;
case TYPE_WEEK:
m_Calendar.add(Calendar.WEEK_OF_YEAR, i_Add);
break;
case TYPE_MONTH:
m_Calendar.add(Calendar.MONTH, i_Add);
break;
default:
break;
}
showRefrenceDate();
updateTableLayout();
}
private void showRefrenceDate() {
//
StringBuilder sb = new StringBuilder();
sb.append("Current refrence date is (YYYY/MM/DD): \n");
sb.append(m_Calendar.get(Calendar.YEAR));
sb.append("/");
sb.append(m_Calendar.get(Calendar.MONTH) + 1);
sb.append("/");
sb.append(m_Calendar.get(Calendar.DAY_OF_MONTH));
textViewSpendingRefrenceDate.setText(sb.toString());
// Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onLongPress(MotionEvent e) {
//
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
//
return true;
}
@Override
public void onShowPress(MotionEvent e) {
//
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
//
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
//
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
//
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
//
return false;
}
}
| false | true | private void menuItemSpentStatistics_Clicked() {
//
int rowIndex = m_Data.length - 1;
HashMap<String, Float> stats = new HashMap<String, Float>();
HashMap<String, Integer> statsCounter = new HashMap<String, Integer>();
StringBuilder stringBuilder = new StringBuilder();
Log.i(TAG, "number of rows: " + rowIndex);
while (rowIndex >= 0) {
// column 2 in m_Data is the category
String key = m_Data[rowIndex][2];
if (stats.containsKey(key)) {
float value = stats.get(key);
Log.i(TAG, "value " + value);
value += Float.parseFloat(m_Data[rowIndex][1]);
stats.put(key, value);
statsCounter.put(key, statsCounter.get(key) + 1);
} else {
stats.put(key,
Float.parseFloat(m_Data[rowIndex][1]));
statsCounter.put(key, 0);
}
rowIndex--;
}
Iterator<String> a = stats.keySet().iterator();
while ( a.hasNext() ){
String key = (String)a.next();
float value = (stats.get(key));
stringBuilder.append("Category " + key);
stringBuilder.append("\n\tTotal Spent: " + value);
stringBuilder.append("\n\tAverage Spent: " + value / (float)statsCounter.get(key));
stringBuilder.append("\n\t# of entries: " + statsCounter.get(key));
}
Dialog d = new Dialog(this);
d.setTitle(getString(R.string.dialogTitleSpentStatistics));
TextView message = new TextView(this);
message.setText(stringBuilder.toString());
d.setContentView(message);
d.show();
}
| private void menuItemSpentStatistics_Clicked() {
//
int rowIndex = m_Data.length - 1;
HashMap<String, Float> stats = new HashMap<String, Float>();
HashMap<String, Integer> statsCounter = new HashMap<String, Integer>();
StringBuilder stringBuilder = new StringBuilder();
Log.i(TAG, "number of rows: " + rowIndex);
while (rowIndex >= 0) {
// column 2 in m_Data is the category
String key = m_Data[rowIndex][2];
if (stats.containsKey(key)) {
float value = stats.get(key);
Log.i(TAG, "value " + value);
value += Float.parseFloat(m_Data[rowIndex][1]);
stats.put(key, value);
statsCounter.put(key, statsCounter.get(key) + 1);
} else {
stats.put(key,
Float.parseFloat(m_Data[rowIndex][1]));
statsCounter.put(key, 1);
}
rowIndex--;
}
Iterator<String> a = stats.keySet().iterator();
while ( a.hasNext() ){
String key = (String)a.next();
float value = (stats.get(key));
stringBuilder.append("\nCategory " + key);
stringBuilder.append("\n\tTotal Spent: " + value);
stringBuilder.append("\n\tAverage Spent: " + value / (float)statsCounter.get(key));
stringBuilder.append("\n\t# of entries: " + statsCounter.get(key));
}
Dialog d = new Dialog(this);
d.setTitle(getString(R.string.dialogTitleSpentStatistics));
TextView message = new TextView(this);
message.setText(stringBuilder.toString());
d.setContentView(message);
d.show();
}
|
diff --git a/src/View/Menu.java b/src/View/Menu.java
index e253282..81b5f50 100644
--- a/src/View/Menu.java
+++ b/src/View/Menu.java
@@ -1,112 +1,112 @@
package View;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.openal.AudioLoader;
import org.newdawn.slick.state.*;
import org.newdawn.slick.util.ResourceLoader;
import Model.MainHub;
public class Menu extends BasicGameState implements ActionListener{
private String mouse = "No input yet";
/** The wav sound effect */
private Audio wavEffect;
private boolean startMusic = true;
Image bg;
Image backgroundImage;
Image startGameButton;
Image exitButton;
Image titleText;
Image warriorImage;
public Menu (int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
backgroundImage = new Image("res/miscImages/bg-gates.png");
startGameButton = new Image("res/buttons/startgame.png");
exitButton = new Image("res/buttons/exit.png");
titleText = new Image("res/miscImages/menuText.png");
try {
wavEffect = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("res/sounds/bg-music.wav"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
gc.setFullscreen(false);
g.setColor(Color.black);
g.drawImage(backgroundImage, 0, 0);
/*if(startMusic){
wavEffect.playAsSoundEffect(1.0f, 1.0f, true);
startMusic = false;
}*/
g.drawImage(titleText, gc.getWidth()/2 - titleText.getWidth()/2, 150);
g.drawImage(startGameButton, gc.getWidth()/2 - startGameButton.getWidth()/2, 325);
g.drawImage(exitButton, gc.getWidth()/2 - exitButton.getWidth()/2, 425);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
Input input = gc.getInput();
// Escape key quits the game
if(input.isKeyDown(Input.KEY_ESCAPE)) gc.exit();
if((580<xPos && xPos<700) && (325<yPos && yPos<370)){
startGameButton = new Image("res/buttons/startgame_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
sbg.enterState(3);
}
} else if((580<xPos && xPos<700) && (425<yPos && yPos<470)){
exitButton = new Image("res/buttons/exit_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
- System.exit(0);
+ gc.exit();
}
}else{
startGameButton = new Image("res/buttons/startgame.png");
exitButton = new Image("res/buttons/exit.png");
}
}
public int getID(){
return 0;
}
public int getWidth(Image image){
return image.getWidth();
}
public int getHeight(Image image){
return image.getHeight();
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
| true | true | public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
Input input = gc.getInput();
// Escape key quits the game
if(input.isKeyDown(Input.KEY_ESCAPE)) gc.exit();
if((580<xPos && xPos<700) && (325<yPos && yPos<370)){
startGameButton = new Image("res/buttons/startgame_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
sbg.enterState(3);
}
} else if((580<xPos && xPos<700) && (425<yPos && yPos<470)){
exitButton = new Image("res/buttons/exit_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
System.exit(0);
}
}else{
startGameButton = new Image("res/buttons/startgame.png");
exitButton = new Image("res/buttons/exit.png");
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
Input input = gc.getInput();
// Escape key quits the game
if(input.isKeyDown(Input.KEY_ESCAPE)) gc.exit();
if((580<xPos && xPos<700) && (325<yPos && yPos<370)){
startGameButton = new Image("res/buttons/startgame_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
sbg.enterState(3);
}
} else if((580<xPos && xPos<700) && (425<yPos && yPos<470)){
exitButton = new Image("res/buttons/exit_p.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
gc.exit();
}
}else{
startGameButton = new Image("res/buttons/startgame.png");
exitButton = new Image("res/buttons/exit.png");
}
}
|
diff --git a/src/com/michitsuchida/marketfavoritter/main/MarketFavoritterActivity.java b/src/com/michitsuchida/marketfavoritter/main/MarketFavoritterActivity.java
index 602db41..10464b0 100644
--- a/src/com/michitsuchida/marketfavoritter/main/MarketFavoritterActivity.java
+++ b/src/com/michitsuchida/marketfavoritter/main/MarketFavoritterActivity.java
@@ -1,577 +1,577 @@
package com.michitsuchida.marketfavoritter.main;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.michitsuchida.marketfavoritter.db.DBMainStore;
/**
* このアプリのメインのActivity。Bookmark一覧を表示する。
*
* @author MichiTsuchida
*/
public class MarketFavoritterActivity extends Activity {
/** LOG TAG */
static final String LOG_TAG = "MarketBookmark";
/** SharedPreferenceに保存するためのキー */
private static final String SHARED_PREF_KEY_SORT_ODER = "SortOrder";
private static final String SHARED_PREF_KEY_FILTER = "Filter";
/** メニューID */
// 並び替え
private final int MENU_ID1 = Menu.FIRST;
// フィルタ
private final int MENU_ID2 = Menu.FIRST + 1;
// アイテム編集
private final int MENU_ID3 = Menu.FIRST + 2;
// アイテム削除
private final int MENU_ID4 = Menu.FIRST + 3;
// 他のアプリに共有
private final int MENU_ID5 = Menu.FIRST + 4;
/** アプリのリスト */
private List<AppElement> mAppList = new ArrayList<AppElement>();
/** DBを操作する */
private DBMainStore mMainStore;
/** SharedPreferenceオブジェクト */
private SharedPreferences mSharedPref;
/**
* onCreate.
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate()");
// SharedPreferenceオブジェクトの初期化
mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.main);
if (mMainStore == null) {
mMainStore = new DBMainStore(this, true);
}
buildListView();
}
/**
* onRestart.
*/
@Override
public void onRestart() {
super.onRestart();
Log.d(LOG_TAG, "onRestert()");
if (mMainStore == null) {
mMainStore = new DBMainStore(this, true);
}
buildListView();
}
/**
* onResume.
*/
@Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume()");
if (mMainStore == null) {
mMainStore = new DBMainStore(this, true);
}
buildListView();
}
/**
* onPause.
*/
@Override
public void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause()");
mMainStore.close();
mMainStore = null;
putFilter("");
}
/**
* メニューボタンが押された時のイベントハンドラ。
*
* @param menu メニュー
* @return メニューが表示される場合はtrue、そうでなければfalse
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean ret = super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ID1, Menu.NONE, R.string.menu_sort_item);
menu.add(0, MENU_ID2, Menu.NONE, R.string.menu_filter_item);
menu.add(0, MENU_ID3, Menu.NONE, R.string.menu_edit_item);
menu.add(0, MENU_ID4, Menu.NONE, R.string.menu_remove_item);
menu.add(0, MENU_ID5, Menu.NONE, R.string.menu_share_item);
return ret;
}
/**
* メニューから項目を選択された時のイベントハンドラ。
*
* @param item メニューアイテム
* @return メニューアイテムが表示される場合はtrue、そうでなければfalse
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean ret = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
// リストをソート
case MENU_ID1:
String[] orders = this.getResources().getStringArray(R.array.sort_order);
AlertDialog.Builder dialogSort = new AlertDialog.Builder(this);
dialogSort.setTitle(R.string.sort_title);
dialogSort.setItems(orders, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// デフォルト(_id昇順)
sort(DBMainStore.COLUMN_ID, DBMainStore.ASC);
break;
case 1:
// アプリ名昇順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.ASC);
break;
case 2:
// アプリ名降順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.DESC);
break;
case 3:
// パッケージ名昇順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.ASC);
break;
case 4:
// パッケージ名降順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.DESC);
break;
default:
// do nothing.
break;
} /* switch */
} /* onClick() */
}); /* setItems() */
dialogSort.show();
break;
// リストをlabelでフィルタリング
case MENU_ID2:
// 「フィルタをクリア」
String clearLabel = getString(R.string.filter_clear_label);
// すべてのデータのラベル部分を取得する
List<AppElement> apps = mMainStore.fetchAllAppData(null);
List<String> labelList = new ArrayList<String>();
for (AppElement elem : apps) {
labelList.add(elem.getLabel());
}
// Log.d(LOG_TAG, labelList.toString());
// ラベルの重複をなくす
List<String> splittedLabelList = new ArrayList<String>();
for (String string1 : labelList) {
// ラベルが1個もないとぬるぽになる
if (string1 != null) {
String[] str = string1.split(",");
for (String string2 : str) {
splittedLabelList.add(string2);
}
}
}
// Log.d(LOG_TAG, splittedLabelList.toString());
List<String> duplicatedLabelList = new ArrayList<String>();
for (int i = 0; i < splittedLabelList.size(); i++) {
if (!duplicatedLabelList.contains(splittedLabelList.get(i))
- && splittedLabelList.equals("")) {
+ && !splittedLabelList.get(i).equals("")) {
duplicatedLabelList.add(splittedLabelList.get(i));
}
}
// 完成したラベルリストを並び替える
Collections.sort(duplicatedLabelList);
// リストの最初に「フィルタをクリア」を格納し、リストを配列に変換
duplicatedLabelList.add(0, clearLabel);
Log.d(LOG_TAG, duplicatedLabelList.toString());
final String[] labelArray = duplicatedLabelList.toArray(new String[0]);
AlertDialog.Builder dialogFilter = new AlertDialog.Builder(this);
dialogFilter.setTitle(R.string.filter_title);
dialogFilter.setItems(labelArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int labelIndex) {
if (labelIndex == 0) {
// 「フィルタをクリア」だから、SharedPreferenceの値をリセットする
putFilter("");
buildListView();
} else {
// 「フィルタをクリア」以外だったらフィルタリングする
filter(labelArray[labelIndex]);
}
}
});
dialogFilter.show();
break;
// リストを編集
case MENU_ID3:
List<String> editIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
editIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (editIds.size() > 0) {
// 編集画面のActivityをチェックついたアイテムの数だけ呼び出す
for (int i = 0; i < editIds.size(); i++) {
// 編集画面を呼び出す
Intent intent = new Intent(this, MarketFavoritterEditActivity.class);
// _idだけ渡して向こうでデータを取得する
intent.putExtra("ID", editIds.get(i));
startActivity(intent);
}
buildListView();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of edit");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// リストから削除
case MENU_ID4:
final List<String> delIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
delIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (delIds.size() > 0) {
AlertDialog.Builder dialogRemove = new AlertDialog.Builder(this);
dialogRemove.setTitle(R.string.dialog_remove_title);
dialogRemove.setMessage(R.string.dialog_remove_text);
// OKボタン
dialogRemove.setPositiveButton(R.string.button_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
mMainStore.delete(delIds.toArray(new String[] {}));
Log.i(LOG_TAG, "Selected item was deleted");
buildListView();
}
});
// キャンセルボタン
dialogRemove.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
// 何もしない
}
});
// キャンセル可能にする
dialogRemove.setCancelable(true);
dialogRemove.show();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of delete");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
} /* if (delIds.size() > 0) */
break;
// アイテムを他のアプリに共有
// "<アプリ名> <マーケットURL>"という感じのテキストを投げる
case MENU_ID5:
List<String> shareIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
shareIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (shareIds.size() == 1) {
AppElement elem = mMainStore.fetchAppDataByColumnAndValue(
DBMainStore.COLUMN_ID, shareIds.get(0));
// Intentにアプリ名とマーケットのURLを埋め込む
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,
elem.getAppName() + " " + elem.getMarketUrl());
try {
// Intent投げる
startActivity(Intent.createChooser(intent,
getString(R.string.dialog_share_title) + elem.getAppName()));
} catch (android.content.ActivityNotFoundException e) {
// 該当するActivityがないときの処理
}
} else if (shareIds.size() > 1) {
Log.d(LOG_TAG, "There are many selected items " + shareIds.size());
Toast.makeText(this, R.string.toast_many_item_is_checked, Toast.LENGTH_LONG)
.show();
} else {
Log.i(LOG_TAG, "There are no selected item to share");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// default
default:
break;
} /* switch */
return ret;
} /* onOptionsItemSelected() */
/**
* アプリのリストを作成する。<br>
* 並び替えのオーダーがある場合は、それに従う。
*/
private void buildListView() {
// SharedPreferenceに保存された並び替えのオーダーを取得して、その順でリストを作成する
mAppList = mMainStore.fetchAllAppData(getSortOrder());
if (mMainStore.getCount() == 0) {
Log.i(LOG_TAG, "AppList is empty!!");
finish();
Toast.makeText(this, R.string.toast_no_item_in_list, Toast.LENGTH_LONG).show();
}
AppElementAdapter adapter = new AppElementAdapter(this, R.id.inflaterLayout, mAppList);
ListView listView = (ListView) findViewById(R.id.mainAppListView);
listView.setAdapter(adapter);
}
/**
* 並び替えを実行する。<br>
* 並び替えた後、アプリのリスト作成まで行う。
*
* @param orderColumn 並び替えの列(データベースのカラム名で指定)
* @param sortOrder 昇順(ASC)または降順(DESC)
*/
private void sort(String orderColumn, String sortOrder) {
String order = orderColumn + " " + sortOrder;
Log.d(LOG_TAG, "Sort order: " + order);
mAppList = mMainStore.fetchFilteredAppData(getFilter(), order);
AppElementAdapter adapter = new AppElementAdapter(this, R.id.inflaterLayout, mAppList);
ListView listView = (ListView) findViewById(R.id.mainAppListView);
listView.setAdapter(adapter);
// 並び替えのオーダーを保存しておく
putSortOrder(order);
}
/**
* フィルタリングを実行する。<br>
* フィルタリングした後、アプリのリスト作成まで行う。
*
* @param filter フィルタリングするラベル
*/
private void filter(String filter) {
Log.d(LOG_TAG, "Filter of: " + filter);
mAppList = mMainStore.fetchFilteredAppData(filter, getSortOrder());
AppElementAdapter adapter = new AppElementAdapter(this, R.id.inflaterLayout, mAppList);
ListView listView = (ListView) findViewById(R.id.mainAppListView);
listView.setAdapter(adapter);
// フィルタリングのラベルを保存しておく
putFilter(filter);
}
/**
* フィルタリングのラベルを取得する。<br>
* 初回起動時は値が無いので、第2引数の値をdefault値として取得する。<br>
* また、もし値が取得出来なかった時もこの値が取得される。
*
* @return 取得したフィルタリングのラベル、値がない場合は""(空文字)
*/
private String getFilter() {
return this.mSharedPref.getString(SHARED_PREF_KEY_FILTER, "");
}
/**
* フィルタリングのラベルをSharedPreferenceに書き込む。<br>
* 最後のcommit()を行った時点で書き込まれる。<br>
*
* @param filter フィルタリングのラベル
*/
private void putFilter(String filter) {
this.mSharedPref.edit().putString(SHARED_PREF_KEY_FILTER, filter).commit();
Log.d(LOG_TAG, "Filtering label put to share preference [" + filter + "]");
}
/**
* 並び替えのオーダーを取得する。<br>
* 初回起動時は値が無いので、第2引数の値をdefault値として取得する。<br>
* また、もし値が取得出来なかった時もこの値が取得される。
*
* @return 取得した並び替えのオーダー、値がない場合はnull
*/
private String getSortOrder() {
return this.mSharedPref.getString(SHARED_PREF_KEY_SORT_ODER, null);
}
/**
* 並び替えのオーダーをSharedPreferenceに書き込む。<br>
* 最後のcommit()を行った時点で書き込まれる。<br>
*
* @param order 並び替えのオーダー
*/
private void putSortOrder(String order) {
this.mSharedPref.edit().putString(SHARED_PREF_KEY_SORT_ODER, order).commit();
Log.d(LOG_TAG, "Sort order put to share preference [" + order + "]");
}
// ============================================================================================
/**
* ArrayAdapterを拡張したインナークラス。
*/
class AppElementAdapter extends ArrayAdapter<AppElement> {
/** AppElement型のリスト */
private List<AppElement> mList;
/** カスタムListViewを作成するためのInflator */
private LayoutInflater mInflater;
/**
* コンストラクタ。
*
* @param context このアプリケーションのコンテキスト
* @param resourceId リソースのID
* @param mList 描画するデータの格納されたリスト
*/
public AppElementAdapter(Context context, int resourceId, List<AppElement> list) {
super(context, resourceId, list);
this.mList = list;
this.mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* AppElement分のViewをInflateして作成する。
*
* @param position AppElementリストのインデックス
* @param convertView View
* @param parent このViewの親View
* @return 作成されたカスタムListView
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Viewが使いまわされていない場合、nullが格納されている
if (convertView == null) {
// 1行分layoutからViewの塊を生成
convertView = mInflater.inflate(R.layout.inflater, null);
// Log.d(LOG_TAG, "New convertView create");
}
// listからAppのデータ、viewから画面にくっついているViewを取り出して値を格納する
final AppElement app = mList.get(position);
TextView appNameText = (TextView) convertView.findViewById(R.id.inflaterAppName);
appNameText.setText(app.getAppName());
TextView appPkgText = (TextView) convertView.findViewById(R.id.inflaterAppPkgName);
appPkgText.setText(app.getPkgName());
TextView appLabel = (TextView) convertView.findViewById(R.id.inflaterLabel);
// ラベルのカンマはスペースに直して表示する
String tmpLabel = app.getLabel();
if (tmpLabel == null) {
tmpLabel = "";
Log.d(LOG_TAG, "Label is empty!");
} else {
tmpLabel = app.getLabel().replace(",", " ");
}
appLabel.setText(tmpLabel);
// Buttonを実装
Button button = (Button) convertView.findViewById(R.id.inflaterButton);
button.setText(R.string.button_market);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// MarketアプリへのIntentを作成して投げる
// AndroidMarketのアプリ詳細画面を開く
// market://details?id=<pkg name>
// AndroidMarketをアプリ開発者名で検索
// market://search?q=pub:<publisher name>
// AndroidMarketをフリーワード検索
// market://search?q=<words>
Uri uri = Uri.parse("market://details?id=" + app.getPkgName());
startActivity(new Intent(Intent.ACTION_VIEW, uri));
Log.d(LOG_TAG, "Throw intent for AndroidMarket. Uri: " + uri.toString());
}
});
// CheckBoxを実装
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.inflaterCheckBox);
final int pos = position;
// setChecked()をやる前にリスナ登録しないと、
// 使いまわしてる他のViewのチェックも道連れにチェックされるw
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton compoundbutton, boolean isChecked) {
Log.d(LOG_TAG,
"pos: " + String.valueOf(pos) + ", mIsChecked: "
+ String.valueOf(isChecked));
mList.get(pos).setIsChecked(isChecked);
}
});
checkBox.setChecked(mList.get(position).getIsChecked());
// これでロングタップした時のポップアップメニューが作れるよ!!
// v.setOnCreateContextMenuListener(new
// OnCreateContextMenuListener() {
// public void onCreateContextMenu(ContextMenu contextmenu, View
// view, ContextMenuInfo contextmenuinfo) {
// }
// });
return convertView;
} /* getView() */
} /* AppElementAdapter */
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
boolean ret = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
// リストをソート
case MENU_ID1:
String[] orders = this.getResources().getStringArray(R.array.sort_order);
AlertDialog.Builder dialogSort = new AlertDialog.Builder(this);
dialogSort.setTitle(R.string.sort_title);
dialogSort.setItems(orders, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// デフォルト(_id昇順)
sort(DBMainStore.COLUMN_ID, DBMainStore.ASC);
break;
case 1:
// アプリ名昇順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.ASC);
break;
case 2:
// アプリ名降順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.DESC);
break;
case 3:
// パッケージ名昇順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.ASC);
break;
case 4:
// パッケージ名降順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.DESC);
break;
default:
// do nothing.
break;
} /* switch */
} /* onClick() */
}); /* setItems() */
dialogSort.show();
break;
// リストをlabelでフィルタリング
case MENU_ID2:
// 「フィルタをクリア」
String clearLabel = getString(R.string.filter_clear_label);
// すべてのデータのラベル部分を取得する
List<AppElement> apps = mMainStore.fetchAllAppData(null);
List<String> labelList = new ArrayList<String>();
for (AppElement elem : apps) {
labelList.add(elem.getLabel());
}
// Log.d(LOG_TAG, labelList.toString());
// ラベルの重複をなくす
List<String> splittedLabelList = new ArrayList<String>();
for (String string1 : labelList) {
// ラベルが1個もないとぬるぽになる
if (string1 != null) {
String[] str = string1.split(",");
for (String string2 : str) {
splittedLabelList.add(string2);
}
}
}
// Log.d(LOG_TAG, splittedLabelList.toString());
List<String> duplicatedLabelList = new ArrayList<String>();
for (int i = 0; i < splittedLabelList.size(); i++) {
if (!duplicatedLabelList.contains(splittedLabelList.get(i))
&& splittedLabelList.equals("")) {
duplicatedLabelList.add(splittedLabelList.get(i));
}
}
// 完成したラベルリストを並び替える
Collections.sort(duplicatedLabelList);
// リストの最初に「フィルタをクリア」を格納し、リストを配列に変換
duplicatedLabelList.add(0, clearLabel);
Log.d(LOG_TAG, duplicatedLabelList.toString());
final String[] labelArray = duplicatedLabelList.toArray(new String[0]);
AlertDialog.Builder dialogFilter = new AlertDialog.Builder(this);
dialogFilter.setTitle(R.string.filter_title);
dialogFilter.setItems(labelArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int labelIndex) {
if (labelIndex == 0) {
// 「フィルタをクリア」だから、SharedPreferenceの値をリセットする
putFilter("");
buildListView();
} else {
// 「フィルタをクリア」以外だったらフィルタリングする
filter(labelArray[labelIndex]);
}
}
});
dialogFilter.show();
break;
// リストを編集
case MENU_ID3:
List<String> editIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
editIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (editIds.size() > 0) {
// 編集画面のActivityをチェックついたアイテムの数だけ呼び出す
for (int i = 0; i < editIds.size(); i++) {
// 編集画面を呼び出す
Intent intent = new Intent(this, MarketFavoritterEditActivity.class);
// _idだけ渡して向こうでデータを取得する
intent.putExtra("ID", editIds.get(i));
startActivity(intent);
}
buildListView();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of edit");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// リストから削除
case MENU_ID4:
final List<String> delIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
delIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (delIds.size() > 0) {
AlertDialog.Builder dialogRemove = new AlertDialog.Builder(this);
dialogRemove.setTitle(R.string.dialog_remove_title);
dialogRemove.setMessage(R.string.dialog_remove_text);
// OKボタン
dialogRemove.setPositiveButton(R.string.button_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
mMainStore.delete(delIds.toArray(new String[] {}));
Log.i(LOG_TAG, "Selected item was deleted");
buildListView();
}
});
// キャンセルボタン
dialogRemove.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
// 何もしない
}
});
// キャンセル可能にする
dialogRemove.setCancelable(true);
dialogRemove.show();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of delete");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
} /* if (delIds.size() > 0) */
break;
// アイテムを他のアプリに共有
// "<アプリ名> <マーケットURL>"という感じのテキストを投げる
case MENU_ID5:
List<String> shareIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
shareIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (shareIds.size() == 1) {
AppElement elem = mMainStore.fetchAppDataByColumnAndValue(
DBMainStore.COLUMN_ID, shareIds.get(0));
// Intentにアプリ名とマーケットのURLを埋め込む
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,
elem.getAppName() + " " + elem.getMarketUrl());
try {
// Intent投げる
startActivity(Intent.createChooser(intent,
getString(R.string.dialog_share_title) + elem.getAppName()));
} catch (android.content.ActivityNotFoundException e) {
// 該当するActivityがないときの処理
}
} else if (shareIds.size() > 1) {
Log.d(LOG_TAG, "There are many selected items " + shareIds.size());
Toast.makeText(this, R.string.toast_many_item_is_checked, Toast.LENGTH_LONG)
.show();
} else {
Log.i(LOG_TAG, "There are no selected item to share");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// default
default:
break;
} /* switch */
return ret;
} /* onOptionsItemSelected() */
| public boolean onOptionsItemSelected(MenuItem item) {
boolean ret = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
// リストをソート
case MENU_ID1:
String[] orders = this.getResources().getStringArray(R.array.sort_order);
AlertDialog.Builder dialogSort = new AlertDialog.Builder(this);
dialogSort.setTitle(R.string.sort_title);
dialogSort.setItems(orders, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// デフォルト(_id昇順)
sort(DBMainStore.COLUMN_ID, DBMainStore.ASC);
break;
case 1:
// アプリ名昇順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.ASC);
break;
case 2:
// アプリ名降順
sort(DBMainStore.COLUMN_APP_NAME, DBMainStore.DESC);
break;
case 3:
// パッケージ名昇順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.ASC);
break;
case 4:
// パッケージ名降順
sort(DBMainStore.COLUMN_APP_PACKAGE, DBMainStore.DESC);
break;
default:
// do nothing.
break;
} /* switch */
} /* onClick() */
}); /* setItems() */
dialogSort.show();
break;
// リストをlabelでフィルタリング
case MENU_ID2:
// 「フィルタをクリア」
String clearLabel = getString(R.string.filter_clear_label);
// すべてのデータのラベル部分を取得する
List<AppElement> apps = mMainStore.fetchAllAppData(null);
List<String> labelList = new ArrayList<String>();
for (AppElement elem : apps) {
labelList.add(elem.getLabel());
}
// Log.d(LOG_TAG, labelList.toString());
// ラベルの重複をなくす
List<String> splittedLabelList = new ArrayList<String>();
for (String string1 : labelList) {
// ラベルが1個もないとぬるぽになる
if (string1 != null) {
String[] str = string1.split(",");
for (String string2 : str) {
splittedLabelList.add(string2);
}
}
}
// Log.d(LOG_TAG, splittedLabelList.toString());
List<String> duplicatedLabelList = new ArrayList<String>();
for (int i = 0; i < splittedLabelList.size(); i++) {
if (!duplicatedLabelList.contains(splittedLabelList.get(i))
&& !splittedLabelList.get(i).equals("")) {
duplicatedLabelList.add(splittedLabelList.get(i));
}
}
// 完成したラベルリストを並び替える
Collections.sort(duplicatedLabelList);
// リストの最初に「フィルタをクリア」を格納し、リストを配列に変換
duplicatedLabelList.add(0, clearLabel);
Log.d(LOG_TAG, duplicatedLabelList.toString());
final String[] labelArray = duplicatedLabelList.toArray(new String[0]);
AlertDialog.Builder dialogFilter = new AlertDialog.Builder(this);
dialogFilter.setTitle(R.string.filter_title);
dialogFilter.setItems(labelArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int labelIndex) {
if (labelIndex == 0) {
// 「フィルタをクリア」だから、SharedPreferenceの値をリセットする
putFilter("");
buildListView();
} else {
// 「フィルタをクリア」以外だったらフィルタリングする
filter(labelArray[labelIndex]);
}
}
});
dialogFilter.show();
break;
// リストを編集
case MENU_ID3:
List<String> editIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
editIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (editIds.size() > 0) {
// 編集画面のActivityをチェックついたアイテムの数だけ呼び出す
for (int i = 0; i < editIds.size(); i++) {
// 編集画面を呼び出す
Intent intent = new Intent(this, MarketFavoritterEditActivity.class);
// _idだけ渡して向こうでデータを取得する
intent.putExtra("ID", editIds.get(i));
startActivity(intent);
}
buildListView();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of edit");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// リストから削除
case MENU_ID4:
final List<String> delIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
delIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (delIds.size() > 0) {
AlertDialog.Builder dialogRemove = new AlertDialog.Builder(this);
dialogRemove.setTitle(R.string.dialog_remove_title);
dialogRemove.setMessage(R.string.dialog_remove_text);
// OKボタン
dialogRemove.setPositiveButton(R.string.button_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
mMainStore.delete(delIds.toArray(new String[] {}));
Log.i(LOG_TAG, "Selected item was deleted");
buildListView();
}
});
// キャンセルボタン
dialogRemove.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
// 何もしない
}
});
// キャンセル可能にする
dialogRemove.setCancelable(true);
dialogRemove.show();
} else {
Log.i(LOG_TAG, "There are no selected item(s) of delete");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
} /* if (delIds.size() > 0) */
break;
// アイテムを他のアプリに共有
// "<アプリ名> <マーケットURL>"という感じのテキストを投げる
case MENU_ID5:
List<String> shareIds = new ArrayList<String>();
for (int i = 0; i < mAppList.size(); i++) {
if (mAppList.get(i).getIsChecked()) {
shareIds.add(String.valueOf(mAppList.get(i).get_id()));
}
}
if (shareIds.size() == 1) {
AppElement elem = mMainStore.fetchAppDataByColumnAndValue(
DBMainStore.COLUMN_ID, shareIds.get(0));
// Intentにアプリ名とマーケットのURLを埋め込む
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,
elem.getAppName() + " " + elem.getMarketUrl());
try {
// Intent投げる
startActivity(Intent.createChooser(intent,
getString(R.string.dialog_share_title) + elem.getAppName()));
} catch (android.content.ActivityNotFoundException e) {
// 該当するActivityがないときの処理
}
} else if (shareIds.size() > 1) {
Log.d(LOG_TAG, "There are many selected items " + shareIds.size());
Toast.makeText(this, R.string.toast_many_item_is_checked, Toast.LENGTH_LONG)
.show();
} else {
Log.i(LOG_TAG, "There are no selected item to share");
Toast.makeText(this, R.string.toast_no_item_is_checked, Toast.LENGTH_LONG)
.show();
}
break;
// default
default:
break;
} /* switch */
return ret;
} /* onOptionsItemSelected() */
|
diff --git a/src/com/android/mms/transaction/SmsMessageSender.java b/src/com/android/mms/transaction/SmsMessageSender.java
index 0aee539b..c59f147e 100644
--- a/src/com/android/mms/transaction/SmsMessageSender.java
+++ b/src/com/android/mms/transaction/SmsMessageSender.java
@@ -1,204 +1,204 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Inbox;
import android.telephony.SmsMessage;
import android.util.Log;
import com.android.mms.LogTag;
import com.android.mms.MmsConfig;
import com.android.mms.ui.MessagingPreferenceActivity;
import com.google.android.mms.MmsException;
import java.util.ArrayList;
public class SmsMessageSender implements MessageSender {
protected final Context mContext;
protected final int mNumberOfDests;
private final String[] mDests;
protected final String mMessageText;
protected final String mServiceCenter;
protected final long mThreadId;
protected long mTimestamp;
private static final String TAG = "SmsMessageSender";
// Default preference values
private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false;
private static final boolean DEFAULT_SMS_SPLIT_COUNTER = false;
private static final String[] SERVICE_CENTER_PROJECTION = new String[] {
Sms.Conversations.REPLY_PATH_PRESENT,
Sms.Conversations.SERVICE_CENTER,
};
private static final int COLUMN_REPLY_PATH_PRESENT = 0;
private static final int COLUMN_SERVICE_CENTER = 1;
public SmsMessageSender(Context context, String[] dests, String msgText, long threadId) {
mContext = context;
mMessageText = msgText;
if (dests != null) {
mNumberOfDests = dests.length;
mDests = new String[mNumberOfDests];
System.arraycopy(dests, 0, mDests, 0, mNumberOfDests);
} else {
mNumberOfDests = 0;
mDests = null;
}
mTimestamp = System.currentTimeMillis();
mThreadId = threadId;
mServiceCenter = getOutgoingServiceCenter(mThreadId);
}
public boolean sendMessage(long token) throws MmsException {
// In order to send the message one by one, instead of sending now, the message will split,
// and be put into the queue along with each destinations
return queueMessage(token);
}
private boolean queueMessage(long token) throws MmsException {
if ((mMessageText == null) || (mNumberOfDests == 0)) {
// Don't try to send an empty message.
throw new MmsException("Null message body or dest.");
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean requestDeliveryReport = prefs.getBoolean(
MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE,
DEFAULT_DELIVERY_REPORT_MODE);
boolean splitMessage = MmsConfig.getSplitSmsEnabled();
boolean splitCounter = prefs.getBoolean(
MessagingPreferenceActivity.SMS_SPLIT_COUNTER,
DEFAULT_SMS_SPLIT_COUNTER);
int[] params = SmsMessage.calculateLength(mMessageText, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int nSmsPages = params[0];
// To split or not to split, that is THE question!
if (splitMessage && (nSmsPages > 1))
{
// Split the message by encoding
ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText);
// Start send loop for split messages
for(int page = 0; page < nSmsPages; page++)
{
// Adds counter at end of message
if(splitCounter) {
String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")";
MessageBody.set(page, counterText);
}
for (int i = 0; i < mNumberOfDests; i++) {
try {
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
MessageBody.get(page), null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
} else { // Send without split or counter
for (int i = 0; i < mNumberOfDests; i++) {
try {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId);
}
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
mMessageText, null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
if (LogTag.DEBUG_SEND) {
Log.e(TAG, "queueMessage SQLiteException", e);
}
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
// Notify the SmsReceiverService to send the message out
mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE,
null,
mContext,
- SmsReceiver.class));
+ PrivilegedSmsReceiver.class));
return false;
}
/**
* Get the service center to use for a reply.
*
* The rule from TS 23.040 D.6 is that we send reply messages to
* the service center of the message to which we're replying, but
* only if we haven't already replied to that message and only if
* <code>TP-Reply-Path</code> was set in that message.
*
* Therefore, return the service center from the most recent
* message in the conversation, but only if it is a message from
* the other party, and only if <code>TP-Reply-Path</code> is set.
* Otherwise, return null.
*/
private String getOutgoingServiceCenter(long threadId) {
Cursor cursor = null;
try {
cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(),
Inbox.CONTENT_URI, SERVICE_CENTER_PROJECTION,
"thread_id = " + threadId, null, "date DESC");
if ((cursor == null) || !cursor.moveToFirst()) {
return null;
}
boolean replyPathPresent = (1 == cursor.getInt(COLUMN_REPLY_PATH_PRESENT));
return replyPathPresent ? cursor.getString(COLUMN_SERVICE_CENTER) : null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void log(String msg) {
Log.d(LogTag.TAG, "[SmsMsgSender] " + msg);
}
}
| true | true | private boolean queueMessage(long token) throws MmsException {
if ((mMessageText == null) || (mNumberOfDests == 0)) {
// Don't try to send an empty message.
throw new MmsException("Null message body or dest.");
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean requestDeliveryReport = prefs.getBoolean(
MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE,
DEFAULT_DELIVERY_REPORT_MODE);
boolean splitMessage = MmsConfig.getSplitSmsEnabled();
boolean splitCounter = prefs.getBoolean(
MessagingPreferenceActivity.SMS_SPLIT_COUNTER,
DEFAULT_SMS_SPLIT_COUNTER);
int[] params = SmsMessage.calculateLength(mMessageText, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int nSmsPages = params[0];
// To split or not to split, that is THE question!
if (splitMessage && (nSmsPages > 1))
{
// Split the message by encoding
ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText);
// Start send loop for split messages
for(int page = 0; page < nSmsPages; page++)
{
// Adds counter at end of message
if(splitCounter) {
String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")";
MessageBody.set(page, counterText);
}
for (int i = 0; i < mNumberOfDests; i++) {
try {
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
MessageBody.get(page), null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
} else { // Send without split or counter
for (int i = 0; i < mNumberOfDests; i++) {
try {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId);
}
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
mMessageText, null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
if (LogTag.DEBUG_SEND) {
Log.e(TAG, "queueMessage SQLiteException", e);
}
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
// Notify the SmsReceiverService to send the message out
mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE,
null,
mContext,
SmsReceiver.class));
return false;
}
| private boolean queueMessage(long token) throws MmsException {
if ((mMessageText == null) || (mNumberOfDests == 0)) {
// Don't try to send an empty message.
throw new MmsException("Null message body or dest.");
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean requestDeliveryReport = prefs.getBoolean(
MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE,
DEFAULT_DELIVERY_REPORT_MODE);
boolean splitMessage = MmsConfig.getSplitSmsEnabled();
boolean splitCounter = prefs.getBoolean(
MessagingPreferenceActivity.SMS_SPLIT_COUNTER,
DEFAULT_SMS_SPLIT_COUNTER);
int[] params = SmsMessage.calculateLength(mMessageText, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int nSmsPages = params[0];
// To split or not to split, that is THE question!
if (splitMessage && (nSmsPages > 1))
{
// Split the message by encoding
ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText);
// Start send loop for split messages
for(int page = 0; page < nSmsPages; page++)
{
// Adds counter at end of message
if(splitCounter) {
String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")";
MessageBody.set(page, counterText);
}
for (int i = 0; i < mNumberOfDests; i++) {
try {
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
MessageBody.get(page), null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
} else { // Send without split or counter
for (int i = 0; i < mNumberOfDests; i++) {
try {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId);
}
Sms.addMessageToUri(mContext.getContentResolver(),
Uri.parse("content://sms/queued"), mDests[i],
mMessageText, null, mTimestamp,
true /* read */,
requestDeliveryReport,
mThreadId);
} catch (SQLiteException e) {
if (LogTag.DEBUG_SEND) {
Log.e(TAG, "queueMessage SQLiteException", e);
}
SqliteWrapper.checkSQLiteException(mContext, e);
}
}
}
// Notify the SmsReceiverService to send the message out
mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE,
null,
mContext,
PrivilegedSmsReceiver.class));
return false;
}
|
diff --git a/impl/src/java/org/sakaiproject/clog/impl/ClogContentProducer.java b/impl/src/java/org/sakaiproject/clog/impl/ClogContentProducer.java
index 2274715..15fc78c 100644
--- a/impl/src/java/org/sakaiproject/clog/impl/ClogContentProducer.java
+++ b/impl/src/java/org/sakaiproject/clog/impl/ClogContentProducer.java
@@ -1,347 +1,347 @@
package org.sakaiproject.clog.impl;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.io.Reader;
import org.sakaiproject.clog.api.datamodel.Comment;
import org.sakaiproject.clog.api.datamodel.Post;
import org.sakaiproject.clog.api.ClogManager;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchService;
import org.sakaiproject.search.api.SearchUtils;
import org.sakaiproject.search.util.HTMLParser;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.apache.log4j.Logger;
public class ClogContentProducer implements EntityContentProducer
{
private ClogManager clogManager = null;
public void setClogManager(ClogManager clogManager)
{
this.clogManager = clogManager;
}
private SearchService searchService = null;
public void setSearchService(SearchService searchService)
{
this.searchService = searchService;
}
private SearchIndexBuilder searchIndexBuilder = null;
public void setSearchIndexBuilder(SearchIndexBuilder searchIndexBuilder)
{
this.searchIndexBuilder = searchIndexBuilder;
}
private Logger logger = Logger.getLogger(ClogContentProducer.class);
public void init()
{
searchService.registerFunction(ClogManager.CLOG_POST_CREATED);
searchService.registerFunction(ClogManager.CLOG_POST_DELETED);
searchService.registerFunction(ClogManager.CLOG_COMMENT_CREATED);
searchService.registerFunction(ClogManager.CLOG_COMMENT_DELETED);
searchIndexBuilder.registerEntityContentProducer(this);
}
public boolean canRead(String reference)
{
if(logger.isDebugEnabled())
logger.debug("canRead()");
// TODO: sort this !
return true;
}
public Integer getAction(Event event)
{
if(logger.isDebugEnabled())
logger.debug("getAction()");
String eventName = event.getEvent();
if(ClogManager.CLOG_POST_CREATED.equals(eventName)
|| ClogManager.CLOG_COMMENT_CREATED.equals(eventName))
{
return SearchBuilderItem.ACTION_ADD;
}
else if(ClogManager.CLOG_POST_DELETED.equals(eventName)
|| ClogManager.CLOG_COMMENT_DELETED.equals(eventName))
{
return SearchBuilderItem.ACTION_DELETE;
}
else
return SearchBuilderItem.ACTION_UNKNOWN;
}
public String getContainer(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getContainer()");
return null;
}
public String getContent(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getContent(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
String type = parts[2];
String id = parts[3];
if(parts.length == 5)
{
type = parts[3];
id = parts[4];
}
try
{
Post post = clogManager.getPost(id);
StringBuilder sb = new StringBuilder();
SearchUtils.appendCleanString(post.getTitle(),sb);
- for (HTMLParser hp = new HTMLParser(post.getContent()); hp.hasNext();)
+ for (HTMLParser hp = new HTMLParser("<p>" + post.getContent() + "</p>"); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
for(Comment comment : post.getComments())
{
- for (HTMLParser hp = new HTMLParser(comment.getContent()); hp.hasNext();)
+ for (HTMLParser hp = new HTMLParser("<p>" + comment.getContent() + "</p>"); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
}
return sb.toString();
}
catch(Exception e)
{
logger.error("Caught exception whilst getting content for post '" + id + "'",e);
}
return null;
}
public Reader getContentReader(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getContentReader(" + ref + ")");
return null;
}
public Map getCustomProperties(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getCustomProperties(" + ref + ")");
return null;
}
public String getCustomRDF(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getCustomRDF(" + ref + ")");
return null;
}
public String getId(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getId(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
if(parts.length == 4)
{
return parts[3];
}
else if(parts.length == 5)
{
return parts[4];
}
return "unknown";
}
public List getSiteContent(String siteId)
{
if(logger.isDebugEnabled())
logger.debug("getSiteContent(" + siteId + ")");
List refs = new ArrayList();
try
{
List<Post> posts = clogManager.getPosts(siteId);
for(Post post : posts)
refs.add(post.getReference());
}
catch(Exception e)
{
logger.error("Caught exception whilst getting site content",e);
}
return refs;
}
public Iterator getSiteContentIterator(String siteId)
{
if(logger.isDebugEnabled())
logger.debug("getSiteContentIterator(" + siteId + ")");
return getSiteContent(siteId).iterator();
}
public String getSiteId(String eventRef)
{
if(logger.isDebugEnabled())
logger.debug("getSiteId(" + eventRef + ")");
String[] parts = eventRef.split(Entity.SEPARATOR);
if(parts.length == 4)
{
String id = parts[3];
return id;
}
else if(parts.length == 5)
{
String siteId = parts[2];
return siteId;
}
return null;
}
public String getSubType(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getSubType(" + ref + ")");
return null;
}
public String getTitle(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getTitle(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
String type = parts[2];
String id = parts[3];
if(parts.length == 5)
{
type = parts[3];
id = parts[4];
}
try
{
Post post = clogManager.getPost(id);
return post.getTitle();
}
catch(Exception e)
{
logger.error("Caught exception whilst getting title for post '" + id + "'",e);
}
return "Unrecognised";
}
public String getTool()
{
return "Clog";
}
public String getType(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getType(" + ref + ")");
return "clog";
}
public String getUrl(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getUrl(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
String type = parts[2];
String id = parts[3];
if(parts.length == 5)
{
type = parts[3];
id = parts[4];
}
try
{
Post post = clogManager.getPost(id);
return post.getUrl();
}
catch(Exception e)
{
logger.error("Caught exception whilst getting url for post '" + id + "'",e);
}
return null;
}
public boolean isContentFromReader(String ref)
{
if(logger.isDebugEnabled())
logger.debug("isContentFromReader(" + ref + ")");
return false;
}
public boolean isForIndex(String ref)
{
if(logger.isDebugEnabled())
logger.debug("isForIndex(" + ref + ")");
return true;
}
public boolean matches(String ref)
{
if(logger.isDebugEnabled())
logger.debug("matches(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
if(ClogManager.ENTITY_PREFIX.equals(parts[1]))
return true;
return false;
}
public boolean matches(Event event)
{
String eventName = event.getEvent();
if(ClogManager.CLOG_POST_CREATED.equals(eventName)
|| ClogManager.CLOG_POST_DELETED.equals(eventName)
|| ClogManager.CLOG_COMMENT_CREATED.equals(eventName)
|| ClogManager.CLOG_COMMENT_DELETED.equals(eventName))
{
return true;
}
return false;
}
}
| false | true | public String getContent(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getContent(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
String type = parts[2];
String id = parts[3];
if(parts.length == 5)
{
type = parts[3];
id = parts[4];
}
try
{
Post post = clogManager.getPost(id);
StringBuilder sb = new StringBuilder();
SearchUtils.appendCleanString(post.getTitle(),sb);
for (HTMLParser hp = new HTMLParser(post.getContent()); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
for(Comment comment : post.getComments())
{
for (HTMLParser hp = new HTMLParser(comment.getContent()); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
}
return sb.toString();
}
catch(Exception e)
{
logger.error("Caught exception whilst getting content for post '" + id + "'",e);
}
return null;
}
| public String getContent(String ref)
{
if(logger.isDebugEnabled())
logger.debug("getContent(" + ref + ")");
String[] parts = ref.split(Entity.SEPARATOR);
String type = parts[2];
String id = parts[3];
if(parts.length == 5)
{
type = parts[3];
id = parts[4];
}
try
{
Post post = clogManager.getPost(id);
StringBuilder sb = new StringBuilder();
SearchUtils.appendCleanString(post.getTitle(),sb);
for (HTMLParser hp = new HTMLParser("<p>" + post.getContent() + "</p>"); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
for(Comment comment : post.getComments())
{
for (HTMLParser hp = new HTMLParser("<p>" + comment.getContent() + "</p>"); hp.hasNext();)
SearchUtils.appendCleanString(hp.next(), sb);
}
return sb.toString();
}
catch(Exception e)
{
logger.error("Caught exception whilst getting content for post '" + id + "'",e);
}
return null;
}
|
diff --git a/app/controllers/PlanService.java b/app/controllers/PlanService.java
index 099579d..4f50b75 100644
--- a/app/controllers/PlanService.java
+++ b/app/controllers/PlanService.java
@@ -1,41 +1,41 @@
package controllers;
import models.RetrievalPlan;
import models.User;
import models.Video;
import net.sf.oval.constraint.NotNull;
import plan.RetrievalPlanCreator;
public class PlanService extends BaseService {
public static void getRetrievalPlan(@NotNull String videoId, @NotNull String userId){
if(validation.hasErrors()){
play.Logger.error("Invalid params: %s", params);
jsonError("Invalid params");
}
play.Logger.info("Retrieval plan requested by user: "+userId+" for video: "+videoId);
- User planRequester = User.find("userId=?", userId).first();
+ User planRequester = User.find("email=?", userId).first();
Video video = Video.find("videoId=?", videoId).first();
if(planRequester == null){
play.Logger.error("No existe el planRequester: %s", userId);
jsonError("No existe el planRequester "+userId);
}
if(video == null){
play.Logger.error("No existe el video: %s", videoId);
jsonError("No existe el video "+videoId);
}
RetrievalPlan plan = new RetrievalPlanCreator(video, planRequester).generateRetrievalPlan();
if(plan == null) {
jsonError("Unable to ellaborate retrieving plan for video "+video.videoId+" for user "+planRequester.email+" - not enough sources available");
}
play.Logger.info("Returning retrieval plan for video: " + videoId);
jsonOk(plan);
}
}
| true | true | public static void getRetrievalPlan(@NotNull String videoId, @NotNull String userId){
if(validation.hasErrors()){
play.Logger.error("Invalid params: %s", params);
jsonError("Invalid params");
}
play.Logger.info("Retrieval plan requested by user: "+userId+" for video: "+videoId);
User planRequester = User.find("userId=?", userId).first();
Video video = Video.find("videoId=?", videoId).first();
if(planRequester == null){
play.Logger.error("No existe el planRequester: %s", userId);
jsonError("No existe el planRequester "+userId);
}
if(video == null){
play.Logger.error("No existe el video: %s", videoId);
jsonError("No existe el video "+videoId);
}
RetrievalPlan plan = new RetrievalPlanCreator(video, planRequester).generateRetrievalPlan();
if(plan == null) {
jsonError("Unable to ellaborate retrieving plan for video "+video.videoId+" for user "+planRequester.email+" - not enough sources available");
}
play.Logger.info("Returning retrieval plan for video: " + videoId);
jsonOk(plan);
}
| public static void getRetrievalPlan(@NotNull String videoId, @NotNull String userId){
if(validation.hasErrors()){
play.Logger.error("Invalid params: %s", params);
jsonError("Invalid params");
}
play.Logger.info("Retrieval plan requested by user: "+userId+" for video: "+videoId);
User planRequester = User.find("email=?", userId).first();
Video video = Video.find("videoId=?", videoId).first();
if(planRequester == null){
play.Logger.error("No existe el planRequester: %s", userId);
jsonError("No existe el planRequester "+userId);
}
if(video == null){
play.Logger.error("No existe el video: %s", videoId);
jsonError("No existe el video "+videoId);
}
RetrievalPlan plan = new RetrievalPlanCreator(video, planRequester).generateRetrievalPlan();
if(plan == null) {
jsonError("Unable to ellaborate retrieving plan for video "+video.videoId+" for user "+planRequester.email+" - not enough sources available");
}
play.Logger.info("Returning retrieval plan for video: " + videoId);
jsonOk(plan);
}
|
diff --git a/src/com/reelfx/Applet.java b/src/com/reelfx/Applet.java
index 09894d2..2d5ae0e 100644
--- a/src/com/reelfx/Applet.java
+++ b/src/com/reelfx/Applet.java
@@ -1,563 +1,563 @@
package com.reelfx;
import java.applet.AppletContext;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import netscape.javascript.JSException;
import netscape.javascript.JSObject;
import com.reelfx.controller.ApplicationController;
import com.reelfx.controller.LinuxController;
import com.reelfx.controller.MacController;
import com.reelfx.controller.WindowsController;
import com.reelfx.model.CaptureViewport;
import com.reelfx.view.AudioSelector;
import com.reelfx.view.InformationBox;
import com.reelfx.view.VolumeVisualizer;
import com.reelfx.view.util.MoveableWindow;
import com.reelfx.view.util.ViewListener;
import com.reelfx.view.util.ViewNotifications;
import com.sun.JarClassLoader;
/**
*
* @author daniel
*
* SPECIAL NOTE ON JSObject on Mac (Used for communicating with Javascript)
* In Eclipse, initially couldn't find the class. This guy said to add a reference to 'plugin.jar'
* (http://stackoverflow.com/questions/1664604/jsobject-download-it-or-available-in-jre-1-6) however
* the only plugin.jar's I found for Java via the 'locate' command were either bad symlinks or inside
* .bundle so I had to create a good symlink called plugin-daniel.jar in /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib
* that pointed to /System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/Deploy.bundle/Contents/Resources/Java/plugin.jar
* I had not issue adding it on Windows or Linux.
*
* further information: http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/java_js.html
*/
// TODO setup log4j
public class Applet extends JApplet {
private static final long serialVersionUID = 4544354980928245103L;
public static File RFX_FOLDER, BIN_FOLDER, DESKTOP_FOLDER;
public static URL DOCUMENT_BASE, CODE_BASE;
public static JApplet APPLET;
public static JSObject JS_BRIDGE;
public static String POST_URL = null, SCREEN_CAPTURE_NAME = null, API_KEY = null, HOST_URL = null;
public static boolean HEADLESS = false;
public static boolean IS_MAC = System.getProperty("os.name").toLowerCase().contains("mac");
public static boolean IS_LINUX = System.getProperty("os.name").toLowerCase().contains("linux");
public static boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
public static boolean DEV_MODE = System.getProperty("user.dir").contains(System.getProperty("user.home")); // assume dev files are in developer's home
@Deprecated
public static GraphicsConfiguration GRAPHICS_CONFIG = null;
public final static CaptureViewport CAPTURE_VIEWPORT = new CaptureViewport();
private ApplicationController controller = null;
// called when this applet is loaded into the browser.
@Override
public void init() {
try {
// finish initializing all static variables
RFX_FOLDER = new File(getRfxFolderPath()); // should be first
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
System.err.println("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
- if(!DEV_MODE && !getParameter("dev_mode").isEmpty())
+ if(!DEV_MODE && getParameter("dev_mode") != null)
DEV_MODE = getParameter("dev_mode").equals("true");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( RFX_FOLDER.exists() && !RFX_FOLDER.isDirectory() && !RFX_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + RFX_FOLDER.getAbsolutePath());
if( !RFX_FOLDER.exists() && !RFX_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + RFX_FOLDER.getAbsolutePath());
// print information to console
System.out.println(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println("Could not create GUI!");
e.printStackTrace();
}
}
/**
* Sends a notification to all the views and each can update itself accordingly.
*
* @param notification
* @param body
*/
public static void sendViewNotification(ViewNotifications notification,Object body) {
//System.out.println("View Notification: "+notification);
// applet is a special case (see ApplicationController constructor)
((ViewListener) APPLET.getContentPane().getComponent(0)).receiveViewNotification(notification, body);
// another special case where the capture viewport is a pseudo-model
Applet.CAPTURE_VIEWPORT.receiveViewNotification(notification, body);
// notify all the open windows
Window[] windows = Window.getWindows();
for(Window win : windows) {
if(win instanceof ViewListener) {
((ViewListener) win).receiveViewNotification(notification, body);
}
}
}
public static void sendViewNotification(ViewNotifications notification) {
sendViewNotification(notification, null);
}
// ---------- BEGIN JAVASCRIPT API ----------
/*
public void prepareForRecording() {
controller.prepareForRecording();
}
public void startRecording() {
// TODO grabs default mixer right now, need a way to select microphones...
//controller.startRecording(AudioSelector.get); // TODO fix when needed
}
*/
/**
* This method piggy backs on record GUI to drive any external (i.e. Flash) GUI.
*/
public void prepareAndRecord() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
controller.recordGUI.prepareForRecording();
} catch (Exception e) {
System.err.println("Can't prepare and start the recording!");
e.printStackTrace();
}
return null;
}
});
}
public void stopRecording() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
controller.recordGUI.stopRecording();
} catch (Exception e) {
System.err.println("Can't stop the recording!");
e.printStackTrace();
}
return null;
}
});
}
/*
public void previewRecording() {
controller.previewRecording();
}
public void postRecording() {
// TODO TEMPORARY until I get the Insight posting process down
controller.askForAndSaveRecording();
}
*/
public void showRecordingInterface() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.showRecordingInterface();
}
});
} catch (Exception e) {
System.err.println("Can't show the recording interface!");
e.printStackTrace();
}
return null;
}
});
}
public void hideRecordingInterface() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.hideRecordingInterface();
}
});
} catch (Exception e) {
System.err.println("Can't hide the recording interface!");
e.printStackTrace();
}
return null;
}
});
}
public static void handleRecordingUpdate(ViewNotifications state,String status) {
if(status == null) status = "";
jsCall("sct_handle_recording_update(\""+state+"\",\""+status+"\");");
}
public static void handleRecordingUIHide() {
jsCall("sct_handle_recording_ui_hide();");
}
public static void handleExistingRecording() {
jsCall("sct_handle_existing_recording()");
}
public static void handleFreshRecording() {
jsCall("sct_handle_fresh_recording()");
}
public static void handleDeletedRecording() {
jsCall("sct_handle_deleted_recording()");
}
public static void redirectWebPage(String url) {
jsCall("sct_redirect_page(\""+url+"\");");
}
public static void sendShowStatus(String message) {
jsCall("sct_show_status(\""+message+"\");");
}
public static void sendHideStatus() {
jsCall("sct_hide_status();");
}
public static void sendInfo(String message) {
jsCall("sct_info(\""+message+"\");");
}
public static void sendError(String message) {
jsCall("sct_error(\""+message+"\");");
}
// ---------- END JAVASCRIPT API ----------
private static void jsCall(String method) {
if(JS_BRIDGE == null) {
System.err.println("Call to "+method+" but no JS Bridge exists. Probably in development mode...");
} else {
//System.out.println("Sending javascript call: "+method);
//JSObject doc = (JSObject) JS_BRIDGE.getMember("document");
//doc.eval(method);
JS_BRIDGE.eval(method);
}
}
/**
* Copies an entire folder out of a jar to a physical location.
*
* Base code: http://forums.sun.com/thread.jspa?threadID=5154854
* Helpful: http://mindprod.com/jgloss/getresourceasstream.html
* Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file
*
* @param jarName Path and name of the jar to extract from
* @param folderName Single name, not path, of the folder to pull from the root of the jar.
*/
public static void copyFolderFromCurrentJar(String jarName, String folderName) {
if(jarName == null || folderName == null) return;
try {
ZipFile z = new ZipFile(jarName);
Enumeration<? extends ZipEntry> entries = z.entries();
// make the folder first
//File folder = new File(RFX_FOLDER.getAbsolutePath()+File.separator+folderName);
//if( !folder.exists() ) folder.mkdir();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.getName().contains(folderName)) {
File f = new File(RFX_FOLDER.getAbsolutePath()+File.separator+entry.getName());
if (entry.isDirectory() && f.mkdir()) {
System.out.println("Created folder "+f.getAbsolutePath()+" for "+entry.getName());
}
else if (!f.exists()) {
if (copyFileFromJar(entry.getName(), f)) {
System.out.println("Copied file: " + entry.getName());
} else {
System.err.println("Could not copy file: "+entry.getName());
}
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Use this one or loading from a remote jar and extracting it.
*
* @param jar
* @param folderName
*/
public static void copyFolderFromRemoteJar(URL jar, String folderName) {
if(jar == null || folderName == null) return;
try {
JarClassLoader jarLoader = new JarClassLoader(jar);
URL u = new URL("jar", "", jar + "!/");
JarURLConnection uc = (JarURLConnection)u.openConnection();
JarFile jarFile = uc.getJarFile();
Enumeration<? extends JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.getName().contains(folderName)) {
File f = new File(RFX_FOLDER.getAbsolutePath()+File.separator+entry.getName());
if (entry.isDirectory() && f.mkdir()) {
System.out.println("Created folder "+f.getAbsolutePath()+" for "+entry.getName());
}
else if (!f.exists()) {
if (copyFileFromJar(entry.getName(), f, jarLoader)) {
System.out.println("Copied file: " + entry.getName());
} else {
System.err.println("Could not copy file: "+entry.getName());
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
protected static boolean copyFileFromJar(String sResource, File fDest) {
return copyFileFromJar(sResource, fDest, Applet.class.getClassLoader());
}
/**
* Copies a file out of the jar to a physical location.
* Doesn't need to be private, uses a resource stream, so may have
* security errors if run from webstart application
*
* Base code: http://forums.sun.com/thread.jspa?threadID=5154854
* Helpful: http://mindprod.com/jgloss/getresourceasstream.html
* Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file
*/
protected static boolean copyFileFromJar(String sResource, File fDest, ClassLoader loader) {
if (sResource == null || fDest == null) return false;
InputStream sIn = null;
OutputStream sOut = null;
File sFile = null;
try {
fDest.getParentFile().mkdirs();
sFile = new File(sResource);
}
catch(Exception e) {
e.printStackTrace();
}
try {
int nLen = 0;
sIn = loader.getResourceAsStream(sResource);
if (sIn == null)
throw new IOException("Could not get resource as stream to copy " + sResource + " from the jar to " + fDest.getAbsolutePath() + ")");
sOut = new FileOutputStream(fDest);
byte[] bBuffer = new byte[1024];
while ((nLen = sIn.read(bBuffer)) > 0)
sOut.write(bBuffer, 0, nLen);
sOut.flush();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (sIn != null)
sIn.close();
if (sOut != null)
sOut.close();
}
catch (IOException eError) {
eError.printStackTrace();
}
}
return fDest.exists();
}
@Override
public String getAppletInfo() {
// base code: http://stackoverflow.com/questions/2234476/how-to-detect-the-current-display-with-java
GRAPHICS_CONFIG = getGraphicsConfiguration();
GraphicsDevice myScreen = GRAPHICS_CONFIG.getDevice();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allScreens = env.getScreenDevices();
int myScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
if (allScreens[i].equals(myScreen))
{
myScreenIndex = i;
break;
}
}
try {
return
"APPLET PROPERLY INITIALIZED WITH THIS VARIABLES:\n"+
"Java Version: \t"+System.getProperty("java.version")+"\n"+
"OS Name: \t"+System.getProperty("os.name")+"\n"+
"OS Version: \t"+System.getProperty("os.version")+"\n"+
"Run Directory: \t"+System.getProperty("user.dir")+"\n"+
"User Home: \t"+System.getProperty("user.home")+"\n"+
"User Name: \t"+System.getProperty("user.name")+"\n"+
"ReelFX Folder: \t"+RFX_FOLDER.getPath()+"\n"+
"Bin Folder: \t"+BIN_FOLDER.getPath()+"\n"+
"User Desktop: \t"+DESKTOP_FOLDER.getPath()+"\n"+
"Code Base: \t"+getCodeBase()+"\n"+
"Document Base: \t"+getDocumentBase()+"\n"+
"Execution URL: \t"+Applet.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()+"\n"+
"Multiple Monitors: \t"+(allScreens.length > 1)+"\n"+
"Applet window is on screen" + myScreenIndex+"\n"+
"Headless: \t"+HEADLESS+"\n";
} catch (URISyntaxException e) {
e.printStackTrace();
return "Error";
}
/*
System.out.println("Have these system variables:");
Map<String, String> sysEnv = System.getenv();
for (String envName : sysEnv.keySet()) {
System.out.format("%s=%s%n", envName, sysEnv.get(envName));
}
*/
//System.out.println("Free space: \n"+TEMP_FOLDER.getFreeSpace()+" GBs"); // Java 1.6 only
//System.out.println("Total space: \n"+TEMP_FOLDER.getTotalSpace()+" GBs");
}
/**
* These must start with "bin".
*
* @return Name of folder and JAR with folder of same name for holding native extensions.
* @throws IOException
*/
public static String getBinFolderName() throws IOException {
if(IS_MAC)
return "bin-mac";
else if(IS_LINUX)
return "bin-linux";
else if(IS_WINDOWS)
return "bin-windows-v1.0";
else
throw new IOException("I don't know what bin folder to use!");
}
public static String getBinFolderPath() throws IOException {
return RFX_FOLDER.getAbsolutePath()+File.separator+getBinFolderName();
}
public static String getRfxFolderPath() throws IOException {
if(IS_MAC)
return System.getProperty("user.home")+File.separator+"Library"+File.separator+"ReelFX";
else if(IS_LINUX)
return System.getProperty("user.home")+File.separator+".ReelFX";
else if(IS_WINDOWS)
return System.getenv("TEMP")+File.separator+"ReelFX";
else
throw new IOException("I don't know where to find the native extensions!");
}
// not tested, and not used
public static String getDesktopFolderPath() throws IOException {
if(IS_MAC || IS_LINUX || IS_WINDOWS)
return System.getProperty("user.home")+File.separator+"Desktop";
else
throw new IOException("I don't know where to find the user's desktop!");
}
/**
* Called when the browser closes the web page.
*
* NOTE: A bug in Mac OS X may prevent this from being called: http://lists.apple.com/archives/java-dev///2009/Oct/msg00042.html
*/
@Override
public void destroy() {
/*try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {*/
System.out.println("Closing down...");
if(controller != null)
controller.closeDown();
controller = null;
/* }
});
} catch (Exception e) { }*/
}
}
| true | true | public void init() {
try {
// finish initializing all static variables
RFX_FOLDER = new File(getRfxFolderPath()); // should be first
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
System.err.println("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
if(!DEV_MODE && !getParameter("dev_mode").isEmpty())
DEV_MODE = getParameter("dev_mode").equals("true");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( RFX_FOLDER.exists() && !RFX_FOLDER.isDirectory() && !RFX_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + RFX_FOLDER.getAbsolutePath());
if( !RFX_FOLDER.exists() && !RFX_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + RFX_FOLDER.getAbsolutePath());
// print information to console
System.out.println(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println("Could not create GUI!");
e.printStackTrace();
}
}
| public void init() {
try {
// finish initializing all static variables
RFX_FOLDER = new File(getRfxFolderPath()); // should be first
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
System.err.println("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
if(!DEV_MODE && getParameter("dev_mode") != null)
DEV_MODE = getParameter("dev_mode").equals("true");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( RFX_FOLDER.exists() && !RFX_FOLDER.isDirectory() && !RFX_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + RFX_FOLDER.getAbsolutePath());
if( !RFX_FOLDER.exists() && !RFX_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + RFX_FOLDER.getAbsolutePath());
// print information to console
System.out.println(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println("Could not create GUI!");
e.printStackTrace();
}
}
|
diff --git a/remoting/src/main/java/hudson/remoting/Which.java b/remoting/src/main/java/hudson/remoting/Which.java
index 2fb29382d..d96b1ac8b 100644
--- a/remoting/src/main/java/hudson/remoting/Which.java
+++ b/remoting/src/main/java/hudson/remoting/Which.java
@@ -1,190 +1,192 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Ullrich Hafner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.remoting;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.JarURLConnection;
import java.lang.reflect.Field;
import java.util.zip.ZipFile;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Locates where a given class is loaded from.
*
* @author Kohsuke Kawaguchi
*/
public class Which {
/**
* Locates the jar file that contains the given class.
*
* @throws IllegalArgumentException
* if failed to determine.
*/
public static URL jarURL(Class clazz) throws IOException {
ClassLoader cl = clazz.getClassLoader();
if(cl==null)
cl = ClassLoader.getSystemClassLoader();
URL res = cl.getResource(clazz.getName().replace('.', '/') + ".class");
if(res==null)
throw new IllegalArgumentException("Unable to locate class file for "+clazz);
return res;
}
/**
* Locates the jar file that contains the given class.
*
* <p>
* Note that jar files are not always loaded from {@link File},
* so for diagnostics purposes {@link #jarURL(Class)} is preferrable.
*
* @throws IllegalArgumentException
* if failed to determine.
*/
public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:/")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
resURL = resURL.substring("zip:/".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
Object delegate = f.get(is);
f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
} finally {
is.close();
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
- String n = jarFile.getName();
- if(n.length()>0) {// JDK6u10 needs this
- return new File(n);
- } else {
- // JDK6u10 apparently starts hiding the real jar file name,
- // so this just keeps getting tricker and trickier...
- try {
- Field f = ZipFile.class.getDeclaredField("name");
- f.setAccessible(true);
- return new File((String) f.get(jarFile));
- } catch (NoSuchFieldException e) {
- LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
- } catch (IllegalAccessException e) {
- LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
+ if (jarFile!=null) {
+ String n = jarFile.getName();
+ if(n.length()>0) {// JDK6u10 needs this
+ return new File(n);
+ } else {
+ // JDK6u10 apparently starts hiding the real jar file name,
+ // so this just keeps getting tricker and trickier...
+ try {
+ Field f = ZipFile.class.getDeclaredField("name");
+ f.setAccessible(true);
+ return new File((String) f.get(jarFile));
+ } catch (NoSuchFieldException e) {
+ LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
+ } catch (IllegalAccessException e) {
+ LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
+ }
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
public static File jarFile(URL resource) throws IOException {
return fromJarUrlToFile(resource.toExternalForm());
}
private static File fromJarUrlToFile(String resURL) throws MalformedURLException {
resURL = resURL.substring(resURL.indexOf(':')+1, resURL.lastIndexOf('!')); // cut off "scheme:" and the file name portion
return new File(decode(new URL(resURL).getPath()));
}
/**
* Decode '%HH'.
*/
private static String decode(String s) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for( int i=0; i<s.length();i++ ) {
char ch = s.charAt(i);
if(ch=='%') {
baos.write(hexToInt(s.charAt(i+1))*16 + hexToInt(s.charAt(i+2)));
i+=2;
continue;
}
baos.write(ch);
}
try {
return new String(baos.toByteArray(),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
}
private static int hexToInt(int ch) {
return Character.getNumericValue(ch);
}
private static final Logger LOGGER = Logger.getLogger(Which.class.getName());
}
| true | true | public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:/")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
resURL = resURL.substring("zip:/".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
Object delegate = f.get(is);
f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
} finally {
is.close();
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
String n = jarFile.getName();
if(n.length()>0) {// JDK6u10 needs this
return new File(n);
} else {
// JDK6u10 apparently starts hiding the real jar file name,
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
| public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:/")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
resURL = resURL.substring("zip:/".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
Object delegate = f.get(is);
f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
} finally {
is.close();
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
if (jarFile!=null) {
String n = jarFile.getName();
if(n.length()>0) {// JDK6u10 needs this
return new File(n);
} else {
// JDK6u10 apparently starts hiding the real jar file name,
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
}
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
|
diff --git a/src/gov/nist/javax/sip/SipStackImpl.java b/src/gov/nist/javax/sip/SipStackImpl.java
index 9189b9b4..a04fdfe0 100755
--- a/src/gov/nist/javax/sip/SipStackImpl.java
+++ b/src/gov/nist/javax/sip/SipStackImpl.java
@@ -1,1794 +1,1794 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
package gov.nist.javax.sip;
import gov.nist.core.CommonLogger;
import gov.nist.core.LogLevels;
import gov.nist.core.ServerLogger;
import gov.nist.core.StackLogger;
import gov.nist.core.net.AddressResolver;
import gov.nist.core.net.NetworkLayer;
import gov.nist.core.net.SslNetworkLayer;
import gov.nist.javax.sip.clientauthutils.AccountManager;
import gov.nist.javax.sip.clientauthutils.AuthenticationHelper;
import gov.nist.javax.sip.clientauthutils.AuthenticationHelperImpl;
import gov.nist.javax.sip.clientauthutils.SecureAccountManager;
import gov.nist.javax.sip.parser.MessageParserFactory;
import gov.nist.javax.sip.parser.PipelinedMsgParser;
import gov.nist.javax.sip.parser.StringMsgParser;
import gov.nist.javax.sip.parser.StringMsgParserFactory;
import gov.nist.javax.sip.stack.ClientAuthType;
import gov.nist.javax.sip.stack.DefaultMessageLogFactory;
import gov.nist.javax.sip.stack.DefaultRouter;
import gov.nist.javax.sip.stack.MessageProcessor;
import gov.nist.javax.sip.stack.MessageProcessorFactory;
import gov.nist.javax.sip.stack.OIOMessageProcessorFactory;
import gov.nist.javax.sip.stack.SIPEventInterceptor;
import gov.nist.javax.sip.stack.SIPMessageValve;
import gov.nist.javax.sip.stack.SIPTransactionStack;
import gov.nist.javax.sip.stack.timers.DefaultSipTimer;
import gov.nist.javax.sip.stack.timers.SipTimer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.Collections;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint;
import javax.sip.ObjectInUseException;
import javax.sip.PeerUnavailableException;
import javax.sip.ProviderDoesNotExistException;
import javax.sip.SipException;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.TransportNotSupportedException;
import javax.sip.address.Router;
import javax.sip.header.HeaderFactory;
import javax.sip.message.Request;
/**
* Implementation of SipStack.
*
* The JAIN-SIP stack is initialized by a set of properties (see the JAIN SIP
* documentation for an explanation of these properties
* {@link javax.sip.SipStack} ).
*
* For NIST SIP stack all properties can also be passed as JVM system properties
* from the command line as -D arguments.
*
* In addition to these, the following are
* meaningful properties for the NIST SIP stack (specify these in the property
* array when you create the JAIN-SIP statck):
* <ul>
*
* <li><b>gov.nist.javax.sip.TRACE_LEVEL = integer </b><br/>
* <b> Use of this property is still supported but deprecated. Please use
* gov.nist.javax.sip.STACK_LOGGER and gov.nist.javax.sip.SERVER_LOGGER for
* integration with logging frameworks and for custom formatting of log records.
* </b> This property is used by the built in log4j based logger. You can use
* the standard log4j level names here (i.e. ERROR, INFO, WARNING, OFF, DEBUG,
* TRACE) If this is set to INFO or above, then incoming valid messages are
* logged in SERVER_LOG. If you set this to 32 and specify a DEBUG_LOG then vast
* amounts of trace information will be dumped in to the specified DEBUG_LOG.
* The server log accumulates the signaling trace. <a href="{@docRoot}
* /tools/tracesviewer/tracesviewer.html"> This can be viewed using the trace
* viewer tool .</a> Please send us both the server log and debug log when
* reporting non-obvious problems. You can also use the strings DEBUG or INFO
* for level 32 and 16 respectively. If the value of this property is set to
* LOG4J, then the effective log levels are determined from the log4j settings
* file (e.g. log4j.properties). The logger name for the stack is specified
* using the gov.nist.javax.sip.LOG4J_LOGGER_NAME property. By default log4j
* logger name for the stack is the same as the stack name. For example, <code>
* properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "LOG4J");
* properties.setProperty("gov.nist.javax.sip.LOG4J_LOGGER_NAME", "SIPStackLogger");
* </code> allows you to now control logging in the stack entirely using log4j
* facilities.</li>
*
* <li><b>gov.nist.javax.sip.LOG_FACTORY = classpath </b> <b> Use of this
* property is still supported but deprecated. Please use
* gov.nist.javax.sip.STACK_LOGGER and gov.nist.javax.sip.SERVER_LOGGER for
* integration with logging frameworks and for custom formatting of log records.
* </b> <br/>
* The fully qualified classpath for an implementation of the MessageLogFactory.
* The stack calls the MessageLogFactory functions to format the log for
* messages that are received or sent. This function allows you to log auxiliary
* information related to the application or environmental conditions into the
* log stream. The log factory must have a default constructor.</li>
*
* <li><b>gov.nist.javax.sip.SERVER_LOG = fileName </b><br/>
* <b> Use of this property is still supported but deprecated. Please use
* gov.nist.javax.sip.STACK_LOGGER and gov.nist.javax.sip.SERVER_LOGGER for
* integration with logging frameworks and for custom formatting of log records.
* </b> Log valid incoming messages here. If this is left null AND the
* TRACE_LEVEL is above INFO (or TRACE) then the messages are printed to stdout.
* Otherwise messages are logged in a format that can later be viewed using the
* trace viewer application which is located in the tools/tracesviewer
* directory. <font color=red> Mail this to us with bug reports. </font></li>
*
* <li><b>gov.nist.javax.sip.DEBUG_LOG = fileName </b> <b> Use of this property
* is still supported but deprecated. Please use gov.nist.javax.sip.STACK_LOGGER
* and gov.nist.javax.sip.SERVER_LOGGER for integration with logging frameworks
* and for custom formatting of log records. </b> <br/>
* Where the debug log goes. <font color=red> Mail this to us with bug reports.
* </font></li>
*
* <li><b>gov.nist.javax.sip.LOG_MESSAGE_CONTENT = true|false </b><br/>
* Set true if you want to capture content into the log. Default is false. A bad
* idea to log content if you are using SIP to push a lot of bytes through TCP.</li>
*
* <li><b>gov.nist.javax.sip.LOG_STACK_TRACE_ON_MESSAGE_SEND = true|false </b><br/>
* Set true if you want to to log a stack trace at INFO level for each message
* send. This is really handy for debugging.</li>
*
* <li><b>gov.nist.javax.sip.STACK_LOGGER = full path name to the class
* implementing gov.nist.core.StackLogger interface</b><br/>
* If this property is defined the sip stack will try to instantiate it through
* a no arg constructor. This allows to use different logging implementations
* than the ones provided by default to log what happens within the stack while
* processing SIP messages. If this property is not defined, the default sip
* stack LogWriter will be used for logging</li>
*
* <li><b>gov.nist.javax.sip.SERVER_LOGGER = full path name to the class
* implementing gov.nist.core.ServerLogger interface</b><br/>
* If this property is defined the sip stack will try to instantiate it through
* a no arg constructor. This allows to use different logging implementations
* than the ones provided by default to log sent/received messages by the sip
* stack. If this property is not defined, the default sip stack ServerLog will
* be used for logging</li>
*
* <li><b>gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING = [true|false] </b>
* <br/>
* Default is <it>true</it>. This is also settable on a per-provider basis. This
* flag is set to true by default. When set
* to <it>false</it> the following behaviors are enabled:
* <ul>
*
* <li>Turn off Merged requests Loop Detection:<br/>
* The following behavior is turned off: If the request has no tag in the To header field,
* the UAS core MUST check the request against ongoing transactions. If the From tag, Call-ID, and CSeq
* exactly match those associated with an ongoing transaction, but the request
* does not match that transaction (based on the matching rules in Section
* 17.2.3), the UAS core SHOULD generate a 482 (Loop Detected) response and pass
* it to the server transaction.
*
* </ul>
*
* <li><b>gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT = [true|false] </b> <br/>
* Default is <it>false</it> This property controls a setting on the Dialog
* objects that the stack manages. Pure B2BUA applications should set this flag
* to <it>true</it>. This property can also be set on a per-dialog basis.
* Setting this to <it>true</it> imposes serialization on re-INVITE and makes
* the sending of re-INVITEs asynchronous. The sending of re-INVITE is
* controlled as follows : If the previous in-DIALOG request was an invite
* ClientTransaction then the next re-INVITEs that uses the dialog will wait
* till an ACK has been sent before admitting the new re-INVITE. If the previous
* in-DIALOG transaction was a INVITE ServerTransaction then Dialog waits for
* ACK before re-INVITE is allowed to be sent. If a dialog is not ACKed within
* 32 seconds, then the dialog is torn down and a BYE sent to the peer.</li>
* <li><b>gov.nist.javax.sip.MAX_MESSAGE_SIZE = integer</b> <br/>
* Maximum size of content that a TCP connection can read. Must be at least 4K.
* Default is "infinity" -- ie. no limit. This is to prevent DOS attacks
* launched by writing to a TCP connection until the server chokes.</li>
*
* <li><b>gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG = [true|false] </b><br/>
* If set to false (the default), the application does NOT get notified when a Dialog in the
* NULL state is terminated. ( Dialogs in the NULL state are not associated with an actual SIP Dialog.
* They are a programming convenience. A Dialog is in the NULL state before the first response for the
* Dialog forming Transaction). If set to true, the SipListener will get a DialogTerminatedEvent
* when a Dialog in the NULL state is terminated.
* </li>
*
* <li><b>gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS = [true|false] </b> <br/>
* Default value is true. Setting this to false makes the Stack close the server
* socket after a Server Transaction goes to the TERMINATED state. This allows a
* server to protectect against TCP based Denial of Service attacks launched by
* clients (ie. initiate hundreds of client transactions). If true (default
* action), the stack will keep the socket open so as to maximize performance at
* the expense of Thread and memory resources - leaving itself open to DOS
* attacks.</li>
*
*
* <li><b>gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS = [true|false] </b> <br/>
* Default value is true. Setting this to false makes the Stack close the server
* socket after a Client Transaction goes to the TERMINATED state. This allows a
* client release any buffers threads and socket connections associated with a
* client transaction after the transaction has terminated at the expense of
* performance.</li>
*
* <li><b>gov.nist.javax.sip.THREAD_POOL_SIZE = integer </b> <br/>
* Concurrency control for number of simultaneous active threads. If
* unspecificed, the default is "infinity". This feature is useful if you are
* trying to build a container.
* <ul>
* <li>
* <li>If this is not specified, <b> and the listener is re-entrant</b>, each
* event delivered to the listener is run in the context of a new thread.</li>
* <li>If this is specified and the listener is re-entrant, then the stack will
* run the listener using a thread from the thread pool. This allows you to
* manage the level of concurrency to a fixed maximum. Threads are pre-allocated
* when the stack is instantiated.</li>
* <li>If this is specified and the listener is not re-entrant, then the stack
* will use the thread pool thread from this pool to parse and manage the state
* machine but will run the listener in its own thread.</li>
* </ul>
*
* <li><b>gov.nist.javax.sip.REENTRANT_LISTENER = true|false </b> <br/>
* Default is false. Set to true if the listener is re-entrant. If the listener
* is re-entrant then the stack manages a thread pool and synchronously calls
* the listener from the same thread which read the message. Multiple
* transactions may concurrently receive messages and this will result in
* multiple threads being active in the listener at the same time. The listener
* has to be written with this in mind. <b> If you want good performance on a
* multithreaded machine write your listener to be re-entrant and set this
* property to be true </b></li>
*
* <li><b>gov.nist.javax.sip.MAX_CONNECTIONS = integer </b> <br/>
* Max number of simultaneous TCP connections handled by stack.</li>
*
* <li><b>gov.nist.javax.sip.MAX_SERVER_TRANSACTIONS = integer </b> <br/>
* Maximum size of server transaction table. The low water mark is 80% of the
* high water mark. Requests are selectively dropped in the lowater mark to
* highwater mark range. Requests are unconditionally accepted if the table is
* smaller than the low water mark. The default highwater mark is 5000</li>
*
* <li><b>gov.nist.javax.sip.MAX_CLIENT_TRANSACTIONS = integer </b> <br/>
* Max number of active client transactions before the caller blocks and waits
* for the number to drop below a threshold. Default is unlimited, i.e. the
* caller never blocks and waits for a client transaction to become available
* (i.e. it does its own resource management in the application).</li>
*
* <li><b>gov.nist.javax.sip.PASS_INVITE_NON_2XX_ACK_TO_LISTENER = true|false
* </b> <br/>
* If true then the listener will see the ACK for non-2xx responses for server
* transactions. This is not standard behavior per RFC 3261 (INVITE server
* transaction state machine) but this is a useful flag for testing. The TCK
* uses this flag for example.</li>
*
* <li><b>gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME = Integer </b> <br/>
* Max time (seconds) before sending a response to a server transaction. If a
* response is not sent within this time period, the transaction will be deleted
* by the stack. Default time is "infinity" - i.e. if the listener never
* responds, the stack will hang on to a reference for the transaction and
* result in a memory leak.
*
* <li><b>gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_ACK = [true|false]</b>
* <br/>
* Default is <it>false</it>. ACK Server Transaction is a Pseuedo-transaction.
* If you want termination notification on ACK transactions (so all server
* transactions can be handled uniformly in user code during cleanup), then set
* this flag to <it>true</it>.</li>
*
* <li><b>gov.nist.javax.sip.READ_TIMEOUT = integer </b> <br/>
* This is relevant for incoming TCP connections to prevent starvation at the
* server. This defines the timeout in miliseconds between successive reads
* after the first byte of a SIP message is read by the stack. All the sip
* headers must be delivered in this interval and each successive buffer must be
* of the content delivered in this interval. Default value is -1 (ie. the stack
* is wide open to starvation attacks) and the client can be as slow as it wants
* to be.</li>
*
* <li><b>gov.nist.javax.sip.NETWORK_LAYER = classpath </b> <br/>
* This is an EXPERIMENTAL property (still under active devlopment). Defines a
* network layer that allows a client to have control over socket allocations
* and monitoring of socket activity. A network layer should implement
* gov.nist.core.net.NetworkLayer. The default implementation simply acts as a
* wrapper for the standard java.net socket layer. This functionality is still
* under active development (may be extended to support security and other
* features).</li>
*
* <li><b>gov.nist.javax.sip.ADDRESS_RESOLVER = classpath </b><br/>
* The fully qualified class path for an implementation of the AddressResolver
* interface. The AddressResolver allows you to support lookup schemes for
* addresses that are not directly resolvable to IP adresses using
* getHostByName. Specifying your own address resolver allows you to customize
* address lookup. The default address resolver is a pass-through address
* resolver (i.e. just returns the input string without doing a resolution). See
* gov.nist.javax.sip.DefaultAddressResolver.</li>
*
* <li><b>gov.nist.javax.sip.AUTO_GENERATE_TIMESTAMP= [true| false] </b><br/>
* (default is false) Automatically generate a getTimeOfDay timestamp for a
* retransmitted request if the original request contained a timestamp. This is
* useful for profiling.</li>
*
* <li><b>gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS = long </b> <br/>
* Defines how often the application intends to audit the SIP Stack about the
* health of its internal threads (the property specifies the time in
* miliseconds between successive audits). The audit allows the application to
* detect catastrophic failures like an internal thread terminating because of
* an exception or getting stuck in a deadlock condition. Events like these will
* make the stack inoperable and therefore require immediate action from the
* application layer (e.g., alarms, traps, reboot, failover, etc.) Thread audits
* are disabled by default. If this property is not specified, audits will
* remain disabled. An example of how to use this property is in
* src/examples/threadaudit.</li>
*
*
*
* <li><b>gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY =
* [true|false] </b> <br/>
* Default is <it>false</it> If set to <it>true</it>, when you are creating a
* message from a <it>String</it>, the MessageFactory will compute the content
* length from the message content and ignore the provided content length
* parameter in the Message. Otherwise, it will use the content length supplied
* and generate a parse exception if the content is truncated.
*
* <li><b>gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED = [true|false]
* </b> <br/>
* Default is <it>true</it>. This flag is added in support of load balancers or
* failover managers where you may want to cancel ongoing transactions from a
* different stack than the original stack. If set to <it>false</it> then the
* CANCEL client transaction is not checked for the existence of the INVITE or
* the state of INVITE when you send the CANCEL request. Hence you can CANCEL an
* INVITE from a different stack than the INVITE. You can also create a CANCEL
* client transaction late and send it out after the INVITE server transaction
* has been Terminated. Clearly this will result in protocol errors. Setting the
* flag to true ( default ) enables you to avoid common protocol errors.</li>
*
* <li><b>gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT = [true|false] </b> <br/>
* Default is <it>false</it> This property controls a setting on the Dialog
* objects that the stack manages. Pure B2BUA applications should set this flag
* to <it>true</it>. This property can also be set on a per-dialog basis.
* Setting this to <it>true</it> imposes serialization on re-INVITE and makes
* the sending of re-INVITEs asynchronous. The sending of re-INVITE is
* controlled as follows : If the previous in-DIALOG request was an invite
* ClientTransaction then the next re-INVITEs that uses the dialog will wait
* till an ACK has been sent before admitting the new re-INVITE. If the previous
* in-DIALOG transaction was a INVITE ServerTransaction then Dialog waits for
* ACK before re-INVITE is allowed to be sent. If a dialog is not ACKed within
* 32 seconds, then the dialog is torn down and a BYE sent to the peer.</li>
*
*
* <li><b>gov.nist.javax.sip.RECEIVE_UDP_BUFFER_SIZE = int </b> <br/>
* Default is <it>8*1024</it>. This property control the size of the UDP buffer
* used for SIP messages. Under load, if the buffer capacity is overflown the
* messages are dropped causing retransmissions, further increasing the load and
* causing even more retransmissions. Good values to this property for servers
* is a big number in the order of 8*8*1024.</li>
*
* <li><b>gov.nist.javax.sip.SEND_UDP_BUFFER_SIZE = int </b> <br/>
* Default is <it>8*1024</it>. This property control the size of the UDP buffer
* used for SIP messages. Under load, if the buffer capacity is overflown the
* messages are dropped causing retransmissions, further increasing the load and
* causing even more retransmissions. Good values to this property for servers
* is a big number in the order of 8*8*1024 or higher.</li>
*
* <li><b>gov.nist.javax.sip.CONGESTION_CONTROL_TIMEOUT = int </b> How
* much time messages are allowed to wait in queue before being dropped due to
* stack being too slow to respond. Default value is 8000 ms. The value is in
* milliseconds
* </li>
*
* <li><b>gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE = integer </b>
* Use 0 or do not set this option to disable it.
*
* When using TCP your phones/clients usually connect independently creating their own TCP
* sockets. Sometimes however SIP devices are allowed to tunnel multiple calls over
* a single socket. This can also be simulated with SIPP by running "sipp -t t1".
*
* In the stack each TCP socket has it's own thread. When all calls are using the same
* socket they all use a single thread, which leads to severe performance penalty,
* especially on multi-core machines.
*
* This option instructs the SIP stack to use a thread pool and split the CPU load
* between many threads. The number of the threads is specified in this parameter.
*
* The processing is split immediately after the parsing of the message. It cannot
* be split before the parsing because in TCP the SIP message size is in the
* Content-Length header of the message and the access to the TCP network stream
* has to be synchronized. Additionally in TCP the message size can be larger.
* This causes most of the parsing for all calls to occur in a single thread, which
* may have impact on the performance in trivial applications using a single socket
* for all calls. In most applications it doesn't have performance impact.
*
* If the phones/clients use separate TCP sockets for each call this option doesn't
* have much impact, except the slightly increased memory footprint caused by the
* thread pool. It is recommended to disable this option in this case by setting it
* 0 or not setting it at all. You can simulate multi-socket mode with "sipp -t t0".
*
* With this option also we avoid closing the TCP socket when something fails, because
* we must keep processing other messages for other calls.
*
* Note: This option relies on accurate Content-Length headers in the SIP messages. It
* cannot recover once a malformed message is processed, because the stream iterator
* will not be aligned any more. Eventually the connection will be closed.
* </li>
*
* <li><b>gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY = [true|false] </b> <br/>
* Default is <it>false</it>. This flag is added to allow Sip Listeners to
* receive all NOTIFY requests including those that are not part of a valid
* dialog.</li>
*
* <li><b>gov.nist.javax.sip.REJECT_STRAY_RESPONSES = [true|false] </b> Default
* is <it>false</it> A flag that checks responses to test whether the response
* corresponds to a via header that was previously generated by us. Note that
* setting this flag implies that the stack will take control over setting the
* VIA header for Sip Requests sent through the stack. The stack will attach a
* suffix to the VIA header branch and check any response arriving at the stack
* to see if that response suffix is present. If it is not present, then the
* stack will silently drop the response.</li>
*
* <li><b>gov.nist.javax.sip.MAX_FORK_TIME_SECONDS = integer </b> Maximum time for which the original
* transaction for which a forked response is received is tracked. This property
* is only relevant to Dialog Stateful applications ( User Agents or B2BUA).
* When a forked response is received in this time interval from when the original
* INVITE client transaction was sent, the stack will place the original INVITE
* client transction in the ResponseEventExt and deliver that to the application.
* The event handler can get the original transaction from this event. </li>
*
* <li><b>gov.nist.javax.sip.EARLY_DIALOG_TIMEOUT_SECONDS=integer </b> Maximum time for which a dialog
* can remain in early state. This is defaulted to 3 minutes ( 180 seconds).
* </li>
*
* <li><b>gov.nist.javax.sip.MESSAGE_PARSER_FACTORY = name of the class implementing gov.nist.javax.sip.parser.MessageParserFactory</b>
* This factory allows pluggable implementations of the MessageParser that will take care of parsing the incoming messages.
* By example one could plug a lazy parser through this factory.</li>
*
* <li><b>gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY = name of the class implementing gov.nist.javax.sip.parser.MessageProcessorFactory</b>
* This factory allows pluggable implementations of the MessageProcessor that will take care of incoming messages.
* By example one could plug a NIO Processor through this factory.</li>
*
* <li><b>gov.nist.javax.sip.TIMER_CLASS_NAME = name of the class implementing gov.nist.javax.sip.stack.timers.SipTimer</b> interface
* This allows pluggable implementations of the Timer that will take care of scheduling the various SIP Timers.
* By example one could plug a regular timer, a scheduled thread pool executor.</li>
*
* <li><b>gov.nist.javax.sip.DELIVER_RETRANSMITTED_ACK_TO_LISTENER=boolean</b> A testing property
* that allows application to see the ACK for retransmitted 200 OK requests. <b>Note that this is for test
* purposes only</b></li>
*
* * <li><b>gov.nist.javax.sip.AGGRESSIVE_CLEANUP=boolean</b> A property that will cleanup Dialog, and Transaction structures
* agrressively to improve memroy usage and performance (up to 50% gain). However one needs to be careful in its code
* on how and when it accesses transaction and dialog data since it cleans up aggressively when transactions changes state
* to COMPLETED or TERMINATED and for Dialog once the ACK is received/sent</li>
*
* <li><b>gov.nist.javax.sip.MIN_KEEPALIVE_TIME_SECONDS = integer</b> Minimum time between keep alive
* pings (CRLF CRLF) from clients. If pings arrive with less than this frequency they will be replied
* with CRLF CRLF if greater they will be rejected. The default is -1 (i.e. do not respond to CRLF CRLF).
* </li>
*
* <li><b>gov.nist.javax.sip.DIALOG_TIMEOUT_FACTOR= integer</b> Default to 64. The number of ticks before a
* dialog that does not receive an ACK receives a Timeout notification. Note that this is only relevant
* if the registered SipListener is of type SipListenerExt
* </li>
*
* <li><b>gov.nist.javax.sip.SIP_MESSAGE_VALVE= String</b> Default to null. The class name of your custom valve component.
* An instance of this class will be created and the SIPMessageValve.processRequest/Response() methods will be called for every message
* before any long-lived SIP Stack resources are allocated (no transactions, no dialogs). From within the processRequest callback
* implementation you can drop messages, send a response statelessly or otherwise transform/pre-process the message before it reaches
* the next steps of the pipeline. Similarly from processResponse() you can manipulate a response or drop it silently, but dropping
* responses is not recommended, because the transaction already exists when the request for the response was sent.
* </li>
*
* <li><b>gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR</b> Default to null. The class name of your custom interceptor object.
* An instance of this object will be created at initialization of the stack. You must implement the interface
* gov.nist.javax.sip.stack.SIPEventInterceptor and handle the lifecycle callbacks. This interface is the solution for
* https://jain-sip.dev.java.net/issues/show_bug.cgi?id=337 . It allows to wrap the JSIP pipeline and execute custom
* analysis logic as SIP messages advance through the pipeline checkpoints. One example implementation of this interceptor
* is <b>gov.nist.javax.sip.stack.CallAnalysisInterceptor</b>, which will periodically check for requests stuck in the
* JAIN SIP threads and if some request is taking too long it will log the stack traces for all threads. The logging can
* occur only on certain events, so it will not overwhelm the CPU. The overall performance penalty by using this class in
* production under load is only 2% peak on average laptop machine. There is minimal locking inside. One known limitation
* of this feature is that you must use gov.nist.javax.sip.REENTRANT_LISTENER=true to ensure that the request will be
* processed in the original thread completely for UDP.</li>
*
* <li><b>gov.nist.javax.sip.TLS_CLIENT_PROTOCOLS = String </b>
* Comma-separated list of protocols to use when creating outgoing TLS connections.
* The default is "SSLv3, SSLv2Hello, TLSv1".
* Some servers do not support SSLv2Hello, so override to "SSLv3, TLSv1".
* </li>
*
* <li><b>gov.nist.javax.sip.TLS_SECURITY_POLICY = String </b> The fully qualified path
* name of a TLS Security Policy implementation that is consulted for certificate verification
* of outbund TLS connections.
* </li>
*
* <li><b>gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE = String </b> Valid values are Default (backward compatible with previous versions)
* , Enabled, Want or Disabled. Set to Enabled if you want the SSL stack to require a valid certificate chain from the client before
* accepting a connection. Set to Want if you want the SSL stack to request a client Certificate, but not fail if one isn't presented.
* A Disabled value will not require a certificate chain.
* </li>
*
* <li><b>javax.net.ssl.keyStore = fileName </b> <br/>
* Default is <it>NULL</it>. If left undefined the keyStore and trustStore will
* be left to the java runtime defaults. If defined, any TLS sockets created
* (client and server) will use the key store provided in the fileName. The
* trust store will default to the same store file. A password must be provided
* to access the keyStore using the following property: <br>
* <code>
* properties.setProperty("javax.net.ssl.keyStorePassword", "<password>");
* </code> <br>
* The trust store can be changed, to a separate file with the following
* setting: <br>
* <code>
* properties.setProperty("javax.net.ssl.trustStore", "<trustStoreFileName location>");
* </code> <br>
* If the trust store property is provided the password on the trust store must
* be the same as the key store. <br>
* <br></li>
* </ul>
* <b> Note that the stack supports the extensions that are defined in
* SipStackExt. These will be supported in the next release of JAIN-SIP. You
* should only use the extensions that are defined in this class. </b>
*
*
* @version 1.2 $Revision: 1.143 $ $Date: 2010-12-02 22:04:18 $
*
* @author M. Ranganathan <br/>
*
*
*
*
*/
public class SipStackImpl extends SIPTransactionStack implements
javax.sip.SipStack, SipStackExt {
private static StackLogger logger = CommonLogger.getLogger(SipStackImpl.class);
private EventScanner eventScanner;
protected Hashtable<String, ListeningPointImpl> listeningPoints;
protected List<SipProviderImpl> sipProviders;
/**
* Max datagram size.
*/
public static final Integer MAX_DATAGRAM_SIZE = 64 * 1024;
// Flag to indicate that the listener is re-entrant and hence
// Use this flag with caution.
private boolean reEntrantListener;
SipListener sipListener;
TlsSecurityPolicy tlsSecurityPolicy;
// Stack semaphore (global lock).
private Semaphore stackSemaphore = new Semaphore(1);
// RFC3261: TLS_RSA_WITH_AES_128_CBC_SHA MUST be supported
// RFC3261: TLS_RSA_WITH_3DES_EDE_CBC_SHA SHOULD be supported for backwards
// compat
private String[] cipherSuites = {
"TLS_RSA_WITH_AES_128_CBC_SHA", // AES difficult to get with
// c++/Windows
// "TLS_RSA_WITH_3DES_EDE_CBC_SHA", // Unsupported by Sun impl,
"SSL_RSA_WITH_3DES_EDE_CBC_SHA", // For backwards comp., C++
// JvB: patch from Sebastien Mazy, issue with mismatching
// ciphersuites
"TLS_DH_anon_WITH_AES_128_CBC_SHA",
"SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", };
// Supported protocols for TLS client: can be overridden by application
private String[] enabledProtocols = {
"SSLv3",
"SSLv2Hello",
"TLSv1"
};
private Properties configurationProperties;
/**
* Creates a new instance of SipStackImpl.
*/
protected SipStackImpl() {
super();
NistSipMessageFactoryImpl msgFactory = new NistSipMessageFactoryImpl(
this);
super.setMessageFactory(msgFactory);
this.eventScanner = new EventScanner(this);
this.listeningPoints = new Hashtable<String, ListeningPointImpl>();
this.sipProviders = Collections.synchronizedList(new LinkedList<SipProviderImpl>());
}
/**
* ReInitialize the stack instance.
*/
private void reInitialize() {
super.reInit();
this.eventScanner = new EventScanner(this);
this.listeningPoints = new Hashtable<String, ListeningPointImpl>();
this.sipProviders = Collections.synchronizedList(new LinkedList<SipProviderImpl>());
this.sipListener = null;
if(!getTimer().isStarted()) {
String defaultTimerName = configurationProperties.getProperty("gov.nist.javax.sip.TIMER_CLASS_NAME",DefaultSipTimer.class.getName());
try {
setTimer((SipTimer)Class.forName(defaultTimerName).newInstance());
getTimer().start(this, configurationProperties);
if (getThreadAuditor().isEnabled()) {
// Start monitoring the timer thread
getTimer().schedule(new PingTimer(null), 0);
}
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.TIMER_CLASS_NAME", e);
}
}
}
/**
* Return true if automatic dialog support is enabled for this stack.
*
* @return boolean, true if automatic dialog support is enabled for this
* stack
*/
boolean isAutomaticDialogSupportEnabled() {
return super.isAutomaticDialogSupportEnabled;
}
/**
* Constructor for the stack.
*
* @param configurationProperties
* -- stack configuration properties including NIST-specific
* extensions.
* @throws PeerUnavailableException
*/
public SipStackImpl(Properties configurationProperties)
throws PeerUnavailableException {
this();
configurationProperties = new MergedSystemProperties(configurationProperties);
this.configurationProperties = configurationProperties;
String address = configurationProperties
.getProperty("javax.sip.IP_ADDRESS");
try {
/** Retrieve the stack IP address */
if (address != null) {
// In version 1.2 of the spec the IP address is
// associated with the listening point and
// is not madatory.
super.setHostAddress(address);
}
} catch (java.net.UnknownHostException ex) {
throw new PeerUnavailableException("bad address " + address);
}
/** Retrieve the stack name */
String name = configurationProperties
.getProperty("javax.sip.STACK_NAME");
if (name == null)
throw new PeerUnavailableException("stack name is missing");
super.setStackName(name);
String stackLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.STACK_LOGGER");
// To log debug messages.
if (stackLoggerClassName == null)
stackLoggerClassName = "gov.nist.core.LogWriter";
try {
Class<?> stackLoggerClass = Class.forName(stackLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = stackLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
StackLogger stackLogger = (StackLogger) cons.newInstance(args);
CommonLogger.legacyLogger = stackLogger;
stackLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
String serverLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.SERVER_LOGGER");
// To log debug messages.
if (serverLoggerClassName == null)
serverLoggerClassName = "gov.nist.javax.sip.stack.ServerLog";
try {
Class<?> serverLoggerClass = Class
.forName(serverLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = serverLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.serverLogger = (ServerLogger) cons.newInstance(args);
serverLogger.setSipStack(this);
serverLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Default router -- use this for routing SIP URIs.
// Our router does not do DNS lookups.
this.outboundProxy = configurationProperties
.getProperty("javax.sip.OUTBOUND_PROXY");
this.defaultRouter = new DefaultRouter(this, outboundProxy);
/** Retrieve the router path */
String routerPath = configurationProperties
.getProperty("javax.sip.ROUTER_PATH");
if (routerPath == null)
routerPath = "gov.nist.javax.sip.stack.DefaultRouter";
try {
Class<?> routerClass = Class.forName(routerPath);
Class<?>[] constructorArgs = new Class[2];
constructorArgs[0] = javax.sip.SipStack.class;
constructorArgs[1] = String.class;
Constructor<?> cons = routerClass.getConstructor(constructorArgs);
Object[] args = new Object[2];
args[0] = (SipStack) this;
args[1] = outboundProxy;
Router router = (Router) cons.newInstance(args);
super.setRouter(router);
} catch (InvocationTargetException ex1) {
logger
.logError(
"could not instantiate router -- invocation target problem",
(Exception) ex1.getCause());
throw new PeerUnavailableException(
"Cound not instantiate router - check constructor", ex1);
} catch (Exception ex) {
logger.logError("could not instantiate router",
(Exception) ex.getCause());
throw new PeerUnavailableException("Could not instantiate router",
ex);
}
// The flag that indicates that the default router is to be ignored.
String useRouterForAll = configurationProperties
.getProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS");
this.useRouterForAll = true;
if (useRouterForAll != null) {
this.useRouterForAll = "true".equalsIgnoreCase(useRouterForAll);
}
/*
* Retrieve the EXTENSION Methods. These are used for instantiation of
* Dialogs.
*/
String extensionMethods = configurationProperties
.getProperty("javax.sip.EXTENSION_METHODS");
if (extensionMethods != null) {
java.util.StringTokenizer st = new java.util.StringTokenizer(
extensionMethods);
while (st.hasMoreTokens()) {
String em = st.nextToken(":");
if (em.equalsIgnoreCase(Request.BYE)
|| em.equalsIgnoreCase(Request.INVITE)
|| em.equalsIgnoreCase(Request.SUBSCRIBE)
|| em.equalsIgnoreCase(Request.NOTIFY)
|| em.equalsIgnoreCase(Request.ACK)
|| em.equalsIgnoreCase(Request.OPTIONS))
throw new PeerUnavailableException("Bad extension method "
+ em);
else
this.addExtensionMethod(em);
}
}
String keyStoreFile = configurationProperties
.getProperty("javax.net.ssl.keyStore");
String trustStoreFile = configurationProperties
.getProperty("javax.net.ssl.trustStore");
if (keyStoreFile != null) {
if (trustStoreFile == null) {
trustStoreFile = keyStoreFile;
}
String keyStorePassword = configurationProperties
.getProperty("javax.net.ssl.keyStorePassword");
try {
this.networkLayer = new SslNetworkLayer(trustStoreFile,
keyStoreFile,
keyStorePassword != null ?
keyStorePassword.toCharArray() : null,
configurationProperties
.getProperty("javax.net.ssl.keyStoreType"));
} catch (Exception e1) {
logger.logError(
"could not instantiate SSL networking", e1);
}
}
// Set the auto dialog support flag.
super.isAutomaticDialogSupportEnabled = configurationProperties
.getProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "on")
.equalsIgnoreCase("on");
super.isAutomaticDialogErrorHandlingEnabled = configurationProperties
.getProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING","true")
.equals(Boolean.TRUE.toString());
if ( super.isAutomaticDialogSupportEnabled ) {
super.isAutomaticDialogErrorHandlingEnabled = true;
}
if (configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME") != null) {
super.maxListenerResponseTime = Integer
.parseInt(configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME"));
if (super.maxListenerResponseTime <= 0)
throw new PeerUnavailableException(
"Bad configuration parameter gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME : should be positive");
} else {
super.maxListenerResponseTime = -1;
}
this.setDeliverTerminatedEventForAck(configurationProperties
.getProperty(
"gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_ACK",
"false").equalsIgnoreCase("true"));
super.setDeliverUnsolicitedNotify(Boolean.parseBoolean( configurationProperties.getProperty(
"gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "false")));
String forkedSubscriptions = configurationProperties
.getProperty("javax.sip.FORKABLE_EVENTS");
if (forkedSubscriptions != null) {
StringTokenizer st = new StringTokenizer(forkedSubscriptions);
while (st.hasMoreTokens()) {
String nextEvent = st.nextToken();
this.forkedEvents.add(nextEvent);
}
}
// Allow application to hook in a TLS Security Policy implementation
String tlsPolicyPath = configurationProperties.getProperty("gov.nist.javax.sip.TLS_SECURITY_POLICY");
if (tlsPolicyPath == null) {
tlsPolicyPath = "gov.nist.javax.sip.stack.DefaultTlsSecurityPolicy";
logger.logWarning("using default tls security policy");
}
try {
Class< ? > tlsPolicyClass = Class.forName(tlsPolicyPath);
Class< ? >[] constructorArgs = new Class[0];
Constructor< ? > cons = tlsPolicyClass.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.tlsSecurityPolicy = (TlsSecurityPolicy) cons.newInstance(args);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Allow application to choose the tls client auth policy on the socket
String clientAuthType = configurationProperties.getProperty("gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE");
if (clientAuthType != null) {
super.clientAuth = ClientAuthType.valueOf(clientAuthType);
logger.logInfo("using " + clientAuthType + " tls auth policy");
}
// The following features are unique to the NIST implementation.
/*
* gets the NetworkLayer implementation, if any. Note that this is a
* NIST only feature.
*/
final String NETWORK_LAYER_KEY = "gov.nist.javax.sip.NETWORK_LAYER";
if (configurationProperties.containsKey(NETWORK_LAYER_KEY)) {
String path = configurationProperties
.getProperty(NETWORK_LAYER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
networkLayer = (NetworkLayer) c.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate NetworkLayer implementation: "
- + path);
+ + path, e);
}
}
final String ADDRESS_RESOLVER_KEY = "gov.nist.javax.sip.ADDRESS_RESOLVER";
if (configurationProperties.containsKey(ADDRESS_RESOLVER_KEY)) {
String path = configurationProperties
.getProperty(ADDRESS_RESOLVER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.addressResolver = (AddressResolver) c
.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate AddressResolver implementation: "
- + path);
+ + path, e);
}
}
String maxConnections = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CONNECTIONS");
if (maxConnections != null) {
try {
this.maxConnections = new Integer(maxConnections).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"max connections - bad value " + ex.getMessage());
}
}
String threadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_POOL_SIZE");
if (threadPoolSize != null) {
try {
this.threadPoolSize = new Integer(threadPoolSize).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"thread pool size - bad value " + ex.getMessage());
}
}
int congetstionControlTimeout = Integer
.parseInt(configurationProperties.getProperty(
"gov.nist.javax.sip.CONGESTION_CONTROL_TIMEOUT",
"8000"));
super.stackCongenstionControlTimeout = congetstionControlTimeout;
String tcpTreadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE");
if (tcpTreadPoolSize != null) {
try {
int threads = new Integer(tcpTreadPoolSize).intValue();
super.setTcpPostParsingThreadPoolSize(threads);
PipelinedMsgParser.setPostParseExcutorSize(threads, congetstionControlTimeout);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"TCP post-parse thread pool size - bad value " + tcpTreadPoolSize + " : " + ex.getMessage());
}
}
String serverTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_SERVER_TRANSACTIONS");
if (serverTransactionTableSize != null) {
try {
this.serverTransactionTableHighwaterMark = new Integer(
serverTransactionTableSize).intValue();
this.serverTransactionTableLowaterMark = this.serverTransactionTableHighwaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
// Issue 256 : consistent with MAX_CLIENT_TRANSACTIONS, if the MAX_SERVER_TRANSACTIONS is not set
// we assume the transaction table size can grow unlimited
this.unlimitedServerTransactionTableSize = true;
}
String clientTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CLIENT_TRANSACTIONS");
if (clientTransactionTableSize != null) {
try {
this.clientTransactionTableHiwaterMark = new Integer(
clientTransactionTableSize).intValue();
this.clientTransactionTableLowaterMark = this.clientTransactionTableLowaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
this.unlimitedClientTransactionTableSize = true;
}
super.cacheServerConnections = true;
String flag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS");
if (flag != null && "false".equalsIgnoreCase(flag.trim())) {
super.cacheServerConnections = false;
}
super.cacheClientConnections = true;
String cacheflag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS");
if (cacheflag != null && "false".equalsIgnoreCase(cacheflag.trim())) {
super.cacheClientConnections = false;
}
String readTimeout = configurationProperties
.getProperty("gov.nist.javax.sip.READ_TIMEOUT");
if (readTimeout != null) {
try {
int rt = Integer.parseInt(readTimeout);
if (rt >= 100) {
super.readTimeout = rt;
} else {
System.err.println("Value too low " + readTimeout);
}
} catch (NumberFormatException nfe) {
// Ignore.
if (logger.isLoggingEnabled())
logger.logError("Bad read timeout " + readTimeout);
}
}
// Get the address of the stun server.
String stunAddr = configurationProperties
.getProperty("gov.nist.javax.sip.STUN_SERVER");
if (stunAddr != null)
this.logger.logWarning(
"Ignoring obsolete property "
+ "gov.nist.javax.sip.STUN_SERVER");
String maxMsgSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE");
try {
if (maxMsgSize != null) {
super.maxMessageSize = new Integer(maxMsgSize).intValue();
if (super.maxMessageSize < 4096)
super.maxMessageSize = 4096;
} else {
// Allow for "infinite" size of message
super.maxMessageSize = 0;
}
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"maxMessageSize - bad value " + ex.getMessage());
}
String rel = configurationProperties
.getProperty("gov.nist.javax.sip.REENTRANT_LISTENER");
this.reEntrantListener = (rel != null && "true".equalsIgnoreCase(rel));
// Check if a thread audit interval is specified
String interval = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS");
if (interval != null) {
try {
// Make the monitored threads ping the auditor twice as fast as
// the audits
getThreadAuditor().setPingIntervalInMillisecs(
Long.valueOf(interval).longValue() / 2);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"THREAD_AUDIT_INTERVAL_IN_MILLISECS - bad value ["
+ interval + "] " + ex.getMessage());
}
}
// JvB: added property for testing
this
.setNon2XXAckPassedToListener(Boolean
.valueOf(
configurationProperties
.getProperty(
"gov.nist.javax.sip.PASS_INVITE_NON_2XX_ACK_TO_LISTENER",
"false")).booleanValue());
this.generateTimeStampHeader = Boolean.valueOf(
configurationProperties.getProperty(
"gov.nist.javax.sip.AUTO_GENERATE_TIMESTAMP", "false"))
.booleanValue();
String messageLogFactoryClasspath = configurationProperties
.getProperty("gov.nist.javax.sip.LOG_FACTORY");
if (messageLogFactoryClasspath != null) {
try {
Class<?> clazz = Class.forName(messageLogFactoryClasspath);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.logRecordFactory = (LogRecordFactory) c
.newInstance(new Object[0]);
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger
.logError(
"Bad configuration value for LOG_FACTORY -- using default logger");
this.logRecordFactory = new DefaultMessageLogFactory();
}
} else {
this.logRecordFactory = new DefaultMessageLogFactory();
}
boolean computeContentLength = configurationProperties.getProperty(
"gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY",
"false").equalsIgnoreCase("true");
StringMsgParser
.setComputeContentLengthFromMessage(computeContentLength);
String tlsClientProtocols = configurationProperties.getProperty(
"gov.nist.javax.sip.TLS_CLIENT_PROTOCOLS");
if (tlsClientProtocols != null)
{
StringTokenizer st = new StringTokenizer(tlsClientProtocols, " ,");
String[] protocols = new String[st.countTokens()];
int i=0;
while (st.hasMoreTokens()) {
protocols[i++] = st.nextToken();
}
this.enabledProtocols = protocols;
}
super.rfc2543Supported = configurationProperties.getProperty(
"gov.nist.javax.sip.RFC_2543_SUPPORT_ENABLED", "true")
.equalsIgnoreCase("true");
super.cancelClientTransactionChecked = configurationProperties
.getProperty(
"gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED",
"true").equalsIgnoreCase("true");
super.logStackTraceOnMessageSend = configurationProperties.getProperty(
"gov.nist.javax.sip.LOG_STACK_TRACE_ON_MESSAGE_SEND", "false")
.equalsIgnoreCase("true");
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug(
"created Sip stack. Properties = " + configurationProperties);
InputStream in = getClass().getResourceAsStream("/TIMESTAMP");
if (in != null) {
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(in));
try {
String buildTimeStamp = streamReader.readLine();
if (in != null) {
in.close();
}
logger.setBuildTimeStamp(buildTimeStamp);
} catch (IOException ex) {
logger.logError("Could not open build timestamp.");
}
}
String bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.RECEIVE_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
int bufferSizeInteger = new Integer(bufferSize).intValue();
super.setReceiveUdpBufferSize(bufferSizeInteger);
bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.SEND_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
bufferSizeInteger = new Integer(bufferSize).intValue();
super.setSendUdpBufferSize(bufferSizeInteger);
super.isBackToBackUserAgent = Boolean
.parseBoolean(configurationProperties.getProperty(
"gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT",
Boolean.FALSE.toString()));
super.checkBranchId = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.REJECT_STRAY_RESPONSES",
Boolean.FALSE.toString()));
super.isDialogTerminatedEventDeliveredForNullDialog = (Boolean.parseBoolean(configurationProperties.getProperty("gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG",
Boolean.FALSE.toString())));
super.maxForkTime = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS","0"));
super.earlyDialogTimeout = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.EARLY_DIALOG_TIMEOUT_SECONDS","180"));
super.minKeepAliveInterval = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.MIN_KEEPALIVE_TIME_SECONDS","-1"));
super.deliverRetransmittedAckToListener = Boolean.parseBoolean(configurationProperties.getProperty
("gov.nist.javax.sip.DELIVER_RETRANSMITTED_ACK_TO_LISTENER","false"));
super.dialogTimeoutFactor = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.DIALOG_TIMEOUT_FACTOR","64"));
String messageParserFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PARSER_FACTORY",StringMsgParserFactory.class.getName());
try {
super.messageParserFactory = (MessageParserFactory) Class.forName(messageParserFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PARSER_FACTORY", e);
}
String messageProcessorFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",OIOMessageProcessorFactory.class.getName());
try {
super.messageProcessorFactory = (MessageProcessorFactory) Class.forName(messageProcessorFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", e);
}
String defaultTimerName = configurationProperties.getProperty("gov.nist.javax.sip.TIMER_CLASS_NAME",DefaultSipTimer.class.getName());
try {
setTimer((SipTimer)Class.forName(defaultTimerName).newInstance());
getTimer().start(this, configurationProperties);
if (getThreadAuditor().isEnabled()) {
// Start monitoring the timer thread
getTimer().schedule(new PingTimer(null), 0);
}
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.TIMER_CLASS_NAME", e);
}
super.aggressiveCleanup = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.AGGRESSIVE_CLEANUP",
Boolean.FALSE.toString()));
String valveClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_MESSAGE_VALVE", null);
if(valveClassName != null && !valveClassName.equals("")) {
try {
super.sipMessageValve = (SIPMessageValve) Class.forName(valveClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipMessageValve.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPMessageValve", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_MESSAGE_VALVE", e);
}
}
String interceptorClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", null);
if(interceptorClassName != null && !interceptorClassName.equals("")) {
try {
super.sipEventInterceptor = (SIPEventInterceptor) Class.forName(interceptorClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipEventInterceptor.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPEventInterceptor", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", e);
}
}
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#createListeningPoint(java.lang.String, int,
* java.lang.String)
*/
public synchronized ListeningPoint createListeningPoint(String address,
int port, String transport) throws TransportNotSupportedException,
InvalidArgumentException {
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug(
"createListeningPoint : address = " + address + " port = "
+ port + " transport = " + transport);
if (address == null)
throw new NullPointerException(
"Address for listening point is null!");
if (transport == null)
throw new NullPointerException("null transport");
if (port <= 0)
throw new InvalidArgumentException("bad port");
if (!transport.equalsIgnoreCase("UDP")
&& !transport.equalsIgnoreCase("TLS")
&& !transport.equalsIgnoreCase("TCP")
&& !transport.equalsIgnoreCase("SCTP"))
throw new TransportNotSupportedException("bad transport "
+ transport);
/** Reusing an old stack instance */
if (!this.isAlive()) {
this.toExit = false;
this.reInitialize();
}
String key = ListeningPointImpl.makeKey(address, port, transport);
ListeningPointImpl lip = (ListeningPointImpl) listeningPoints.get(key);
if (lip != null) {
return lip;
} else {
try {
InetAddress inetAddr = InetAddress.getByName(address);
MessageProcessor messageProcessor = this
.createMessageProcessor(inetAddr, port, transport);
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
this.logger.logDebug(
"Created Message Processor: " + address
+ " port = " + port + " transport = "
+ transport);
}
lip = new ListeningPointImpl(this, port, transport);
lip.messageProcessor = messageProcessor;
messageProcessor.setListeningPoint(lip);
this.listeningPoints.put(key, lip);
// start processing messages.
messageProcessor.start();
return (ListeningPoint) lip;
} catch (java.io.IOException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"Invalid argument address = " + address + " port = "
+ port + " transport = " + transport);
throw new InvalidArgumentException(ex.getMessage(), ex);
}
}
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#createSipProvider(javax.sip.ListeningPoint)
*/
public SipProvider createSipProvider(ListeningPoint listeningPoint)
throws ObjectInUseException {
if (listeningPoint == null)
throw new NullPointerException("null listeningPoint");
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
this.logger.logDebug(
"createSipProvider: " + listeningPoint);
ListeningPointImpl listeningPointImpl = (ListeningPointImpl) listeningPoint;
if (listeningPointImpl.sipProvider != null)
throw new ObjectInUseException("Provider already attached!");
SipProviderImpl provider = new SipProviderImpl(this);
provider.setListeningPoint(listeningPointImpl);
listeningPointImpl.sipProvider = provider;
this.sipProviders.add(provider);
return provider;
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#deleteListeningPoint(javax.sip.ListeningPoint)
*/
public void deleteListeningPoint(ListeningPoint listeningPoint)
throws ObjectInUseException {
if (listeningPoint == null)
throw new NullPointerException("null listeningPoint arg");
ListeningPointImpl lip = (ListeningPointImpl) listeningPoint;
// Stop the message processing thread in the listening point.
super.removeMessageProcessor(lip.messageProcessor);
String key = lip.getKey();
this.listeningPoints.remove(key);
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#deleteSipProvider(javax.sip.SipProvider)
*/
public void deleteSipProvider(SipProvider sipProvider)
throws ObjectInUseException {
if (sipProvider == null)
throw new NullPointerException("null provider arg");
SipProviderImpl sipProviderImpl = (SipProviderImpl) sipProvider;
// JvB: API doc is not clear, but in_use ==
// sipProviderImpl.sipListener!=null
// so we should throw if app did not call removeSipListener
// sipProviderImpl.sipListener = null;
if (sipProviderImpl.getSipListener() != null) {
throw new ObjectInUseException(
"SipProvider still has an associated SipListener!");
}
sipProviderImpl.removeListeningPoints();
// Bug reported by Rafael Barriuso
sipProviderImpl.stop();
sipProviders.remove(sipProvider);
if (sipProviders.isEmpty()) {
this.stopStack();
}
}
/**
* Get the IP Address of the stack.
*
* @see javax.sip.SipStack#getIPAddress()
* @deprecated
*/
public String getIPAddress() {
return super.getHostAddress();
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#getListeningPoints()
*/
public java.util.Iterator getListeningPoints() {
return this.listeningPoints.values().iterator();
}
/**
* Return true if retransmission filter is active.
*
* @see javax.sip.SipStack#isRetransmissionFilterActive()
* @deprecated
*/
public boolean isRetransmissionFilterActive() {
return true;
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#getSipProviders()
*/
public java.util.Iterator<SipProviderImpl> getSipProviders() {
return this.sipProviders.iterator();
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#getStackName()
*/
public String getStackName() {
return this.stackName;
}
/**
* Finalization -- stop the stack on finalization. Exit the transaction
* scanner and release all resources.
*
* @see java.lang.Object#finalize()
*/
protected void finalize() {
this.stopStack();
}
/**
* This uses the default stack address to create a listening point.
*
* @see javax.sip.SipStack#createListeningPoint(java.lang.String, int,
* java.lang.String)
* @deprecated
*/
public ListeningPoint createListeningPoint(int port, String transport)
throws TransportNotSupportedException, InvalidArgumentException {
if (super.stackAddress == null)
throw new NullPointerException(
"Stack does not have a default IP Address!");
return this.createListeningPoint(super.stackAddress, port, transport);
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#stop()
*/
public void stop() {
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
logger.logDebug("stopStack -- stoppping the stack");
logger.logStackTrace();
}
this.stopStack();
if(super.sipMessageValve != null)
super.sipMessageValve.destroy();
if(super.sipEventInterceptor != null)
super.sipEventInterceptor.destroy();
this.sipProviders = Collections.synchronizedList(new LinkedList<SipProviderImpl>());
this.listeningPoints = new Hashtable<String, ListeningPointImpl>();
/*
* Check for presence of an event scanner ( may happen if stack is
* stopped before listener is attached ).
*/
if (this.eventScanner != null)
this.eventScanner.forceStop();
this.eventScanner = null;
PipelinedMsgParser.shutdownTcpThreadpool();
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipStack#start()
*/
public void start() throws ProviderDoesNotExistException, SipException {
// Start a new event scanner if one does not exist.
if (this.eventScanner == null) {
this.eventScanner = new EventScanner(this);
}
}
/**
* Get the listener for the stack. A stack can have only one listener. To
* get an event from a provider, the listener has to be registered with the
* provider. The SipListener is application code.
*
* @return -- the stack SipListener
*
*/
public SipListener getSipListener() {
return this.sipListener;
}
/**
* Get the TLS Security Policy implementation for the stack. The TlsSecurityPolicy is application code.
*
* @return -- the TLS Security Policy implementation
*
*/
public TlsSecurityPolicy getTlsSecurityPolicy() {
return this.tlsSecurityPolicy;
}
/**
* Get the message log factory registered with the stack.
*
* @return -- the messageLogFactory of the stack.
*/
public LogRecordFactory getLogRecordFactory() {
return super.logRecordFactory;
}
/**
* Set the log appender ( this is useful if you want to specify a particular
* log format or log to something other than a file for example). This method
* is will be removed May 11, 2010 or shortly there after.
*
* @param Appender
* - the log4j appender to add.
* @deprecated TODO: remove this method May 11, 2010.
*/
@Deprecated
public void addLogAppender(org.apache.log4j.Appender appender) {
if (this.logger instanceof gov.nist.core.LogWriter) {
((gov.nist.core.LogWriter) this.logger).addAppender(appender);
}
}
/**
* Get the log4j logger ( for log stream integration ).
* This method will be removed May 11, 2010 or shortly there after.
*
* @return the log4j logger.
* @deprecated TODO: This method will be removed May 11, 2010.
*/
@Deprecated
public org.apache.log4j.Logger getLogger() {
if (this.logger instanceof gov.nist.core.LogWriter) {
return ((gov.nist.core.LogWriter) this.logger).getLogger();
}
return null;
}
public EventScanner getEventScanner() {
return eventScanner;
}
/*
* (non-Javadoc)
*
* @see
* gov.nist.javax.sip.SipStackExt#getAuthenticationHelper(gov.nist.javax
* .sip.clientauthutils.AccountManager, javax.sip.header.HeaderFactory)
*/
public AuthenticationHelper getAuthenticationHelper(
AccountManager accountManager, HeaderFactory headerFactory) {
return new AuthenticationHelperImpl(this, accountManager, headerFactory);
}
/*
* (non-Javadoc)
*
* @see
* gov.nist.javax.sip.SipStackExt#getAuthenticationHelper(gov.nist.javax
* .sip.clientauthutils.AccountManager, javax.sip.header.HeaderFactory)
*/
public AuthenticationHelper getSecureAuthenticationHelper(
SecureAccountManager accountManager, HeaderFactory headerFactory) {
return new AuthenticationHelperImpl(this, accountManager, headerFactory);
}
/**
* Set the list of cipher suites supported by the stack. A stack can have
* only one set of suites. These are not validated against the supported
* cipher suites of the java runtime, so specifying a cipher here does not
* guarantee that it will work.<br>
* The stack has a default cipher suite of:
* <ul>
* <li>TLS_RSA_WITH_AES_128_CBC_SHA</li>
* <li>SSL_RSA_WITH_3DES_EDE_CBC_SHA</li>
* <li>TLS_DH_anon_WITH_AES_128_CBC_SHA</li>
* <li>SSL_DH_anon_WITH_3DES_EDE_CBC_SHA</li>
* </ul>
*
* <b>NOTE: This function must be called before adding a TLS listener</b>
*
* @param String
* [] The new set of ciphers to support.
* @return
*
*/
public void setEnabledCipherSuites(String[] newCipherSuites) {
cipherSuites = newCipherSuites;
}
/**
* Return the currently enabled cipher suites of the Stack.
*
* @return The currently enabled cipher suites.
*/
public String[] getEnabledCipherSuites() {
return cipherSuites;
}
/**
* Set the list of protocols supported by the stack for outgoing TLS connections.
* A stack can have only one set of protocols.
* These are not validated against the supported
* protocols of the java runtime, so specifying a protocol here does not
* guarantee that it will work.<br>
* The stack has a default protocol suite of:
* <ul>
* <li>SSLv3</li>
* <li>SSLv2Hello</li>
* <li>TLSv1</li>
* </ul>
*
* <b>NOTE: This function must be called before creating a TLSMessageChannel.</b>
*
* @param String
* [] The new set of protocols to use for outgoing TLS connections.
* @return
*
*/
public void setEnabledProtocols(String[] newProtocols) {
enabledProtocols = newProtocols;
}
/**
* Return the currently enabled protocols to use when creating TLS connection.
*
* @return The currently enabled protocols.
*/
public String[] getEnabledProtocols() {
return enabledProtocols;
}
/**
* Set the "back to back User Agent" flag.
*
* @param flag
* - boolean flag to set.
*
*/
public void setIsBackToBackUserAgent(boolean flag) {
super.isBackToBackUserAgent = flag;
}
/**
* Get the "back to back User Agent" flag.
*
* return the value of the flag
*
*/
public boolean isBackToBackUserAgent() {
return super.isBackToBackUserAgent;
}
public boolean isAutomaticDialogErrorHandlingEnabled() {
return super.isAutomaticDialogErrorHandlingEnabled;
}
public void setTlsSecurityPolicy(TlsSecurityPolicy tlsSecurityPolicy) {
this.tlsSecurityPolicy = tlsSecurityPolicy;
}
public boolean acquireSem() {
try {
return this.stackSemaphore.tryAcquire(10, TimeUnit.SECONDS);
} catch ( InterruptedException ex) {
return false;
}
}
public void releaseSem() {
this.stackSemaphore.release();
}
/**
* @return the configurationProperties
*/
public Properties getConfigurationProperties() {
return configurationProperties;
}
/**
* @return the reEntrantListener
*/
public boolean isReEntrantListener() {
return reEntrantListener;
}
}
| false | true | public SipStackImpl(Properties configurationProperties)
throws PeerUnavailableException {
this();
configurationProperties = new MergedSystemProperties(configurationProperties);
this.configurationProperties = configurationProperties;
String address = configurationProperties
.getProperty("javax.sip.IP_ADDRESS");
try {
/** Retrieve the stack IP address */
if (address != null) {
// In version 1.2 of the spec the IP address is
// associated with the listening point and
// is not madatory.
super.setHostAddress(address);
}
} catch (java.net.UnknownHostException ex) {
throw new PeerUnavailableException("bad address " + address);
}
/** Retrieve the stack name */
String name = configurationProperties
.getProperty("javax.sip.STACK_NAME");
if (name == null)
throw new PeerUnavailableException("stack name is missing");
super.setStackName(name);
String stackLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.STACK_LOGGER");
// To log debug messages.
if (stackLoggerClassName == null)
stackLoggerClassName = "gov.nist.core.LogWriter";
try {
Class<?> stackLoggerClass = Class.forName(stackLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = stackLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
StackLogger stackLogger = (StackLogger) cons.newInstance(args);
CommonLogger.legacyLogger = stackLogger;
stackLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
String serverLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.SERVER_LOGGER");
// To log debug messages.
if (serverLoggerClassName == null)
serverLoggerClassName = "gov.nist.javax.sip.stack.ServerLog";
try {
Class<?> serverLoggerClass = Class
.forName(serverLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = serverLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.serverLogger = (ServerLogger) cons.newInstance(args);
serverLogger.setSipStack(this);
serverLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Default router -- use this for routing SIP URIs.
// Our router does not do DNS lookups.
this.outboundProxy = configurationProperties
.getProperty("javax.sip.OUTBOUND_PROXY");
this.defaultRouter = new DefaultRouter(this, outboundProxy);
/** Retrieve the router path */
String routerPath = configurationProperties
.getProperty("javax.sip.ROUTER_PATH");
if (routerPath == null)
routerPath = "gov.nist.javax.sip.stack.DefaultRouter";
try {
Class<?> routerClass = Class.forName(routerPath);
Class<?>[] constructorArgs = new Class[2];
constructorArgs[0] = javax.sip.SipStack.class;
constructorArgs[1] = String.class;
Constructor<?> cons = routerClass.getConstructor(constructorArgs);
Object[] args = new Object[2];
args[0] = (SipStack) this;
args[1] = outboundProxy;
Router router = (Router) cons.newInstance(args);
super.setRouter(router);
} catch (InvocationTargetException ex1) {
logger
.logError(
"could not instantiate router -- invocation target problem",
(Exception) ex1.getCause());
throw new PeerUnavailableException(
"Cound not instantiate router - check constructor", ex1);
} catch (Exception ex) {
logger.logError("could not instantiate router",
(Exception) ex.getCause());
throw new PeerUnavailableException("Could not instantiate router",
ex);
}
// The flag that indicates that the default router is to be ignored.
String useRouterForAll = configurationProperties
.getProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS");
this.useRouterForAll = true;
if (useRouterForAll != null) {
this.useRouterForAll = "true".equalsIgnoreCase(useRouterForAll);
}
/*
* Retrieve the EXTENSION Methods. These are used for instantiation of
* Dialogs.
*/
String extensionMethods = configurationProperties
.getProperty("javax.sip.EXTENSION_METHODS");
if (extensionMethods != null) {
java.util.StringTokenizer st = new java.util.StringTokenizer(
extensionMethods);
while (st.hasMoreTokens()) {
String em = st.nextToken(":");
if (em.equalsIgnoreCase(Request.BYE)
|| em.equalsIgnoreCase(Request.INVITE)
|| em.equalsIgnoreCase(Request.SUBSCRIBE)
|| em.equalsIgnoreCase(Request.NOTIFY)
|| em.equalsIgnoreCase(Request.ACK)
|| em.equalsIgnoreCase(Request.OPTIONS))
throw new PeerUnavailableException("Bad extension method "
+ em);
else
this.addExtensionMethod(em);
}
}
String keyStoreFile = configurationProperties
.getProperty("javax.net.ssl.keyStore");
String trustStoreFile = configurationProperties
.getProperty("javax.net.ssl.trustStore");
if (keyStoreFile != null) {
if (trustStoreFile == null) {
trustStoreFile = keyStoreFile;
}
String keyStorePassword = configurationProperties
.getProperty("javax.net.ssl.keyStorePassword");
try {
this.networkLayer = new SslNetworkLayer(trustStoreFile,
keyStoreFile,
keyStorePassword != null ?
keyStorePassword.toCharArray() : null,
configurationProperties
.getProperty("javax.net.ssl.keyStoreType"));
} catch (Exception e1) {
logger.logError(
"could not instantiate SSL networking", e1);
}
}
// Set the auto dialog support flag.
super.isAutomaticDialogSupportEnabled = configurationProperties
.getProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "on")
.equalsIgnoreCase("on");
super.isAutomaticDialogErrorHandlingEnabled = configurationProperties
.getProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING","true")
.equals(Boolean.TRUE.toString());
if ( super.isAutomaticDialogSupportEnabled ) {
super.isAutomaticDialogErrorHandlingEnabled = true;
}
if (configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME") != null) {
super.maxListenerResponseTime = Integer
.parseInt(configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME"));
if (super.maxListenerResponseTime <= 0)
throw new PeerUnavailableException(
"Bad configuration parameter gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME : should be positive");
} else {
super.maxListenerResponseTime = -1;
}
this.setDeliverTerminatedEventForAck(configurationProperties
.getProperty(
"gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_ACK",
"false").equalsIgnoreCase("true"));
super.setDeliverUnsolicitedNotify(Boolean.parseBoolean( configurationProperties.getProperty(
"gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "false")));
String forkedSubscriptions = configurationProperties
.getProperty("javax.sip.FORKABLE_EVENTS");
if (forkedSubscriptions != null) {
StringTokenizer st = new StringTokenizer(forkedSubscriptions);
while (st.hasMoreTokens()) {
String nextEvent = st.nextToken();
this.forkedEvents.add(nextEvent);
}
}
// Allow application to hook in a TLS Security Policy implementation
String tlsPolicyPath = configurationProperties.getProperty("gov.nist.javax.sip.TLS_SECURITY_POLICY");
if (tlsPolicyPath == null) {
tlsPolicyPath = "gov.nist.javax.sip.stack.DefaultTlsSecurityPolicy";
logger.logWarning("using default tls security policy");
}
try {
Class< ? > tlsPolicyClass = Class.forName(tlsPolicyPath);
Class< ? >[] constructorArgs = new Class[0];
Constructor< ? > cons = tlsPolicyClass.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.tlsSecurityPolicy = (TlsSecurityPolicy) cons.newInstance(args);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Allow application to choose the tls client auth policy on the socket
String clientAuthType = configurationProperties.getProperty("gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE");
if (clientAuthType != null) {
super.clientAuth = ClientAuthType.valueOf(clientAuthType);
logger.logInfo("using " + clientAuthType + " tls auth policy");
}
// The following features are unique to the NIST implementation.
/*
* gets the NetworkLayer implementation, if any. Note that this is a
* NIST only feature.
*/
final String NETWORK_LAYER_KEY = "gov.nist.javax.sip.NETWORK_LAYER";
if (configurationProperties.containsKey(NETWORK_LAYER_KEY)) {
String path = configurationProperties
.getProperty(NETWORK_LAYER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
networkLayer = (NetworkLayer) c.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate NetworkLayer implementation: "
+ path);
}
}
final String ADDRESS_RESOLVER_KEY = "gov.nist.javax.sip.ADDRESS_RESOLVER";
if (configurationProperties.containsKey(ADDRESS_RESOLVER_KEY)) {
String path = configurationProperties
.getProperty(ADDRESS_RESOLVER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.addressResolver = (AddressResolver) c
.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate AddressResolver implementation: "
+ path);
}
}
String maxConnections = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CONNECTIONS");
if (maxConnections != null) {
try {
this.maxConnections = new Integer(maxConnections).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"max connections - bad value " + ex.getMessage());
}
}
String threadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_POOL_SIZE");
if (threadPoolSize != null) {
try {
this.threadPoolSize = new Integer(threadPoolSize).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"thread pool size - bad value " + ex.getMessage());
}
}
int congetstionControlTimeout = Integer
.parseInt(configurationProperties.getProperty(
"gov.nist.javax.sip.CONGESTION_CONTROL_TIMEOUT",
"8000"));
super.stackCongenstionControlTimeout = congetstionControlTimeout;
String tcpTreadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE");
if (tcpTreadPoolSize != null) {
try {
int threads = new Integer(tcpTreadPoolSize).intValue();
super.setTcpPostParsingThreadPoolSize(threads);
PipelinedMsgParser.setPostParseExcutorSize(threads, congetstionControlTimeout);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"TCP post-parse thread pool size - bad value " + tcpTreadPoolSize + " : " + ex.getMessage());
}
}
String serverTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_SERVER_TRANSACTIONS");
if (serverTransactionTableSize != null) {
try {
this.serverTransactionTableHighwaterMark = new Integer(
serverTransactionTableSize).intValue();
this.serverTransactionTableLowaterMark = this.serverTransactionTableHighwaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
// Issue 256 : consistent with MAX_CLIENT_TRANSACTIONS, if the MAX_SERVER_TRANSACTIONS is not set
// we assume the transaction table size can grow unlimited
this.unlimitedServerTransactionTableSize = true;
}
String clientTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CLIENT_TRANSACTIONS");
if (clientTransactionTableSize != null) {
try {
this.clientTransactionTableHiwaterMark = new Integer(
clientTransactionTableSize).intValue();
this.clientTransactionTableLowaterMark = this.clientTransactionTableLowaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
this.unlimitedClientTransactionTableSize = true;
}
super.cacheServerConnections = true;
String flag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS");
if (flag != null && "false".equalsIgnoreCase(flag.trim())) {
super.cacheServerConnections = false;
}
super.cacheClientConnections = true;
String cacheflag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS");
if (cacheflag != null && "false".equalsIgnoreCase(cacheflag.trim())) {
super.cacheClientConnections = false;
}
String readTimeout = configurationProperties
.getProperty("gov.nist.javax.sip.READ_TIMEOUT");
if (readTimeout != null) {
try {
int rt = Integer.parseInt(readTimeout);
if (rt >= 100) {
super.readTimeout = rt;
} else {
System.err.println("Value too low " + readTimeout);
}
} catch (NumberFormatException nfe) {
// Ignore.
if (logger.isLoggingEnabled())
logger.logError("Bad read timeout " + readTimeout);
}
}
// Get the address of the stun server.
String stunAddr = configurationProperties
.getProperty("gov.nist.javax.sip.STUN_SERVER");
if (stunAddr != null)
this.logger.logWarning(
"Ignoring obsolete property "
+ "gov.nist.javax.sip.STUN_SERVER");
String maxMsgSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE");
try {
if (maxMsgSize != null) {
super.maxMessageSize = new Integer(maxMsgSize).intValue();
if (super.maxMessageSize < 4096)
super.maxMessageSize = 4096;
} else {
// Allow for "infinite" size of message
super.maxMessageSize = 0;
}
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"maxMessageSize - bad value " + ex.getMessage());
}
String rel = configurationProperties
.getProperty("gov.nist.javax.sip.REENTRANT_LISTENER");
this.reEntrantListener = (rel != null && "true".equalsIgnoreCase(rel));
// Check if a thread audit interval is specified
String interval = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS");
if (interval != null) {
try {
// Make the monitored threads ping the auditor twice as fast as
// the audits
getThreadAuditor().setPingIntervalInMillisecs(
Long.valueOf(interval).longValue() / 2);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"THREAD_AUDIT_INTERVAL_IN_MILLISECS - bad value ["
+ interval + "] " + ex.getMessage());
}
}
// JvB: added property for testing
this
.setNon2XXAckPassedToListener(Boolean
.valueOf(
configurationProperties
.getProperty(
"gov.nist.javax.sip.PASS_INVITE_NON_2XX_ACK_TO_LISTENER",
"false")).booleanValue());
this.generateTimeStampHeader = Boolean.valueOf(
configurationProperties.getProperty(
"gov.nist.javax.sip.AUTO_GENERATE_TIMESTAMP", "false"))
.booleanValue();
String messageLogFactoryClasspath = configurationProperties
.getProperty("gov.nist.javax.sip.LOG_FACTORY");
if (messageLogFactoryClasspath != null) {
try {
Class<?> clazz = Class.forName(messageLogFactoryClasspath);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.logRecordFactory = (LogRecordFactory) c
.newInstance(new Object[0]);
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger
.logError(
"Bad configuration value for LOG_FACTORY -- using default logger");
this.logRecordFactory = new DefaultMessageLogFactory();
}
} else {
this.logRecordFactory = new DefaultMessageLogFactory();
}
boolean computeContentLength = configurationProperties.getProperty(
"gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY",
"false").equalsIgnoreCase("true");
StringMsgParser
.setComputeContentLengthFromMessage(computeContentLength);
String tlsClientProtocols = configurationProperties.getProperty(
"gov.nist.javax.sip.TLS_CLIENT_PROTOCOLS");
if (tlsClientProtocols != null)
{
StringTokenizer st = new StringTokenizer(tlsClientProtocols, " ,");
String[] protocols = new String[st.countTokens()];
int i=0;
while (st.hasMoreTokens()) {
protocols[i++] = st.nextToken();
}
this.enabledProtocols = protocols;
}
super.rfc2543Supported = configurationProperties.getProperty(
"gov.nist.javax.sip.RFC_2543_SUPPORT_ENABLED", "true")
.equalsIgnoreCase("true");
super.cancelClientTransactionChecked = configurationProperties
.getProperty(
"gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED",
"true").equalsIgnoreCase("true");
super.logStackTraceOnMessageSend = configurationProperties.getProperty(
"gov.nist.javax.sip.LOG_STACK_TRACE_ON_MESSAGE_SEND", "false")
.equalsIgnoreCase("true");
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug(
"created Sip stack. Properties = " + configurationProperties);
InputStream in = getClass().getResourceAsStream("/TIMESTAMP");
if (in != null) {
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(in));
try {
String buildTimeStamp = streamReader.readLine();
if (in != null) {
in.close();
}
logger.setBuildTimeStamp(buildTimeStamp);
} catch (IOException ex) {
logger.logError("Could not open build timestamp.");
}
}
String bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.RECEIVE_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
int bufferSizeInteger = new Integer(bufferSize).intValue();
super.setReceiveUdpBufferSize(bufferSizeInteger);
bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.SEND_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
bufferSizeInteger = new Integer(bufferSize).intValue();
super.setSendUdpBufferSize(bufferSizeInteger);
super.isBackToBackUserAgent = Boolean
.parseBoolean(configurationProperties.getProperty(
"gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT",
Boolean.FALSE.toString()));
super.checkBranchId = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.REJECT_STRAY_RESPONSES",
Boolean.FALSE.toString()));
super.isDialogTerminatedEventDeliveredForNullDialog = (Boolean.parseBoolean(configurationProperties.getProperty("gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG",
Boolean.FALSE.toString())));
super.maxForkTime = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS","0"));
super.earlyDialogTimeout = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.EARLY_DIALOG_TIMEOUT_SECONDS","180"));
super.minKeepAliveInterval = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.MIN_KEEPALIVE_TIME_SECONDS","-1"));
super.deliverRetransmittedAckToListener = Boolean.parseBoolean(configurationProperties.getProperty
("gov.nist.javax.sip.DELIVER_RETRANSMITTED_ACK_TO_LISTENER","false"));
super.dialogTimeoutFactor = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.DIALOG_TIMEOUT_FACTOR","64"));
String messageParserFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PARSER_FACTORY",StringMsgParserFactory.class.getName());
try {
super.messageParserFactory = (MessageParserFactory) Class.forName(messageParserFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PARSER_FACTORY", e);
}
String messageProcessorFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",OIOMessageProcessorFactory.class.getName());
try {
super.messageProcessorFactory = (MessageProcessorFactory) Class.forName(messageProcessorFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", e);
}
String defaultTimerName = configurationProperties.getProperty("gov.nist.javax.sip.TIMER_CLASS_NAME",DefaultSipTimer.class.getName());
try {
setTimer((SipTimer)Class.forName(defaultTimerName).newInstance());
getTimer().start(this, configurationProperties);
if (getThreadAuditor().isEnabled()) {
// Start monitoring the timer thread
getTimer().schedule(new PingTimer(null), 0);
}
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.TIMER_CLASS_NAME", e);
}
super.aggressiveCleanup = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.AGGRESSIVE_CLEANUP",
Boolean.FALSE.toString()));
String valveClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_MESSAGE_VALVE", null);
if(valveClassName != null && !valveClassName.equals("")) {
try {
super.sipMessageValve = (SIPMessageValve) Class.forName(valveClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipMessageValve.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPMessageValve", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_MESSAGE_VALVE", e);
}
}
String interceptorClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", null);
if(interceptorClassName != null && !interceptorClassName.equals("")) {
try {
super.sipEventInterceptor = (SIPEventInterceptor) Class.forName(interceptorClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipEventInterceptor.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPEventInterceptor", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", e);
}
}
}
| public SipStackImpl(Properties configurationProperties)
throws PeerUnavailableException {
this();
configurationProperties = new MergedSystemProperties(configurationProperties);
this.configurationProperties = configurationProperties;
String address = configurationProperties
.getProperty("javax.sip.IP_ADDRESS");
try {
/** Retrieve the stack IP address */
if (address != null) {
// In version 1.2 of the spec the IP address is
// associated with the listening point and
// is not madatory.
super.setHostAddress(address);
}
} catch (java.net.UnknownHostException ex) {
throw new PeerUnavailableException("bad address " + address);
}
/** Retrieve the stack name */
String name = configurationProperties
.getProperty("javax.sip.STACK_NAME");
if (name == null)
throw new PeerUnavailableException("stack name is missing");
super.setStackName(name);
String stackLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.STACK_LOGGER");
// To log debug messages.
if (stackLoggerClassName == null)
stackLoggerClassName = "gov.nist.core.LogWriter";
try {
Class<?> stackLoggerClass = Class.forName(stackLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = stackLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
StackLogger stackLogger = (StackLogger) cons.newInstance(args);
CommonLogger.legacyLogger = stackLogger;
stackLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate stack logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
String serverLoggerClassName = configurationProperties
.getProperty("gov.nist.javax.sip.SERVER_LOGGER");
// To log debug messages.
if (serverLoggerClassName == null)
serverLoggerClassName = "gov.nist.javax.sip.stack.ServerLog";
try {
Class<?> serverLoggerClass = Class
.forName(serverLoggerClassName);
Class<?>[] constructorArgs = new Class[0];
Constructor<?> cons = serverLoggerClass
.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.serverLogger = (ServerLogger) cons.newInstance(args);
serverLogger.setSipStack(this);
serverLogger.setStackProperties(configurationProperties);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException(
"Cound not instantiate server logger "
+ stackLoggerClassName
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Default router -- use this for routing SIP URIs.
// Our router does not do DNS lookups.
this.outboundProxy = configurationProperties
.getProperty("javax.sip.OUTBOUND_PROXY");
this.defaultRouter = new DefaultRouter(this, outboundProxy);
/** Retrieve the router path */
String routerPath = configurationProperties
.getProperty("javax.sip.ROUTER_PATH");
if (routerPath == null)
routerPath = "gov.nist.javax.sip.stack.DefaultRouter";
try {
Class<?> routerClass = Class.forName(routerPath);
Class<?>[] constructorArgs = new Class[2];
constructorArgs[0] = javax.sip.SipStack.class;
constructorArgs[1] = String.class;
Constructor<?> cons = routerClass.getConstructor(constructorArgs);
Object[] args = new Object[2];
args[0] = (SipStack) this;
args[1] = outboundProxy;
Router router = (Router) cons.newInstance(args);
super.setRouter(router);
} catch (InvocationTargetException ex1) {
logger
.logError(
"could not instantiate router -- invocation target problem",
(Exception) ex1.getCause());
throw new PeerUnavailableException(
"Cound not instantiate router - check constructor", ex1);
} catch (Exception ex) {
logger.logError("could not instantiate router",
(Exception) ex.getCause());
throw new PeerUnavailableException("Could not instantiate router",
ex);
}
// The flag that indicates that the default router is to be ignored.
String useRouterForAll = configurationProperties
.getProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS");
this.useRouterForAll = true;
if (useRouterForAll != null) {
this.useRouterForAll = "true".equalsIgnoreCase(useRouterForAll);
}
/*
* Retrieve the EXTENSION Methods. These are used for instantiation of
* Dialogs.
*/
String extensionMethods = configurationProperties
.getProperty("javax.sip.EXTENSION_METHODS");
if (extensionMethods != null) {
java.util.StringTokenizer st = new java.util.StringTokenizer(
extensionMethods);
while (st.hasMoreTokens()) {
String em = st.nextToken(":");
if (em.equalsIgnoreCase(Request.BYE)
|| em.equalsIgnoreCase(Request.INVITE)
|| em.equalsIgnoreCase(Request.SUBSCRIBE)
|| em.equalsIgnoreCase(Request.NOTIFY)
|| em.equalsIgnoreCase(Request.ACK)
|| em.equalsIgnoreCase(Request.OPTIONS))
throw new PeerUnavailableException("Bad extension method "
+ em);
else
this.addExtensionMethod(em);
}
}
String keyStoreFile = configurationProperties
.getProperty("javax.net.ssl.keyStore");
String trustStoreFile = configurationProperties
.getProperty("javax.net.ssl.trustStore");
if (keyStoreFile != null) {
if (trustStoreFile == null) {
trustStoreFile = keyStoreFile;
}
String keyStorePassword = configurationProperties
.getProperty("javax.net.ssl.keyStorePassword");
try {
this.networkLayer = new SslNetworkLayer(trustStoreFile,
keyStoreFile,
keyStorePassword != null ?
keyStorePassword.toCharArray() : null,
configurationProperties
.getProperty("javax.net.ssl.keyStoreType"));
} catch (Exception e1) {
logger.logError(
"could not instantiate SSL networking", e1);
}
}
// Set the auto dialog support flag.
super.isAutomaticDialogSupportEnabled = configurationProperties
.getProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "on")
.equalsIgnoreCase("on");
super.isAutomaticDialogErrorHandlingEnabled = configurationProperties
.getProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING","true")
.equals(Boolean.TRUE.toString());
if ( super.isAutomaticDialogSupportEnabled ) {
super.isAutomaticDialogErrorHandlingEnabled = true;
}
if (configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME") != null) {
super.maxListenerResponseTime = Integer
.parseInt(configurationProperties
.getProperty("gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME"));
if (super.maxListenerResponseTime <= 0)
throw new PeerUnavailableException(
"Bad configuration parameter gov.nist.javax.sip.MAX_LISTENER_RESPONSE_TIME : should be positive");
} else {
super.maxListenerResponseTime = -1;
}
this.setDeliverTerminatedEventForAck(configurationProperties
.getProperty(
"gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_ACK",
"false").equalsIgnoreCase("true"));
super.setDeliverUnsolicitedNotify(Boolean.parseBoolean( configurationProperties.getProperty(
"gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "false")));
String forkedSubscriptions = configurationProperties
.getProperty("javax.sip.FORKABLE_EVENTS");
if (forkedSubscriptions != null) {
StringTokenizer st = new StringTokenizer(forkedSubscriptions);
while (st.hasMoreTokens()) {
String nextEvent = st.nextToken();
this.forkedEvents.add(nextEvent);
}
}
// Allow application to hook in a TLS Security Policy implementation
String tlsPolicyPath = configurationProperties.getProperty("gov.nist.javax.sip.TLS_SECURITY_POLICY");
if (tlsPolicyPath == null) {
tlsPolicyPath = "gov.nist.javax.sip.stack.DefaultTlsSecurityPolicy";
logger.logWarning("using default tls security policy");
}
try {
Class< ? > tlsPolicyClass = Class.forName(tlsPolicyPath);
Class< ? >[] constructorArgs = new Class[0];
Constructor< ? > cons = tlsPolicyClass.getConstructor(constructorArgs);
Object[] args = new Object[0];
this.tlsSecurityPolicy = (TlsSecurityPolicy) cons.newInstance(args);
} catch (InvocationTargetException ex1) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex1);
} catch (Exception ex) {
throw new IllegalArgumentException("Cound not instantiate TLS security policy " + tlsPolicyPath
+ "- check that it is present on the classpath and that there is a no-args constructor defined",
ex);
}
// Allow application to choose the tls client auth policy on the socket
String clientAuthType = configurationProperties.getProperty("gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE");
if (clientAuthType != null) {
super.clientAuth = ClientAuthType.valueOf(clientAuthType);
logger.logInfo("using " + clientAuthType + " tls auth policy");
}
// The following features are unique to the NIST implementation.
/*
* gets the NetworkLayer implementation, if any. Note that this is a
* NIST only feature.
*/
final String NETWORK_LAYER_KEY = "gov.nist.javax.sip.NETWORK_LAYER";
if (configurationProperties.containsKey(NETWORK_LAYER_KEY)) {
String path = configurationProperties
.getProperty(NETWORK_LAYER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
networkLayer = (NetworkLayer) c.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate NetworkLayer implementation: "
+ path, e);
}
}
final String ADDRESS_RESOLVER_KEY = "gov.nist.javax.sip.ADDRESS_RESOLVER";
if (configurationProperties.containsKey(ADDRESS_RESOLVER_KEY)) {
String path = configurationProperties
.getProperty(ADDRESS_RESOLVER_KEY);
try {
Class<?> clazz = Class.forName(path);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.addressResolver = (AddressResolver) c
.newInstance(new Object[0]);
} catch (Exception e) {
throw new PeerUnavailableException(
"can't find or instantiate AddressResolver implementation: "
+ path, e);
}
}
String maxConnections = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CONNECTIONS");
if (maxConnections != null) {
try {
this.maxConnections = new Integer(maxConnections).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"max connections - bad value " + ex.getMessage());
}
}
String threadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_POOL_SIZE");
if (threadPoolSize != null) {
try {
this.threadPoolSize = new Integer(threadPoolSize).intValue();
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"thread pool size - bad value " + ex.getMessage());
}
}
int congetstionControlTimeout = Integer
.parseInt(configurationProperties.getProperty(
"gov.nist.javax.sip.CONGESTION_CONTROL_TIMEOUT",
"8000"));
super.stackCongenstionControlTimeout = congetstionControlTimeout;
String tcpTreadPoolSize = configurationProperties
.getProperty("gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE");
if (tcpTreadPoolSize != null) {
try {
int threads = new Integer(tcpTreadPoolSize).intValue();
super.setTcpPostParsingThreadPoolSize(threads);
PipelinedMsgParser.setPostParseExcutorSize(threads, congetstionControlTimeout);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger.logError(
"TCP post-parse thread pool size - bad value " + tcpTreadPoolSize + " : " + ex.getMessage());
}
}
String serverTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_SERVER_TRANSACTIONS");
if (serverTransactionTableSize != null) {
try {
this.serverTransactionTableHighwaterMark = new Integer(
serverTransactionTableSize).intValue();
this.serverTransactionTableLowaterMark = this.serverTransactionTableHighwaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
// Issue 256 : consistent with MAX_CLIENT_TRANSACTIONS, if the MAX_SERVER_TRANSACTIONS is not set
// we assume the transaction table size can grow unlimited
this.unlimitedServerTransactionTableSize = true;
}
String clientTransactionTableSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_CLIENT_TRANSACTIONS");
if (clientTransactionTableSize != null) {
try {
this.clientTransactionTableHiwaterMark = new Integer(
clientTransactionTableSize).intValue();
this.clientTransactionTableLowaterMark = this.clientTransactionTableLowaterMark * 80 / 100;
// Lowater is 80% of highwater
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
this.logger
.logError(
"transaction table size - bad value "
+ ex.getMessage());
}
} else {
this.unlimitedClientTransactionTableSize = true;
}
super.cacheServerConnections = true;
String flag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS");
if (flag != null && "false".equalsIgnoreCase(flag.trim())) {
super.cacheServerConnections = false;
}
super.cacheClientConnections = true;
String cacheflag = configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS");
if (cacheflag != null && "false".equalsIgnoreCase(cacheflag.trim())) {
super.cacheClientConnections = false;
}
String readTimeout = configurationProperties
.getProperty("gov.nist.javax.sip.READ_TIMEOUT");
if (readTimeout != null) {
try {
int rt = Integer.parseInt(readTimeout);
if (rt >= 100) {
super.readTimeout = rt;
} else {
System.err.println("Value too low " + readTimeout);
}
} catch (NumberFormatException nfe) {
// Ignore.
if (logger.isLoggingEnabled())
logger.logError("Bad read timeout " + readTimeout);
}
}
// Get the address of the stun server.
String stunAddr = configurationProperties
.getProperty("gov.nist.javax.sip.STUN_SERVER");
if (stunAddr != null)
this.logger.logWarning(
"Ignoring obsolete property "
+ "gov.nist.javax.sip.STUN_SERVER");
String maxMsgSize = configurationProperties
.getProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE");
try {
if (maxMsgSize != null) {
super.maxMessageSize = new Integer(maxMsgSize).intValue();
if (super.maxMessageSize < 4096)
super.maxMessageSize = 4096;
} else {
// Allow for "infinite" size of message
super.maxMessageSize = 0;
}
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"maxMessageSize - bad value " + ex.getMessage());
}
String rel = configurationProperties
.getProperty("gov.nist.javax.sip.REENTRANT_LISTENER");
this.reEntrantListener = (rel != null && "true".equalsIgnoreCase(rel));
// Check if a thread audit interval is specified
String interval = configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS");
if (interval != null) {
try {
// Make the monitored threads ping the auditor twice as fast as
// the audits
getThreadAuditor().setPingIntervalInMillisecs(
Long.valueOf(interval).longValue() / 2);
} catch (NumberFormatException ex) {
if (logger.isLoggingEnabled())
logger.logError(
"THREAD_AUDIT_INTERVAL_IN_MILLISECS - bad value ["
+ interval + "] " + ex.getMessage());
}
}
// JvB: added property for testing
this
.setNon2XXAckPassedToListener(Boolean
.valueOf(
configurationProperties
.getProperty(
"gov.nist.javax.sip.PASS_INVITE_NON_2XX_ACK_TO_LISTENER",
"false")).booleanValue());
this.generateTimeStampHeader = Boolean.valueOf(
configurationProperties.getProperty(
"gov.nist.javax.sip.AUTO_GENERATE_TIMESTAMP", "false"))
.booleanValue();
String messageLogFactoryClasspath = configurationProperties
.getProperty("gov.nist.javax.sip.LOG_FACTORY");
if (messageLogFactoryClasspath != null) {
try {
Class<?> clazz = Class.forName(messageLogFactoryClasspath);
Constructor<?> c = clazz.getConstructor(new Class[0]);
this.logRecordFactory = (LogRecordFactory) c
.newInstance(new Object[0]);
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger
.logError(
"Bad configuration value for LOG_FACTORY -- using default logger");
this.logRecordFactory = new DefaultMessageLogFactory();
}
} else {
this.logRecordFactory = new DefaultMessageLogFactory();
}
boolean computeContentLength = configurationProperties.getProperty(
"gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY",
"false").equalsIgnoreCase("true");
StringMsgParser
.setComputeContentLengthFromMessage(computeContentLength);
String tlsClientProtocols = configurationProperties.getProperty(
"gov.nist.javax.sip.TLS_CLIENT_PROTOCOLS");
if (tlsClientProtocols != null)
{
StringTokenizer st = new StringTokenizer(tlsClientProtocols, " ,");
String[] protocols = new String[st.countTokens()];
int i=0;
while (st.hasMoreTokens()) {
protocols[i++] = st.nextToken();
}
this.enabledProtocols = protocols;
}
super.rfc2543Supported = configurationProperties.getProperty(
"gov.nist.javax.sip.RFC_2543_SUPPORT_ENABLED", "true")
.equalsIgnoreCase("true");
super.cancelClientTransactionChecked = configurationProperties
.getProperty(
"gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED",
"true").equalsIgnoreCase("true");
super.logStackTraceOnMessageSend = configurationProperties.getProperty(
"gov.nist.javax.sip.LOG_STACK_TRACE_ON_MESSAGE_SEND", "false")
.equalsIgnoreCase("true");
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug(
"created Sip stack. Properties = " + configurationProperties);
InputStream in = getClass().getResourceAsStream("/TIMESTAMP");
if (in != null) {
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(in));
try {
String buildTimeStamp = streamReader.readLine();
if (in != null) {
in.close();
}
logger.setBuildTimeStamp(buildTimeStamp);
} catch (IOException ex) {
logger.logError("Could not open build timestamp.");
}
}
String bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.RECEIVE_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
int bufferSizeInteger = new Integer(bufferSize).intValue();
super.setReceiveUdpBufferSize(bufferSizeInteger);
bufferSize = configurationProperties.getProperty(
"gov.nist.javax.sip.SEND_UDP_BUFFER_SIZE", MAX_DATAGRAM_SIZE
.toString());
bufferSizeInteger = new Integer(bufferSize).intValue();
super.setSendUdpBufferSize(bufferSizeInteger);
super.isBackToBackUserAgent = Boolean
.parseBoolean(configurationProperties.getProperty(
"gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT",
Boolean.FALSE.toString()));
super.checkBranchId = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.REJECT_STRAY_RESPONSES",
Boolean.FALSE.toString()));
super.isDialogTerminatedEventDeliveredForNullDialog = (Boolean.parseBoolean(configurationProperties.getProperty("gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG",
Boolean.FALSE.toString())));
super.maxForkTime = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS","0"));
super.earlyDialogTimeout = Integer.parseInt(
configurationProperties.getProperty("gov.nist.javax.sip.EARLY_DIALOG_TIMEOUT_SECONDS","180"));
super.minKeepAliveInterval = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.MIN_KEEPALIVE_TIME_SECONDS","-1"));
super.deliverRetransmittedAckToListener = Boolean.parseBoolean(configurationProperties.getProperty
("gov.nist.javax.sip.DELIVER_RETRANSMITTED_ACK_TO_LISTENER","false"));
super.dialogTimeoutFactor = Integer.parseInt(configurationProperties.getProperty("gov.nist.javax.sip.DIALOG_TIMEOUT_FACTOR","64"));
String messageParserFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PARSER_FACTORY",StringMsgParserFactory.class.getName());
try {
super.messageParserFactory = (MessageParserFactory) Class.forName(messageParserFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PARSER_FACTORY", e);
}
String messageProcessorFactoryName = configurationProperties.getProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",OIOMessageProcessorFactory.class.getName());
try {
super.messageProcessorFactory = (MessageProcessorFactory) Class.forName(messageProcessorFactoryName).newInstance();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", e);
}
String defaultTimerName = configurationProperties.getProperty("gov.nist.javax.sip.TIMER_CLASS_NAME",DefaultSipTimer.class.getName());
try {
setTimer((SipTimer)Class.forName(defaultTimerName).newInstance());
getTimer().start(this, configurationProperties);
if (getThreadAuditor().isEnabled()) {
// Start monitoring the timer thread
getTimer().schedule(new PingTimer(null), 0);
}
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.TIMER_CLASS_NAME", e);
}
super.aggressiveCleanup = Boolean.parseBoolean(configurationProperties
.getProperty("gov.nist.javax.sip.AGGRESSIVE_CLEANUP",
Boolean.FALSE.toString()));
String valveClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_MESSAGE_VALVE", null);
if(valveClassName != null && !valveClassName.equals("")) {
try {
super.sipMessageValve = (SIPMessageValve) Class.forName(valveClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipMessageValve.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPMessageValve", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_MESSAGE_VALVE", e);
}
}
String interceptorClassName = configurationProperties.getProperty("gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", null);
if(interceptorClassName != null && !interceptorClassName.equals("")) {
try {
super.sipEventInterceptor = (SIPEventInterceptor) Class.forName(interceptorClassName).newInstance();
final SipStack thisStack = this;
new Thread() {
public void run() {
try {
Thread.sleep(100);
sipEventInterceptor.init(thisStack);
} catch (Exception e) {
logger
.logError("Error intializing SIPEventInterceptor", e);
}
}
}.start();
} catch (Exception e) {
logger
.logError(
"Bad configuration value for gov.nist.javax.sip.SIP_EVENT_INTERCEPTOR", e);
}
}
}
|
diff --git a/src/main/java/com/threewks/thundr/rest/intercept/RestActionInterceptor.java b/src/main/java/com/threewks/thundr/rest/intercept/RestActionInterceptor.java
index 6482530..a1f36be 100644
--- a/src/main/java/com/threewks/thundr/rest/intercept/RestActionInterceptor.java
+++ b/src/main/java/com/threewks/thundr/rest/intercept/RestActionInterceptor.java
@@ -1,62 +1,66 @@
/*
* This file is a component of thundr, a software library from 3wks.
* Read more: http://www.3wks.com.au/thundr
* Copyright (C) 2013 3wks, <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.threewks.thundr.rest.intercept;
import com.threewks.thundr.action.method.ActionInterceptor;
import com.threewks.thundr.http.exception.HttpStatusException;
import com.threewks.thundr.logger.Logger;
import com.threewks.thundr.rest.RestView;
import com.threewks.thundr.rest.RestViewResolver;
import com.threewks.thundr.rest.dto.ErrorDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RestActionInterceptor implements ActionInterceptor<Rest> {
RestViewResolver viewResolver;
public RestActionInterceptor(RestViewResolver viewResolver) {
this.viewResolver = viewResolver;
}
@Override
public <T> T before(Rest annotation, HttpServletRequest req, HttpServletResponse res) {
return null;
}
@Override
public <T> T after(Rest annotation, HttpServletRequest req, HttpServletResponse res) {
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> T exception(Rest annotation, Exception e, HttpServletRequest req, HttpServletResponse res) {
- int status = (e instanceof HttpStatusException) ?
- ((HttpStatusException) e).getStatus() :
- HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ HttpStatusException statusException;
+ if (e instanceof HttpStatusException) {
+ statusException = (HttpStatusException) e;
+ } else {
+ statusException = new HttpStatusException(e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error: %s", e.getMessage());
+ }
- Logger.error("Unhandled exception in REST controller method: %s",
- ExceptionUtils.getStackTrace(e));
+ String description = (statusException.getStatus() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ?
+ ExceptionUtils.getStackTrace(e) : e.getMessage();
+ Logger.error("REST exception: %s - %s", statusException.getStatus(), description);
- return (T) new RestView(new ErrorDto(e.getMessage()), status);
+ return (T) new RestView(new ErrorDto(e.getMessage()), statusException.getStatus());
}
}
| false | true | public <T> T exception(Rest annotation, Exception e, HttpServletRequest req, HttpServletResponse res) {
int status = (e instanceof HttpStatusException) ?
((HttpStatusException) e).getStatus() :
HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
Logger.error("Unhandled exception in REST controller method: %s",
ExceptionUtils.getStackTrace(e));
return (T) new RestView(new ErrorDto(e.getMessage()), status);
}
| public <T> T exception(Rest annotation, Exception e, HttpServletRequest req, HttpServletResponse res) {
HttpStatusException statusException;
if (e instanceof HttpStatusException) {
statusException = (HttpStatusException) e;
} else {
statusException = new HttpStatusException(e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error: %s", e.getMessage());
}
String description = (statusException.getStatus() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ?
ExceptionUtils.getStackTrace(e) : e.getMessage();
Logger.error("REST exception: %s - %s", statusException.getStatus(), description);
return (T) new RestView(new ErrorDto(e.getMessage()), statusException.getStatus());
}
|
diff --git a/onebusaway-api-webapp/src/main/java/org/onebusaway/api/actions/siri/StopMonitoringController.java b/onebusaway-api-webapp/src/main/java/org/onebusaway/api/actions/siri/StopMonitoringController.java
index 5294af9f..015715f3 100644
--- a/onebusaway-api-webapp/src/main/java/org/onebusaway/api/actions/siri/StopMonitoringController.java
+++ b/onebusaway-api-webapp/src/main/java/org/onebusaway/api/actions/siri/StopMonitoringController.java
@@ -1,307 +1,309 @@
/*
* Copyright 2010, OpenPlans Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.onebusaway.api.actions.siri;
import org.onebusaway.geospatial.model.CoordinatePoint;
import org.onebusaway.siri.model.DistanceExtensions;
import org.onebusaway.siri.model.Distances;
import org.onebusaway.siri.model.MonitoredCall;
import org.onebusaway.siri.model.MonitoredStopVisit;
import org.onebusaway.siri.model.OnwardCall;
import org.onebusaway.siri.model.ServiceDelivery;
import org.onebusaway.siri.model.Siri;
import org.onebusaway.siri.model.StopMonitoringDelivery;
import org.onebusaway.siri.model.VehicleLocation;
import org.onebusaway.transit_data.model.AgencyBean;
import org.onebusaway.transit_data.model.ArrivalAndDepartureBean;
import org.onebusaway.transit_data.model.ArrivalsAndDeparturesQueryBean;
import org.onebusaway.transit_data.model.ListBean;
import org.onebusaway.transit_data.model.RouteBean;
import org.onebusaway.transit_data.model.StopBean;
import org.onebusaway.transit_data.model.StopWithArrivalsAndDeparturesBean;
import org.onebusaway.transit_data.model.TripStopTimeBean;
import org.onebusaway.transit_data.model.trips.TripBean;
import org.onebusaway.transit_data.model.trips.TripDetailsBean;
import org.onebusaway.transit_data.model.trips.TripDetailsQueryBean;
import org.onebusaway.transit_data.model.trips.TripStatusBean;
import org.onebusaway.transit_data.services.TransitDataService;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.conversion.annotations.TypeConversion;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/**
* For a given stop, return the vehicles that are going to stop there soon.
* Optionally, return the next stops for those vehicles.
*/
public class StopMonitoringController implements ModelDriven<Object>,
ServletRequestAware {
private Object _response;
private HttpServletRequest _request;
@Autowired
private TransitDataService _transitDataService;
private Date _time;
@TypeConversion(converter = "org.onebusaway.api.actions.siri.Iso8601DateTimeConverter")
public void setTime(Date time) {
_time = time;
}
/**
* This is the default action for
*
* @return
* @throws IOException
*/
public DefaultHttpHeaders index() throws IOException {
/* find the stop */
String stopId = _request.getParameter("MonitoringRef");
if (stopId == null) {
throw new IllegalArgumentException("Expected parameter MonitoringRef");
}
String agencyId = _request.getParameter("OperatorRef");
if (agencyId == null) {
throw new IllegalArgumentException("Expected parameter OperatorRef");
}
AgencyBean agency = _transitDataService.getAgency(agencyId);
if (agency == null) {
throw new IllegalArgumentException("No such agency: " + agencyId);
}
String routeId = _request.getParameter("LineRef");
String directionId = _request.getParameter("DirectionRef");
String detailLevel = _request.getParameter("StopMonitoringDetailLevel");
boolean includeOnwardCalls = false;
if (detailLevel != null) {
includeOnwardCalls = detailLevel.equals("calls");
}
if (_time == null)
_time = new Date();
// convert ids to agency_and_id
stopId = agencyId + "_" + stopId;
if (routeId != null) {
routeId = agencyId + "_" + routeId;
}
if (directionId != null) {
directionId = agencyId + "_" + directionId;
}
ArrivalsAndDeparturesQueryBean arrivalsQuery = new ArrivalsAndDeparturesQueryBean();
arrivalsQuery.setTime(_time.getTime());
- arrivalsQuery.setMinutesBefore(30);
- arrivalsQuery.setMinutesAfter(30);
- arrivalsQuery.setFrequencyMinutesBefore(30);
- arrivalsQuery.setFrequencyMinutesAfter(30);
+ arrivalsQuery.setMinutesBefore(60);
+ arrivalsQuery.setMinutesAfter(60);
+ arrivalsQuery.setFrequencyMinutesBefore(60);
+ arrivalsQuery.setFrequencyMinutesAfter(360);
StopWithArrivalsAndDeparturesBean stopWithArrivalsAndDepartures = _transitDataService.getStopWithArrivalsAndDepartures(
stopId, arrivalsQuery);
if (stopWithArrivalsAndDepartures == null) {
throw new IllegalArgumentException("Bogus stop parameter");
}
GregorianCalendar now = new GregorianCalendar();
now.setTime(_time);
Siri siri = new Siri();
siri.ServiceDelivery = new ServiceDelivery();
siri.ServiceDelivery.ResponseTimestamp = now;
siri.ServiceDelivery.stopMonitoringDeliveries = new ArrayList<StopMonitoringDelivery>();
StopMonitoringDelivery delivery = new StopMonitoringDelivery();
siri.ServiceDelivery.stopMonitoringDeliveries.add(delivery);
delivery.ResponseTimestamp = now;
delivery.ValidUntil = (Calendar) now.clone();
delivery.ValidUntil.add(Calendar.MINUTE, 1);
delivery.visits = new ArrayList<MonitoredStopVisit>();
for (ArrivalAndDepartureBean adbean : stopWithArrivalsAndDepartures.getArrivalsAndDepartures()) {
double distanceFromStop = adbean.getDistanceFromStop();
if (distanceFromStop < 0) {
/* passed this stop */
continue;
}
TripBean trip = adbean.getTrip();
RouteBean route = trip.getRoute();
if (routeId != null && !route.getId().equals(routeId)) {
// filtered out
continue;
}
if (directionId != null && !trip.getDirectionId().equals(directionId)) {
// filtered out
continue;
}
/* gather data about trip, route, and stops */
TripDetailsQueryBean query = new TripDetailsQueryBean();
query.setTripId(trip.getId());
query.setServiceDate(adbean.getServiceDate());
query.setTime(now.getTime().getTime());
query.setVehicleId(adbean.getVehicleId());
ListBean<TripDetailsBean> trips = _transitDataService.getTripDetails(query);
for (TripDetailsBean specificTripDetails : trips.getList()) {
MonitoredStopVisit MonitoredStopVisit = new MonitoredStopVisit();
TripStatusBean status = specificTripDetails.getStatus();
if (status == null) {
// this trip has no status. Let's skip it.
continue;
}
if (status.isPredicted() == false) {
/* only show trips with realtime info */
continue;
}
MonitoredStopVisit.RecordedAtTime = new GregorianCalendar();
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.MonitoredVehicleJourney = SiriUtils.getMonitoredVehicleJourney(
specificTripDetails, new Date(status.getServiceDate()),
status.getVehicleId());
MonitoredStopVisit.MonitoredVehicleJourney.VehicleRef = status.getVehicleId();
MonitoredCall monitoredCall = new MonitoredCall();
MonitoredStopVisit.MonitoredVehicleJourney.MonitoredCall = monitoredCall;
monitoredCall.Extensions = new DistanceExtensions();
monitoredCall.StopPointRef = SiriUtils.getIdWithoutAgency(stopId);
CoordinatePoint position = status.getLocation();
if (position != null) {
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation = new VehicleLocation();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Latitude = status.getLocation().getLat();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Longitude = status.getLocation().getLon();
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
}
MonitoredStopVisit.MonitoredVehicleJourney.ProgressRate = SiriUtils.getProgressRateForStatus(status.getStatus());
int i = 0;
boolean started = false;
+ boolean found = false;
List<TripStopTimeBean> stopTimes = specificTripDetails.getSchedule().getStopTimes();
/*
* go through every stop in the trip to (a) find out how far many stops
* away the bus is from this stop and (b) populate, if necessary,
* onwardCalls
*/
HashMap<String, Integer> visitNumberForStop = new HashMap<String, Integer>();
for (TripStopTimeBean stopTime : stopTimes) {
StopBean stop = stopTime.getStop();
int visitNumber = SiriUtils.getVisitNumber(visitNumberForStop, stop);
if (started) {
i++;
}
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
if (stopTime.getDistanceAlongTrip() >= distance) {
/*
* this stop time is further along the route than the vehicle is so
* we will now start counting stops until we hit the requested stop
*/
started = true;
}
if (started && stopTime.getStop().getId().equals(stopId)) {
+ found = true;
/* we have hit the requested stop */
monitoredCall.VehicleAtStop = stopTime.getDistanceAlongTrip()
- distance < 10;
monitoredCall.Extensions.Distances = new Distances();
monitoredCall.Extensions.Distances.StopsFromCall = i;
monitoredCall.Extensions.Distances.CallDistanceAlongRoute = stopTime.getDistanceAlongTrip();;
monitoredCall.Extensions.Distances.DistanceFromCall = distanceFromStop;
monitoredCall.VisitNumber = visitNumber;
if (includeOnwardCalls) {
List<OnwardCall> onwardCalls = SiriUtils.getOnwardCalls(
stopTimes, status.getServiceDate(), distance, stop);
MonitoredStopVisit.MonitoredVehicleJourney.OnwardCalls = onwardCalls;
}
}
}
- if (started == false) {
+ if (!started || !found) {
/* remove trips which have already passed this stop */
continue;
}
delivery.visits.add(MonitoredStopVisit);
}
}
// sort MonitoredStopVisits by distance from stop
Collections.sort(delivery.visits, new Comparator<MonitoredStopVisit>() {
@Override
public int compare(MonitoredStopVisit arg0, MonitoredStopVisit arg1) {
return (int) (arg0.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall - arg1.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall);
}
});
_response = siri;
return new DefaultHttpHeaders();
}
@Override
public Object getModel() {
return _response;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this._request = request;
}
public void setService(TransitDataService service) {
this._transitDataService = service;
}
public TransitDataService getService() {
return _transitDataService;
}
}
| false | true | public DefaultHttpHeaders index() throws IOException {
/* find the stop */
String stopId = _request.getParameter("MonitoringRef");
if (stopId == null) {
throw new IllegalArgumentException("Expected parameter MonitoringRef");
}
String agencyId = _request.getParameter("OperatorRef");
if (agencyId == null) {
throw new IllegalArgumentException("Expected parameter OperatorRef");
}
AgencyBean agency = _transitDataService.getAgency(agencyId);
if (agency == null) {
throw new IllegalArgumentException("No such agency: " + agencyId);
}
String routeId = _request.getParameter("LineRef");
String directionId = _request.getParameter("DirectionRef");
String detailLevel = _request.getParameter("StopMonitoringDetailLevel");
boolean includeOnwardCalls = false;
if (detailLevel != null) {
includeOnwardCalls = detailLevel.equals("calls");
}
if (_time == null)
_time = new Date();
// convert ids to agency_and_id
stopId = agencyId + "_" + stopId;
if (routeId != null) {
routeId = agencyId + "_" + routeId;
}
if (directionId != null) {
directionId = agencyId + "_" + directionId;
}
ArrivalsAndDeparturesQueryBean arrivalsQuery = new ArrivalsAndDeparturesQueryBean();
arrivalsQuery.setTime(_time.getTime());
arrivalsQuery.setMinutesBefore(30);
arrivalsQuery.setMinutesAfter(30);
arrivalsQuery.setFrequencyMinutesBefore(30);
arrivalsQuery.setFrequencyMinutesAfter(30);
StopWithArrivalsAndDeparturesBean stopWithArrivalsAndDepartures = _transitDataService.getStopWithArrivalsAndDepartures(
stopId, arrivalsQuery);
if (stopWithArrivalsAndDepartures == null) {
throw new IllegalArgumentException("Bogus stop parameter");
}
GregorianCalendar now = new GregorianCalendar();
now.setTime(_time);
Siri siri = new Siri();
siri.ServiceDelivery = new ServiceDelivery();
siri.ServiceDelivery.ResponseTimestamp = now;
siri.ServiceDelivery.stopMonitoringDeliveries = new ArrayList<StopMonitoringDelivery>();
StopMonitoringDelivery delivery = new StopMonitoringDelivery();
siri.ServiceDelivery.stopMonitoringDeliveries.add(delivery);
delivery.ResponseTimestamp = now;
delivery.ValidUntil = (Calendar) now.clone();
delivery.ValidUntil.add(Calendar.MINUTE, 1);
delivery.visits = new ArrayList<MonitoredStopVisit>();
for (ArrivalAndDepartureBean adbean : stopWithArrivalsAndDepartures.getArrivalsAndDepartures()) {
double distanceFromStop = adbean.getDistanceFromStop();
if (distanceFromStop < 0) {
/* passed this stop */
continue;
}
TripBean trip = adbean.getTrip();
RouteBean route = trip.getRoute();
if (routeId != null && !route.getId().equals(routeId)) {
// filtered out
continue;
}
if (directionId != null && !trip.getDirectionId().equals(directionId)) {
// filtered out
continue;
}
/* gather data about trip, route, and stops */
TripDetailsQueryBean query = new TripDetailsQueryBean();
query.setTripId(trip.getId());
query.setServiceDate(adbean.getServiceDate());
query.setTime(now.getTime().getTime());
query.setVehicleId(adbean.getVehicleId());
ListBean<TripDetailsBean> trips = _transitDataService.getTripDetails(query);
for (TripDetailsBean specificTripDetails : trips.getList()) {
MonitoredStopVisit MonitoredStopVisit = new MonitoredStopVisit();
TripStatusBean status = specificTripDetails.getStatus();
if (status == null) {
// this trip has no status. Let's skip it.
continue;
}
if (status.isPredicted() == false) {
/* only show trips with realtime info */
continue;
}
MonitoredStopVisit.RecordedAtTime = new GregorianCalendar();
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.MonitoredVehicleJourney = SiriUtils.getMonitoredVehicleJourney(
specificTripDetails, new Date(status.getServiceDate()),
status.getVehicleId());
MonitoredStopVisit.MonitoredVehicleJourney.VehicleRef = status.getVehicleId();
MonitoredCall monitoredCall = new MonitoredCall();
MonitoredStopVisit.MonitoredVehicleJourney.MonitoredCall = monitoredCall;
monitoredCall.Extensions = new DistanceExtensions();
monitoredCall.StopPointRef = SiriUtils.getIdWithoutAgency(stopId);
CoordinatePoint position = status.getLocation();
if (position != null) {
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation = new VehicleLocation();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Latitude = status.getLocation().getLat();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Longitude = status.getLocation().getLon();
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
}
MonitoredStopVisit.MonitoredVehicleJourney.ProgressRate = SiriUtils.getProgressRateForStatus(status.getStatus());
int i = 0;
boolean started = false;
List<TripStopTimeBean> stopTimes = specificTripDetails.getSchedule().getStopTimes();
/*
* go through every stop in the trip to (a) find out how far many stops
* away the bus is from this stop and (b) populate, if necessary,
* onwardCalls
*/
HashMap<String, Integer> visitNumberForStop = new HashMap<String, Integer>();
for (TripStopTimeBean stopTime : stopTimes) {
StopBean stop = stopTime.getStop();
int visitNumber = SiriUtils.getVisitNumber(visitNumberForStop, stop);
if (started) {
i++;
}
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
if (stopTime.getDistanceAlongTrip() >= distance) {
/*
* this stop time is further along the route than the vehicle is so
* we will now start counting stops until we hit the requested stop
*/
started = true;
}
if (started && stopTime.getStop().getId().equals(stopId)) {
/* we have hit the requested stop */
monitoredCall.VehicleAtStop = stopTime.getDistanceAlongTrip()
- distance < 10;
monitoredCall.Extensions.Distances = new Distances();
monitoredCall.Extensions.Distances.StopsFromCall = i;
monitoredCall.Extensions.Distances.CallDistanceAlongRoute = stopTime.getDistanceAlongTrip();;
monitoredCall.Extensions.Distances.DistanceFromCall = distanceFromStop;
monitoredCall.VisitNumber = visitNumber;
if (includeOnwardCalls) {
List<OnwardCall> onwardCalls = SiriUtils.getOnwardCalls(
stopTimes, status.getServiceDate(), distance, stop);
MonitoredStopVisit.MonitoredVehicleJourney.OnwardCalls = onwardCalls;
}
}
}
if (started == false) {
/* remove trips which have already passed this stop */
continue;
}
delivery.visits.add(MonitoredStopVisit);
}
}
// sort MonitoredStopVisits by distance from stop
Collections.sort(delivery.visits, new Comparator<MonitoredStopVisit>() {
@Override
public int compare(MonitoredStopVisit arg0, MonitoredStopVisit arg1) {
return (int) (arg0.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall - arg1.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall);
}
});
_response = siri;
return new DefaultHttpHeaders();
}
| public DefaultHttpHeaders index() throws IOException {
/* find the stop */
String stopId = _request.getParameter("MonitoringRef");
if (stopId == null) {
throw new IllegalArgumentException("Expected parameter MonitoringRef");
}
String agencyId = _request.getParameter("OperatorRef");
if (agencyId == null) {
throw new IllegalArgumentException("Expected parameter OperatorRef");
}
AgencyBean agency = _transitDataService.getAgency(agencyId);
if (agency == null) {
throw new IllegalArgumentException("No such agency: " + agencyId);
}
String routeId = _request.getParameter("LineRef");
String directionId = _request.getParameter("DirectionRef");
String detailLevel = _request.getParameter("StopMonitoringDetailLevel");
boolean includeOnwardCalls = false;
if (detailLevel != null) {
includeOnwardCalls = detailLevel.equals("calls");
}
if (_time == null)
_time = new Date();
// convert ids to agency_and_id
stopId = agencyId + "_" + stopId;
if (routeId != null) {
routeId = agencyId + "_" + routeId;
}
if (directionId != null) {
directionId = agencyId + "_" + directionId;
}
ArrivalsAndDeparturesQueryBean arrivalsQuery = new ArrivalsAndDeparturesQueryBean();
arrivalsQuery.setTime(_time.getTime());
arrivalsQuery.setMinutesBefore(60);
arrivalsQuery.setMinutesAfter(60);
arrivalsQuery.setFrequencyMinutesBefore(60);
arrivalsQuery.setFrequencyMinutesAfter(360);
StopWithArrivalsAndDeparturesBean stopWithArrivalsAndDepartures = _transitDataService.getStopWithArrivalsAndDepartures(
stopId, arrivalsQuery);
if (stopWithArrivalsAndDepartures == null) {
throw new IllegalArgumentException("Bogus stop parameter");
}
GregorianCalendar now = new GregorianCalendar();
now.setTime(_time);
Siri siri = new Siri();
siri.ServiceDelivery = new ServiceDelivery();
siri.ServiceDelivery.ResponseTimestamp = now;
siri.ServiceDelivery.stopMonitoringDeliveries = new ArrayList<StopMonitoringDelivery>();
StopMonitoringDelivery delivery = new StopMonitoringDelivery();
siri.ServiceDelivery.stopMonitoringDeliveries.add(delivery);
delivery.ResponseTimestamp = now;
delivery.ValidUntil = (Calendar) now.clone();
delivery.ValidUntil.add(Calendar.MINUTE, 1);
delivery.visits = new ArrayList<MonitoredStopVisit>();
for (ArrivalAndDepartureBean adbean : stopWithArrivalsAndDepartures.getArrivalsAndDepartures()) {
double distanceFromStop = adbean.getDistanceFromStop();
if (distanceFromStop < 0) {
/* passed this stop */
continue;
}
TripBean trip = adbean.getTrip();
RouteBean route = trip.getRoute();
if (routeId != null && !route.getId().equals(routeId)) {
// filtered out
continue;
}
if (directionId != null && !trip.getDirectionId().equals(directionId)) {
// filtered out
continue;
}
/* gather data about trip, route, and stops */
TripDetailsQueryBean query = new TripDetailsQueryBean();
query.setTripId(trip.getId());
query.setServiceDate(adbean.getServiceDate());
query.setTime(now.getTime().getTime());
query.setVehicleId(adbean.getVehicleId());
ListBean<TripDetailsBean> trips = _transitDataService.getTripDetails(query);
for (TripDetailsBean specificTripDetails : trips.getList()) {
MonitoredStopVisit MonitoredStopVisit = new MonitoredStopVisit();
TripStatusBean status = specificTripDetails.getStatus();
if (status == null) {
// this trip has no status. Let's skip it.
continue;
}
if (status.isPredicted() == false) {
/* only show trips with realtime info */
continue;
}
MonitoredStopVisit.RecordedAtTime = new GregorianCalendar();
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.RecordedAtTime.setTimeInMillis(status.getLastUpdateTime());
MonitoredStopVisit.MonitoredVehicleJourney = SiriUtils.getMonitoredVehicleJourney(
specificTripDetails, new Date(status.getServiceDate()),
status.getVehicleId());
MonitoredStopVisit.MonitoredVehicleJourney.VehicleRef = status.getVehicleId();
MonitoredCall monitoredCall = new MonitoredCall();
MonitoredStopVisit.MonitoredVehicleJourney.MonitoredCall = monitoredCall;
monitoredCall.Extensions = new DistanceExtensions();
monitoredCall.StopPointRef = SiriUtils.getIdWithoutAgency(stopId);
CoordinatePoint position = status.getLocation();
if (position != null) {
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation = new VehicleLocation();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Latitude = status.getLocation().getLat();
MonitoredStopVisit.MonitoredVehicleJourney.VehicleLocation.Longitude = status.getLocation().getLon();
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
}
MonitoredStopVisit.MonitoredVehicleJourney.ProgressRate = SiriUtils.getProgressRateForStatus(status.getStatus());
int i = 0;
boolean started = false;
boolean found = false;
List<TripStopTimeBean> stopTimes = specificTripDetails.getSchedule().getStopTimes();
/*
* go through every stop in the trip to (a) find out how far many stops
* away the bus is from this stop and (b) populate, if necessary,
* onwardCalls
*/
HashMap<String, Integer> visitNumberForStop = new HashMap<String, Integer>();
for (TripStopTimeBean stopTime : stopTimes) {
StopBean stop = stopTime.getStop();
int visitNumber = SiriUtils.getVisitNumber(visitNumberForStop, stop);
if (started) {
i++;
}
double distance = status.getDistanceAlongTrip();
if (Double.isNaN(distance)) {
distance = status.getScheduledDistanceAlongTrip();
}
if (stopTime.getDistanceAlongTrip() >= distance) {
/*
* this stop time is further along the route than the vehicle is so
* we will now start counting stops until we hit the requested stop
*/
started = true;
}
if (started && stopTime.getStop().getId().equals(stopId)) {
found = true;
/* we have hit the requested stop */
monitoredCall.VehicleAtStop = stopTime.getDistanceAlongTrip()
- distance < 10;
monitoredCall.Extensions.Distances = new Distances();
monitoredCall.Extensions.Distances.StopsFromCall = i;
monitoredCall.Extensions.Distances.CallDistanceAlongRoute = stopTime.getDistanceAlongTrip();;
monitoredCall.Extensions.Distances.DistanceFromCall = distanceFromStop;
monitoredCall.VisitNumber = visitNumber;
if (includeOnwardCalls) {
List<OnwardCall> onwardCalls = SiriUtils.getOnwardCalls(
stopTimes, status.getServiceDate(), distance, stop);
MonitoredStopVisit.MonitoredVehicleJourney.OnwardCalls = onwardCalls;
}
}
}
if (!started || !found) {
/* remove trips which have already passed this stop */
continue;
}
delivery.visits.add(MonitoredStopVisit);
}
}
// sort MonitoredStopVisits by distance from stop
Collections.sort(delivery.visits, new Comparator<MonitoredStopVisit>() {
@Override
public int compare(MonitoredStopVisit arg0, MonitoredStopVisit arg1) {
return (int) (arg0.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall - arg1.MonitoredVehicleJourney.MonitoredCall.Extensions.Distances.DistanceFromCall);
}
});
_response = siri;
return new DefaultHttpHeaders();
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java
index 941c39186..eb2a85303 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java
@@ -1,176 +1,178 @@
package com.badlogic.gdx.scenes.scene2d.utils;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;
/** Manages drag and drop operations through registered drag sources and drop targets.
* @author Nathan Sweet */
public class DragAndDrop {
Source source;
Payload payload;
Actor dragActor;
Target target;
boolean isValidTarget;
Array<Target> targets = new Array();
private float tapSquareSize = 8;
private int button;
float dragActorX = 14, dragActorY = -20;
public void addSource (final Source source) {
DragListener listener = new DragListener() {
public void dragStart (InputEvent event, float x, float y, int pointer) {
payload = source.dragStart(event, getTouchDownX(), getTouchDownY(), pointer);
event.stop();
}
public void drag (InputEvent event, float x, float y, int pointer) {
+ if (payload == null) return;
Stage stage = event.getStage();
// Find target.
Target newTarget = null;
isValidTarget = false;
for (int i = 0, n = targets.size; i < n; i++) {
Target target = targets.get(i);
target.actor.stageToLocalCoordinates(Vector2.tmp.set(event.getStageX(), event.getStageY()));
if (target.actor.hit(Vector2.tmp.x, Vector2.tmp.y) == null) continue;
newTarget = target;
isValidTarget = target.drag(source, payload, Vector2.tmp.x, Vector2.tmp.y, pointer);
break;
}
if (newTarget != target) {
if (target != null) target.reset();
target = newTarget;
}
// Add/remove and position the drag actor.
Actor actor = null;
if (target != null) actor = isValidTarget ? payload.validDragActor : payload.invalidDragActor;
if (actor == null) actor = payload.dragActor;
if (actor == null) return;
if (dragActor != actor) {
if (dragActor != null) dragActor.remove();
dragActor = actor;
stage.addActor(actor);
}
float actorX = event.getStageX() + dragActorX;
float actorY = event.getStageY() + dragActorY - actor.getHeight();
if (actorX < 0) actorX = 0;
if (actorY < 0) actorY = 0;
if (actorX + actor.getWidth() > stage.getWidth()) actorX = stage.getWidth() - actor.getWidth();
if (actorY + actor.getHeight() > stage.getHeight()) actorY = stage.getHeight() - actor.getHeight();
actor.setPosition(actorX, actorY);
}
public void dragStop (InputEvent event, float x, float y, int pointer) {
+ if (payload == null) return;
if (isValidTarget) target.drop(source, payload);
source.dragStop(event, x, y, pointer, isValidTarget ? target : null);
DragAndDrop.this.source = null;
payload = null;
if (target != null) target.reset();
target = null;
isValidTarget = false;
if (dragActor != null) dragActor.remove();
dragActor = null;
}
};
listener.setTapSquareSize(tapSquareSize);
listener.setButton(button);
source.actor.addCaptureListener(listener);
}
public void addTarget (Target target) {
targets.add(target);
}
/** Sets the distance a touch must travel before being considered a drag. */
public void setTapSquareSize (float halfTapSquareSize) {
tapSquareSize = halfTapSquareSize;
}
/** Sets the button to listen for, all other buttons are ignored. Default is {@link Buttons#LEFT}. Use -1 for any button. */
public void setButton (int button) {
this.button = button;
}
public void setDragActorPosition (float dragActorX, float dragActorY) {
this.dragActorX = dragActorX;
this.dragActorY = dragActorY;
}
/** A target where a payload can be dragged from.
* @author Nathan Sweet */
static abstract public class Source {
final Actor actor;
public Source (Actor actor) {
this.actor = actor;
}
/** @return May be null. */
abstract public Payload dragStart (InputEvent event, float x, float y, int pointer);
/** @param target null if not dropped on a valid target. */
public void dragStop (InputEvent event, float x, float y, int pointer, Target target) {
}
public Actor getActor () {
return actor;
}
}
/** A target where a payload can be dropped to.
* @author Nathan Sweet */
static abstract public class Target {
final Actor actor;
public Target (Actor actor) {
this.actor = actor;
}
/** Called when the object is dragged over the target. The coordinates are in the target's local coordinate system.
* @return true if this is a valid target for the object. */
abstract public boolean drag (Source source, Payload payload, float x, float y, int pointer);
/** Called when the object is no longer over the target. */
public void reset () {
}
abstract public void drop (Source source, Payload payload);
public Actor getActor () {
return actor;
}
}
/** The payload of a drag and drop operation. Actors can be optionally provided to follow the cursor and change when over a
* target. */
static public class Payload {
Actor dragActor, validDragActor, invalidDragActor;
Object object;
public void setDragActor (Actor dragActor) {
this.dragActor = dragActor;
}
public void setValidDragActor (Actor validDragActor) {
this.validDragActor = validDragActor;
}
public void setInvalidDragActor (Actor invalidDragActor) {
this.invalidDragActor = invalidDragActor;
}
public Object getObject () {
return object;
}
public void setObject (Object object) {
this.object = object;
}
}
}
| false | true | public void addSource (final Source source) {
DragListener listener = new DragListener() {
public void dragStart (InputEvent event, float x, float y, int pointer) {
payload = source.dragStart(event, getTouchDownX(), getTouchDownY(), pointer);
event.stop();
}
public void drag (InputEvent event, float x, float y, int pointer) {
Stage stage = event.getStage();
// Find target.
Target newTarget = null;
isValidTarget = false;
for (int i = 0, n = targets.size; i < n; i++) {
Target target = targets.get(i);
target.actor.stageToLocalCoordinates(Vector2.tmp.set(event.getStageX(), event.getStageY()));
if (target.actor.hit(Vector2.tmp.x, Vector2.tmp.y) == null) continue;
newTarget = target;
isValidTarget = target.drag(source, payload, Vector2.tmp.x, Vector2.tmp.y, pointer);
break;
}
if (newTarget != target) {
if (target != null) target.reset();
target = newTarget;
}
// Add/remove and position the drag actor.
Actor actor = null;
if (target != null) actor = isValidTarget ? payload.validDragActor : payload.invalidDragActor;
if (actor == null) actor = payload.dragActor;
if (actor == null) return;
if (dragActor != actor) {
if (dragActor != null) dragActor.remove();
dragActor = actor;
stage.addActor(actor);
}
float actorX = event.getStageX() + dragActorX;
float actorY = event.getStageY() + dragActorY - actor.getHeight();
if (actorX < 0) actorX = 0;
if (actorY < 0) actorY = 0;
if (actorX + actor.getWidth() > stage.getWidth()) actorX = stage.getWidth() - actor.getWidth();
if (actorY + actor.getHeight() > stage.getHeight()) actorY = stage.getHeight() - actor.getHeight();
actor.setPosition(actorX, actorY);
}
public void dragStop (InputEvent event, float x, float y, int pointer) {
if (isValidTarget) target.drop(source, payload);
source.dragStop(event, x, y, pointer, isValidTarget ? target : null);
DragAndDrop.this.source = null;
payload = null;
if (target != null) target.reset();
target = null;
isValidTarget = false;
if (dragActor != null) dragActor.remove();
dragActor = null;
}
};
listener.setTapSquareSize(tapSquareSize);
listener.setButton(button);
source.actor.addCaptureListener(listener);
}
| public void addSource (final Source source) {
DragListener listener = new DragListener() {
public void dragStart (InputEvent event, float x, float y, int pointer) {
payload = source.dragStart(event, getTouchDownX(), getTouchDownY(), pointer);
event.stop();
}
public void drag (InputEvent event, float x, float y, int pointer) {
if (payload == null) return;
Stage stage = event.getStage();
// Find target.
Target newTarget = null;
isValidTarget = false;
for (int i = 0, n = targets.size; i < n; i++) {
Target target = targets.get(i);
target.actor.stageToLocalCoordinates(Vector2.tmp.set(event.getStageX(), event.getStageY()));
if (target.actor.hit(Vector2.tmp.x, Vector2.tmp.y) == null) continue;
newTarget = target;
isValidTarget = target.drag(source, payload, Vector2.tmp.x, Vector2.tmp.y, pointer);
break;
}
if (newTarget != target) {
if (target != null) target.reset();
target = newTarget;
}
// Add/remove and position the drag actor.
Actor actor = null;
if (target != null) actor = isValidTarget ? payload.validDragActor : payload.invalidDragActor;
if (actor == null) actor = payload.dragActor;
if (actor == null) return;
if (dragActor != actor) {
if (dragActor != null) dragActor.remove();
dragActor = actor;
stage.addActor(actor);
}
float actorX = event.getStageX() + dragActorX;
float actorY = event.getStageY() + dragActorY - actor.getHeight();
if (actorX < 0) actorX = 0;
if (actorY < 0) actorY = 0;
if (actorX + actor.getWidth() > stage.getWidth()) actorX = stage.getWidth() - actor.getWidth();
if (actorY + actor.getHeight() > stage.getHeight()) actorY = stage.getHeight() - actor.getHeight();
actor.setPosition(actorX, actorY);
}
public void dragStop (InputEvent event, float x, float y, int pointer) {
if (payload == null) return;
if (isValidTarget) target.drop(source, payload);
source.dragStop(event, x, y, pointer, isValidTarget ? target : null);
DragAndDrop.this.source = null;
payload = null;
if (target != null) target.reset();
target = null;
isValidTarget = false;
if (dragActor != null) dragActor.remove();
dragActor = null;
}
};
listener.setTapSquareSize(tapSquareSize);
listener.setButton(button);
source.actor.addCaptureListener(listener);
}
|
diff --git a/bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/TopologyCapabilities.java b/bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/TopologyCapabilities.java
index d2cdcc0842..755c7c007d 100644
--- a/bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/TopologyCapabilities.java
+++ b/bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/TopologyCapabilities.java
@@ -1,261 +1,261 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.event.impl.jobs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo;
import org.apache.sling.event.impl.support.Environment;
import org.apache.sling.event.jobs.QueueConfiguration;
import org.apache.sling.event.jobs.consumer.JobConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The capabilities of a topology.
*/
public class TopologyCapabilities {
/** Logger. */
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/** Map: key: topic, value: sling IDs */
private final Map<String, List<InstanceDescription>> instanceCapabilities;
/** Round robin map. */
private final Map<String, Integer> roundRobinMap = new HashMap<String, Integer>();
/** Instance map. */
private final Map<String, InstanceDescription> instanceMap = new HashMap<String, InstanceDescription>();
/** Is this the leader of the cluster? */
private final boolean isLeader;
/** Is this still active? */
private volatile boolean active = true;
/** Change count. */
private final long changeCount;
/** All instances. */
private final Map<String, String> allInstances;
/** Instance comparator. */
private final InstanceDescriptionComparator instanceComparator;
/** Disable distribution flag. */
private final boolean disableDistribution;
public static final class InstanceDescriptionComparator implements Comparator<InstanceDescription> {
private final String localClusterId;
public InstanceDescriptionComparator(final String clusterId) {
this.localClusterId = clusterId;
}
@Override
public int compare(final InstanceDescription o1, final InstanceDescription o2) {
if ( o1.getSlingId().equals(o2.getSlingId()) ) {
return 0;
}
final boolean o1IsLocalCluster = localClusterId.equals(o1.getClusterView().getId());
final boolean o2IsLocalCluster = localClusterId.equals(o2.getClusterView().getId());
if ( o1IsLocalCluster && !o2IsLocalCluster ) {
return -1;
}
if ( !o1IsLocalCluster && o2IsLocalCluster ) {
return 1;
}
if ( o1IsLocalCluster ) {
if ( o1.isLeader() && !o2.isLeader() ) {
return -1;
} else if ( o2.isLeader() && !o1.isLeader() ) {
return 1;
}
}
return o1.getSlingId().compareTo(o2.getSlingId());
}
}
public static Map<String, String> getAllInstancesMap(final TopologyView view) {
final Map<String, String> allInstances = new TreeMap<String, String>();
for(final InstanceDescription desc : view.getInstances() ) {
final String topics = desc.getProperty(JobConsumer.PROPERTY_TOPICS);
if ( topics != null && topics.length() > 0 ) {
allInstances.put(desc.getSlingId(), topics);
} else {
allInstances.put(desc.getSlingId(), "");
}
}
return allInstances;
}
public TopologyCapabilities(final TopologyView view, final boolean disableDistribution, final long changeCount) {
this.disableDistribution = disableDistribution;
this.instanceComparator = new InstanceDescriptionComparator(view.getLocalInstance().getClusterView().getId());
this.changeCount = changeCount;
this.isLeader = view.getLocalInstance().isLeader();
this.allInstances = getAllInstancesMap(view);
final Map<String, List<InstanceDescription>> newCaps = new HashMap<String, List<InstanceDescription>>();
for(final InstanceDescription desc : view.getInstances() ) {
final String topics = desc.getProperty(JobConsumer.PROPERTY_TOPICS);
if ( topics != null && topics.length() > 0 ) {
this.logger.debug("Capabilities of {} : {}", desc.getSlingId(), topics);
for(final String topic : topics.split(",") ) {
List<InstanceDescription> list = newCaps.get(topic);
if ( list == null ) {
list = new ArrayList<InstanceDescription>();
newCaps.put(topic, list);
}
list.add(desc);
Collections.sort(list, this.instanceComparator);
}
}
this.instanceMap.put(desc.getSlingId(), desc);
}
this.instanceCapabilities = newCaps;
}
public boolean isSame(final Map<String, String> newAllInstancesMap) {
return this.allInstances.equals(newAllInstancesMap);
}
public void deactivate() {
this.active = false;
}
public boolean isActive() {
return this.active;
}
public long getChangeCount() {
return this.changeCount;
}
public boolean isActive(final String instanceId) {
return this.allInstances.containsKey(instanceId);
}
/**
* Is the current instance the leader?
*/
public boolean isLeader() {
return this.isLeader;
}
/**
* Return the potential targets (Sling IDs) sorted by ID
*/
public List<InstanceDescription> getPotentialTargets(final String jobTopic, final Map<String, Object> jobProperties) {
// calculate potential targets
final List<InstanceDescription> potentialTargets = new ArrayList<InstanceDescription>();
// first: topic targets - directly handling the topic
final List<InstanceDescription> topicTargets = this.instanceCapabilities.get(jobTopic);
if ( topicTargets != null ) {
potentialTargets.addAll(topicTargets);
}
// second: category targets - handling the topic category
final int pos = jobTopic.lastIndexOf('/');
if ( pos > 0 ) {
final String category = jobTopic.substring(0, pos + 1).concat("*");
final List<InstanceDescription> categoryTargets = this.instanceCapabilities.get(category);
if ( categoryTargets != null ) {
potentialTargets.addAll(categoryTargets);
}
}
// third: bridged consumers
final List<InstanceDescription> bridgedTargets = (jobProperties != null && jobProperties.containsKey(JobImpl.PROPERTY_BRIDGED_EVENT) ? this.instanceCapabilities.get("/") : null);
if ( bridgedTargets != null ) {
potentialTargets.addAll(bridgedTargets);
}
Collections.sort(potentialTargets, this.instanceComparator);
return potentialTargets;
}
/**
* Detect the target instance.
*/
public String detectTarget(final String jobTopic, final Map<String, Object> jobProperties,
final QueueInfo queueInfo) {
final List<InstanceDescription> potentialTargets = this.getPotentialTargets(jobTopic, jobProperties);
logger.debug("Potential targets for {} : {}", jobTopic, potentialTargets);
String createdOn = null;
if ( jobProperties != null ) {
createdOn = (String) jobProperties.get(org.apache.sling.event.jobs.Job.PROPERTY_JOB_CREATED_INSTANCE);
}
if ( createdOn == null ) {
createdOn = Environment.APPLICATION_ID;
}
final InstanceDescription createdOnInstance = this.instanceMap.get(createdOn);
if ( potentialTargets != null && potentialTargets.size() > 0 ) {
if ( createdOnInstance != null ) {
// create a list with local targets first.
final List<InstanceDescription> localTargets = new ArrayList<InstanceDescription>();
for(final InstanceDescription desc : potentialTargets) {
if ( desc.getClusterView().getId().equals(createdOnInstance.getClusterView().getId()) ) {
if ( !this.disableDistribution || desc.isLeader() ) {
localTargets.add(desc);
}
}
}
- if ( localTargets != null ) {
+ if ( localTargets.size() > 0 ) {
potentialTargets.clear();
potentialTargets.addAll(localTargets);
logger.debug("Potential targets filtered for {} : {}", jobTopic, potentialTargets);
}
}
if ( queueInfo.queueConfiguration.getType() == QueueConfiguration.Type.ORDERED ) {
// for ordered queues we always pick the first as we have to pick the same target on each cluster view
// on all instances (TODO - we could try to do some round robin of the whole queue)
final String result = potentialTargets.get(0).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
// TODO - this is a simple round robin which is not based on the actual load
// of the instances
Integer index = this.roundRobinMap.get(jobTopic);
if ( index == null ) {
index = 0;
}
if ( index >= potentialTargets.size() ) {
index = 0;
}
this.roundRobinMap.put(jobTopic, index + 1);
final String result = potentialTargets.get(index).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
return null;
}
}
| true | true | public String detectTarget(final String jobTopic, final Map<String, Object> jobProperties,
final QueueInfo queueInfo) {
final List<InstanceDescription> potentialTargets = this.getPotentialTargets(jobTopic, jobProperties);
logger.debug("Potential targets for {} : {}", jobTopic, potentialTargets);
String createdOn = null;
if ( jobProperties != null ) {
createdOn = (String) jobProperties.get(org.apache.sling.event.jobs.Job.PROPERTY_JOB_CREATED_INSTANCE);
}
if ( createdOn == null ) {
createdOn = Environment.APPLICATION_ID;
}
final InstanceDescription createdOnInstance = this.instanceMap.get(createdOn);
if ( potentialTargets != null && potentialTargets.size() > 0 ) {
if ( createdOnInstance != null ) {
// create a list with local targets first.
final List<InstanceDescription> localTargets = new ArrayList<InstanceDescription>();
for(final InstanceDescription desc : potentialTargets) {
if ( desc.getClusterView().getId().equals(createdOnInstance.getClusterView().getId()) ) {
if ( !this.disableDistribution || desc.isLeader() ) {
localTargets.add(desc);
}
}
}
if ( localTargets != null ) {
potentialTargets.clear();
potentialTargets.addAll(localTargets);
logger.debug("Potential targets filtered for {} : {}", jobTopic, potentialTargets);
}
}
if ( queueInfo.queueConfiguration.getType() == QueueConfiguration.Type.ORDERED ) {
// for ordered queues we always pick the first as we have to pick the same target on each cluster view
// on all instances (TODO - we could try to do some round robin of the whole queue)
final String result = potentialTargets.get(0).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
// TODO - this is a simple round robin which is not based on the actual load
// of the instances
Integer index = this.roundRobinMap.get(jobTopic);
if ( index == null ) {
index = 0;
}
if ( index >= potentialTargets.size() ) {
index = 0;
}
this.roundRobinMap.put(jobTopic, index + 1);
final String result = potentialTargets.get(index).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
return null;
}
| public String detectTarget(final String jobTopic, final Map<String, Object> jobProperties,
final QueueInfo queueInfo) {
final List<InstanceDescription> potentialTargets = this.getPotentialTargets(jobTopic, jobProperties);
logger.debug("Potential targets for {} : {}", jobTopic, potentialTargets);
String createdOn = null;
if ( jobProperties != null ) {
createdOn = (String) jobProperties.get(org.apache.sling.event.jobs.Job.PROPERTY_JOB_CREATED_INSTANCE);
}
if ( createdOn == null ) {
createdOn = Environment.APPLICATION_ID;
}
final InstanceDescription createdOnInstance = this.instanceMap.get(createdOn);
if ( potentialTargets != null && potentialTargets.size() > 0 ) {
if ( createdOnInstance != null ) {
// create a list with local targets first.
final List<InstanceDescription> localTargets = new ArrayList<InstanceDescription>();
for(final InstanceDescription desc : potentialTargets) {
if ( desc.getClusterView().getId().equals(createdOnInstance.getClusterView().getId()) ) {
if ( !this.disableDistribution || desc.isLeader() ) {
localTargets.add(desc);
}
}
}
if ( localTargets.size() > 0 ) {
potentialTargets.clear();
potentialTargets.addAll(localTargets);
logger.debug("Potential targets filtered for {} : {}", jobTopic, potentialTargets);
}
}
if ( queueInfo.queueConfiguration.getType() == QueueConfiguration.Type.ORDERED ) {
// for ordered queues we always pick the first as we have to pick the same target on each cluster view
// on all instances (TODO - we could try to do some round robin of the whole queue)
final String result = potentialTargets.get(0).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
// TODO - this is a simple round robin which is not based on the actual load
// of the instances
Integer index = this.roundRobinMap.get(jobTopic);
if ( index == null ) {
index = 0;
}
if ( index >= potentialTargets.size() ) {
index = 0;
}
this.roundRobinMap.put(jobTopic, index + 1);
final String result = potentialTargets.get(index).getSlingId();
logger.debug("Target for {} : {}", jobTopic, result);
return result;
}
return null;
}
|
diff --git a/src/main/org/testng/TestRunner.java b/src/main/org/testng/TestRunner.java
index f595d58..d23b72f 100644
--- a/src/main/org/testng/TestRunner.java
+++ b/src/main/org/testng/TestRunner.java
@@ -1,1077 +1,1076 @@
package org.testng;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.testng.internal.ClassHelper;
import org.testng.internal.ConfigurationGroupMethods;
import org.testng.internal.Constants;
import org.testng.internal.IInvoker;
import org.testng.internal.IMethodWorker;
import org.testng.internal.ITestResultNotifier;
import org.testng.internal.InvokedMethod;
import org.testng.internal.Invoker;
import org.testng.internal.MethodHelper;
import org.testng.internal.ResultMap;
import org.testng.internal.RunInfo;
import org.testng.internal.TestMethodWorker;
import org.testng.internal.TestNGClassFinder;
import org.testng.internal.TestNGMethod;
import org.testng.internal.TestNGMethodFinder;
import org.testng.internal.Utils;
import org.testng.internal.XmlMethodSelector;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.thread.IPooledExecutor;
import org.testng.internal.thread.ThreadUtil;
import org.testng.junit.IJUnitTestRunner;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlPackage;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
/**
* This class takes care of running one Test.
*
* @author Cedric Beust, Apr 26, 2004
* @author <a href = "mailto:the_mindstorm@evolva.ro">Alexandru Popescu</a>
*/
public class TestRunner implements ITestContext, ITestResultNotifier {
/* generated */
private static final long serialVersionUID = 4247820024988306670L;
private ISuite m_suite;
protected XmlTest m_xmlTest;
private String m_testName;
private boolean m_debug = false;
transient private List<XmlClass> m_testClassesFromXml= null;
transient private List<XmlPackage> m_packageNamesFromXml= null;
transient private IInvoker m_invoker= null;
transient private IAnnotationFinder m_annotationFinder= null;
/** ITestListeners support. */
transient private List<ITestListener> m_testListeners = new ArrayList<ITestListener>();
/**
* All the test methods we found, associated with their respective classes.
* Note that these test methods might belong to different classes.
* We pick which ones to run at runtime.
*/
private ITestNGMethod[] m_allTestMethods = new ITestNGMethod[0];
// Information about this test run
private Date m_startDate = null;
private Date m_endDate = null;
/** A map to keep track of Class <-> IClass. */
transient private Map<Class, ITestClass> m_classMap= new HashMap<Class, ITestClass>();
/** Where the reports will be created. */
private String m_outputDirectory= Constants.getDefaultValueFor(Constants.PROP_OUTPUT_DIR);
// The XML method selector (groups/methods included/excluded in XML)
private XmlMethodSelector m_xmlMethodSelector = new XmlMethodSelector();
private static int m_verbose = 1;
//
// These next fields contain all the configuration methods found on this class.
// At initialization time, they just contain all the various @Configuration methods
// found in all the classes we are going to run. When comes the time to run them,
// only a subset of them are run: those that are enabled and belong on the same class as
// (or a parent of) the test class.
//
private ITestNGMethod[] m_beforeClassMethods = {};
private ITestNGMethod[] m_afterClassMethods = {};
/** */
private ITestNGMethod[] m_beforeSuiteMethods = {};
private ITestNGMethod[] m_afterSuiteMethods = {};
private ITestNGMethod[] m_beforeXmlTestMethods = {};
private ITestNGMethod[] m_afterXmlTestMethods = {};
private List<ITestNGMethod> m_excludedMethods = new ArrayList<ITestNGMethod>();
private ConfigurationGroupMethods m_groupMethods = null;
// Meta groups
private Map<String, List<String>> m_metaGroups = new HashMap<String, List<String>>();
// All the tests that were run along with their result
private IResultMap m_passedTests = new ResultMap();
private IResultMap m_failedTests = new ResultMap();
private IResultMap m_failedButWithinSuccessPercentageTests = new ResultMap();
private IResultMap m_skippedTests = new ResultMap();
private RunInfo m_runInfo= new RunInfo();
// The host where this test was run, or null if run locally
private String m_host;
public TestRunner(ISuite suite,
XmlTest test,
String outputDirectory,
IAnnotationFinder finder) {
init(suite, test, outputDirectory, finder);
}
public TestRunner(ISuite suite, XmlTest test, IAnnotationFinder finder) {
init(suite, test, suite.getOutputDirectory(), finder);
}
public TestRunner(ISuite suite, XmlTest test) {
init(suite, test, suite.getOutputDirectory(), suite.getAnnotationFinder(test.getAnnotations()));
}
private void init(ISuite suite,
XmlTest test,
String outputDirectory,
IAnnotationFinder annotationFinder)
{
m_xmlTest= test;
m_suite = suite;
m_testName = test.getName();
m_host = suite.getHost();
m_testClassesFromXml= test.getXmlClasses();
m_packageNamesFromXml= test.getXmlPackages();
if(null != m_packageNamesFromXml) {
for(XmlPackage xp: m_packageNamesFromXml) {
m_testClassesFromXml.addAll(xp.getXmlClasses());
}
}
m_annotationFinder= annotationFinder;
m_invoker= new Invoker(this, this, m_suite.getSuiteState(), m_annotationFinder);
setVerbose(test.getVerbose());
if (suite.getParallel() != null) {
log(3, "Running the tests in parallel mode:" + suite.getParallel());
}
setOutputDirectory(outputDirectory);
// Finish our initialization
init();
}
public IInvoker getInvoker() {
return m_invoker;
}
public ITestNGMethod[] getBeforeSuiteMethods() {
return m_beforeSuiteMethods;
}
public ITestNGMethod[] getAfterSuiteMethods() {
return m_afterSuiteMethods;
}
public ITestNGMethod[] getBeforeTestConfigurationMethods() {
return m_beforeXmlTestMethods;
}
public ITestNGMethod[] getAfterTestConfigurationMethods() {
return m_afterXmlTestMethods;
}
private void init() {
initMetaGroups(m_xmlTest);
initRunInfo(m_xmlTest);
// Init methods and class map
// JUnit behavior is different and doesn't need this initialization step
if(!m_xmlTest.isJUnit()) {
initMethods();
}
}
/**
* Initialize meta groups
*/
private void initMetaGroups(XmlTest xmlTest) {
Map<String, List<String>> metaGroups = xmlTest.getMetaGroups();
for (String name : metaGroups.keySet()) {
addMetaGroup(name, metaGroups.get(name));
}
}
private void initRunInfo(final XmlTest xmlTest) {
// Groups
m_xmlMethodSelector.setIncludedGroups(createGroups(m_xmlTest.getIncludedGroups()));
m_xmlMethodSelector.setExcludedGroups(createGroups(m_xmlTest.getExcludedGroups()));
m_xmlMethodSelector.setExpression(m_xmlTest.getExpression());
// Methods
m_xmlMethodSelector.setXmlClasses(m_xmlTest.getXmlClasses());
m_runInfo.addMethodSelector(m_xmlMethodSelector, 10);
// Add user-specified method selectors (only class selectors, we can ignore
// script selectors here)
if (null != xmlTest.getMethodSelectors()) {
for (org.testng.xml.XmlMethodSelector selector : xmlTest.getMethodSelectors()) {
if (selector.getClassName() != null) {
IMethodSelector s = ClassHelper.createSelector(selector);
m_runInfo.addMethodSelector(s, selector.getPriority());
}
}
}
}
private void initMethods() {
//
// Calculate all the methods we need to invoke
//
List<ITestNGMethod> beforeClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> testMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeXmlTestMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterXmlTestMethods = new ArrayList<ITestNGMethod>();
ITestClassFinder testClassFinder= new TestNGClassFinder(Utils.xmlClassesToClasses(m_testClassesFromXml),
null,
m_xmlTest,
m_annotationFinder);
ITestMethodFinder testMethodFinder= new TestNGMethodFinder(m_runInfo, m_annotationFinder);
//
// Initialize TestClasses
//
IClass[] classes = testClassFinder.findTestClasses();
for (IClass ic : classes) {
// Create TestClass
ITestClass tc = new TestClass(ic,
m_testName,
testMethodFinder,
m_annotationFinder,
- m_runInfo,
- this);
+ m_runInfo);
m_classMap.put(ic.getRealClass(), tc);
}
//
// Calculate groups methods
//
Map<String, List<ITestNGMethod>> beforeGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), true);
Map<String, List<ITestNGMethod>> afterGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), false);
//
// Walk through all the TestClasses, store their method
// and initialize them with the correct ITestClass
//
for (ITestClass tc : m_classMap.values()) {
fixMethodsWithClass(tc.getBeforeClassMethods(), tc, beforeClassMethods);
fixMethodsWithClass(tc.getBeforeTestMethods(), tc, null); // HINT: does not link back to beforeTestMethods
fixMethodsWithClass(tc.getTestMethods(), tc, testMethods);
fixMethodsWithClass(tc.getAfterTestMethods(), tc, null);
fixMethodsWithClass(tc.getAfterClassMethods(), tc, afterClassMethods);
fixMethodsWithClass(tc.getBeforeSuiteMethods(), tc, beforeSuiteMethods);
fixMethodsWithClass(tc.getAfterSuiteMethods(), tc, afterSuiteMethods);
fixMethodsWithClass(tc.getBeforeTestConfigurationMethods(), tc, beforeXmlTestMethods);
fixMethodsWithClass(tc.getAfterTestConfigurationMethods(), tc, afterXmlTestMethods);
fixMethodsWithClass(tc.getBeforeGroupsMethods(), tc,
MethodHelper.uniqueMethodList(beforeGroupMethods.values()));
fixMethodsWithClass(tc.getAfterGroupsMethods(), tc,
MethodHelper.uniqueMethodList(afterGroupMethods.values()));
}
m_runInfo.setTestMethods(testMethods);
//
// Sort the methods
//
m_beforeSuiteMethods = MethodHelper.collectAndOrderMethods(beforeSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
m_beforeXmlTestMethods = MethodHelper.collectAndOrderMethods(beforeXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_beforeClassMethods = MethodHelper.collectAndOrderMethods(beforeClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_allTestMethods = MethodHelper.collectAndOrderMethods(testMethods,
true,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterClassMethods = MethodHelper.collectAndOrderMethods(afterClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterXmlTestMethods = MethodHelper.collectAndOrderMethods(afterXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_afterSuiteMethods = MethodHelper.collectAndOrderMethods(afterSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
// shared group methods
m_groupMethods = new ConfigurationGroupMethods(m_allTestMethods, beforeGroupMethods, afterGroupMethods);
}
private static void ppp(String s) {
if (true) {
System.out.println("[TestRunner] " + s);
}
}
private void fixMethodsWithClass(ITestNGMethod[] methods,
ITestClass testCls,
List<ITestNGMethod> methodList) {
for (ITestNGMethod itm : methods) {
itm.setTestClass(testCls);
if (methodList != null) {
methodList.add(itm);
}
}
}
public Collection<ITestClass> getIClass() {
return m_classMap.values();
}
/**
* FIXME: not used
*/
private IClass findIClass(IClass[] classes, Class cls) {
for (IClass c : classes) {
if (c.getRealClass().equals(cls)) {
return c;
}
}
return null;
}
public String getName() {
return m_testName;
}
public String[] getIncludedGroups() {
Map<String, String> ig= m_xmlMethodSelector.getIncludedGroups();
String[] result= (String[]) ig.values().toArray((new String[ig.size()]));
return result;
}
public String[] getExcludedGroups() {
Map<String, String> eg= m_xmlMethodSelector.getExcludedGroups();
String[] result= (String[]) eg.values().toArray((new String[eg.size()]));
return result;
}
public void setTestName(String name) {
m_testName = name;
}
public void setOutputDirectory(String od) {
if (od == null) { m_outputDirectory = null; return; } //for maven2
File file = new File(od);
file.mkdirs();
m_outputDirectory= file.getAbsolutePath();
}
public String getOutputDirectory() {
return m_outputDirectory;
}
/**
* @return Returns the endDate.
*/
public Date getEndDate() {
return m_endDate;
}
/**
* @return Returns the startDate.
*/
public Date getStartDate() {
return m_startDate;
}
private void addMetaGroup(String name, List<String> groupNames) {
m_metaGroups.put(name, groupNames);
}
/**
* Calculate the transitive closure of all the MetaGroups
*
* @param groups
* @param unfinishedGroups
* @param result The transitive closure containing all the groups found
*/
private void collectGroups(String[] groups,
List<String> unfinishedGroups,
Map<String, String> result) {
for (String gn : groups) {
List<String> subGroups = m_metaGroups.get(gn);
if (null != subGroups) {
for (String sg : subGroups) {
if (null == result.get(sg)) {
result.put(sg, sg);
unfinishedGroups.add(sg);
}
}
}
}
}
private Map<String, String> createGroups(List<String> groups) {
return createGroups((String[]) groups.toArray(new String[groups.size()]));
}
private Map<String, String> createGroups(String[] groups) {
Map<String, String> result= new HashMap<String, String>();
// Groups that were passed on the command line
for (String group : groups) {
result.put(group, group);
}
// See if we have any MetaGroups and
// expand them if they match one of the groups
// we have just been passed
List<String> unfinishedGroups = new ArrayList<String>();
if (m_metaGroups.size() > 0) {
collectGroups(groups, unfinishedGroups, result);
// Do we need to loop over unfinished groups?
while (unfinishedGroups.size() > 0) {
String[] uGroups = (String[]) unfinishedGroups.toArray(new String[unfinishedGroups.size()]);
unfinishedGroups = new ArrayList<String>();
collectGroups(uGroups, unfinishedGroups, result);
}
}
// Utils.dumpMap(result);
return result;
}
/**
* The main entry method for TestRunner.
*
* This is where all the hard work is done:
* - Invoke configuration methods
* - Invoke test methods
* - Catch exceptions
* - Collect results
* - Invoke listeners
* - etc...
*/
public void run() {
beforeRun();
try {
XmlTest test= getTest();
if(test.isJUnit()) {
privateRunJUnit(test);
}
else {
privateRun(test);
}
}
finally {
afterRun();
}
}
/** Before run preparements. */
private void beforeRun() {
//
// Log the start date
//
m_startDate = new Date(System.currentTimeMillis());
// Log start
logStart();
// Invoke listeners
fireEvent(true /*start*/);
}
private void privateRunJUnit(XmlTest xmlTest) {
final Class[] classes= Utils.xmlClassesToClasses(m_testClassesFromXml);
final List<ITestNGMethod> runMethods= new ArrayList<ITestNGMethod>();
List<IMethodWorker> workers= new ArrayList<IMethodWorker>();
// FIXME: directly referincing JUnitTestRunner which uses JUnit classes
// may result in an class resolution exception under different JVMs
// The resolution process is not specified in the JVM spec with a specific implementation,
// so it can be eager => failure
workers.add(new IMethodWorker() {
/**
* @see org.testng.internal.IMethodWorker#getMaxTimeOut()
*/
public long getMaxTimeOut() {
return 0;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
for(Class tc: classes) {
IJUnitTestRunner tr= ClassHelper.createTestRunner(TestRunner.this);
try {
tr.run(tc);
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
runMethods.addAll(tr.getTestMethods());
}
}
}
});
runWorkers(workers, "" /* JUnit does not support parallel */);
m_allTestMethods= runMethods.toArray(new ITestNGMethod[runMethods.size()]);
}
public void privateRun(XmlTest xmlTest) {
Map<String, String> params = xmlTest.getParameters();
//
// Calculate the lists of tests that can be run in sequence and in parallel
//
List<List<ITestNGMethod>> sequentialList= new ArrayList<List<ITestNGMethod>>();
List<ITestNGMethod> parallelList= new ArrayList<ITestNGMethod>();
computeTestLists(sequentialList, parallelList);
log(3, "Found " + (sequentialList.size() + parallelList.size()) + " applicable methods");
//
// Find out all the group methods
//
// m_groupMethods = findGroupMethods(m_classMap.values());
//
// Create the workers
//
List<TestMethodWorker> workers = new ArrayList<TestMethodWorker>();
// These two variables are used throughout the workers to keep track
// of what beforeClass/afterClass methods have been invoked
Map<ITestClass, ITestClass> beforeClassMethods = new HashMap<ITestClass, ITestClass>();
Map<ITestClass, ITestClass> afterClassMethods = new HashMap<ITestClass, ITestClass>();
ClassMethodMap cmm = new ClassMethodMap(m_allTestMethods);
// All the sequential tests are place in one worker, guaranteeing they
// will be invoked sequentially
if (sequentialList.size() > 0) {
for (List<ITestNGMethod> sl : sequentialList) {
workers.add(new TestMethodWorker(m_invoker,
sl.toArray(new ITestNGMethod[sl.size()]),
m_xmlTest.getSuite(),
params,
beforeClassMethods,
afterClassMethods,
m_allTestMethods,
m_groupMethods,
cmm));
}
}
// All the parallel tests are placed in a separate worker, so they can be
// invoked in parallel
if (parallelList.size() > 0) {
for (ITestNGMethod tm : parallelList) {
workers.add(new TestMethodWorker(m_invoker,
new ITestNGMethod[] { tm },
m_xmlTest.getSuite(),
params,
beforeClassMethods,
afterClassMethods,
m_allTestMethods,
m_groupMethods,
cmm));
}
}
runWorkers(workers, xmlTest.getParallel());
}
//
// Invoke the workers
//
private void runWorkers(List<? extends IMethodWorker> workers, String parallelMode) {
if (XmlSuite.PARALLEL_METHODS.equals(parallelMode)
|| "true".equalsIgnoreCase(parallelMode))
{
//
// Parallel run
//
// Default timeout for individual methods: 10 seconds
long maxTimeOut = m_xmlTest.getTimeOut(10 * 1000);
for (IMethodWorker tmw : workers) {
long mt= tmw.getMaxTimeOut();
if (mt > maxTimeOut) {
maxTimeOut= mt;
}
}
ThreadUtil.execute(workers, m_xmlTest.getSuite().getThreadCount(), maxTimeOut, false);
}
else {
//
// Sequential run
//
for (IMethodWorker tmw : workers) {
tmw.run();
}
}
}
private void afterRun() {
//
// Log the end date
//
m_endDate = new Date(System.currentTimeMillis());
if (getVerbose() >= 3) {
dumpInvokedMethods();
}
// Invoke listeners
fireEvent(false /*stop*/);
// Statistics
// logResults();
}
/**
* @param regexps
* @param group
* @return true if the map contains at least one regexp that matches the
* given group
*/
private boolean containsString(Map<String, String> regexps, String group) {
for (String regexp : regexps.values()) {
boolean match = Pattern.matches(regexp, group);
if (match) {
return true;
}
}
return false;
}
/**
* Creates the
* @param sequentialList
* @param parallelList
*/
private void computeTestLists(List<List<ITestNGMethod>> sl,
List<ITestNGMethod> parallelList)
{
Map<String, String> groupsDependedUpon= new HashMap<String, String>();
Map<String, String> methodsDependedUpon= new HashMap<String, String>();
Map<String, List<ITestNGMethod>> sequentialAttributeList = new HashMap<String, List<ITestNGMethod>>();
List<ITestNGMethod> sequentialList = new ArrayList<ITestNGMethod>();
for (int i= m_allTestMethods.length - 1; i >= 0; i--) {
ITestNGMethod tm= m_allTestMethods[i];
//
// If the class this method belongs to has @Test(sequential = true), we
// put this method in the sequential list right away
//
Class cls = tm.getMethod().getDeclaringClass();
org.testng.internal.annotations.ITest test =
(org.testng.internal.annotations.ITest) m_annotationFinder.
findAnnotation(cls, org.testng.internal.annotations.ITest.class);
if (test != null) {
if (test.getSequential()) {
String className = cls.getName();
List<ITestNGMethod> list = sequentialAttributeList.get(className);
if (list == null) {
list = new ArrayList<ITestNGMethod>();
sequentialAttributeList.put(className, list);
}
list.add(0, tm);
continue;
}
}
//
// Otherwise, determine if it depends on other methods/groups or if
// it is depended upon
//
String[] currentGroups = tm.getGroups();
String[] currentGroupsDependedUpon= tm.getGroupsDependedUpon();
String[] currentMethodsDependedUpon= tm.getMethodsDependedUpon();
String thisMethodName = tm.getMethod().getDeclaringClass().getName() + "." +
tm.getMethod().getName();
if (currentGroupsDependedUpon.length > 0) {
for (String gdu : currentGroupsDependedUpon) {
groupsDependedUpon.put(gdu, gdu);
}
sequentialList.add(0, tm);
}
else if (currentMethodsDependedUpon.length > 0) {
for (String cmu : currentMethodsDependedUpon) {
methodsDependedUpon.put(cmu, cmu);
}
sequentialList.add(0, tm);
}
// Is there a method that depends on the current method?
else if (containsString(methodsDependedUpon, thisMethodName)) {
sequentialList.add(0, tm);
}
else if (currentGroups.length > 0) {
boolean isSequential= false;
for (String group : currentGroups) {
if (containsString(groupsDependedUpon, group)) {
sequentialList.add(0, tm);
isSequential = true;
break;
}
}
if (!isSequential) {
parallelList.add(0, tm);
}
}
else {
parallelList.add(0, tm);
}
}
//
// Put all the sequential methods in the output argument
//
if(sequentialList.size() > 0) {
sl.add(sequentialList);
}
for (List<ITestNGMethod> l : sequentialAttributeList.values()) {
sl.add(l);
}
//
// Finally, sort the parallel methods by classes
//
Collections.sort(parallelList, TestNGMethod.SORT_BY_CLASS);
if (getVerbose() >= 2) {
log(3, "WILL BE RUN IN RANDOM ORDER:");
for (ITestNGMethod tm : parallelList) {
log(3, " " + tm);
}
log(3, "WILL BE RUN SEQUENTIALLY:");
for (List<ITestNGMethod> l : sl) {
for (ITestNGMethod tm : l) {
log(3, " " + tm);
}
log(3, "====");
}
log(3, "===");
}
}
/**
* TODO: not used
*/
// private void invokeClassConfigurations(ITestNGMethod[] classMethods,
// XmlTest xmlTest,
// boolean before) {
// for (IClass testClass : m_classMap.values()) {
// m_invoker.invokeConfigurations(testClass,
// null,
// classMethods,
// m_xmlTest.getSuite(),
// xmlTest.getParameters(),
// null /* instance */);
//
// String msg= "Marking class " + testClass + " as " + (before ? "before" : "after")
// + "ConfigurationClass =true";
//
// log(3, msg);
// }
// }
/**
* Logs the beginning of the {@link #privateRun()}.
*/
private void logStart() {
log(3,
"Running test " + m_testName + " on " + m_classMap.size() + " " + " classes, "
+ " included groups:[" + mapToString(m_xmlMethodSelector.getIncludedGroups())
+ "] excluded groups:[" + mapToString(m_xmlMethodSelector.getExcludedGroups()) + "]");
if (getVerbose() >= 3) {
for (ITestClass tc : m_classMap.values()) {
((TestClass) tc).dump();
}
}
}
/**
* Trigger the start/finish event.
*
* @param isStart <tt>true</tt> if the event is for start, <tt>false</tt> if the
* event is for finish
*/
private void fireEvent(boolean isStart) {
for (ITestListener itl : m_testListeners) {
if (isStart) {
itl.onStart(this);
}
else {
itl.onFinish(this);
}
}
}
/////
// ITestResultNotifier
//
public void addPassedTest(ITestNGMethod tm, ITestResult tr) {
synchronized(m_passedTests) {
m_passedTests.addResult(tr, tm);
}
}
public Set<ITestResult> getPassedTests(ITestNGMethod tm) {
return m_passedTests.getResults(tm);
}
public void addSkippedTest(ITestNGMethod tm, ITestResult tr) {
synchronized(m_skippedTests) {
m_skippedTests.addResult(tr, tm);
}
}
public void addInvokedMethod(InvokedMethod im) {
synchronized(m_invokedMethods) {
m_invokedMethods.add(im);
}
}
public void addFailedTest(ITestNGMethod testMethod, ITestResult result) {
logFailedTest(testMethod, result, false /* withinSuccessPercentage */);
}
public void addFailedButWithinSuccessPercentageTest(ITestNGMethod testMethod,
ITestResult result) {
logFailedTest(testMethod, result, true /* withinSuccessPercentage */);
}
public XmlTest getTest() {
return m_xmlTest;
}
public List<ITestListener> getTestListeners() {
return m_testListeners;
}
//
// ITestResultNotifier
/////
/**
* FIXME: not used
*
* @param declaringClass
* @return
*/
private IClass findTestClass(Class<?> declaringClass) {
IClass result= m_classMap.get(declaringClass);
if (null == result) {
for (Class cls : m_classMap.keySet()) {
if (declaringClass.isAssignableFrom(cls)) {
result= m_classMap.get(cls);
assert null != result : "Should never happen";
}
}
}
return result;
}
public ITestNGMethod[] getTestMethods() {
return m_allTestMethods;
}
private void logFailedTest(ITestNGMethod method,
ITestResult tr,
boolean withinSuccessPercentage) {
if (withinSuccessPercentage) {
synchronized(m_failedButWithinSuccessPercentageTests) {
m_failedButWithinSuccessPercentageTests.addResult(tr, method);
}
}
else {
synchronized(m_failedTests) {
m_failedTests.addResult(tr, method);
}
}
}
private String mapToString(Map m) {
StringBuffer result= new StringBuffer();
for (Object o : m.values()) {
result.append(o.toString()).append(" ");
}
return result.toString();
}
private void log(int level, String s) {
Utils.log("TestRunner", level, s);
}
public static int getVerbose() {
return m_verbose;
}
public void setVerbose(int n) {
m_verbose = n;
}
private void log(String s) {
Utils.log("TestRunner", 2, s);
}
public IResultMap getPassedTests() {
return m_passedTests;
}
public IResultMap getSkippedTests() {
return m_skippedTests;
}
public IResultMap getFailedTests() {
return m_failedTests;
}
public IResultMap getFailedButWithinSuccessPercentageTests() {
return m_failedButWithinSuccessPercentageTests;
}
/////
// Listeners
//
public void addTestListener(ITestListener il) {
m_testListeners.add(il);
}
//
// Listeners
/////
/**
* @return Returns the suite.
*/
public ISuite getSuite() {
return m_suite;
}
private List<InvokedMethod> m_invokedMethods = new ArrayList<InvokedMethod>();
public ITestNGMethod[] getAllTestMethods() {
return m_allTestMethods;
}
private void dumpInvokedMethods() {
System.out.println("\n*********** INVOKED METHODS\n");
for (InvokedMethod im : m_invokedMethods) {
if (im.isTestMethod()) {
System.out.print("\t\t");
}
else if (im.isConfigurationMethod()) {
System.out.print("\t");
}
else {
continue;
}
System.out.println("" + im);
}
System.out.println("\n***********\n");
}
/**
* @return
*/
public List<ITestNGMethod> getInvokedMethods() {
List<ITestNGMethod> result= new ArrayList<ITestNGMethod>();
for (InvokedMethod im : m_invokedMethods) {
ITestNGMethod tm= im.getTestMethod();
tm.setDate(im.getDate());
result.add(tm);
}
return result;
}
public String getHost() {
return m_host;
}
public Collection<ITestNGMethod> getExcludedMethods() {
Map<ITestNGMethod, ITestNGMethod> vResult =
new HashMap<ITestNGMethod, ITestNGMethod>();
for (ITestNGMethod m : m_excludedMethods) {
vResult.put(m, m);
}
return vResult.keySet();
}
} // TestRunner
| true | true | private void initMethods() {
//
// Calculate all the methods we need to invoke
//
List<ITestNGMethod> beforeClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> testMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeXmlTestMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterXmlTestMethods = new ArrayList<ITestNGMethod>();
ITestClassFinder testClassFinder= new TestNGClassFinder(Utils.xmlClassesToClasses(m_testClassesFromXml),
null,
m_xmlTest,
m_annotationFinder);
ITestMethodFinder testMethodFinder= new TestNGMethodFinder(m_runInfo, m_annotationFinder);
//
// Initialize TestClasses
//
IClass[] classes = testClassFinder.findTestClasses();
for (IClass ic : classes) {
// Create TestClass
ITestClass tc = new TestClass(ic,
m_testName,
testMethodFinder,
m_annotationFinder,
m_runInfo,
this);
m_classMap.put(ic.getRealClass(), tc);
}
//
// Calculate groups methods
//
Map<String, List<ITestNGMethod>> beforeGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), true);
Map<String, List<ITestNGMethod>> afterGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), false);
//
// Walk through all the TestClasses, store their method
// and initialize them with the correct ITestClass
//
for (ITestClass tc : m_classMap.values()) {
fixMethodsWithClass(tc.getBeforeClassMethods(), tc, beforeClassMethods);
fixMethodsWithClass(tc.getBeforeTestMethods(), tc, null); // HINT: does not link back to beforeTestMethods
fixMethodsWithClass(tc.getTestMethods(), tc, testMethods);
fixMethodsWithClass(tc.getAfterTestMethods(), tc, null);
fixMethodsWithClass(tc.getAfterClassMethods(), tc, afterClassMethods);
fixMethodsWithClass(tc.getBeforeSuiteMethods(), tc, beforeSuiteMethods);
fixMethodsWithClass(tc.getAfterSuiteMethods(), tc, afterSuiteMethods);
fixMethodsWithClass(tc.getBeforeTestConfigurationMethods(), tc, beforeXmlTestMethods);
fixMethodsWithClass(tc.getAfterTestConfigurationMethods(), tc, afterXmlTestMethods);
fixMethodsWithClass(tc.getBeforeGroupsMethods(), tc,
MethodHelper.uniqueMethodList(beforeGroupMethods.values()));
fixMethodsWithClass(tc.getAfterGroupsMethods(), tc,
MethodHelper.uniqueMethodList(afterGroupMethods.values()));
}
m_runInfo.setTestMethods(testMethods);
//
// Sort the methods
//
m_beforeSuiteMethods = MethodHelper.collectAndOrderMethods(beforeSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
m_beforeXmlTestMethods = MethodHelper.collectAndOrderMethods(beforeXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_beforeClassMethods = MethodHelper.collectAndOrderMethods(beforeClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_allTestMethods = MethodHelper.collectAndOrderMethods(testMethods,
true,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterClassMethods = MethodHelper.collectAndOrderMethods(afterClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterXmlTestMethods = MethodHelper.collectAndOrderMethods(afterXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_afterSuiteMethods = MethodHelper.collectAndOrderMethods(afterSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
// shared group methods
m_groupMethods = new ConfigurationGroupMethods(m_allTestMethods, beforeGroupMethods, afterGroupMethods);
}
| private void initMethods() {
//
// Calculate all the methods we need to invoke
//
List<ITestNGMethod> beforeClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> testMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterClassMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterSuiteMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> beforeXmlTestMethods = new ArrayList<ITestNGMethod>();
List<ITestNGMethod> afterXmlTestMethods = new ArrayList<ITestNGMethod>();
ITestClassFinder testClassFinder= new TestNGClassFinder(Utils.xmlClassesToClasses(m_testClassesFromXml),
null,
m_xmlTest,
m_annotationFinder);
ITestMethodFinder testMethodFinder= new TestNGMethodFinder(m_runInfo, m_annotationFinder);
//
// Initialize TestClasses
//
IClass[] classes = testClassFinder.findTestClasses();
for (IClass ic : classes) {
// Create TestClass
ITestClass tc = new TestClass(ic,
m_testName,
testMethodFinder,
m_annotationFinder,
m_runInfo);
m_classMap.put(ic.getRealClass(), tc);
}
//
// Calculate groups methods
//
Map<String, List<ITestNGMethod>> beforeGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), true);
Map<String, List<ITestNGMethod>> afterGroupMethods= MethodHelper.findGroupsMethods(m_classMap.values(), false);
//
// Walk through all the TestClasses, store their method
// and initialize them with the correct ITestClass
//
for (ITestClass tc : m_classMap.values()) {
fixMethodsWithClass(tc.getBeforeClassMethods(), tc, beforeClassMethods);
fixMethodsWithClass(tc.getBeforeTestMethods(), tc, null); // HINT: does not link back to beforeTestMethods
fixMethodsWithClass(tc.getTestMethods(), tc, testMethods);
fixMethodsWithClass(tc.getAfterTestMethods(), tc, null);
fixMethodsWithClass(tc.getAfterClassMethods(), tc, afterClassMethods);
fixMethodsWithClass(tc.getBeforeSuiteMethods(), tc, beforeSuiteMethods);
fixMethodsWithClass(tc.getAfterSuiteMethods(), tc, afterSuiteMethods);
fixMethodsWithClass(tc.getBeforeTestConfigurationMethods(), tc, beforeXmlTestMethods);
fixMethodsWithClass(tc.getAfterTestConfigurationMethods(), tc, afterXmlTestMethods);
fixMethodsWithClass(tc.getBeforeGroupsMethods(), tc,
MethodHelper.uniqueMethodList(beforeGroupMethods.values()));
fixMethodsWithClass(tc.getAfterGroupsMethods(), tc,
MethodHelper.uniqueMethodList(afterGroupMethods.values()));
}
m_runInfo.setTestMethods(testMethods);
//
// Sort the methods
//
m_beforeSuiteMethods = MethodHelper.collectAndOrderMethods(beforeSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
m_beforeXmlTestMethods = MethodHelper.collectAndOrderMethods(beforeXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_beforeClassMethods = MethodHelper.collectAndOrderMethods(beforeClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_allTestMethods = MethodHelper.collectAndOrderMethods(testMethods,
true,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterClassMethods = MethodHelper.collectAndOrderMethods(afterClassMethods,
false,
m_runInfo,
m_annotationFinder,
m_excludedMethods);
m_afterXmlTestMethods = MethodHelper.collectAndOrderMethods(afterXmlTestMethods,
false,
m_runInfo,
m_annotationFinder,
true, // CQ added by me
m_excludedMethods);
m_afterSuiteMethods = MethodHelper.collectAndOrderMethods(afterSuiteMethods,
false,
m_runInfo,
m_annotationFinder,
true /* unique */,
m_excludedMethods);
// shared group methods
m_groupMethods = new ConfigurationGroupMethods(m_allTestMethods, beforeGroupMethods, afterGroupMethods);
}
|
diff --git a/org.openscada.ca.client.jaxws/src/org/openscada/ca/client/jaxws/RemoteConfigurationClient.java b/org.openscada.ca.client.jaxws/src/org/openscada/ca/client/jaxws/RemoteConfigurationClient.java
index 9ca4cdfe1..9306921df 100644
--- a/org.openscada.ca.client.jaxws/src/org/openscada/ca/client/jaxws/RemoteConfigurationClient.java
+++ b/org.openscada.ca.client.jaxws/src/org/openscada/ca/client/jaxws/RemoteConfigurationClient.java
@@ -1,107 +1,110 @@
/*
* This file is part of the OpenSCADA project
* Copyright (C) 2006-2010 TH4 SYSTEMS GmbH (http://th4-systems.com)
*
* OpenSCADA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenSCADA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenSCADA. If not, see
* <http://opensource.org/licenses/lgpl-3.0.html> for a copy of the LGPLv3 License.
*/
package org.openscada.ca.client.jaxws;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
import org.openscada.ca.servlet.jaxws.RemoteConfigurationAdministrator;
public class RemoteConfigurationClient
{
private static final QName serviceName = QName.valueOf ( "{http://jaxws.servlet.ca.openscada.org/}ConfigurationAdministratorServiceService" );
private final RemoteConfigurationAdministrator port;
public RemoteConfigurationClient ( final String hostname, final int port ) throws MalformedURLException
{
this ( new URL ( String.format ( "http://%s:%s/org.openscada.ca.servlet.jaxws?WSDL", hostname, port ) ), serviceName );
}
public RemoteConfigurationClient ( final String url ) throws MalformedURLException
{
this ( new URL ( url ), serviceName );
}
public RemoteConfigurationClient ( final String url, final String serviceName ) throws MalformedURLException
{
this ( new URL ( url ), QName.valueOf ( serviceName ) );
}
public RemoteConfigurationClient () throws MalformedURLException
{
this ( new URL ( "http://localhost:9999/org.openscada.ca.servlet.jaxws?WSDL" ), serviceName );
}
public RemoteConfigurationClient ( final URL url ) throws MalformedURLException
{
this ( url, serviceName );
}
public RemoteConfigurationClient ( final URL url, final QName serviceName )
{
this.port = createPort ( url );
}
protected RemoteConfigurationAdministrator createPort ( final URL url )
{
final Service service = javax.xml.ws.Service.create ( url, serviceName );
final RemoteConfigurationAdministrator port = service.getPort ( RemoteConfigurationAdministrator.class );
// adding "Accept-Encoding"
final Map<String, List<String>> httpHeaders = new HashMap<String, List<String>> ();
httpHeaders.put ( "Accept-Encoding", Collections.singletonList ( "gzip" ) );
final Map<String, Object> requestContext = ( (BindingProvider)port ).getRequestContext ();
requestContext.put ( MessageContext.HTTP_REQUEST_HEADERS, httpHeaders );
// security
final String user = url.getUserInfo ();
- final int findColon = user.indexOf ( ':' );
- if ( findColon > 0 && findColon + 1 < user.length () )
+ if ( user != null )
{
- requestContext.put ( BindingProvider.USERNAME_PROPERTY, user.substring ( 0, findColon ) );
- requestContext.put ( BindingProvider.PASSWORD_PROPERTY, user.substring ( findColon + 1 ) );
- }
- else
- {
- requestContext.put ( BindingProvider.USERNAME_PROPERTY, user );
+ final int findColon = user.indexOf ( ':' );
+ if ( ( findColon > 0 ) && ( ( findColon + 1 ) < user.length () ) )
+ {
+ requestContext.put ( BindingProvider.USERNAME_PROPERTY, user.substring ( 0, findColon ) );
+ requestContext.put ( BindingProvider.PASSWORD_PROPERTY, user.substring ( findColon + 1 ) );
+ }
+ else
+ {
+ requestContext.put ( BindingProvider.USERNAME_PROPERTY, user );
+ }
}
return port;
}
public RemoteConfigurationAdministrator getPort ()
{
return this.port;
}
}
| false | true | protected RemoteConfigurationAdministrator createPort ( final URL url )
{
final Service service = javax.xml.ws.Service.create ( url, serviceName );
final RemoteConfigurationAdministrator port = service.getPort ( RemoteConfigurationAdministrator.class );
// adding "Accept-Encoding"
final Map<String, List<String>> httpHeaders = new HashMap<String, List<String>> ();
httpHeaders.put ( "Accept-Encoding", Collections.singletonList ( "gzip" ) );
final Map<String, Object> requestContext = ( (BindingProvider)port ).getRequestContext ();
requestContext.put ( MessageContext.HTTP_REQUEST_HEADERS, httpHeaders );
// security
final String user = url.getUserInfo ();
final int findColon = user.indexOf ( ':' );
if ( findColon > 0 && findColon + 1 < user.length () )
{
requestContext.put ( BindingProvider.USERNAME_PROPERTY, user.substring ( 0, findColon ) );
requestContext.put ( BindingProvider.PASSWORD_PROPERTY, user.substring ( findColon + 1 ) );
}
else
{
requestContext.put ( BindingProvider.USERNAME_PROPERTY, user );
}
return port;
}
| protected RemoteConfigurationAdministrator createPort ( final URL url )
{
final Service service = javax.xml.ws.Service.create ( url, serviceName );
final RemoteConfigurationAdministrator port = service.getPort ( RemoteConfigurationAdministrator.class );
// adding "Accept-Encoding"
final Map<String, List<String>> httpHeaders = new HashMap<String, List<String>> ();
httpHeaders.put ( "Accept-Encoding", Collections.singletonList ( "gzip" ) );
final Map<String, Object> requestContext = ( (BindingProvider)port ).getRequestContext ();
requestContext.put ( MessageContext.HTTP_REQUEST_HEADERS, httpHeaders );
// security
final String user = url.getUserInfo ();
if ( user != null )
{
final int findColon = user.indexOf ( ':' );
if ( ( findColon > 0 ) && ( ( findColon + 1 ) < user.length () ) )
{
requestContext.put ( BindingProvider.USERNAME_PROPERTY, user.substring ( 0, findColon ) );
requestContext.put ( BindingProvider.PASSWORD_PROPERTY, user.substring ( findColon + 1 ) );
}
else
{
requestContext.put ( BindingProvider.USERNAME_PROPERTY, user );
}
}
return port;
}
|
diff --git a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderTest.java b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderTest.java
index 547272f9c..21cf3f341 100644
--- a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderTest.java
+++ b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderTest.java
@@ -1,49 +1,51 @@
package org.opentripplanner.graph_builder.impl.osm;
import java.io.File;
import junit.framework.TestCase;
import org.junit.Test;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.Turn;
public class OpenStreetMapGraphBuilderTest extends TestCase {
@Test
public void testGraphBuilder() throws Exception {
Graph gg = new Graph();
OpenStreetMapGraphBuilderImpl loader = new OpenStreetMapGraphBuilderImpl();
FileBasedOpenStreetMapProviderImpl provider = new FileBasedOpenStreetMapProviderImpl();
File file = new File(getClass().getResource("map.osm.gz").getFile());
provider.setPath(file);
loader.setProvider(provider);
loader.buildGraph(gg);
Vertex v1 = gg.getVertex("osm node 288969929 at 52");
Vertex v2 = gg.getVertex("osm node 288969929 at 141");
Vertex v3 = gg.getVertex("osm node 288969929 at 219");
v1.getName();
- assertTrue (v1.getName().contains("Kamiennogórska") && v1.getName().contains("Mariana Smoluchowskiego"));
+ assertTrue("name of v1 must be like \"Kamiennog�rska at Marian Smoluchowskiego\"; was "
+ + v1.getName(), v1.getName().contains("Kamiennog�rska")
+ & v1.getName().contains("Mariana Smoluchowskiego"));
for (Edge e : v1.getOutgoing()) {
if (e instanceof Turn) {
Turn t = (Turn) e;
if (e.getToVertex() == v2) {
assertTrue(t.turnAngle > 80 && t.turnAngle < 100);
}
if (e.getToVertex() == v3) {
assertTrue(t.turnAngle == 0);
}
}
}
}
}
| true | true | public void testGraphBuilder() throws Exception {
Graph gg = new Graph();
OpenStreetMapGraphBuilderImpl loader = new OpenStreetMapGraphBuilderImpl();
FileBasedOpenStreetMapProviderImpl provider = new FileBasedOpenStreetMapProviderImpl();
File file = new File(getClass().getResource("map.osm.gz").getFile());
provider.setPath(file);
loader.setProvider(provider);
loader.buildGraph(gg);
Vertex v1 = gg.getVertex("osm node 288969929 at 52");
Vertex v2 = gg.getVertex("osm node 288969929 at 141");
Vertex v3 = gg.getVertex("osm node 288969929 at 219");
v1.getName();
assertTrue (v1.getName().contains("Kamiennogórska") && v1.getName().contains("Mariana Smoluchowskiego"));
for (Edge e : v1.getOutgoing()) {
if (e instanceof Turn) {
Turn t = (Turn) e;
if (e.getToVertex() == v2) {
assertTrue(t.turnAngle > 80 && t.turnAngle < 100);
}
if (e.getToVertex() == v3) {
assertTrue(t.turnAngle == 0);
}
}
}
}
| public void testGraphBuilder() throws Exception {
Graph gg = new Graph();
OpenStreetMapGraphBuilderImpl loader = new OpenStreetMapGraphBuilderImpl();
FileBasedOpenStreetMapProviderImpl provider = new FileBasedOpenStreetMapProviderImpl();
File file = new File(getClass().getResource("map.osm.gz").getFile());
provider.setPath(file);
loader.setProvider(provider);
loader.buildGraph(gg);
Vertex v1 = gg.getVertex("osm node 288969929 at 52");
Vertex v2 = gg.getVertex("osm node 288969929 at 141");
Vertex v3 = gg.getVertex("osm node 288969929 at 219");
v1.getName();
assertTrue("name of v1 must be like \"Kamiennog�rska at Marian Smoluchowskiego\"; was "
+ v1.getName(), v1.getName().contains("Kamiennog�rska")
& v1.getName().contains("Mariana Smoluchowskiego"));
for (Edge e : v1.getOutgoing()) {
if (e instanceof Turn) {
Turn t = (Turn) e;
if (e.getToVertex() == v2) {
assertTrue(t.turnAngle > 80 && t.turnAngle < 100);
}
if (e.getToVertex() == v3) {
assertTrue(t.turnAngle == 0);
}
}
}
}
|
diff --git a/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/match/eobject/ProximityEObjectMatcher.java b/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/match/eobject/ProximityEObjectMatcher.java
index d5cc7616f..6708ba079 100644
--- a/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/match/eobject/ProximityEObjectMatcher.java
+++ b/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/match/eobject/ProximityEObjectMatcher.java
@@ -1,410 +1,410 @@
/*******************************************************************************
* Copyright (c) 2012 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.compare.match.eobject;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.common.util.Monitor;
import org.eclipse.emf.compare.CompareFactory;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.Match;
import org.eclipse.emf.compare.match.eobject.EObjectIndex.Side;
import org.eclipse.emf.compare.match.eobject.internal.ByTypeIndex;
import org.eclipse.emf.compare.match.eobject.internal.MatchAheadOfTime;
import org.eclipse.emf.ecore.EObject;
/**
* This matcher is using a distance function to match EObject. It guarantees that elements are matched with
* the other EObject having the lowest distance. If two elements have the same distance regarding the other
* EObject it will arbitrary pick one. (You should probably not rely on this and make sure your distance only
* return 0 if both EObject have the very same content). The matcher will try to use the fact that it is a
* distance to achieve a suitable scalability. It is also build on the following assumptions :
* <ul>
* <li>Most EObjects have no difference and have their corresponding EObject on the other sides of the model
* (right and origins)</li>
* <li>Two consecutive calls on the distance function with the same parameters will give the same distance.</li>
* </ul>
* The scalability you'll get will highly depend on the complexity of the distance function. The
* implementation is not caching any distance result from two EObjects.
*
* @author <a href="mailto:[email protected]">Cedric Brun</a>
*/
public class ProximityEObjectMatcher implements IEObjectMatcher, ScopeQuery {
/**
* Number of elements to index before a starting a match ahead step.
*/
private static final int NB_ELEMENTS_BETWEEN_MATCH_AHEAD = 10000;
/**
* The index which keep the EObjects.
*/
private EObjectIndex index;
/**
* Keeps track of which side was the EObject from.
*/
private Map<EObject, Side> eObjectsToSide = Maps.newHashMap();
/**
* Create the matcher using the given distance function.
*
* @param meter
* a function to measure the distance between two {@link EObject}s.
*/
public ProximityEObjectMatcher(DistanceFunction meter) {
this.index = new ByTypeIndex(meter, this);
}
/**
* {@inheritDoc}
*/
public void createMatches(Comparison comparison, Iterator<? extends EObject> leftEObjects,
Iterator<? extends EObject> rightEObjects, Iterator<? extends EObject> originEObjects,
Monitor monitor) {
// FIXME: how to create an EMF submonitor
Monitor subMonitor = new BasicMonitor();
subMonitor.beginTask("indexing objects", 1);
int nbElements = 0;
int lastSegment = 0;
/*
* We are iterating through the three sides of the scope at the same time so that index might apply
* pre-matching strategies elements if they wish.
*/
- while (leftEObjects.hasNext() || rightEObjects.hasNext() || leftEObjects.hasNext()) {
+ while (leftEObjects.hasNext() || rightEObjects.hasNext() || originEObjects.hasNext()) {
if (leftEObjects.hasNext()) {
EObject next = leftEObjects.next();
nbElements++;
index.index(next, Side.LEFT);
eObjectsToSide.put(next, Side.LEFT);
}
if (rightEObjects.hasNext()) {
EObject next = rightEObjects.next();
index.index(next, Side.RIGHT);
eObjectsToSide.put(next, Side.RIGHT);
}
if (originEObjects.hasNext()) {
EObject next = originEObjects.next();
index.index(next, Side.ORIGIN);
eObjectsToSide.put(next, Side.ORIGIN);
}
if (nbElements / NB_ELEMENTS_BETWEEN_MATCH_AHEAD > lastSegment) {
matchAheadOfTime(comparison, subMonitor);
lastSegment++;
}
}
subMonitor.worked(1);
subMonitor.done();
// FIXME: how to create an EMF submonitor
subMonitor = new BasicMonitor();
subMonitor.beginTask("matching objects", nbElements);
matchIndexedObjects(comparison, subMonitor);
createUnmatchesForRemainingObjects(comparison);
subMonitor.done();
restructureMatchModel(comparison);
}
/**
* If the index supports it, match element ahead of time, in case of failure the elements are kept and
* will be processed again later on.
*
* @param comparison
* the current comoparison.
* @param monitor
* monitor to track progress.
*/
private void matchAheadOfTime(Comparison comparison, Monitor monitor) {
if (index instanceof MatchAheadOfTime) {
matchList(comparison, ((MatchAheadOfTime)index).getValuesToMatchAhead(Side.LEFT), false, monitor);
matchList(comparison, ((MatchAheadOfTime)index).getValuesToMatchAhead(Side.RIGHT), false, monitor);
}
}
/**
* Match elements for real, if no match is found for an element, an object will be created to represent
* this unmatch and the element will not be processed again.
*
* @param comparison
* the current comparison.
* @param subMonitor
* monitor to track progress.
*/
private void matchIndexedObjects(Comparison comparison, Monitor subMonitor) {
Iterable<EObject> todo = index.getValuesStillThere(Side.LEFT);
while (todo.iterator().hasNext()) {
todo = matchList(comparison, todo, true, subMonitor);
}
todo = index.getValuesStillThere(Side.RIGHT);
while (todo.iterator().hasNext()) {
todo = matchList(comparison, todo, true, subMonitor);
}
}
/**
* Create all the Match objects for the remaining EObjects.
*
* @param comparison
* the current comparison.
*/
private void createUnmatchesForRemainingObjects(Comparison comparison) {
for (EObject notFound : index.getValuesStillThere(Side.RIGHT)) {
areMatching(comparison, null, notFound, null);
}
for (EObject notFound : index.getValuesStillThere(Side.LEFT)) {
areMatching(comparison, notFound, null, null);
}
for (EObject notFound : index.getValuesStillThere(Side.ORIGIN)) {
areMatching(comparison, null, null, notFound);
}
}
/**
* Process the list of objects matching them. This method might not be able to process all the EObjects if
* - for instance, their container has not been matched already. Every object which could not be matched
* is returned in the list.
*
* @param comparison
* the comparison being built.
* @param todoList
* the list of objects to process.
* @param createUnmatches
* whether elements which have no match should trigger the creation of a Match object (meaning
* we won't try to match them afterwards) or not.
* @param monitor
* a monitor to track progress.
* @return the list of EObjects which could not be processed for some reason.
*/
private Iterable<EObject> matchList(Comparison comparison, Iterable<EObject> todoList,
boolean createUnmatches, Monitor monitor) {
Set<EObject> remainingResult = Sets.newLinkedHashSet();
List<EObject> requiredContainers = Lists.newArrayList();
Iterator<EObject> todo = todoList.iterator();
while (todo.hasNext()) {
EObject next = todo.next();
/*
* Let's first add every container which is in scope
*/
EObject container = next.eContainer();
while (container != null && isInScope(container)) {
if (comparison.getMatch(container) == null) {
requiredContainers.add(0, container);
}
container = container.eContainer();
}
}
Iterator<EObject> containersAndTodo = Iterators.concat(requiredContainers.iterator(), todoList
.iterator());
while (containersAndTodo.hasNext()) {
EObject next = containersAndTodo.next();
/*
* At this point you need to be sure the element has not been matched in any other way before.
*/
if (comparison.getMatch(next) == null) {
if (!tryToMatch(comparison, next, createUnmatches)) {
remainingResult.add(next);
monitor.worked(1);
}
}
}
return remainingResult;
}
/**
* Try to create a Match. If the match got created, register it (having actual left/right/origin matches
* or not), if not, then return false. Cases where it might not create the match : if some required data
* has not been computed yet (for instance if the container of an object has not been matched and if the
* distance need to know if it's match to find the children matches).
*
* @param comparison
* the comparison under construction, it will be updated with the new match.
* @param a
* object to match.
* @param createUnmatches
* whether elements which have no match should trigger the creation of a Match object (meaning
* we won't try to match them afterwards) or not.
* @return false if the conditions are not fulfilled to create the match, true otherwhise.
*/
private boolean tryToMatch(Comparison comparison, EObject a, boolean createUnmatches) {
boolean okToMatch = false;
Side aSide = eObjectsToSide.get(a);
assert aSide != null;
Side bSide = Side.LEFT;
Side cSide = Side.RIGHT;
if (aSide == Side.RIGHT) {
bSide = Side.LEFT;
cSide = Side.ORIGIN;
} else if (aSide == Side.LEFT) {
bSide = Side.RIGHT;
cSide = Side.ORIGIN;
} else if (aSide == Side.ORIGIN) {
bSide = Side.LEFT;
cSide = Side.RIGHT;
}
assert aSide != bSide;
assert bSide != cSide;
assert cSide != aSide;
Map<Side, EObject> closests = index.findClosests(comparison, a, aSide);
if (closests != null) {
EObject lObj = closests.get(bSide);
EObject aObj = closests.get(cSide);
if (lObj != null || aObj != null) {
// we have at least one other match
areMatching(comparison, closests.get(Side.LEFT), closests.get(Side.RIGHT), closests
.get(Side.ORIGIN));
okToMatch = true;
} else if (createUnmatches) {
areMatching(comparison, closests.get(Side.LEFT), closests.get(Side.RIGHT), closests
.get(Side.ORIGIN));
okToMatch = true;
}
}
return okToMatch;
}
/**
* Process all the matches of the given comparison and re-attach them to their parent if one is found.
*
* @param comparison
* the comparison to restructure.
*/
private void restructureMatchModel(Comparison comparison) {
Iterator<Match> it = ImmutableList.copyOf(Iterators.filter(comparison.eAllContents(), Match.class))
.iterator();
while (it.hasNext()) {
Match cur = it.next();
EObject possibleContainer = null;
if (cur.getLeft() != null) {
possibleContainer = cur.getLeft().eContainer();
}
if (possibleContainer == null && cur.getRight() != null) {
possibleContainer = cur.getRight().eContainer();
}
if (possibleContainer == null && cur.getOrigin() != null) {
possibleContainer = cur.getOrigin().eContainer();
}
Match possibleContainerMatch = comparison.getMatch(possibleContainer);
if (possibleContainerMatch != null) {
((BasicEList<Match>)possibleContainerMatch.getSubmatches()).addUnique(cur);
}
}
}
/**
* Register the given object as a match and add it in the comparison.
*
* @param comparison
* container for the Match.
* @param left
* left element.
* @param right
* right element
* @param origin
* origin element.
* @return the created match.
*/
private Match areMatching(Comparison comparison, EObject left, EObject right, EObject origin) {
Match result = CompareFactory.eINSTANCE.createMatch();
result.setLeft(left);
result.setRight(right);
result.setOrigin(origin);
((BasicEList<Match>)comparison.getMatches()).addUnique(result);
if (left != null) {
index.remove(left, Side.LEFT);
}
if (right != null) {
index.remove(right, Side.RIGHT);
}
if (origin != null) {
index.remove(origin, Side.ORIGIN);
}
return result;
}
/**
* This represent a distance function used by the {@link ProximityEObjectMatcher} to compare EObjects and
* retrieve the closest EObject from one side to another. Axioms of the distance are supposed to be
* respected more especially :
* <ul>
* <li>symetry : dist(a,b) == dist(b,a)</li>
* <li>separation :dist(a,a) == 0</li>
* </ul>
* Triangular inequality is not leveraged with the current implementation but might be at some point to
* speed up the indexing. <br/>
* computing the distance between two EObjects should be a <b> fast operation</b> or the scalability of
* the whole matching phase will be poor.
*
* @author cedric brun <[email protected]>
*/
public interface DistanceFunction {
/**
* Return the distance between two EObjects. When the two objects should considered as completely
* different the implementation is expected to return Integer.MAX_VALUE.
*
* @param inProgress
* the comparison being processed right now. This might be used for the distance to
* retrieve other matches for instance.
* @param a
* first object.
* @param b
* second object.
* @return the distance between the two EObjects or Integer.MAX_VALUE when the objects are considered
* too different to be the same.
*/
double distance(Comparison inProgress, EObject a, EObject b);
/**
* Check that two objects are equals from the distance function point of view (distance should be 0)
* You should prefer this method when you just want to check objects are not equals enabling the
* distance to stop sooner.
*
* @param inProgress
* the comparison being processed right now. This might be used for the distance to
* retrieve other matches for instance.
* @param a
* first object.
* @param b
* second object.
* @return true of the two objects are equals, false otherwise.
*/
boolean areIdentic(Comparison inProgress, EObject a, EObject b);
}
/**
* {@inheritDoc}
*/
public boolean isInScope(EObject eContainer) {
return eObjectsToSide.get(eContainer) != null;
}
}
| true | true | public void createMatches(Comparison comparison, Iterator<? extends EObject> leftEObjects,
Iterator<? extends EObject> rightEObjects, Iterator<? extends EObject> originEObjects,
Monitor monitor) {
// FIXME: how to create an EMF submonitor
Monitor subMonitor = new BasicMonitor();
subMonitor.beginTask("indexing objects", 1);
int nbElements = 0;
int lastSegment = 0;
/*
* We are iterating through the three sides of the scope at the same time so that index might apply
* pre-matching strategies elements if they wish.
*/
while (leftEObjects.hasNext() || rightEObjects.hasNext() || leftEObjects.hasNext()) {
if (leftEObjects.hasNext()) {
EObject next = leftEObjects.next();
nbElements++;
index.index(next, Side.LEFT);
eObjectsToSide.put(next, Side.LEFT);
}
if (rightEObjects.hasNext()) {
EObject next = rightEObjects.next();
index.index(next, Side.RIGHT);
eObjectsToSide.put(next, Side.RIGHT);
}
if (originEObjects.hasNext()) {
EObject next = originEObjects.next();
index.index(next, Side.ORIGIN);
eObjectsToSide.put(next, Side.ORIGIN);
}
if (nbElements / NB_ELEMENTS_BETWEEN_MATCH_AHEAD > lastSegment) {
matchAheadOfTime(comparison, subMonitor);
lastSegment++;
}
}
subMonitor.worked(1);
subMonitor.done();
// FIXME: how to create an EMF submonitor
subMonitor = new BasicMonitor();
subMonitor.beginTask("matching objects", nbElements);
matchIndexedObjects(comparison, subMonitor);
createUnmatchesForRemainingObjects(comparison);
subMonitor.done();
restructureMatchModel(comparison);
}
| public void createMatches(Comparison comparison, Iterator<? extends EObject> leftEObjects,
Iterator<? extends EObject> rightEObjects, Iterator<? extends EObject> originEObjects,
Monitor monitor) {
// FIXME: how to create an EMF submonitor
Monitor subMonitor = new BasicMonitor();
subMonitor.beginTask("indexing objects", 1);
int nbElements = 0;
int lastSegment = 0;
/*
* We are iterating through the three sides of the scope at the same time so that index might apply
* pre-matching strategies elements if they wish.
*/
while (leftEObjects.hasNext() || rightEObjects.hasNext() || originEObjects.hasNext()) {
if (leftEObjects.hasNext()) {
EObject next = leftEObjects.next();
nbElements++;
index.index(next, Side.LEFT);
eObjectsToSide.put(next, Side.LEFT);
}
if (rightEObjects.hasNext()) {
EObject next = rightEObjects.next();
index.index(next, Side.RIGHT);
eObjectsToSide.put(next, Side.RIGHT);
}
if (originEObjects.hasNext()) {
EObject next = originEObjects.next();
index.index(next, Side.ORIGIN);
eObjectsToSide.put(next, Side.ORIGIN);
}
if (nbElements / NB_ELEMENTS_BETWEEN_MATCH_AHEAD > lastSegment) {
matchAheadOfTime(comparison, subMonitor);
lastSegment++;
}
}
subMonitor.worked(1);
subMonitor.done();
// FIXME: how to create an EMF submonitor
subMonitor = new BasicMonitor();
subMonitor.beginTask("matching objects", nbElements);
matchIndexedObjects(comparison, subMonitor);
createUnmatchesForRemainingObjects(comparison);
subMonitor.done();
restructureMatchModel(comparison);
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java
index f68e1f1f97..8a72fb3949 100644
--- a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java
+++ b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java
@@ -1,146 +1,147 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.transaction.impl;
import com.hazelcast.collection.CollectionProxyId;
import com.hazelcast.collection.CollectionProxyType;
import com.hazelcast.collection.CollectionService;
import com.hazelcast.collection.list.ObjectListProxy;
import com.hazelcast.collection.set.ObjectSetProxy;
import com.hazelcast.core.*;
import com.hazelcast.map.MapService;
import com.hazelcast.queue.QueueService;
import com.hazelcast.spi.TransactionalService;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.transaction.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author mdogan 2/26/13
*/
final class TransactionContextImpl implements TransactionContext {
private final NodeEngineImpl nodeEngine;
private final TransactionImpl transaction;
private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap = new HashMap<TransactionalObjectKey, TransactionalObject>(2);
TransactionContextImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngineImpl nodeEngine,
TransactionOptions options, String ownerUuid) {
this.nodeEngine = nodeEngine;
this.transaction = new TransactionImpl(transactionManagerService, nodeEngine, options, ownerUuid);
}
public String getTxnId() {
return transaction.getTxnId();
}
public void beginTransaction() {
transaction.begin();
}
public void commitTransaction() throws TransactionException {
if (transaction.getTransactionType().equals(TransactionOptions.TransactionType.TWO_PHASE)) {
transaction.prepare();
}
transaction.commit();
}
public void rollbackTransaction() {
transaction.rollback();
}
@SuppressWarnings("unchecked")
public <K, V> TransactionalMap<K, V> getMap(String name) {
return (TransactionalMap<K, V>) getTransactionalObject(MapService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
public <E> TransactionalQueue<E> getQueue(String name) {
return (TransactionalQueue<E>) getTransactionalObject(QueueService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) {
return (TransactionalMultiMap<K, V>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(name, null, CollectionProxyType.MULTI_MAP));
}
@SuppressWarnings("unchecked")
public <E> TransactionalList<E> getList(String name) {
return (TransactionalList<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectListProxy.COLLECTION_LIST_NAME, name, CollectionProxyType.LIST));
}
@SuppressWarnings("unchecked")
public <E> TransactionalSet<E> getSet(String name) {
return (TransactionalSet<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectSetProxy.COLLECTION_SET_NAME, name, CollectionProxyType.SET));
}
@SuppressWarnings("unchecked")
public TransactionalObject getTransactionalObject(String serviceName, Object id) {
if (transaction.getState() != Transaction.State.ACTIVE) {
throw new TransactionNotActiveException("No transaction is found while accessing " +
"transactional object -> " + serviceName + "[" + id + "]!");
}
TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id);
TransactionalObject obj = txnObjectMap.get(key);
if (obj == null) {
final Object service = nodeEngine.getService(serviceName);
if (service instanceof TransactionalService) {
+ nodeEngine.getProxyService().initializeDistributedObject(serviceName, id);
obj = ((TransactionalService) service).createTransactionalObject(id, transaction);
txnObjectMap.put(key, obj);
} else {
throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!");
}
}
return obj;
}
Transaction getTransaction() {
return transaction;
}
private class TransactionalObjectKey {
private final String serviceName;
private final Object id;
TransactionalObjectKey(String serviceName, Object id) {
this.serviceName = serviceName;
this.id = id;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TransactionalObjectKey)) return false;
TransactionalObjectKey that = (TransactionalObjectKey) o;
if (!id.equals(that.id)) return false;
if (!serviceName.equals(that.serviceName)) return false;
return true;
}
public int hashCode() {
int result = serviceName.hashCode();
result = 31 * result + id.hashCode();
return result;
}
}
}
| true | true | public TransactionalObject getTransactionalObject(String serviceName, Object id) {
if (transaction.getState() != Transaction.State.ACTIVE) {
throw new TransactionNotActiveException("No transaction is found while accessing " +
"transactional object -> " + serviceName + "[" + id + "]!");
}
TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id);
TransactionalObject obj = txnObjectMap.get(key);
if (obj == null) {
final Object service = nodeEngine.getService(serviceName);
if (service instanceof TransactionalService) {
obj = ((TransactionalService) service).createTransactionalObject(id, transaction);
txnObjectMap.put(key, obj);
} else {
throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!");
}
}
return obj;
}
| public TransactionalObject getTransactionalObject(String serviceName, Object id) {
if (transaction.getState() != Transaction.State.ACTIVE) {
throw new TransactionNotActiveException("No transaction is found while accessing " +
"transactional object -> " + serviceName + "[" + id + "]!");
}
TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id);
TransactionalObject obj = txnObjectMap.get(key);
if (obj == null) {
final Object service = nodeEngine.getService(serviceName);
if (service instanceof TransactionalService) {
nodeEngine.getProxyService().initializeDistributedObject(serviceName, id);
obj = ((TransactionalService) service).createTransactionalObject(id, transaction);
txnObjectMap.put(key, obj);
} else {
throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!");
}
}
return obj;
}
|
diff --git a/tests/src/org/jboss/test/messaging/tools/ServerManagement.java b/tests/src/org/jboss/test/messaging/tools/ServerManagement.java
index cc9e3ed64..e5dfc2438 100644
--- a/tests/src/org/jboss/test/messaging/tools/ServerManagement.java
+++ b/tests/src/org/jboss/test/messaging/tools/ServerManagement.java
@@ -1,1109 +1,1116 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.messaging.tools;
import java.rmi.Naming;
import java.util.Hashtable;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.management.ObjectName;
import javax.management.NotificationListener;
import javax.management.Notification;
import javax.transaction.UserTransaction;
import org.jboss.jms.message.MessageIdGeneratorFactory;
import org.jboss.jms.server.DestinationManager;
import org.jboss.logging.Logger;
import org.jboss.messaging.core.plugin.contract.MessageStore;
import org.jboss.messaging.core.plugin.contract.PersistenceManager;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.test.messaging.tools.jmx.rmi.LocalTestServer;
import org.jboss.test.messaging.tools.jmx.rmi.RMITestServer;
import org.jboss.test.messaging.tools.jmx.rmi.Server;
import org.jboss.test.messaging.tools.jmx.rmi.NotificationListenerID;
import org.jboss.test.messaging.tools.jndi.InVMInitialContextFactory;
import org.jboss.test.messaging.tools.jndi.RemoteInitialContextFactory;
/**
* Collection of static methods to use to start/stop and interact with the in-memory JMS server. It
* is also use to start/stop a remote server.
*
* @author <a href="mailto:[email protected]">Ovidiu Feodorov</a>
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @version <tt>$Revision$</tt>
*
* $Id$
*/
public class ServerManagement
{
// Constants -----------------------------------------------------
public static final int MAX_SERVER_COUNT = 10;
// logging levels used by the remote client to forward log output on a remote server
public static int FATAL = 0;
public static int ERROR = 1;
public static int WARN = 2;
public static int INFO = 3;
public static int DEBUG = 4;
public static int TRACE = 5;
public static final String DEFAULT_QUEUE_CONTEXT = "/queue";
public static final String DEFAULT_TOPIC_CONTEXT = "/topic";
// Static --------------------------------------------------------
private static Logger log = Logger.getLogger(ServerManagement.class);
private static ServerHolder[] servers = new ServerHolder[MAX_SERVER_COUNT];
// Map<NotificationListener - NotificationListenerPoller>
private static Map notificationListenerPollers = new HashMap();
public static boolean isLocal()
{
return !"true".equals(System.getProperty("remote"));
}
public static boolean isRemote()
{
return !isLocal();
}
public static boolean isClustered()
{
return "true".equals(System.getProperty("test.clustered"));
}
/**
* May return null if the server is not initialized.
*/
public synchronized static Server getServer()
{
return getServer(0);
}
/**
* May return null if the corresponding server is not initialized.
*/
public synchronized static Server getServer(int i)
{
if (servers[i] == null)
{
return null;
}
else
{
return ((ServerHolder)servers[i]).getServer();
}
}
public static synchronized Server create() throws Exception
{
return create(0);
}
/**
* Makes sure that a "hollow" TestServer (either local or remote, depending on the nature of the
* test), exists and it's ready to be started.
*/
public static synchronized Server create(int i) throws Exception
{
if (servers[i] == null)
{
if (isLocal())
{
servers[i] = new ServerHolder(new LocalTestServer(i), false);
}
else
{
Server s = acquireRemote(2, i, true);
if (s != null)
{
servers[i] = new ServerHolder(s, false);
}
else
{
// most likely the remote server is not started, so spawn it
servers[i] = new ServerHolder(ServerManagement.spawn(i), true);
log.info("server " + i + " online");
}
}
}
return servers[i].getServer();
}
/**
* Will clear the database at startup.
*/
public static synchronized void start(String config) throws Exception
{
start(0, config, true);
}
/**
* Will clear the database at startup.
*/
public static synchronized void start(int i, String config) throws Exception
{
start(i, config, true);
}
/**
* When this method correctly completes, the server (local or remote) is started and fully
* operational (the service container and the server peer are created and started)
*/
public static synchronized void start(int i, String config, boolean clearDatabase)
throws Exception
{
Server s = create(i);
MessageIdGeneratorFactory.instance.clear();
log.info("starting server " + i);
s.start(config, clearDatabase);
log.info("server " + i + " started");
}
public static synchronized boolean isStarted(int i)
{
if (servers[i] == null)
{
return false;
}
try
{
return servers[i].getServer().isStarted();
}
catch(Exception e)
{
return false;
}
}
public static synchronized void stop() throws Exception
{
stop(0);
}
/**
* The method stops the local or remote server, bringing it to a "hollow" state. A stopped
* server is identical with a server that has just been created, but not started.
* @return true if the server was effectively stopped, or false if the server was alreayd stopped
* when the method was invoked.
*/
public static synchronized boolean stop(int i) throws Exception
{
if (servers[i] == null)
{
log.warn("server " + i + " has not been created, so it cannot be stopped");
return false;
}
else
{
boolean stopped = servers[i].getServer().stop();
if (stopped)
{
log.info("server " + i + " stopped");
}
return stopped;
}
}
/**
* Abruptly kills the VM running the specified server, simulating a crash. A local server
* cannot be killed, the method is a noop if this is the case.
*/
public static synchronized void kill(int i) throws Exception
{
if (servers[i] == null)
{
log.warn("server " + i + " has not been created, so it cannot be killed");
}
else
{
log.trace("invoking kill() on server " + i);
servers[i].getServer().kill();
log.info("server " + i + " killed");
servers[i] = null;
}
}
/**
* This method make sure that all servers that have been implicitely spawned when as a side
* effect of create() and/or start() are killed. The method is important because a forked
* ant junit task won't exit if processes created by it are still active. If you run tests
* from ant, always call killSpawnedServers() in tearDown().
*
* The servers created directed invoking spawn() are not subject to destroySpawnedServers(); they
* need to be explicitely killed.
*
* @return a List<Integer> containing the indexes of the destroyed servers.
*
*/
public static synchronized List destroySpawnedServers() throws Exception
{
List destroyed = new ArrayList();
for(int i = 0; i < servers.length; i++)
{
if (servers[i] != null && servers[i].isSpawned())
{
Server s = servers[i].getServer();
destroyed.add(new Integer(s.getServerID()));
s.stop();
s.kill();
servers[i] = null;
}
}
return destroyed;
}
/**
* For a local test, is a noop, but for a remote test, the method call spawns a new VM,
* irrespective of the fact that a server with same index may already exist (if you want to
* avoid conflicts, you need to check this externally).
*
* The remote server so created is no different from a server started using start-rmi-server
* script.
*/
private static synchronized Server spawn(final int i) throws Exception
{
if(isLocal())
{
return null;
}
StringBuffer sb = new StringBuffer();
sb.append("java").append(' ');
sb.append("-Xmx512M").append(' ');
String moduleOutput = System.getProperty("module.output");
if (moduleOutput == null)
{
moduleOutput = "./output";
}
sb.append("-Dmodule.output=").append(moduleOutput).append(' ');
sb.append("-Dtest.bind.address=localhost").append(' ');
String database = System.getProperty("test.database");
if (database != null)
{
sb.append("-Dtest.database=").append(database).append(' ');
}
String serialization = System.getProperty("test.serialization");
if (serialization != null)
{
sb.append("-Dtest.serialization=").append(serialization).append(' ');
}
sb.append("-Dtest.server.index=").append(i).append(' ');
String clustered = System.getProperty("test.clustered");
if (clustered != null && clustered.trim().length() == 0)
{
clustered = null;
}
if (clustered != null)
{
sb.append("-Dtest.clustered=").append(clustered).append(' ');
}
String remoting = System.getProperty("test.remoting");
if (remoting != null)
{
sb.append("-Dtest.remoting=").append(remoting).append(' ');
}
String testLogfileSuffix = System.getProperty("test.logfile.suffix");
if (testLogfileSuffix == null)
{
testLogfileSuffix = "undefined-test-type";
}
else
{
int pos;
if ((pos = testLogfileSuffix.lastIndexOf("client")) != -1)
{
testLogfileSuffix = testLogfileSuffix.substring(0, pos) + "server";
}
if (clustered != null)
{
testLogfileSuffix += i;
}
}
sb.append("-Dtest.logfile.suffix=").append(testLogfileSuffix).append(' ');
String classPath = System.getProperty("java.class.path");
//System.out.println("CLASSPATH: " + classPath);
- sb.append("-cp").append(" \"").append(classPath).append("\" ");
+ if (System.getProperty("os.name").equals("Linux"))
+ {
+ sb.append("-cp").append(" ").append(classPath).append(" ");
+ }
+ else
+ {
+ sb.append("-cp").append(" \"").append(classPath).append("\" ");
+ }
sb.append("org.jboss.test.messaging.tools.jmx.rmi.RMITestServer");
String commandLine = sb.toString();
//System.out.println(commandLine);
Process process = Runtime.getRuntime().exec(commandLine);
log.trace("process: " + process);
// if you ever need to debug the spawing process, turn this flag to true:
final boolean verbose = false;
final BufferedReader rs = new BufferedReader(new InputStreamReader(process.getInputStream()));
final BufferedReader re = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = rs.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDOUT: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDOUT reader thread").start();
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = re.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDERR: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDERR reader thread").start();
// put the invoking thread on wait until the server is actually up and running and bound
// in the RMI registry
long maxWaitTime = 30; // seconds
long startTime = System.currentTimeMillis();
Server s = null;
log.info("spawned server " + i + ", waiting for it to come online");
while(System.currentTimeMillis() - startTime < maxWaitTime * 1000)
{
s = acquireRemote(1, i, true);
if (s != null)
{
break;
}
}
if (s == null)
{
log.error("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
throw new Exception("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
}
return s;
}
public static ObjectName deploy(String mbeanConfiguration) throws Exception
{
insureStarted();
return servers[0].getServer().deploy(mbeanConfiguration);
}
public static void undeploy(ObjectName on) throws Exception
{
insureStarted();
servers[0].getServer().undeploy(on);
}
public static Object getAttribute(ObjectName on, String attribute) throws Exception
{
return getAttribute(0, on, attribute);
}
public static Object getAttribute(int serverIndex, ObjectName on, String attribute)
throws Exception
{
insureStarted(serverIndex);
return servers[serverIndex].getServer().getAttribute(on, attribute);
}
public static void setAttribute(ObjectName on, String name, String valueAsString)
throws Exception
{
insureStarted();
servers[0].getServer().setAttribute(on, name, valueAsString);
}
public static Object invoke(ObjectName on, String operationName,
Object[] params, String[] signature) throws Exception
{
insureStarted();
return servers[0].getServer().invoke(on, operationName, params, signature);
}
public static void addNotificationListener(int serverIndex, ObjectName on,
NotificationListener listener) throws Exception
{
insureStarted(serverIndex);
if (isLocal())
{
// add the listener directly to the server
servers[serverIndex].getServer().addNotificationListener(on, listener);
}
else
{
// is remote, need to poll
NotificationListenerPoller p =
new NotificationListenerPoller(((ServerHolder)servers[serverIndex]).getServer(),
on, listener);
synchronized(notificationListenerPollers)
{
notificationListenerPollers.put(listener, p);
}
new Thread(p, "Poller for " + Integer.toHexString(p.hashCode())).start();
}
}
public static void removeNotificationListener(int serverIndex, ObjectName on,
NotificationListener listener) throws Exception
{
insureStarted(serverIndex);
if (isLocal())
{
// remove the listener directly
servers[serverIndex].getServer().removeNotificationListener(on, listener);
}
else
{
// is remote
NotificationListenerPoller p = null;
synchronized(notificationListenerPollers)
{
p = (NotificationListenerPoller)notificationListenerPollers.remove(listener);
}
if (p != null)
{
// stop the polling thread
p.stop();
}
}
}
public static Set query(ObjectName pattern) throws Exception
{
insureStarted();
return servers[0].getServer().query(pattern);
}
public static UserTransaction getUserTransaction() throws Exception
{
insureStarted();
return servers[0].getServer().getUserTransaction();
}
public static void log(int level, String text)
{
log(level, text, 0);
}
public static void log(int level, String text, int index)
{
if (isRemote())
{
if (servers[index] == null)
{
log.debug("The remote server " + index + " has not been created yet " +
"so this log won't make it to the server!");
return;
}
try
{
servers[index].getServer().log(level, text);
}
catch(Exception e)
{
log.error("failed to forward the logging request to the remote server", e);
}
}
}
public static void startServerPeer() throws Exception
{
startServerPeer(0, null, null);
}
/**
* @param serverPeerID - if null, the jboss-service.xml value will be used.
* @param defaultQueueJNDIContext - if null, the jboss-service.xml value will be used.
* @param defaultTopicJNDIContext - if null, the jboss-service.xml value will be used.
*/
public static void startServerPeer(int serverPeerID,
String defaultQueueJNDIContext,
String defaultTopicJNDIContext) throws Exception
{
insureStarted();
servers[0].getServer().
startServerPeer(serverPeerID, defaultQueueJNDIContext, defaultTopicJNDIContext, false);
}
public static void stopServerPeer() throws Exception
{
insureStarted();
servers[0].getServer().stopServerPeer();
}
public static boolean isServerPeerStarted() throws Exception
{
insureStarted();
return servers[0].getServer().isServerPeerStarted();
}
public static ObjectName getServerPeerObjectName() throws Exception
{
insureStarted();
return servers[0].getServer().getServerPeerObjectName();
}
/**
* @return a Set<String> with the subsystems currently registered with the Connector.
* This method is supposed to work locally as well as remotely.
*/
public static Set getConnectorSubsystems() throws Exception
{
insureStarted();
return servers[0].getServer().getConnectorSubsystems();
}
/**
* Add a ServerInvocationHandler to the remoting Connector. This method is supposed to work
* locally as well as remotely.
*/
public static void addServerInvocationHandler(String subsystem,
ServerInvocationHandler handler) throws Exception
{
insureStarted();
servers[0].getServer().addServerInvocationHandler(subsystem, handler);
}
/**
* Remove a ServerInvocationHandler from the remoting Connector. This method is supposed to work
* locally as well as remotely.
*/
public static void removeServerInvocationHandler(String subsystem)
throws Exception
{
insureStarted();
servers[0].getServer().removeServerInvocationHandler(subsystem);
}
public static MessageStore getMessageStore() throws Exception
{
insureStarted();
return servers[0].getServer().getMessageStore();
}
public static DestinationManager getDestinationManager()
throws Exception
{
insureStarted();
return servers[0].getServer().getDestinationManager();
}
public static PersistenceManager getPersistenceManager()
throws Exception
{
insureStarted();
return servers[0].getServer().getPersistenceManager();
}
public static void configureSecurityForDestination(String destName, String config)
throws Exception
{
insureStarted();
servers[0].getServer().configureSecurityForDestination(destName, config);
}
public static void setDefaultSecurityConfig(String config) throws Exception
{
insureStarted();
servers[0].getServer().setDefaultSecurityConfig(config);
}
public static String getDefaultSecurityConfig() throws Exception
{
insureStarted();
return servers[0].getServer().getDefaultSecurityConfig();
}
/**
* Simulates a topic deployment (copying the topic descriptor in the deploy directory).
*/
public static void deployClusteredTopic(String name, int serverIndex) throws Exception
{
insureStarted(serverIndex);
servers[serverIndex].getServer().deployTopic(name, null, true);
}
/**
* Simulates a topic deployment (copying the topic descriptor in the deploy directory).
*/
public static void deployTopic(String name) throws Exception
{
deployTopic(name, null);
}
/**
* Simulates a topic deployment (copying the topic descriptor in the deploy directory).
*/
public static void deployTopic(String name, String jndiName) throws Exception
{
insureStarted();
servers[0].getServer().deployTopic(name, jndiName, false);
}
/**
* Simulates a topic deployment (copying the topic descriptor in the deploy directory).
*/
public static void deployTopic(String name, int fullSize, int pageSize, int downCacheSize)
throws Exception
{
deployTopic(name, null, fullSize, pageSize, downCacheSize);
}
/**
* Simulates a topic deployment (copying the topic descriptor in the deploy directory).
*/
public static void deployTopic(String name, String jndiName, int fullSize, int pageSize,
int downCacheSize) throws Exception
{
insureStarted();
servers[0].getServer().deployTopic(name, jndiName, fullSize, pageSize, downCacheSize, false);
}
/**
* Simulates a topic un-deployment (deleting the topic descriptor from the deploy directory).
*/
public static void undeployTopic(String name) throws Exception
{
undeployDestination(false, name);
}
/**
* Simulates a topic un-deployment (deleting the topic descriptor from the deploy directory).
*/
public static void undeployTopic(String name, int serverIndex) throws Exception
{
undeployDestination(false, name, serverIndex);
}
/**
* Creates a topic programatically.
*/
public static void createTopic(String name, String jndiName) throws Exception
{
insureStarted();
servers[0].getServer().createTopic(name, jndiName);
}
/**
* Destroys a programatically created topic.
*/
public static boolean destroyTopic(String name) throws Exception
{
return servers[0].getServer().destroyDestination(false, name);
}
/**
* Simulates a queue deployment (copying the queue descriptor in the deploy directory).
*/
public static void deployClusteredQueue(String name, int serverIndex) throws Exception
{
insureStarted(serverIndex);
servers[serverIndex].getServer().deployQueue(name, null, true);
}
/**
* Simulates a queue deployment (copying the queue descriptor in the deploy directory).
*/
public static void deployQueue(String name) throws Exception
{
deployQueue(name, null);
}
/**
* Simulates a queue deployment (copying the queue descriptor in the deploy directory).
*/
public static void deployQueue(String name, String jndiName) throws Exception
{
insureStarted();
servers[0].getServer().deployQueue(name, jndiName, false);
}
/**
* Simulates a queue deployment (copying the queue descriptor in the deploy directory).
*/
public static void deployQueue(String name, int fullSize, int pageSize, int downCacheSize)
throws Exception
{
deployQueue(name, null, fullSize, pageSize, downCacheSize);
}
/**
* Simulates a queue deployment (copying the queue descriptor in the deploy directory).
*/
public static void deployQueue(String name, String jndiName, int fullSize, int pageSize,
int downCacheSize) throws Exception
{
insureStarted();
servers[0].getServer().deployQueue(name, jndiName, fullSize, pageSize, downCacheSize, false);
}
/**
* Simulates a queue un-deployment (deleting the queue descriptor from the deploy directory).
*/
public static void undeployQueue(String name) throws Exception
{
undeployDestination(true, name);
}
/**
* Simulates a queue un-deployment (deleting the queue descriptor from the deploy directory).
*/
public static void undeployQueue(String name, int serverIndex) throws Exception
{
undeployDestination(true, name, serverIndex);
}
/**
* Creates a queue programatically.
*/
public static void createQueue(String name, String jndiName) throws Exception
{
insureStarted();
servers[0].getServer().createQueue(name, jndiName);
}
/**
* Destroys a programatically created queue.
*/
public static boolean destroyQueue(String name) throws Exception
{
return servers[0].getServer().destroyDestination(true, name);
}
/**
* Simulates a destination un-deployment (deleting the destination descriptor from the deploy
* directory).
*/
private static void undeployDestination(boolean isQueue, String name) throws Exception
{
insureStarted();
servers[0].getServer().undeployDestination(isQueue, name);
}
/**
* Simulates a destination un-deployment (deleting the destination descriptor from the deploy
* directory).
*/
private static void undeployDestination(boolean isQueue, String name, int serverIndex)
throws Exception
{
insureStarted(serverIndex);
servers[serverIndex].getServer().undeployDestination(isQueue, name);
}
public static void deployConnectionFactory(String objectName,
String[] jndiBindings,
int prefetchSize,
int defaultTempQueueFullSize,
int defaultTempQueuePageSize,
int defaultTempQueueDownCacheSize)
throws Exception
{
servers[0].getServer().deployConnectionFactory(objectName,
jndiBindings,
prefetchSize,
defaultTempQueueFullSize,
defaultTempQueuePageSize,
defaultTempQueueDownCacheSize);
}
public static void deployConnectionFactory(String objectName,
String[] jndiBindings,
int prefetchSize)
throws Exception
{
servers[0].getServer().deployConnectionFactory(objectName, jndiBindings, prefetchSize);
}
public static void deployConnectionFactory(String objectName,
String[] jndiBindings)
throws Exception
{
servers[0].getServer().deployConnectionFactory(objectName, jndiBindings);
}
public static void undeployConnectionFactory(ObjectName objectName) throws Exception
{
servers[0].getServer().undeployConnectionFactory(objectName);
}
public static Hashtable getJNDIEnvironment()
{
return getJNDIEnvironment(0);
}
public static Hashtable getJNDIEnvironment(int serverIndex)
{
if (isLocal())
{
return InVMInitialContextFactory.getJNDIEnvironment(serverIndex);
}
else
{
return RemoteInitialContextFactory.getJNDIEnvironment(serverIndex);
}
}
public static Server acquireRemote(int initialRetries, int index, boolean quiet)
{
String name =
"//localhost:" + RMITestServer.DEFAULT_REGISTRY_PORT + "/" +
RMITestServer.RMI_SERVER_PREFIX + index;
Server s = null;
int retries = initialRetries;
while(s == null && retries > 0)
{
int attempt = initialRetries - retries + 1;
try
{
String msg = "trying to connect to the remote RMI server " + index +
(attempt == 1 ? "" : ", attempt " + attempt);
if(quiet)
{
log.debug(msg);
}
else
{
log.info(msg);
}
s = (Server)Naming.lookup(name);
log.debug("connected to remote server " + index);
}
catch(Exception e)
{
log.debug("failed to get the RMI server stub, attempt " +
(initialRetries - retries + 1), e);
try
{
Thread.sleep(500);
}
catch(InterruptedException e2)
{
// OK
}
retries--;
}
}
return s;
}
// Attributes ----------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
// Private -------------------------------------------------------
private static void insureStarted() throws Exception
{
insureStarted(0);
}
private static void insureStarted(int i) throws Exception
{
if (servers[i] == null)
{
throw new Exception("The server " + i + " has not been created!");
}
if (!servers[i].getServer().isStarted())
{
throw new Exception("The server " + i + " has not been started!");
}
}
// Inner classes -------------------------------------------------
private static long listenerIDCounter = 0;
static class NotificationListenerPoller implements Runnable
{
public static final int POLL_INTERVAL = 500;
private long id;
private Server server;
private NotificationListener listener;
private volatile boolean running;
private synchronized static long generateID()
{
return listenerIDCounter++;
}
NotificationListenerPoller(Server server, ObjectName on, NotificationListener listener)
throws Exception
{
id = generateID();
this.server = server;
server.addNotificationListener(on, new NotificationListenerID(id));
this.listener = listener;
this.running = true;
}
public void run()
{
while(running)
{
try
{
List notifications = server.pollNotificationListener(id);
for(Iterator i = notifications.iterator(); i.hasNext(); )
{
Notification n = (Notification)i.next();
listener.handleNotification(n, null);
}
Thread.sleep(POLL_INTERVAL);
}
catch(Exception e)
{
log.error(e);
stop();
}
}
}
public void stop()
{
running = false;
}
}
private static class ServerHolder
{
private Server server;
private boolean spawned;
ServerHolder(Server server, boolean spawned)
{
this.server = server;
this.spawned = spawned;
}
public Server getServer()
{
return server;
}
public boolean isSpawned()
{
return spawned;
}
}
}
| true | true | private static synchronized Server spawn(final int i) throws Exception
{
if(isLocal())
{
return null;
}
StringBuffer sb = new StringBuffer();
sb.append("java").append(' ');
sb.append("-Xmx512M").append(' ');
String moduleOutput = System.getProperty("module.output");
if (moduleOutput == null)
{
moduleOutput = "./output";
}
sb.append("-Dmodule.output=").append(moduleOutput).append(' ');
sb.append("-Dtest.bind.address=localhost").append(' ');
String database = System.getProperty("test.database");
if (database != null)
{
sb.append("-Dtest.database=").append(database).append(' ');
}
String serialization = System.getProperty("test.serialization");
if (serialization != null)
{
sb.append("-Dtest.serialization=").append(serialization).append(' ');
}
sb.append("-Dtest.server.index=").append(i).append(' ');
String clustered = System.getProperty("test.clustered");
if (clustered != null && clustered.trim().length() == 0)
{
clustered = null;
}
if (clustered != null)
{
sb.append("-Dtest.clustered=").append(clustered).append(' ');
}
String remoting = System.getProperty("test.remoting");
if (remoting != null)
{
sb.append("-Dtest.remoting=").append(remoting).append(' ');
}
String testLogfileSuffix = System.getProperty("test.logfile.suffix");
if (testLogfileSuffix == null)
{
testLogfileSuffix = "undefined-test-type";
}
else
{
int pos;
if ((pos = testLogfileSuffix.lastIndexOf("client")) != -1)
{
testLogfileSuffix = testLogfileSuffix.substring(0, pos) + "server";
}
if (clustered != null)
{
testLogfileSuffix += i;
}
}
sb.append("-Dtest.logfile.suffix=").append(testLogfileSuffix).append(' ');
String classPath = System.getProperty("java.class.path");
//System.out.println("CLASSPATH: " + classPath);
sb.append("-cp").append(" \"").append(classPath).append("\" ");
sb.append("org.jboss.test.messaging.tools.jmx.rmi.RMITestServer");
String commandLine = sb.toString();
//System.out.println(commandLine);
Process process = Runtime.getRuntime().exec(commandLine);
log.trace("process: " + process);
// if you ever need to debug the spawing process, turn this flag to true:
final boolean verbose = false;
final BufferedReader rs = new BufferedReader(new InputStreamReader(process.getInputStream()));
final BufferedReader re = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = rs.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDOUT: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDOUT reader thread").start();
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = re.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDERR: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDERR reader thread").start();
// put the invoking thread on wait until the server is actually up and running and bound
// in the RMI registry
long maxWaitTime = 30; // seconds
long startTime = System.currentTimeMillis();
Server s = null;
log.info("spawned server " + i + ", waiting for it to come online");
while(System.currentTimeMillis() - startTime < maxWaitTime * 1000)
{
s = acquireRemote(1, i, true);
if (s != null)
{
break;
}
}
if (s == null)
{
log.error("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
throw new Exception("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
}
return s;
}
| private static synchronized Server spawn(final int i) throws Exception
{
if(isLocal())
{
return null;
}
StringBuffer sb = new StringBuffer();
sb.append("java").append(' ');
sb.append("-Xmx512M").append(' ');
String moduleOutput = System.getProperty("module.output");
if (moduleOutput == null)
{
moduleOutput = "./output";
}
sb.append("-Dmodule.output=").append(moduleOutput).append(' ');
sb.append("-Dtest.bind.address=localhost").append(' ');
String database = System.getProperty("test.database");
if (database != null)
{
sb.append("-Dtest.database=").append(database).append(' ');
}
String serialization = System.getProperty("test.serialization");
if (serialization != null)
{
sb.append("-Dtest.serialization=").append(serialization).append(' ');
}
sb.append("-Dtest.server.index=").append(i).append(' ');
String clustered = System.getProperty("test.clustered");
if (clustered != null && clustered.trim().length() == 0)
{
clustered = null;
}
if (clustered != null)
{
sb.append("-Dtest.clustered=").append(clustered).append(' ');
}
String remoting = System.getProperty("test.remoting");
if (remoting != null)
{
sb.append("-Dtest.remoting=").append(remoting).append(' ');
}
String testLogfileSuffix = System.getProperty("test.logfile.suffix");
if (testLogfileSuffix == null)
{
testLogfileSuffix = "undefined-test-type";
}
else
{
int pos;
if ((pos = testLogfileSuffix.lastIndexOf("client")) != -1)
{
testLogfileSuffix = testLogfileSuffix.substring(0, pos) + "server";
}
if (clustered != null)
{
testLogfileSuffix += i;
}
}
sb.append("-Dtest.logfile.suffix=").append(testLogfileSuffix).append(' ');
String classPath = System.getProperty("java.class.path");
//System.out.println("CLASSPATH: " + classPath);
if (System.getProperty("os.name").equals("Linux"))
{
sb.append("-cp").append(" ").append(classPath).append(" ");
}
else
{
sb.append("-cp").append(" \"").append(classPath).append("\" ");
}
sb.append("org.jboss.test.messaging.tools.jmx.rmi.RMITestServer");
String commandLine = sb.toString();
//System.out.println(commandLine);
Process process = Runtime.getRuntime().exec(commandLine);
log.trace("process: " + process);
// if you ever need to debug the spawing process, turn this flag to true:
final boolean verbose = false;
final BufferedReader rs = new BufferedReader(new InputStreamReader(process.getInputStream()));
final BufferedReader re = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = rs.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDOUT: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDOUT reader thread").start();
new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = re.readLine()) != null)
{
if (verbose)
{
System.out.println("SERVER " + i + " STDERR: " + line);
}
}
}
catch(Exception e)
{
log.error("exception", e);
}
}
}, "Server " + i + " STDERR reader thread").start();
// put the invoking thread on wait until the server is actually up and running and bound
// in the RMI registry
long maxWaitTime = 30; // seconds
long startTime = System.currentTimeMillis();
Server s = null;
log.info("spawned server " + i + ", waiting for it to come online");
while(System.currentTimeMillis() - startTime < maxWaitTime * 1000)
{
s = acquireRemote(1, i, true);
if (s != null)
{
break;
}
}
if (s == null)
{
log.error("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
throw new Exception("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ...");
}
return s;
}
|
diff --git a/tools/gem/org.eclipse.ptp.gem/src/org/eclipse/ptp/gem/handlers/GemHandler.java b/tools/gem/org.eclipse.ptp.gem/src/org/eclipse/ptp/gem/handlers/GemHandler.java
index 66428169a..dfbcb1f15 100644
--- a/tools/gem/org.eclipse.ptp.gem/src/org/eclipse/ptp/gem/handlers/GemHandler.java
+++ b/tools/gem/org.eclipse.ptp.gem/src/org/eclipse/ptp/gem/handlers/GemHandler.java
@@ -1,139 +1,139 @@
/*******************************************************************************
* Copyright (c) 2009, 2012 University of Utah School of Computing
* 50 S Central Campus Dr. 3190 Salt Lake City, UT 84112
* http://www.cs.utah.edu/formal_verification/
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alan Humphrey - Initial API and implementation
* Christopher Derrick - Initial API and implementation
* Prof. Ganesh Gopalakrishnan - Project Advisor
*******************************************************************************/
package org.eclipse.ptp.gem.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.ptp.gem.messages.Messages;
import org.eclipse.ptp.gem.util.GemUtilities;
import org.eclipse.ptp.gem.views.GemAnalyzer;
import org.eclipse.ptp.gem.views.GemBrowser;
import org.eclipse.ptp.gem.views.GemConsole;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
/**
* Handler for associated GEM commands declared in plugin.xml.
*
* Extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class GemHandler extends AbstractHandler {
/**
* Constructor.
*
* @param none
*/
public GemHandler() {
super();
}
/**
* The command has been executed, so extract the needed information from the
* application context.
*
* @param event
* The Event to process
* @return Object <code>null</code>
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
// Process the command associated with the event
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = window.getActivePage();
final Command cmd = event.getCommand();
final String cmdString = cmd.getId();
// If we are just changing number of processes, do so and break early
if (cmdString.equals("org.eclipse.ptp.gem.commands.numprocsCommand")) { //$NON-NLS-1$
GemUtilities.setNumProcesses();
return null;
}
// Otherwise do analysis, filter extension and do the work
final IEditorPart editor = page.getActiveEditor();
IFile inputFile = null;
boolean isSourceFileExtension = false;
if (editor == null) {
- GemUtilities.showErrorDialog(Messages.GemHandler_0);
+ // do nothing here as there really is nothing to do
return null;
}
final IFileEditorInput editorInput = (IFileEditorInput) editor.getEditorInput();
inputFile = editorInput.getFile();
final String extension = inputFile.getFileExtension();
if (extension != null) {
// The most common C & C++ source file extensions
isSourceFileExtension = extension.equals("c") //$NON-NLS-1$
|| extension.equals("cpp") || extension.equals("c++") //$NON-NLS-1$ //$NON-NLS-2$
|| extension.equals("cc") || extension.equals("cp"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isSourceFileExtension) {
// Save most recent file reference to hidden preference as a URI
GemUtilities.saveMostRecentURI(inputFile.getLocationURI());
// ask for command line arguments
GemUtilities.setCommandLineArgs();
// Activate all inactive views and open up to the console
try {
final IViewReference[] activeViews = page.getViewReferences();
boolean foundBrowser = false;
boolean foundAnalyzer = false;
for (final IViewReference ref : activeViews) {
if (ref.getId().equals(GemBrowser.ID)) {
foundBrowser = true;
}
if (ref.getId().equals(GemAnalyzer.ID)) {
foundAnalyzer = true;
}
}
// open the Browser view if it's not already
if (!foundBrowser) {
page.showView(GemBrowser.ID);
}
// open the Analyzer view if it's not already
if (!foundAnalyzer) {
page.showView(GemAnalyzer.ID);
}
page.showView(GemConsole.ID);
GemUtilities.initGemViews(inputFile, true, true);
} catch (final PartInitException e) {
GemUtilities.logExceptionDetail(e);
}
} else {
GemUtilities.showErrorDialog(Messages.GemHandler_1);
}
return null;
}
}
| true | true | public Object execute(ExecutionEvent event) throws ExecutionException {
// Process the command associated with the event
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = window.getActivePage();
final Command cmd = event.getCommand();
final String cmdString = cmd.getId();
// If we are just changing number of processes, do so and break early
if (cmdString.equals("org.eclipse.ptp.gem.commands.numprocsCommand")) { //$NON-NLS-1$
GemUtilities.setNumProcesses();
return null;
}
// Otherwise do analysis, filter extension and do the work
final IEditorPart editor = page.getActiveEditor();
IFile inputFile = null;
boolean isSourceFileExtension = false;
if (editor == null) {
GemUtilities.showErrorDialog(Messages.GemHandler_0);
return null;
}
final IFileEditorInput editorInput = (IFileEditorInput) editor.getEditorInput();
inputFile = editorInput.getFile();
final String extension = inputFile.getFileExtension();
if (extension != null) {
// The most common C & C++ source file extensions
isSourceFileExtension = extension.equals("c") //$NON-NLS-1$
|| extension.equals("cpp") || extension.equals("c++") //$NON-NLS-1$ //$NON-NLS-2$
|| extension.equals("cc") || extension.equals("cp"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isSourceFileExtension) {
// Save most recent file reference to hidden preference as a URI
GemUtilities.saveMostRecentURI(inputFile.getLocationURI());
// ask for command line arguments
GemUtilities.setCommandLineArgs();
// Activate all inactive views and open up to the console
try {
final IViewReference[] activeViews = page.getViewReferences();
boolean foundBrowser = false;
boolean foundAnalyzer = false;
for (final IViewReference ref : activeViews) {
if (ref.getId().equals(GemBrowser.ID)) {
foundBrowser = true;
}
if (ref.getId().equals(GemAnalyzer.ID)) {
foundAnalyzer = true;
}
}
// open the Browser view if it's not already
if (!foundBrowser) {
page.showView(GemBrowser.ID);
}
// open the Analyzer view if it's not already
if (!foundAnalyzer) {
page.showView(GemAnalyzer.ID);
}
page.showView(GemConsole.ID);
GemUtilities.initGemViews(inputFile, true, true);
} catch (final PartInitException e) {
GemUtilities.logExceptionDetail(e);
}
} else {
GemUtilities.showErrorDialog(Messages.GemHandler_1);
}
return null;
}
| public Object execute(ExecutionEvent event) throws ExecutionException {
// Process the command associated with the event
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = window.getActivePage();
final Command cmd = event.getCommand();
final String cmdString = cmd.getId();
// If we are just changing number of processes, do so and break early
if (cmdString.equals("org.eclipse.ptp.gem.commands.numprocsCommand")) { //$NON-NLS-1$
GemUtilities.setNumProcesses();
return null;
}
// Otherwise do analysis, filter extension and do the work
final IEditorPart editor = page.getActiveEditor();
IFile inputFile = null;
boolean isSourceFileExtension = false;
if (editor == null) {
// do nothing here as there really is nothing to do
return null;
}
final IFileEditorInput editorInput = (IFileEditorInput) editor.getEditorInput();
inputFile = editorInput.getFile();
final String extension = inputFile.getFileExtension();
if (extension != null) {
// The most common C & C++ source file extensions
isSourceFileExtension = extension.equals("c") //$NON-NLS-1$
|| extension.equals("cpp") || extension.equals("c++") //$NON-NLS-1$ //$NON-NLS-2$
|| extension.equals("cc") || extension.equals("cp"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isSourceFileExtension) {
// Save most recent file reference to hidden preference as a URI
GemUtilities.saveMostRecentURI(inputFile.getLocationURI());
// ask for command line arguments
GemUtilities.setCommandLineArgs();
// Activate all inactive views and open up to the console
try {
final IViewReference[] activeViews = page.getViewReferences();
boolean foundBrowser = false;
boolean foundAnalyzer = false;
for (final IViewReference ref : activeViews) {
if (ref.getId().equals(GemBrowser.ID)) {
foundBrowser = true;
}
if (ref.getId().equals(GemAnalyzer.ID)) {
foundAnalyzer = true;
}
}
// open the Browser view if it's not already
if (!foundBrowser) {
page.showView(GemBrowser.ID);
}
// open the Analyzer view if it's not already
if (!foundAnalyzer) {
page.showView(GemAnalyzer.ID);
}
page.showView(GemConsole.ID);
GemUtilities.initGemViews(inputFile, true, true);
} catch (final PartInitException e) {
GemUtilities.logExceptionDetail(e);
}
} else {
GemUtilities.showErrorDialog(Messages.GemHandler_1);
}
return null;
}
|
diff --git a/src/java/org/rapidcontext/core/data/Data.java b/src/java/org/rapidcontext/core/data/Data.java
index ff917dc..1da089f 100644
--- a/src/java/org/rapidcontext/core/data/Data.java
+++ b/src/java/org/rapidcontext/core/data/Data.java
@@ -1,949 +1,949 @@
/*
* RapidContext <http://www.rapidcontext.com/>
* Copyright (c) 2007-2009 Per Cederberg & Dynabyte AB.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the RapidContext LICENSE.txt file for more details.
*/
package org.rapidcontext.core.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* A generic, anonymous, and untyped data object. A data object is
* more or less a hash table with name and value properties. The
* data object can also contain an indexable array of values, or
* a combination of both. The property names are non-empty strings,
* and values may have any Java data object type, such as strings,
* numbers, dates, etc. Values may also be set to data objects, but
* circular references or custom-defined classes should be avoided
* in order to keep compliance with the standard data serializers.
*
* @author Per Cederberg, Dynabyte AB
* @version 1.0
*/
public class Data implements Cloneable {
/**
* A hash map containing property names and values.
*/
private LinkedHashMap props = null;
/**
* An optional list of indexable array values.
*/
private ArrayList list = null;
/**
* The sealed flag. When this flag is set to true, no further
* changes are permitted to this data object. Any calls to the
* modifier methods will result in a run-time exception.
*/
private boolean sealed = false;
/**
* Creates a new empty data object.
*/
public Data() {
// Nothing to do here
}
/**
* Creates a new empty data object for list values. By default a
* data object is created with a null array value list, but if
* this constructor is used the list will be initialized with
* the specified capacity and by default represents an empty
* list instead of an empty object.
*
* @param initialCapacity the initial array capacity
*/
public Data(int initialCapacity) {
if (initialCapacity >= 0) {
list = new ArrayList(initialCapacity);
}
}
/**
* Returns a string representation of this object.
*
* @return a string representation of this object
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
String[] keys;
if (this.props != null) {
keys = this.keys();
buffer.append("{ ");
for (int i = 0; i < 3 && i < keys.length; i++) {
if (i > 0) {
buffer.append(", ");
}
buffer.append(keys[i]);
buffer.append(": ");
buffer.append(this.props.get(keys[i]));
}
- if (this.list.size() > 3) {
+ if (keys.length > 3) {
buffer.append(", ...");
}
buffer.append(" }");
} else if (this.list != null) {
buffer.append("[");
for (int i = 0; i < 5 && i < this.list.size(); i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(this.list.get(i));
}
if (this.list.size() > 5) {
buffer.append(",...");
}
buffer.append("]");
} else {
buffer.append("<empty data object>");
}
return buffer.toString();
}
/**
* Creates a copy of this object. The copy is a "deep copy", as
* all properties and array entries containing data objects will
* be recursively cloned.
*
* @return a deep copy of this object
*/
public Object clone() {
Data res;
Iterator iter;
Object name;
Object value;
if (this.list != null) {
res = new Data(this.list.size());
} else {
res = new Data();
}
if (this.props != null) {
res.props = new LinkedHashMap(this.props.size());
iter = this.props.keySet().iterator();
while (iter.hasNext()) {
name = iter.next();
value = this.props.get(name);
if (value instanceof Data) {
value = ((Data) value).clone();
}
res.props.put(name, value);
}
}
if (this.list != null) {
res.list = new ArrayList(this.list.size());
for (int i = 0; i < this.list.size(); i++) {
value = this.list.get(i);
if (value instanceof Data) {
value = ((Data) value).clone();
}
res.list.add(value);
}
}
return res;
}
/**
* Seals this object and prohibits any further modifications.
* If the seal is applied recursively, any data objects
* referenced by this object will also be sealed. Once sealed,
* this instance is an immutable read-only data object.
*
* @param recursive the recursive flag
*/
public void seal(boolean recursive) {
Iterator iter;
Object name;
Object value;
this.sealed = true;
if (recursive && this.props != null) {
iter = this.props.keySet().iterator();
while (iter.hasNext()) {
name = iter.next();
value = this.props.get(name);
if (value instanceof Data) {
((Data) value).seal(recursive);
}
}
}
if (recursive && this.list != null) {
for (int i = 0; i < this.list.size(); i++) {
value = this.list.get(i);
if (value instanceof Data) {
((Data) value).seal(recursive);
}
}
}
}
/**
* Returns the size of the properties map.
*
* @return the size of the properties map, or
* -1 if not used
*/
public int mapSize() {
if (this.props == null) {
return -1;
} else {
return this.props.size();
}
}
/**
* Returns the size of the data array.
*
* @return the length of the data array, or
* -1 if not used
*/
public int arraySize() {
if (this.list == null) {
return -1;
} else {
return this.list.size();
}
}
/**
* Checks if the specified property key is defined in this
* object. Note that a key name may be defined but still have a
* null value.
*
* @param key the property key name
*
* @return true if the property key is defined, or
* false otherwise
*/
public boolean containsKey(String key) {
return this.props != null && this.props.containsKey(key);
}
/**
* Checks if the specified array index is defined in this object.
* Note that an index may be defined but still have a null value.
*
* @param index the array index
*
* @return true if the array index is defined, or
* false otherwise
*/
public boolean containsIndex(int index) {
return this.list != null &&
index >= 0 && index < this.list.size();
}
/**
* Checks if the specified value is contained in this object.
* Note that both the property and array values will be compared
* to the specified value.
*
* @param value the value to check for
*
* @return true if the value exists, or
* false otherwise
*/
public boolean containsValue(Object value) {
return keyOf(value) != null || indexOf(value) >= 0;
}
/**
* Returns the first property key having the specified value.
*
* @param value the value to check for
*
* @return the property key name, or
* null if the value wasn't found
*/
public String keyOf(Object value) {
Iterator iter;
String name;
Object obj;
if (this.props != null) {
iter = this.props.keySet().iterator();
while (iter.hasNext()) {
name = (String) iter.next();
obj = this.props.get(name);
if (obj == null && value == null) {
return name;
} else if (obj != null && obj.equals(value)) {
return name;
}
}
}
return null;
}
/**
* Returns the array index of the specified value.
*
* @param value the value to check for
*
* @return the array index, or
* -1 if the value wasn't found
*/
public int indexOf(Object value) {
return (this.list == null) ? -1 : this.list.indexOf(value);
}
/**
* Returns an array with all the defined property key names. The
* keys are ordered as originally added to this object.
*
* @return an array with all property key names
*/
public String[] keys() {
String[] res;
Iterator iter;
int pos = 0;
if (this.props == null) {
res = new String[0];
} else {
res = new String[this.props.size()];
iter = this.props.keySet().iterator();
while (iter.hasNext()) {
res[pos++] = (String) iter.next();
}
}
return res;
}
/**
* Returns the property value for the specified key.
*
* @param key the property key name
*
* @return the property value, or
* null if the key is not defined
*/
public Object get(String key) {
if (this.props == null) {
return null;
} else {
return this.props.get(key);
}
}
/**
* Returns the array value at the specified index.
*
* @param index the array index
*
* @return the array value, or
* null if the index is not defined
*/
public Object get(int index) {
if (this.list == null || index >= this.list.size()) {
return null;
} else {
return list.get(index);
}
}
/**
* Returns the property value for the specified key. If the key
* is not defined or if the value is set to null, a default
* value will be returned instead.
*
* @param key the property key name
* @param defaultValue the default value
*
* @return the property value, or
* the default value if the key is not defined
*/
public Object get(String key, Object defaultValue) {
Object value = get(key);
return (value == null) ? defaultValue : value;
}
/**
* Returns the array value at the specified index. If the index
* is not defined or if the value is set to null, a default
* value will be returned instead.
*
* @param index the array index
* @param defaultValue the default value
*
* @return the array value, or
* the default value if the index is not defined
*/
public Object get(int index, Object defaultValue) {
Object value = get(index);
return (value == null) ? defaultValue : value;
}
/**
* Returns the string property value for the specified key. If
* the key is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a string, the toString() method will be called.
*
* @param key the property key name
* @param defaultValue the default value
*
* @return the property string value, or
* the default value if the key is not defined
*/
public String getString(String key, String defaultValue) {
Object value = get(key);
if (value == null) {
return defaultValue;
} else if (value instanceof String) {
return (String) value;
} else {
return value.toString();
}
}
/**
* Returns the string array value for the specified index. If
* the index is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a string, the toString() method will be called.
*
* @param index the array index
* @param defaultValue the default value
*
* @return the array string value, or
* the default value if the index is not defined
*/
public String getString(int index, String defaultValue) {
Object value = get(index);
if (value == null) {
return defaultValue;
} else if (value instanceof String) {
return (String) value;
} else {
return value.toString();
}
}
/**
* Returns the boolean property value for the specified key. If
* the key is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a boolean, any object that does not equal FALSE, "",
* "false" or 0 will be converted to true.
*
* @param key the property key name
* @param defaultValue the default value
*
* @return the property boolean value, or
* the default value if the key is not defined
*/
public boolean getBoolean(String key, boolean defaultValue) {
Object value = get(key);
if (value == null) {
return defaultValue;
} else if (value instanceof Boolean) {
return ((Boolean) value).booleanValue();
} else {
return !value.equals(Boolean.FALSE) &&
!value.equals("") &&
!value.equals("false") &&
!value.equals(Integer.valueOf(0));
}
}
/**
* Returns the boolean array value for the specified index. If
* the index is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a boolean, any object that does not equal FALSE, "",
* "false" or 0 will be converted to true.
*
* @param index the array index
* @param defaultValue the default value
*
* @return the array boolean value, or
* the default value if the index is not defined
*/
public boolean getBoolean(int index, boolean defaultValue) {
Object value = get(index);
if (value == null) {
return defaultValue;
} else if (value instanceof Boolean) {
return ((Boolean) value).booleanValue();
} else {
return !value.equals(Boolean.FALSE) &&
!value.equals("") &&
!value.equals("false") &&
!value.equals(Integer.valueOf(0));
}
}
/**
* Returns the integer property value for the specified key. If
* the key is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a number, a conversion of the toString() value of the
* object will be attempted.
*
* @param key the property key name
* @param defaultValue the default value
*
* @return the property integer value, or
* the default value if the key is not defined
*
* @throws NumberFormatException if the value didn't contain a
* valid integer
*/
public int getInt(String key, int defaultValue)
throws NumberFormatException {
Object value = get(key);
if (value == null) {
return defaultValue;
} else if (value instanceof Number) {
return ((Number) value).intValue();
} else {
return Integer.parseInt(value.toString());
}
}
/**
* Returns the integer array value for the specified index. If
* the index is not defined or if the value is set to null, a
* default value will be returned instead. If the value object
* is not a number, a conversion of the toString() value of the
* object will be attempted.
*
* @param index the array index
* @param defaultValue the default value
*
* @return the array integer value, or
* the default value if the index is not defined
*
* @throws NumberFormatException if the value didn't contain a
* valid integer
*/
public int getInt(int index, int defaultValue)
throws NumberFormatException {
Object value = get(index);
if (value == null) {
return defaultValue;
} else if (value instanceof Number) {
return ((Number) value).intValue();
} else {
return Integer.parseInt(value.toString());
}
}
/**
* Returns the data object property value for the specified key.
* If the value is not a data object, an exception will be
* thrown.
*
* @param key the property key name
*
* @return the property data object value, or
* null if the key is not defined
*
* @throws ClassCastException if the value is not a data object
* instance (or null)
*/
public Data getData(String key) throws ClassCastException {
return (Data) get(key);
}
/**
* Returns the data object array value for the specified index.
* If the value is not a data object, an exception will be
* thrown.
*
* @param index the array index
*
* @return the array data object value, or
* null if the index is not defined
*
* @throws ClassCastException if the value is not a data object
* instance (or null)
*/
public Data getData(int index) throws ClassCastException {
return (Data) get(index);
}
/**
* Modifies or defines the property value for the specified key.
*
* @param key the property key name
* @param value the property value
*
* @throws NullPointerException if the key is null or an empty
* string
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void set(String key, Object value)
throws NullPointerException, UnsupportedOperationException {
String msg;
if (this.sealed) {
msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (key == null || key.length() == 0) {
msg = "property key cannot be null or empty";
throw new NullPointerException(msg);
}
if (this.props == null) {
this.props = new LinkedHashMap();
}
this.props.put(key, value);
}
/**
* Modifies or defines the array value for the specified index.
* The array will automatically be padded with null values to
* accommodate positive indexes.
*
* @param index the array index
* @param value the array value
*
* @throws IndexOutOfBoundsException if index is negative
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void set(int index, Object value)
throws IndexOutOfBoundsException, UnsupportedOperationException {
if (this.sealed) {
String msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (this.list == null) {
this.list = new ArrayList(index + 1);
}
while (index >= this.list.size()) {
this.list.add(null);
}
this.list.set(index, value);
}
/**
* Modifies or defines the boolean property value for the
* specified key.
*
* @param key the property key name
* @param value the property value
*
* @throws NullPointerException if the key is null or an empty
* string
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void setBoolean(String key, boolean value)
throws NullPointerException, UnsupportedOperationException {
set(key, Boolean.valueOf(value));
}
/**
* Modifies or defines the boolean array value for the specified
* index.
*
* @param index the array index
* @param value the array value
*
* @throws IndexOutOfBoundsException if index is negative
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void setBoolean(int index, boolean value)
throws IndexOutOfBoundsException, UnsupportedOperationException {
set(index, Boolean.valueOf(value));
}
/**
* Modifies or defines the integer property value for the
* specified key.
*
* @param key the property key name
* @param value the property value
*
* @throws NullPointerException if the key is null or an empty
* string
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void setInt(String key, int value)
throws NullPointerException, UnsupportedOperationException {
set(key, Integer.valueOf(value));
}
/**
* Modifies or defines the integer array value for the specified
* index.
*
* @param index the array index
* @param value the array value
*
* @throws IndexOutOfBoundsException if index is negative
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void setInt(int index, int value)
throws IndexOutOfBoundsException, UnsupportedOperationException {
set(index, Integer.valueOf(value));
}
/**
* Adds a property value using the specified key if possible. If the key is
* already in use, a new unique key will be generated instead. This will
* ensure that an existing value will not be overwritten.
*
* @param key the suggested property key name
* @param value the property value
*
* @return the property key name used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public String add(String key, Object value)
throws UnsupportedOperationException {
String keyName = key;
int attempt = 0;
while (containsKey(keyName)) {
attempt++;
keyName = key + "_" + attempt;
}
set(keyName, value);
return keyName;
}
/**
* Adds an array value at the first available index. This method
* uses the current array size to determine which index to use.
*
* @param value the array value
*
* @return the array index used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public int add(Object value) throws UnsupportedOperationException {
int index = arraySize();
if (this.sealed) {
String msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (index < 0) {
index = 0;
}
set(index, value);
return index;
}
/**
* Adds a boolean property value using the specified key if possible. If
* the key is already in use, a new unique key will be generated instead.
* This will ensure that an existing value will not be overwritten.
*
* @param key the suggested property key name
* @param value the property value
*
* @return the property key name used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public String addBoolean(String key, boolean value)
throws UnsupportedOperationException {
return add(key, Boolean.valueOf(value));
}
/**
* Adds a boolean array value at the first available index. This
* method uses the current array size to determine which index
* to use.
*
* @param value the array value
*
* @return the array index used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public int addBoolean(boolean value)
throws UnsupportedOperationException {
return add(Boolean.valueOf(value));
}
/**
* Adds an integer property value using the specified key if possible. If
* the key is already in use, a new unique key will be generated instead.
* This will ensure that an existing value will not be overwritten.
*
* @param key the suggested property key name
* @param value the property value
*
* @return the property key name used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public String addInt(String key, int value)
throws UnsupportedOperationException {
return add(key, Integer.valueOf(value));
}
/**
* Adds an integer array value at the first available index. This
* method uses the current array size to determine which index
* to use.
*
* @param value the array value
*
* @return the array index used
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public int addInt(int value) throws UnsupportedOperationException {
return add(Integer.valueOf(value));
}
/**
* Deletes the specified property key and its value.
*
* @param key the property key name
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void remove(String key) throws UnsupportedOperationException {
if (this.sealed) {
String msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (this.props != null) {
this.props.remove(key);
}
}
/**
* Deletes the specified array index and its value. All
* subsequent array values will be shifted forward by one step.
*
* @param index the array index
*
* @throws UnsupportedOperationException if this object has been
* sealed
*/
public void remove(int index) throws UnsupportedOperationException {
if (this.sealed) {
String msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (this.list != null && index < this.list.size()) {
this.list.remove(index);
}
}
/**
* Sorts all values in this array according to their natural
* ordering. Note that the array MUST NOT contain data objects
* if this method is used, since they are not comparable (will
* result in a ClassCastException).
*
* @throws UnsupportedOperationException if this object has been
* sealed
* @throws ClassCastException if the array values are not
* comparable (for example, strings and integers)
*
* @see #sort(String)
*/
public void sort()
throws UnsupportedOperationException, ClassCastException {
sort((Comparator) null);
}
/**
* Sorts all values in this array according to the natural
* ordering of the specified data object key. Note that the
* array MUST contain data objects with comparable key values if
* this method is used, or a ClassCastException will be thrown.
*
* @param key the property key name
*
* @throws UnsupportedOperationException if this object has been
* sealed
* @throws ClassCastException if the array values are not
* data objects
*
* @see #sort()
*/
public void sort(String key)
throws UnsupportedOperationException, ClassCastException {
sort(new DataComparator(key));
}
/**
* Sorts all values in this array according to the comparator
* specified.
*
* @param c the object comparator to use
*
* @throws UnsupportedOperationException if this object has been
* sealed
* @throws ClassCastException if the array values were not
* comparable
*/
public void sort(Comparator c)
throws UnsupportedOperationException, ClassCastException {
if (this.sealed) {
String msg = "cannot modify sealed data object";
throw new UnsupportedOperationException(msg);
}
if (this.list != null) {
if (c == null) {
Collections.sort(this.list);
} else {
Collections.sort(this.list, c);
}
}
}
}
| true | true | public String toString() {
StringBuffer buffer = new StringBuffer();
String[] keys;
if (this.props != null) {
keys = this.keys();
buffer.append("{ ");
for (int i = 0; i < 3 && i < keys.length; i++) {
if (i > 0) {
buffer.append(", ");
}
buffer.append(keys[i]);
buffer.append(": ");
buffer.append(this.props.get(keys[i]));
}
if (this.list.size() > 3) {
buffer.append(", ...");
}
buffer.append(" }");
} else if (this.list != null) {
buffer.append("[");
for (int i = 0; i < 5 && i < this.list.size(); i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(this.list.get(i));
}
if (this.list.size() > 5) {
buffer.append(",...");
}
buffer.append("]");
} else {
buffer.append("<empty data object>");
}
return buffer.toString();
}
| public String toString() {
StringBuffer buffer = new StringBuffer();
String[] keys;
if (this.props != null) {
keys = this.keys();
buffer.append("{ ");
for (int i = 0; i < 3 && i < keys.length; i++) {
if (i > 0) {
buffer.append(", ");
}
buffer.append(keys[i]);
buffer.append(": ");
buffer.append(this.props.get(keys[i]));
}
if (keys.length > 3) {
buffer.append(", ...");
}
buffer.append(" }");
} else if (this.list != null) {
buffer.append("[");
for (int i = 0; i < 5 && i < this.list.size(); i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(this.list.get(i));
}
if (this.list.size() > 5) {
buffer.append(",...");
}
buffer.append("]");
} else {
buffer.append("<empty data object>");
}
return buffer.toString();
}
|
diff --git a/Reversi/src/reversi/server/display/ReversiAsciiDisplayController.java b/Reversi/src/reversi/server/display/ReversiAsciiDisplayController.java
index 15c5972..0880dd1 100644
--- a/Reversi/src/reversi/server/display/ReversiAsciiDisplayController.java
+++ b/Reversi/src/reversi/server/display/ReversiAsciiDisplayController.java
@@ -1,89 +1,88 @@
package reversi.server.display;
import java.util.Map;
import reversi.models.ReversiBoard;
import reversi.models.ReversiEntity;
import reversi.models.ReversiPlayer;
import base.models.BoardPiece;
import base.models.Position;
public class ReversiAsciiDisplayController {
public static final String whiteReversiPiece = "O";
public static final String blackReversiPiece = "@";
public static final String boardPipe = "|";
public static final String boardEmptySpace = "_";
public static final String commentLine = ";";
private static final String[] columnAlpha = { "a", "b", "c", "d", "e", "f",
"g", "h" };
public static String drawBoard(ReversiBoard board) {
- Map<Position, BoardPiece<ReversiEntity>> boardPieces = board
- .getBoardElements();
+ Map<Position, BoardPiece<ReversiEntity>> boardPieces = board.getBoardElements();
StringBuilder builder = new StringBuilder();
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
builder.append(boardEmptySpace);
builder.append(" ");
}
- builder.append("\n");
+ builder.append("\r\n");
for (int r = 1; r <= 8; r += 1) {
builder.append(commentLine);
builder.append(r);
for (int c = 0; c < 8; c += 1) {
builder.append(boardPipe);
Position position = new Position(c, r);
BoardPiece<ReversiEntity> boardPiece = boardPieces.get(position);
String representation = drawElement(boardPiece);
builder.append(representation);
}
builder.append(boardPipe);
- builder.append("\n");
+ builder.append("\r\n");
}
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
String currentColumn = columnAlpha[c];
builder.append(currentColumn);
builder.append(" ");
}
String output = builder.toString();
return output;
}
public static String drawElement(BoardPiece<ReversiEntity> piece) {
String result = "";
ReversiEntity reversiPiece = piece.getEntity();
if (reversiPiece == null) {
result = boardEmptySpace;
} else {
ReversiPlayer player = reversiPiece.getOwner();
result = player.getAsciiDisplayPiece();
}
return result;
}
}
| false | true | public static String drawBoard(ReversiBoard board) {
Map<Position, BoardPiece<ReversiEntity>> boardPieces = board
.getBoardElements();
StringBuilder builder = new StringBuilder();
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
builder.append(boardEmptySpace);
builder.append(" ");
}
builder.append("\n");
for (int r = 1; r <= 8; r += 1) {
builder.append(commentLine);
builder.append(r);
for (int c = 0; c < 8; c += 1) {
builder.append(boardPipe);
Position position = new Position(c, r);
BoardPiece<ReversiEntity> boardPiece = boardPieces.get(position);
String representation = drawElement(boardPiece);
builder.append(representation);
}
builder.append(boardPipe);
builder.append("\n");
}
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
String currentColumn = columnAlpha[c];
builder.append(currentColumn);
builder.append(" ");
}
String output = builder.toString();
return output;
}
| public static String drawBoard(ReversiBoard board) {
Map<Position, BoardPiece<ReversiEntity>> boardPieces = board.getBoardElements();
StringBuilder builder = new StringBuilder();
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
builder.append(boardEmptySpace);
builder.append(" ");
}
builder.append("\r\n");
for (int r = 1; r <= 8; r += 1) {
builder.append(commentLine);
builder.append(r);
for (int c = 0; c < 8; c += 1) {
builder.append(boardPipe);
Position position = new Position(c, r);
BoardPiece<ReversiEntity> boardPiece = boardPieces.get(position);
String representation = drawElement(boardPiece);
builder.append(representation);
}
builder.append(boardPipe);
builder.append("\r\n");
}
builder.append(commentLine);
builder.append(" ");
for(int c = 0; c < 8; c += 1)
{
String currentColumn = columnAlpha[c];
builder.append(currentColumn);
builder.append(" ");
}
String output = builder.toString();
return output;
}
|
diff --git a/android-xbmcremote/src/org/xbmc/android/remote/business/cm/ControlManager.java b/android-xbmcremote/src/org/xbmc/android/remote/business/cm/ControlManager.java
index 93af406..c305cc8 100644
--- a/android-xbmcremote/src/org/xbmc/android/remote/business/cm/ControlManager.java
+++ b/android-xbmcremote/src/org/xbmc/android/remote/business/cm/ControlManager.java
@@ -1,404 +1,406 @@
package org.xbmc.android.remote.business.cm;
import java.util.ArrayList;
import java.util.List;
import org.xbmc.android.jsonrpc.api.AbstractCall;
import org.xbmc.android.jsonrpc.api.call.AudioLibrary;
import org.xbmc.android.jsonrpc.api.call.Player;
import org.xbmc.android.jsonrpc.api.call.Player.GetActivePlayers;
import org.xbmc.android.jsonrpc.api.call.Player.GetActivePlayers.GetActivePlayersResult;
import org.xbmc.android.jsonrpc.api.call.Player.Seek;
import org.xbmc.android.jsonrpc.api.call.Playlist;
import org.xbmc.android.jsonrpc.api.call.VideoLibrary;
import org.xbmc.android.jsonrpc.api.model.GlobalModel.Time;
import org.xbmc.android.jsonrpc.api.model.ListModel;
import org.xbmc.android.jsonrpc.api.model.ListModel.AllItems;
import org.xbmc.android.jsonrpc.api.model.ListModel.BaseItem;
import org.xbmc.android.jsonrpc.api.model.PlayerModel;
import org.xbmc.android.jsonrpc.api.model.PlayerModel.PropertyValue;
import org.xbmc.android.jsonrpc.api.model.PlaylistModel;
import org.xbmc.android.util.StringUtil;
import org.xbmc.api.business.DataResponse;
import org.xbmc.api.business.IControlManager;
import org.xbmc.api.data.IControlClient;
import org.xbmc.api.data.IControlClient.ICurrentlyPlaying;
import org.xbmc.api.info.PlayStatus;
import org.xbmc.api.type.MediaType;
import org.xbmc.api.type.SeekType;
import android.content.Context;
import android.util.Log;
public class ControlManager extends AbstractManager implements IControlManager {
public void playFile(DataResponse<Boolean> response, String filename,
Context context) {
call(new Player.Open(new PlaylistModel.Item(
new PlaylistModel.Item.File(filename))),
new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
public void playFolder(DataResponse<Boolean> response, final String foldername,
String playlistType, Context context) {
call(new Player.Open(new PlaylistModel.Item(
new PlaylistModel.Item.Directory(foldername))),
new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
public void queueFolder(DataResponse<Boolean> response, String foldername,
String playlistType, Context context) {
call(new Playlist.Add(Integer.parseInt(playlistType), new PlaylistModel.Item(
new PlaylistModel.Item.Directory(foldername))),
new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
public void playUrl(DataResponse<Boolean> response, String url,
Context context) {
playFile(response, url, context);
}
public void seek(final DataResponse<Boolean> response, SeekType type,
final int progress, final Context context) {
callRaw(new Player.GetActivePlayers(),
new ApiHandler<Integer, GetActivePlayers.GetActivePlayersResult>() {
@Override
public Integer handleResponse(
AbstractCall<GetActivePlayersResult> apiCall) {
ArrayList<GetActivePlayersResult> results = apiCall
.getResults();
if (results.size() == 0) {
return 0;
}
GetActivePlayersResult result = results.get(results.size() - 1);
final int playerid = result.playerid;
call(new Player.Seek(playerid, (double) progress),
new ApiHandler<Boolean, Seek.SeekResult>() {
@Override
public Boolean handleResponse(
AbstractCall<Seek.SeekResult> apiCall) {
// Seek.SeekResult result =
// apiCall.getResule();
// result.
// TODO: This could update the position
// directly
return Boolean.TRUE;
}
}, response, context);
return result.playerid;
}
}, context);
}
public void updateLibrary(DataResponse<Boolean> response, String mediaType,
Context context) {
if ("music".equals(mediaType)) {
call(new AudioLibrary.Scan(""), new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
} else if ("pictures".equals(mediaType)) {
//?
} else if ("video".equals(mediaType)) {
call(new VideoLibrary.Scan(""), new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
}
public void showPicture(DataResponse<Boolean> response, String filename,
Context context) {
playFile(response, filename, context);
}
public void getCurrentlyPlaying(
final DataResponse<ICurrentlyPlaying> response,
final Context context) {
callRaw(new Player.GetActivePlayers(),
new ApiHandler<Integer, GetActivePlayers.GetActivePlayersResult>() {
@Override
public Integer handleResponse(
AbstractCall<GetActivePlayersResult> apiCall) {
ArrayList<GetActivePlayersResult> results = apiCall
.getResults();
if (results.size() == 0) {
return 0;
}
GetActivePlayersResult result = results.get(results.size() - 1);
final int playerid = result.playerid;
callRaw(new Player.GetProperties(playerid, "time",
"speed", "position","totaltime", "percentage"),
new ApiHandler<Boolean, PlayerModel.PropertyValue>() {
@Override
public Boolean handleResponse(
AbstractCall<PropertyValue> apiCall) {
final PropertyValue propertyValue = apiCall
.getResult();
call(new Player.GetItem(playerid,
BaseItem.ALBUMARTIST,
BaseItem.FILE,
BaseItem.DURATION,
BaseItem.ARTIST,
BaseItem.ALBUM,
BaseItem.THUMBNAIL,
BaseItem.SHOWTITLE,
BaseItem.SEASON,
BaseItem.EPISODE,
BaseItem.FANART,
BaseItem.RUNTIME,
BaseItem.TAGLINE,
BaseItem.TITLE,
BaseItem.GENRE),
new ApiHandler<ICurrentlyPlaying, ListModel.AllItems>() {
@Override
public ICurrentlyPlaying handleResponse(
AbstractCall<AllItems> apiCall) {
return getCurrentlyPlaying(
apiCall.getResult(),
propertyValue);
}
}, response, context);
return Boolean.TRUE;
}
}, context);
return result.playerid;
}
}, context);
}
private ICurrentlyPlaying getCurrentlyPlaying(
final ListModel.AllItems item, final PropertyValue propertyValue) {
if (item == null)
return IControlClient.NOTHING_PLAYING;
if (item.file != null && item.file.contains("Nothing Playing")) {
return IControlClient.NOTHING_PLAYING;
} else {
return new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = 5036994329211476714L;
public String getTitle() {
if ("song".equals(item.type)) {
return item.label;
} else if ("episode".equals(item.type)) {
return item.showtitle;
} else if ("movie".equals(item.type)) {
return item.title;
}
String[] path = item.file.split("/");
return path[path.length - 1];
}
public int getTime() {
return parseTime(propertyValue.time);
}
public int getPlayStatus() {
return PlayStatus.parse(propertyValue.speed);
}
public int getPlaylistPosition() {
return propertyValue.position;
}
public float getPercentage() {
return propertyValue.percentage.floatValue();
}
public String getFilename() {
return item.file;
}
public int getDuration() {
return parseTime(propertyValue.totaltime);
}
public String getArtist() {
if ("song".equals(item.type)) {
List<String> albumArtist = item.albumartist;
if (albumArtist.size() > 0) {
return albumArtist.get(0);
}
if (item.artist.size() > 0) {
return item.artist.get(0);
}
} else if ("episode".equals(item.type)) {
if (Integer.valueOf(item.season) == 0) {
return "Specials / Episode " + item.episode;
} else {
return "Season " + item.season + " / Episode "
+ item.episode;
}
} else if ("movie".equals(item.type)) {
return StringUtil.join(" / ", item.genre);
} else if ("picture".equals(item.type)) {
return "Image";
}
return "";
}
public String getAlbum() {
if ("song".equals(item.type)) {
return item.album;
} else if ("episode".equals(item.type)) {
return item.title;
} else if ("movie".equals(item.type)) {
String title = item.tagline;
if (title != null) {
return title;
}
}
String[] path = item.file.replaceAll("\\\\", "/").split("/");
+ if (path.length<2)
+ return "";
return path[path.length - 2];
}
public int getMediaType() {
return MediaType.MUSIC;
}
public boolean isPlaying() {
return propertyValue.speed > 0;
}
public int getHeight() {
return 0;
}
public int getWidth() {
return 0;
}
private int parseTime(Time time) {
int hours = time.hours;
// int milliseconds =
// time.get("milliseconds").getIntValue();
int minutes = time.minutes;
int seconds = time.seconds;
return (hours * 3600) + (minutes * 60) + seconds;
}
public String getThumbnail() {
return item.thumbnail;
}
public String getFanart() {
return item.fanart;
}
};
}
}
/**
* getPlaylistId only returns Music or Video currently so it's useful for playlist management
*/
public void getPlaylistId(DataResponse<Integer> response, Context context) {
call(new Player.GetActivePlayers(),
new ApiHandler<Integer, GetActivePlayers.GetActivePlayersResult>() {
@Override
public Integer handleResponse(
AbstractCall<GetActivePlayersResult> apiCall) {
ArrayList<GetActivePlayersResult> results = apiCall
.getResults();
if (results.size() == 0) {
return 0;
}
GetActivePlayersResult result = results.get(0);
return result.playerid;
}
}, response, context);
}
public void setPlaylistId(DataResponse<Boolean> response, int id,
Context context) {
response.value = Boolean.TRUE;
onFinish(response);
}
public void setPlaylistPos(final DataResponse<Boolean> response, final int position,
final Context context) {
getPlaylistId(new DataResponse<Integer>() {
@Override
public void run() {
call(new Player.GoTo(value, position),
new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
}, context);
}
public void clearPlaylist(DataResponse<Boolean> response,
String playlistId, Context context) {
call(new Playlist.Clear(Integer.parseInt(playlistId)),
new ApiHandler<Boolean, String>() {
@Override
public Boolean handleResponse(AbstractCall<String> apiCall) {
return "OK".equals(apiCall.getResult());
}
}, response, context);
}
public void setGuiSetting(DataResponse<Boolean> response, int setting,
String value, Context context) {
// TODO Auto-generated method stub
}
public void getVolume(DataResponse<Integer> response, Context context) {
// TODO Auto-generated method stub
}
public void sendText(DataResponse<Boolean> response, String text,
Context context) {
// TODO Auto-generated method stub
}
}
| true | true | private ICurrentlyPlaying getCurrentlyPlaying(
final ListModel.AllItems item, final PropertyValue propertyValue) {
if (item == null)
return IControlClient.NOTHING_PLAYING;
if (item.file != null && item.file.contains("Nothing Playing")) {
return IControlClient.NOTHING_PLAYING;
} else {
return new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = 5036994329211476714L;
public String getTitle() {
if ("song".equals(item.type)) {
return item.label;
} else if ("episode".equals(item.type)) {
return item.showtitle;
} else if ("movie".equals(item.type)) {
return item.title;
}
String[] path = item.file.split("/");
return path[path.length - 1];
}
public int getTime() {
return parseTime(propertyValue.time);
}
public int getPlayStatus() {
return PlayStatus.parse(propertyValue.speed);
}
public int getPlaylistPosition() {
return propertyValue.position;
}
public float getPercentage() {
return propertyValue.percentage.floatValue();
}
public String getFilename() {
return item.file;
}
public int getDuration() {
return parseTime(propertyValue.totaltime);
}
public String getArtist() {
if ("song".equals(item.type)) {
List<String> albumArtist = item.albumartist;
if (albumArtist.size() > 0) {
return albumArtist.get(0);
}
if (item.artist.size() > 0) {
return item.artist.get(0);
}
} else if ("episode".equals(item.type)) {
if (Integer.valueOf(item.season) == 0) {
return "Specials / Episode " + item.episode;
} else {
return "Season " + item.season + " / Episode "
+ item.episode;
}
} else if ("movie".equals(item.type)) {
return StringUtil.join(" / ", item.genre);
} else if ("picture".equals(item.type)) {
return "Image";
}
return "";
}
public String getAlbum() {
if ("song".equals(item.type)) {
return item.album;
} else if ("episode".equals(item.type)) {
return item.title;
} else if ("movie".equals(item.type)) {
String title = item.tagline;
if (title != null) {
return title;
}
}
String[] path = item.file.replaceAll("\\\\", "/").split("/");
return path[path.length - 2];
}
public int getMediaType() {
return MediaType.MUSIC;
}
public boolean isPlaying() {
return propertyValue.speed > 0;
}
public int getHeight() {
return 0;
}
public int getWidth() {
return 0;
}
private int parseTime(Time time) {
int hours = time.hours;
// int milliseconds =
// time.get("milliseconds").getIntValue();
int minutes = time.minutes;
int seconds = time.seconds;
return (hours * 3600) + (minutes * 60) + seconds;
}
public String getThumbnail() {
return item.thumbnail;
}
public String getFanart() {
return item.fanart;
}
};
}
}
| private ICurrentlyPlaying getCurrentlyPlaying(
final ListModel.AllItems item, final PropertyValue propertyValue) {
if (item == null)
return IControlClient.NOTHING_PLAYING;
if (item.file != null && item.file.contains("Nothing Playing")) {
return IControlClient.NOTHING_PLAYING;
} else {
return new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = 5036994329211476714L;
public String getTitle() {
if ("song".equals(item.type)) {
return item.label;
} else if ("episode".equals(item.type)) {
return item.showtitle;
} else if ("movie".equals(item.type)) {
return item.title;
}
String[] path = item.file.split("/");
return path[path.length - 1];
}
public int getTime() {
return parseTime(propertyValue.time);
}
public int getPlayStatus() {
return PlayStatus.parse(propertyValue.speed);
}
public int getPlaylistPosition() {
return propertyValue.position;
}
public float getPercentage() {
return propertyValue.percentage.floatValue();
}
public String getFilename() {
return item.file;
}
public int getDuration() {
return parseTime(propertyValue.totaltime);
}
public String getArtist() {
if ("song".equals(item.type)) {
List<String> albumArtist = item.albumartist;
if (albumArtist.size() > 0) {
return albumArtist.get(0);
}
if (item.artist.size() > 0) {
return item.artist.get(0);
}
} else if ("episode".equals(item.type)) {
if (Integer.valueOf(item.season) == 0) {
return "Specials / Episode " + item.episode;
} else {
return "Season " + item.season + " / Episode "
+ item.episode;
}
} else if ("movie".equals(item.type)) {
return StringUtil.join(" / ", item.genre);
} else if ("picture".equals(item.type)) {
return "Image";
}
return "";
}
public String getAlbum() {
if ("song".equals(item.type)) {
return item.album;
} else if ("episode".equals(item.type)) {
return item.title;
} else if ("movie".equals(item.type)) {
String title = item.tagline;
if (title != null) {
return title;
}
}
String[] path = item.file.replaceAll("\\\\", "/").split("/");
if (path.length<2)
return "";
return path[path.length - 2];
}
public int getMediaType() {
return MediaType.MUSIC;
}
public boolean isPlaying() {
return propertyValue.speed > 0;
}
public int getHeight() {
return 0;
}
public int getWidth() {
return 0;
}
private int parseTime(Time time) {
int hours = time.hours;
// int milliseconds =
// time.get("milliseconds").getIntValue();
int minutes = time.minutes;
int seconds = time.seconds;
return (hours * 3600) + (minutes * 60) + seconds;
}
public String getThumbnail() {
return item.thumbnail;
}
public String getFanart() {
return item.fanart;
}
};
}
}
|
diff --git a/illacompiler/src/main/java/illarion/compile/Compiler.java b/illacompiler/src/main/java/illarion/compile/Compiler.java
index 99fbef42..af90094e 100644
--- a/illacompiler/src/main/java/illarion/compile/Compiler.java
+++ b/illacompiler/src/main/java/illarion/compile/Compiler.java
@@ -1,101 +1,102 @@
package illarion.compile;
import illarion.compile.impl.Compile;
import org.apache.commons.cli.*;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumMap;
import java.util.Map;
/**
* This the the main class for the compiler. It determines the kind of compiler required for the set file and performs
* the compiling operation.
*
* @author Martin Karing <[email protected]>
*/
public class Compiler {
private static Map<CompilerType, Path> storagePaths;
public static void main(final String[] args) {
Options options = new Options();
- final Option npcDir = new Option("n", "npc-dir", true, "The where the compiled NPC files are stored.");
+ final Option npcDir = new Option("n", "npc-dir", true, "The place where the compiled NPC files are stored.");
npcDir.setArgs(1);
npcDir.setArgName("directory");
npcDir.setRequired(true);
options.addOption(npcDir);
- final Option questDir = new Option("q", "quest-dir", true, "The where the compiled Quest files are stored.");
+ final Option questDir = new Option("q", "quest-dir", true,
+ "The place where the compiled Quest files are " + "stored.");
questDir.setArgs(1);
questDir.setArgName("directory");
questDir.setRequired(true);
options.addOption(questDir);
CommandLineParser parser = new GnuParser();
try {
CommandLine cmd = parser.parse(options, args);
storagePaths = new EnumMap<>(CompilerType.class);
storagePaths.put(CompilerType.easyNPC, Paths.get(cmd.getOptionValue('n')));
storagePaths.put(CompilerType.easyQuest, Paths.get(cmd.getOptionValue('q')));
String[] files = cmd.getArgs();
for (String file : files) {
Path path = Paths.get(file);
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
FileVisitResult result = super.visitFile(file, attrs);
if (result == FileVisitResult.CONTINUE) {
processPath(file);
return FileVisitResult.CONTINUE;
}
return result;
}
});
} else {
processPath(path);
}
}
} catch (final ParseException e) {
final HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java -jar illarion_compiler.jar", options);
+ helpFormatter.printHelp("java -jar compiler.jar [Options] File", options);
System.exit(-1);
} catch (final IOException e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
}
}
private static void processPath(@Nonnull final Path path) throws IOException {
if (Files.isDirectory(path)) {
return;
}
int compileResult = 1;
for (CompilerType type : CompilerType.values()) {
if (type.isValidFile(path)) {
Compile compile = type.getImplementation();
compile.setTargetDir(storagePaths.get(type));
compileResult = compile.compileFile(path);
if (compileResult == 0) {
break;
}
}
}
switch (compileResult) {
case 1:
System.out.println("Skipped file: " + path.getFileName());
break;
case 0:
return;
default:
System.exit(compileResult);
}
}
}
| false | true | public static void main(final String[] args) {
Options options = new Options();
final Option npcDir = new Option("n", "npc-dir", true, "The where the compiled NPC files are stored.");
npcDir.setArgs(1);
npcDir.setArgName("directory");
npcDir.setRequired(true);
options.addOption(npcDir);
final Option questDir = new Option("q", "quest-dir", true, "The where the compiled Quest files are stored.");
questDir.setArgs(1);
questDir.setArgName("directory");
questDir.setRequired(true);
options.addOption(questDir);
CommandLineParser parser = new GnuParser();
try {
CommandLine cmd = parser.parse(options, args);
storagePaths = new EnumMap<>(CompilerType.class);
storagePaths.put(CompilerType.easyNPC, Paths.get(cmd.getOptionValue('n')));
storagePaths.put(CompilerType.easyQuest, Paths.get(cmd.getOptionValue('q')));
String[] files = cmd.getArgs();
for (String file : files) {
Path path = Paths.get(file);
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
FileVisitResult result = super.visitFile(file, attrs);
if (result == FileVisitResult.CONTINUE) {
processPath(file);
return FileVisitResult.CONTINUE;
}
return result;
}
});
} else {
processPath(path);
}
}
} catch (final ParseException e) {
final HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("java -jar illarion_compiler.jar", options);
System.exit(-1);
} catch (final IOException e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
}
}
| public static void main(final String[] args) {
Options options = new Options();
final Option npcDir = new Option("n", "npc-dir", true, "The place where the compiled NPC files are stored.");
npcDir.setArgs(1);
npcDir.setArgName("directory");
npcDir.setRequired(true);
options.addOption(npcDir);
final Option questDir = new Option("q", "quest-dir", true,
"The place where the compiled Quest files are " + "stored.");
questDir.setArgs(1);
questDir.setArgName("directory");
questDir.setRequired(true);
options.addOption(questDir);
CommandLineParser parser = new GnuParser();
try {
CommandLine cmd = parser.parse(options, args);
storagePaths = new EnumMap<>(CompilerType.class);
storagePaths.put(CompilerType.easyNPC, Paths.get(cmd.getOptionValue('n')));
storagePaths.put(CompilerType.easyQuest, Paths.get(cmd.getOptionValue('q')));
String[] files = cmd.getArgs();
for (String file : files) {
Path path = Paths.get(file);
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
FileVisitResult result = super.visitFile(file, attrs);
if (result == FileVisitResult.CONTINUE) {
processPath(file);
return FileVisitResult.CONTINUE;
}
return result;
}
});
} else {
processPath(path);
}
}
} catch (final ParseException e) {
final HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("java -jar compiler.jar [Options] File", options);
System.exit(-1);
} catch (final IOException e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
}
}
|
diff --git a/OHHClient/src/OperationHotHammer/Display/Hud.java b/OHHClient/src/OperationHotHammer/Display/Hud.java
index 56730a6..492376b 100644
--- a/OHHClient/src/OperationHotHammer/Display/Hud.java
+++ b/OHHClient/src/OperationHotHammer/Display/Hud.java
@@ -1,35 +1,35 @@
package OperationHotHammer.Display;
import OperationHotHammer.Display.Text.Text;
import java.awt.Font;
import java.util.LinkedHashMap;
import java.util.Map;
import org.newdawn.slick.Color;
public enum Hud {
INSTANCE;
private LinkedHashMap<String,String> vars = new LinkedHashMap<>();
private float fontSize = 20f;
private Text uifont = new Text("OperationHotHammer/Assets/Fonts/DisposableDroidBB.ttf", Font.PLAIN, fontSize, false);
public void set(String name, String value) {
vars.put(name, value);
}
public void draw(int screenWidth, int screenHeight) {
int line = 0;
int column = 0;
for (Map.Entry<String, String> entry : vars.entrySet()) {
uifont.draw(10+column, 10+fontSize*line++, entry.getKey() + ": " + entry.getValue(), Color.white);
if(10+fontSize*line+fontSize > screenHeight-10) {
- column += 300;
+ column += 300;
line = 0;
}
}
}
}
| true | true | public void draw(int screenWidth, int screenHeight) {
int line = 0;
int column = 0;
for (Map.Entry<String, String> entry : vars.entrySet()) {
uifont.draw(10+column, 10+fontSize*line++, entry.getKey() + ": " + entry.getValue(), Color.white);
if(10+fontSize*line+fontSize > screenHeight-10) {
column += 300;
line = 0;
}
}
}
| public void draw(int screenWidth, int screenHeight) {
int line = 0;
int column = 0;
for (Map.Entry<String, String> entry : vars.entrySet()) {
uifont.draw(10+column, 10+fontSize*line++, entry.getKey() + ": " + entry.getValue(), Color.white);
if(10+fontSize*line+fontSize > screenHeight-10) {
column += 300;
line = 0;
}
}
}
|
diff --git a/src/main/java/sce/finalprojects/sceprojectbackend/runnables/LifecycleSchedulerRunnable.java b/src/main/java/sce/finalprojects/sceprojectbackend/runnables/LifecycleSchedulerRunnable.java
index b5cdc6d..7265d00 100644
--- a/src/main/java/sce/finalprojects/sceprojectbackend/runnables/LifecycleSchedulerRunnable.java
+++ b/src/main/java/sce/finalprojects/sceprojectbackend/runnables/LifecycleSchedulerRunnable.java
@@ -1,145 +1,145 @@
package sce.finalprojects.sceprojectbackend.runnables;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import sce.finalprojects.sceprojectbackend.algorithms.EfficientHAC;
import sce.finalprojects.sceprojectbackend.algorithms.Maintenance;
import sce.finalprojects.sceprojectbackend.algorithms.xmlGenerator;
import sce.finalprojects.sceprojectbackend.database.DatabaseOperations;
import sce.finalprojects.sceprojectbackend.datatypes.ArrayOfCommentsDO;
import sce.finalprojects.sceprojectbackend.datatypes.ArticleSetupRequestDO;
import sce.finalprojects.sceprojectbackend.datatypes.ClusterRepresentationDO;
import sce.finalprojects.sceprojectbackend.datatypes.CommentEntityDS;
import sce.finalprojects.sceprojectbackend.datatypes.LifecycleStageDO;
import sce.finalprojects.sceprojectbackend.factories.ArrayOfCommentsFactory;
import sce.finalprojects.sceprojectbackend.managers.LifecycleScheduleManager;
import sce.finalprojects.sceprojectbackend.managers.MaintenanceDataManager;
import sce.finalprojects.sceprojectbackend.utils.MarkupUtility;
public class LifecycleSchedulerRunnable implements Callable<Set<ClusterRepresentationDO>>{
private String articleID;
private String articleUrl;
private String commentsAmountURL;
private String maintenanceURL;
private int runsCounter;
private int intialAmountOfComments;
private long createTimestamp;
public LifecycleSchedulerRunnable(ArticleSetupRequestDO request) {
super();
this.articleID = request.getArticleID();
this.articleUrl = request.getUrl();
this.intialAmountOfComments = request.getCommentsCount();
this.commentsAmountURL = request.getCommentsAmountRetrievalURL();
this.createTimestamp = System.currentTimeMillis();
this.maintenanceURL = request.getMaintenanceURL();
}
private void setupNextRun(){
long delay = calculateDelay();
if(delay > 0){
LifecycleScheduleManager.scheduleRun(this, delay);
}
}
private long calculateDelay(){
long age = (System.currentTimeMillis() - this.createTimestamp)/1000;
for(LifecycleStageDO lcs: LifecycleScheduleManager.stages){
if(age >= lcs.getFrom() && age < lcs.getTo())
return (long) lcs.getInterval();
}
return -1;
}
private void complete(){
this.intialAmountOfComments = 0;
}
@Override
public Set<ClusterRepresentationDO> call() throws Exception {
try{
if(runsCounter == 0){
System.out.println("LIFECYCLE: Initial Run");
DatabaseOperations.addNewArticle(this.articleID, this.articleUrl, this.intialAmountOfComments, this.commentsAmountURL,this.maintenanceURL);
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
ArrayOfCommentsDO articleCommentsArray = commentFactory.get(this.articleID);
commentFactory.save(articleCommentsArray);
EfficientHAC effHAC = new EfficientHAC(articleCommentsArray.arrayOfComment, articleCommentsArray.vect);
effHAC.runAlgorithm();
- xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, this.intialAmountOfComments);
+ xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, DatabaseOperations.getArticleNumOfComments(this.articleID));
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
this.runsCounter++;
return DatabaseOperations.getHACRootID(this.articleID);
}else{
String newNumUrl = DatabaseOperations.getNewNumberOfCommentsUrl(this.articleID);
int newNumOfComments = MarkupUtility.getLatestCommentAmount(newNumUrl);
int currentAmountOfComments = DatabaseOperations.getArticleNumOfComments(articleID);
if(currentAmountOfComments >= newNumOfComments){
System.out.println("LIFECYCLE: No new comments. Nothing to do");
return null;
}
this.runsCounter++;
if(runsCounter%3 == 0){
System.out.println("LIFECYCLE: Rebuild run");
//String articleUrl = DatabaseOperations.getUrl(this.articleID);
ArrayList<String> articleCommentsMarkup = DatabaseOperations.getAllArticleCommentsHtml(this.articleID);
String maintenanceUrl = DatabaseOperations.getMaintenanceUrl(this.articleID);
//1.Retrieve only the new comments + replace the old vectors + set the new words (SARIT)
ArrayList<CommentEntityDS> updatedArticleComments = MaintenanceDataManager.gettingCommentsForReBuilding(maintenanceUrl, articleID, newNumOfComments, currentAmountOfComments, articleCommentsMarkup);
//2.save to DB the new comments
DatabaseOperations.setComments(this.articleID, updatedArticleComments);
//3.save the newNumberOfComments to article table
//DatabaseOperations.setArticleNumOfComments(this.articleID, newNumOfComments);
//4.retrieve all the comments from DB
ArrayOfCommentsDO commentsDO = new ArrayOfCommentsDO(this.articleID,DatabaseOperations.getAllComentsWithoutHTML(this.articleID));
//5.save to cache
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
commentFactory.save(commentsDO);
//6.run efficient
EfficientHAC effHAC = new EfficientHAC(commentsDO.arrayOfComment, commentsDO.vect);
effHAC.runAlgorithm();
xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, newNumOfComments);
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
}else{
System.out.println("LIFECYCLE: Maintenance run");
Maintenance maint = new Maintenance();
maint.addNewElementsToHAC(MaintenanceDataManager.gettingCommentsForMaintenance(DatabaseOperations.getMaintenanceUrl(articleID), articleID, newNumOfComments, currentAmountOfComments), articleID);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
setupNextRun();
complete();
}
return new HashSet<ClusterRepresentationDO>();
}
}
| true | true | public Set<ClusterRepresentationDO> call() throws Exception {
try{
if(runsCounter == 0){
System.out.println("LIFECYCLE: Initial Run");
DatabaseOperations.addNewArticle(this.articleID, this.articleUrl, this.intialAmountOfComments, this.commentsAmountURL,this.maintenanceURL);
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
ArrayOfCommentsDO articleCommentsArray = commentFactory.get(this.articleID);
commentFactory.save(articleCommentsArray);
EfficientHAC effHAC = new EfficientHAC(articleCommentsArray.arrayOfComment, articleCommentsArray.vect);
effHAC.runAlgorithm();
xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, this.intialAmountOfComments);
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
this.runsCounter++;
return DatabaseOperations.getHACRootID(this.articleID);
}else{
String newNumUrl = DatabaseOperations.getNewNumberOfCommentsUrl(this.articleID);
int newNumOfComments = MarkupUtility.getLatestCommentAmount(newNumUrl);
int currentAmountOfComments = DatabaseOperations.getArticleNumOfComments(articleID);
if(currentAmountOfComments >= newNumOfComments){
System.out.println("LIFECYCLE: No new comments. Nothing to do");
return null;
}
this.runsCounter++;
if(runsCounter%3 == 0){
System.out.println("LIFECYCLE: Rebuild run");
//String articleUrl = DatabaseOperations.getUrl(this.articleID);
ArrayList<String> articleCommentsMarkup = DatabaseOperations.getAllArticleCommentsHtml(this.articleID);
String maintenanceUrl = DatabaseOperations.getMaintenanceUrl(this.articleID);
//1.Retrieve only the new comments + replace the old vectors + set the new words (SARIT)
ArrayList<CommentEntityDS> updatedArticleComments = MaintenanceDataManager.gettingCommentsForReBuilding(maintenanceUrl, articleID, newNumOfComments, currentAmountOfComments, articleCommentsMarkup);
//2.save to DB the new comments
DatabaseOperations.setComments(this.articleID, updatedArticleComments);
//3.save the newNumberOfComments to article table
//DatabaseOperations.setArticleNumOfComments(this.articleID, newNumOfComments);
//4.retrieve all the comments from DB
ArrayOfCommentsDO commentsDO = new ArrayOfCommentsDO(this.articleID,DatabaseOperations.getAllComentsWithoutHTML(this.articleID));
//5.save to cache
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
commentFactory.save(commentsDO);
//6.run efficient
EfficientHAC effHAC = new EfficientHAC(commentsDO.arrayOfComment, commentsDO.vect);
effHAC.runAlgorithm();
xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, newNumOfComments);
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
}else{
System.out.println("LIFECYCLE: Maintenance run");
Maintenance maint = new Maintenance();
maint.addNewElementsToHAC(MaintenanceDataManager.gettingCommentsForMaintenance(DatabaseOperations.getMaintenanceUrl(articleID), articleID, newNumOfComments, currentAmountOfComments), articleID);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
setupNextRun();
complete();
}
return new HashSet<ClusterRepresentationDO>();
}
| public Set<ClusterRepresentationDO> call() throws Exception {
try{
if(runsCounter == 0){
System.out.println("LIFECYCLE: Initial Run");
DatabaseOperations.addNewArticle(this.articleID, this.articleUrl, this.intialAmountOfComments, this.commentsAmountURL,this.maintenanceURL);
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
ArrayOfCommentsDO articleCommentsArray = commentFactory.get(this.articleID);
commentFactory.save(articleCommentsArray);
EfficientHAC effHAC = new EfficientHAC(articleCommentsArray.arrayOfComment, articleCommentsArray.vect);
effHAC.runAlgorithm();
xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, DatabaseOperations.getArticleNumOfComments(this.articleID));
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
this.runsCounter++;
return DatabaseOperations.getHACRootID(this.articleID);
}else{
String newNumUrl = DatabaseOperations.getNewNumberOfCommentsUrl(this.articleID);
int newNumOfComments = MarkupUtility.getLatestCommentAmount(newNumUrl);
int currentAmountOfComments = DatabaseOperations.getArticleNumOfComments(articleID);
if(currentAmountOfComments >= newNumOfComments){
System.out.println("LIFECYCLE: No new comments. Nothing to do");
return null;
}
this.runsCounter++;
if(runsCounter%3 == 0){
System.out.println("LIFECYCLE: Rebuild run");
//String articleUrl = DatabaseOperations.getUrl(this.articleID);
ArrayList<String> articleCommentsMarkup = DatabaseOperations.getAllArticleCommentsHtml(this.articleID);
String maintenanceUrl = DatabaseOperations.getMaintenanceUrl(this.articleID);
//1.Retrieve only the new comments + replace the old vectors + set the new words (SARIT)
ArrayList<CommentEntityDS> updatedArticleComments = MaintenanceDataManager.gettingCommentsForReBuilding(maintenanceUrl, articleID, newNumOfComments, currentAmountOfComments, articleCommentsMarkup);
//2.save to DB the new comments
DatabaseOperations.setComments(this.articleID, updatedArticleComments);
//3.save the newNumberOfComments to article table
//DatabaseOperations.setArticleNumOfComments(this.articleID, newNumOfComments);
//4.retrieve all the comments from DB
ArrayOfCommentsDO commentsDO = new ArrayOfCommentsDO(this.articleID,DatabaseOperations.getAllComentsWithoutHTML(this.articleID));
//5.save to cache
ArrayOfCommentsFactory commentFactory = new ArrayOfCommentsFactory();
commentFactory.save(commentsDO);
//6.run efficient
EfficientHAC effHAC = new EfficientHAC(commentsDO.arrayOfComment, commentsDO.vect);
effHAC.runAlgorithm();
xmlGenerator xmlGen = new xmlGenerator(this.articleID, effHAC.a, newNumOfComments);
Maintenance maintenance = new Maintenance();
maintenance.mapXmlHacToClusters(this.articleID);
}else{
System.out.println("LIFECYCLE: Maintenance run");
Maintenance maint = new Maintenance();
maint.addNewElementsToHAC(MaintenanceDataManager.gettingCommentsForMaintenance(DatabaseOperations.getMaintenanceUrl(articleID), articleID, newNumOfComments, currentAmountOfComments), articleID);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
setupNextRun();
complete();
}
return new HashSet<ClusterRepresentationDO>();
}
|
diff --git a/Model/src/java/fr/cg95/cvq/external/impl/ExternalService.java b/Model/src/java/fr/cg95/cvq/external/impl/ExternalService.java
index 17d1eaba4..e524f1ab0 100644
--- a/Model/src/java/fr/cg95/cvq/external/impl/ExternalService.java
+++ b/Model/src/java/fr/cg95/cvq/external/impl/ExternalService.java
@@ -1,452 +1,466 @@
package fr.cg95.cvq.external.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlObject;
import org.springframework.context.ApplicationListener;
import fr.cg95.cvq.business.external.ExternalServiceIdentifierMapping;
import fr.cg95.cvq.business.external.ExternalServiceIndividualMapping;
import fr.cg95.cvq.business.external.ExternalServiceTrace;
import fr.cg95.cvq.business.external.TraceStatusEnum;
import fr.cg95.cvq.business.payment.ExternalAccountItem;
import fr.cg95.cvq.business.payment.ExternalDepositAccountItem;
import fr.cg95.cvq.business.payment.ExternalInvoiceItem;
import fr.cg95.cvq.business.payment.Payment;
import fr.cg95.cvq.business.payment.PaymentEvent;
import fr.cg95.cvq.business.payment.PurchaseItem;
import fr.cg95.cvq.dao.external.IExternalServiceMappingDAO;
import fr.cg95.cvq.dao.external.IExternalServiceTraceDAO;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.external.ExternalServiceBean;
import fr.cg95.cvq.external.ExternalServiceUtils;
import fr.cg95.cvq.external.IExternalProviderService;
import fr.cg95.cvq.external.IExternalService;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.security.annotation.Context;
import fr.cg95.cvq.security.annotation.ContextPrivilege;
import fr.cg95.cvq.security.annotation.ContextType;
import fr.cg95.cvq.service.authority.LocalAuthorityConfigurationBean;
import fr.cg95.cvq.util.Critere;
import fr.cg95.cvq.xml.common.HomeFolderType;
import fr.cg95.cvq.xml.common.IndividualType;
import fr.cg95.cvq.xml.common.RequestType;
public class ExternalService implements IExternalService, ApplicationListener<PaymentEvent> {
private static Logger logger = Logger.getLogger(ExternalService.class);
private IExternalServiceTraceDAO externalServiceTraceDAO;
private IExternalServiceMappingDAO externalServiceMappingDAO;
@Override
public boolean authenticate(String externalServiceLabel, String password) {
IExternalProviderService externalProviderService =
getExternalServiceByLabel(externalServiceLabel);
if (externalProviderService == null) {
logger.warn("authenticate() unable to find a matching service for " + externalServiceLabel);
return false;
}
ExternalServiceBean esb = getBeanForExternalService(externalProviderService);
if (esb.getPassword().equals(password))
return true;
logger.warn("authenticate() authentication failed for service " + externalServiceLabel);
return false;
}
@Override
public List<String> checkExternalReferential(XmlObject request,
Set<IExternalProviderService> externalProviderServices) {
List<String> errors = new ArrayList<String>();
for (IExternalProviderService eps : externalProviderServices) {
errors.addAll(eps.checkExternalReferential(request));
}
return errors;
}
@Override
public void sendRequest(XmlObject xmlObject,
Set<IExternalProviderService> externalProviderServices) throws CvqException {
RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject(xmlObject);
HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder();
for (IExternalProviderService externalProviderService : externalProviderServices) {
// before sending the request to the external service, eventually set
// the external identifiers if they are known ...
String externalServiceLabel = externalProviderService.getLabel();
ExternalServiceIdentifierMapping esim =
getIdentifierMapping(externalServiceLabel, xmlHomeFolder.getId());
if (esim != null) {
fillHomeFolderWithEsim(xmlHomeFolder, esim);
+ // To Refactor : also fill requester and subject with external capdemat ids for Horanet
+ for (ExternalServiceIndividualMapping esimInd : esim.getIndividualsMappings()) {
+ if (esimInd.getIndividualId() != null
+ && esimInd.getIndividualId().equals(xmlRequest.getRequester().getId())) {
+ xmlRequest.getRequester().setExternalCapdematId(esimInd.getExternalCapDematId());
+ xmlRequest.getRequester().setExternalId(esimInd.getExternalId());
+ }
+ if (xmlRequest.getSubject() != null && xmlRequest.getSubject().getChild() != null) {
+ if (esimInd.getIndividualId() != null
+ && esimInd.getIndividualId().equals(xmlRequest.getSubject().getChild().getId()))
+ xmlRequest.getSubject().getChild().setExternalCapdematId(esimInd.getExternalCapDematId());
+ xmlRequest.getSubject().getChild().setExternalId(esimInd.getExternalId());
+ }
+ }
} else {
// no existing external service mapping : create a new one to store
// the CapDemat external identifier
esim = new ExternalServiceIdentifierMapping();
esim.setExternalServiceLabel(externalServiceLabel);
esim.setHomeFolderId(xmlHomeFolder.getId());
esim.setExternalCapDematId(UUID.randomUUID().toString());
xmlHomeFolder.setExternalCapdematId(esim.getExternalCapDematId());
for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) {
String externalCapDematId = UUID.randomUUID().toString();
esim.addIndividualMapping(xmlIndividual.getId(), externalCapDematId, "");
xmlIndividual.setExternalCapdematId(externalCapDematId);
}
externalServiceMappingDAO.create(esim);
}
ExternalServiceTrace est = null;
if (!externalProviderService.handlesTraces()) {
est = new ExternalServiceTrace(new Date(), String.valueOf(xmlRequest.getId()),
null, "capdemat", null, externalServiceLabel, null);
}
try {
logger.debug("sendRequest() routing request to external service "
+ externalServiceLabel);
String externalId = externalProviderService.sendRequest(xmlRequest);
if (externalId != null && !externalId.equals("")) {
esim.setExternalId(externalId);
externalServiceMappingDAO.update(esim);
}
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.SENT);
}
} catch (CvqException ce) {
logger.error("sendRequest() error while sending request to "
+ externalServiceLabel);
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.NOT_SENT);
}
}
if (!externalProviderService.handlesTraces()) {
externalServiceTraceDAO.create(est);
}
}
}
@Override
public Map<String, Object> loadExternalInformations(XmlObject xmlObject)
throws CvqException {
RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject(xmlObject);
List<ExternalServiceIdentifierMapping> esimList =
externalServiceMappingDAO.getIdentifierMappings(xmlRequest.getHomeFolder().getId());
if (esimList == null || esimList.isEmpty())
return Collections.emptyMap();
Map<String, Object> informations = new TreeMap<String, Object>();
for (ExternalServiceIdentifierMapping esim : esimList) {
IExternalProviderService externalProviderService =
getExternalServiceByLabel(esim.getExternalServiceLabel());
fillHomeFolderWithEsim(xmlRequest.getHomeFolder(), esim);
try {
informations.putAll(externalProviderService.loadExternalInformations(xmlRequest));
} catch (CvqException e) {
logger.warn("loadExternalInformations()" +
"Failed to retrieve information for " + externalProviderService.getLabel());
}
}
return informations;
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public Set<ExternalAccountItem> getExternalAccounts(Long homeFolderId, String type)
throws CvqException {
// FIXME : this can cause backward compatibility problems
// not sure that all existing accounts have a mapping
List<ExternalServiceIdentifierMapping> esimList =
externalServiceMappingDAO.getIdentifierMappings(homeFolderId);
if (esimList == null || esimList.isEmpty())
return Collections.emptySet();
Set<ExternalAccountItem> accountsInfoSet = new HashSet<ExternalAccountItem>();
for (ExternalServiceIdentifierMapping esim : esimList) {
IExternalProviderService externalProviderService =
getExternalServiceByLabel(esim.getExternalServiceLabel());
ExternalServiceBean esb = getBeanForExternalService(externalProviderService);
// ask accounts information by home folder or by request
// according to what the external service supports
if (esb.supportAccountsByHomeFolder()) {
Map<String, List<ExternalAccountItem>> homeFolderAccounts =
externalProviderService.getAccountsByHomeFolder(homeFolderId,
esim.getExternalCapDematId(), esim.getExternalId());
if (homeFolderAccounts != null && homeFolderAccounts.get(type) != null) {
accountsInfoSet.addAll(homeFolderAccounts.get(type));
}
} else if (esb.supportAccountsByRequest()) {
logger.warn("getExternalAccounts() accounts by request is currently not supported");
}
}
return accountsInfoSet;
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public void loadDepositAccountDetails(ExternalDepositAccountItem edai) throws CvqException {
IExternalProviderService externalProviderService =
getExternalServiceByLabel(edai.getExternalServiceLabel());
externalProviderService.loadDepositAccountDetails(edai);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public void loadInvoiceDetails(ExternalInvoiceItem eii) throws CvqException {
IExternalProviderService externalProviderService =
getExternalServiceByLabel(eii.getExternalServiceLabel());
externalProviderService.loadInvoiceDetails(eii);
}
@Context(types = {ContextType.SUPER_ADMIN})
private void creditHomeFolderAccounts(Payment payment)
throws CvqException {
Map<String, List<PurchaseItem>> externalServicesToNotify =
new HashMap<String, List<PurchaseItem>>();
Set<PurchaseItem> purchaseItems = payment.getPurchaseItems();
for (PurchaseItem purchaseItem : purchaseItems) {
// if purchase item is managed by an external service,
// stack it for notification of the associated external service
if (purchaseItem instanceof ExternalAccountItem) {
logger.debug("creditHomeFolderAccounts() item managed by an external service : "
+ purchaseItem.getFriendlyLabel());
ExternalAccountItem externalAccountItem = (ExternalAccountItem) purchaseItem;
externalAccountItem.setSupportedBroker(payment.getBroker());
String externalServiceLabel = externalAccountItem.getExternalServiceLabel();
if (externalServicesToNotify.get(externalServiceLabel) == null) {
externalServicesToNotify.put(externalServiceLabel,
new ArrayList<PurchaseItem>());
}
externalServicesToNotify.get(externalServiceLabel).add(purchaseItem);
}
}
if (!externalServicesToNotify.isEmpty()) {
for (String externalServiceLabel : externalServicesToNotify.keySet()) {
IExternalProviderService service = getExternalServiceByLabel(externalServiceLabel);
if (service == null) {
logger.error("notifyPayments() No external service with label " +
externalServiceLabel + " has been found");
continue;
}
ExternalServiceIdentifierMapping esim =
getIdentifierMapping(externalServiceLabel, payment.getHomeFolderId());
service.creditHomeFolderAccounts(externalServicesToNotify.get(externalServiceLabel),
payment.getCvqReference(), payment.getBankReference(),
payment.getHomeFolderId(),
esim == null ? null : esim.getExternalCapDematId(),
esim == null ? null : esim.getExternalId(), payment.getCommitDate());
}
}
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public Map<Date, String> getConsumptions(Long key, Date dateFrom, Date dateTo,
Set<IExternalProviderService> externalProviderServices)
throws CvqException {
Map<Date, String> resultMap = new HashMap<Date, String>();
for (IExternalProviderService externalProviderService : externalProviderServices) {
Map<Date, String> serviceMap =
externalProviderService.getConsumptions(key, dateFrom, dateTo);
if (serviceMap != null && !serviceMap.isEmpty())
resultMap.putAll(serviceMap);
}
return resultMap;
}
private void fillHomeFolderWithEsim(HomeFolderType xmlHomeFolder,
ExternalServiceIdentifierMapping esim) {
xmlHomeFolder.setExternalId(esim.getExternalId());
xmlHomeFolder.setExternalCapdematId(esim.getExternalCapDematId());
for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) {
Set<ExternalServiceIndividualMapping> esimSet =
esim.getIndividualsMappings();
for (ExternalServiceIndividualMapping esimTemp : esimSet) {
if (esimTemp.getIndividualId().equals(xmlIndividual.getId())) {
xmlIndividual.setExternalId(esimTemp.getExternalId());
xmlIndividual.setExternalCapdematId(esimTemp.getExternalCapDematId());
break;
}
}
}
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public Long addTrace(ExternalServiceTrace trace) {
trace.setDate(new Date());
return externalServiceTraceDAO.create(trace);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public List<ExternalServiceTrace> getTraces(Set<Critere> criteriaSet,
String sort, String dir, int count, int offset) {
return externalServiceTraceDAO.get(criteriaSet, sort, dir, count, offset, false);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public Long getTracesCount(Set<Critere> criteriaSet) {
return externalServiceTraceDAO.getCount(criteriaSet, false);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public List<ExternalServiceTrace> getLastTraces(Set<Critere> criteriaSet,
String sort, String dir, int count, int offset) {
return externalServiceTraceDAO.get(criteriaSet, sort, dir, count, offset, true);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public Long getLastTracesCount(Set<Critere> criteriaSet) {
return externalServiceTraceDAO.getCount(criteriaSet, true);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public ExternalServiceIdentifierMapping
getIdentifierMapping(String externalServiceLabel, Long homeFolderId) {
return externalServiceMappingDAO
.getIdentifierMapping(externalServiceLabel, homeFolderId);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ)
public ExternalServiceIdentifierMapping
getIdentifierMapping(String externalServiceLabel, String externalCapdematId) {
return externalServiceMappingDAO.getIdentifierMapping(externalServiceLabel, externalCapdematId);
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public List<ExternalServiceIdentifierMapping> getIdentifierMappings(Long homeFolderId) {
return externalServiceMappingDAO.getIdentifierMappings(homeFolderId);
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public void setExternalId(String externalServiceLabel, Long homeFolderId, Long individualId,
String externalId) {
ExternalServiceIdentifierMapping identifierMapping =
getIdentifierMapping(externalServiceLabel, homeFolderId);
if (identifierMapping.getIndividualsMappings() == null) {
identifierMapping.addIndividualMapping(individualId, UUID.randomUUID().toString(), externalId);
} else {
Iterator<ExternalServiceIndividualMapping> it =
identifierMapping.getIndividualsMappings().iterator();
ExternalServiceIndividualMapping newMapping =
new ExternalServiceIndividualMapping(individualId, UUID.randomUUID().toString(), externalId);
while (it.hasNext()) {
ExternalServiceIndividualMapping esim = it.next();
if (esim.getIndividualId().equals(individualId)) {
newMapping.setExternalCapDematId(esim.getExternalCapDematId());
it.remove();
break;
}
}
identifierMapping.getIndividualsMappings().add(newMapping);
}
externalServiceMappingDAO.update(identifierMapping);
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public void deleteIdentifierMappings(final String externalServiceLabel, final Long homeFolderId) {
ExternalServiceIdentifierMapping esim = getIdentifierMapping(externalServiceLabel, homeFolderId);
externalServiceMappingDAO.delete(esim);
}
/**
* Get the configuration bean associated to the given external provider service.
*/
@Override
public ExternalServiceBean getBeanForExternalService(IExternalProviderService externalProviderService) {
LocalAuthorityConfigurationBean lacb = SecurityContext.getCurrentConfigurationBean();
return lacb.getExternalServices().get(externalProviderService);
}
/**
* Get the external provider service that has the given label.
*/
@Override
public IExternalProviderService getExternalServiceByLabel(final String externalServiceLabel) {
LocalAuthorityConfigurationBean lacb = SecurityContext.getCurrentConfigurationBean();
Map<IExternalProviderService, ExternalServiceBean> externalProviderServices =
lacb.getExternalServices();
if (externalProviderServices == null || externalProviderServices.isEmpty())
return null;
for (IExternalProviderService service : externalProviderServices.keySet()) {
if (service.getLabel().equals(externalServiceLabel))
return service;
}
return null;
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public void addHomeFolderMapping(String externalServiceLabel, Long homeFolderId,
String externalId) {
ExternalServiceIdentifierMapping esim =
getIdentifierMapping(externalServiceLabel, homeFolderId);
if (esim == null) {
esim = new ExternalServiceIdentifierMapping();
esim.setExternalServiceLabel(externalServiceLabel);
esim.setHomeFolderId(homeFolderId);
esim.setExternalCapDematId(UUID.randomUUID().toString());
}
esim.setExternalId(externalId);
externalServiceMappingDAO.create(esim);
}
@Override
public void onApplicationEvent(PaymentEvent paymentEvent) {
logger.debug("onApplicationEvent() got a payment event of type " + paymentEvent.getEvent());
if (paymentEvent.getEvent().equals(PaymentEvent.EVENT_TYPE.PAYMENT_VALIDATED))
try {
creditHomeFolderAccounts(paymentEvent.getPayment());
} catch (CvqException e) {
// FIXME : we have nothing to handle this
logger.error("onApplicationEvent() unable to credit home folder account");
e.printStackTrace();
}
}
public void setExternalServiceTraceDAO(IExternalServiceTraceDAO externalServiceTraceDAO) {
this.externalServiceTraceDAO = externalServiceTraceDAO;
}
public void setExternalServiceMappingDAO(IExternalServiceMappingDAO externalServiceMappingDAO) {
this.externalServiceMappingDAO = externalServiceMappingDAO;
}
}
| true | true | public void sendRequest(XmlObject xmlObject,
Set<IExternalProviderService> externalProviderServices) throws CvqException {
RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject(xmlObject);
HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder();
for (IExternalProviderService externalProviderService : externalProviderServices) {
// before sending the request to the external service, eventually set
// the external identifiers if they are known ...
String externalServiceLabel = externalProviderService.getLabel();
ExternalServiceIdentifierMapping esim =
getIdentifierMapping(externalServiceLabel, xmlHomeFolder.getId());
if (esim != null) {
fillHomeFolderWithEsim(xmlHomeFolder, esim);
} else {
// no existing external service mapping : create a new one to store
// the CapDemat external identifier
esim = new ExternalServiceIdentifierMapping();
esim.setExternalServiceLabel(externalServiceLabel);
esim.setHomeFolderId(xmlHomeFolder.getId());
esim.setExternalCapDematId(UUID.randomUUID().toString());
xmlHomeFolder.setExternalCapdematId(esim.getExternalCapDematId());
for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) {
String externalCapDematId = UUID.randomUUID().toString();
esim.addIndividualMapping(xmlIndividual.getId(), externalCapDematId, "");
xmlIndividual.setExternalCapdematId(externalCapDematId);
}
externalServiceMappingDAO.create(esim);
}
ExternalServiceTrace est = null;
if (!externalProviderService.handlesTraces()) {
est = new ExternalServiceTrace(new Date(), String.valueOf(xmlRequest.getId()),
null, "capdemat", null, externalServiceLabel, null);
}
try {
logger.debug("sendRequest() routing request to external service "
+ externalServiceLabel);
String externalId = externalProviderService.sendRequest(xmlRequest);
if (externalId != null && !externalId.equals("")) {
esim.setExternalId(externalId);
externalServiceMappingDAO.update(esim);
}
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.SENT);
}
} catch (CvqException ce) {
logger.error("sendRequest() error while sending request to "
+ externalServiceLabel);
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.NOT_SENT);
}
}
if (!externalProviderService.handlesTraces()) {
externalServiceTraceDAO.create(est);
}
}
}
| public void sendRequest(XmlObject xmlObject,
Set<IExternalProviderService> externalProviderServices) throws CvqException {
RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject(xmlObject);
HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder();
for (IExternalProviderService externalProviderService : externalProviderServices) {
// before sending the request to the external service, eventually set
// the external identifiers if they are known ...
String externalServiceLabel = externalProviderService.getLabel();
ExternalServiceIdentifierMapping esim =
getIdentifierMapping(externalServiceLabel, xmlHomeFolder.getId());
if (esim != null) {
fillHomeFolderWithEsim(xmlHomeFolder, esim);
// To Refactor : also fill requester and subject with external capdemat ids for Horanet
for (ExternalServiceIndividualMapping esimInd : esim.getIndividualsMappings()) {
if (esimInd.getIndividualId() != null
&& esimInd.getIndividualId().equals(xmlRequest.getRequester().getId())) {
xmlRequest.getRequester().setExternalCapdematId(esimInd.getExternalCapDematId());
xmlRequest.getRequester().setExternalId(esimInd.getExternalId());
}
if (xmlRequest.getSubject() != null && xmlRequest.getSubject().getChild() != null) {
if (esimInd.getIndividualId() != null
&& esimInd.getIndividualId().equals(xmlRequest.getSubject().getChild().getId()))
xmlRequest.getSubject().getChild().setExternalCapdematId(esimInd.getExternalCapDematId());
xmlRequest.getSubject().getChild().setExternalId(esimInd.getExternalId());
}
}
} else {
// no existing external service mapping : create a new one to store
// the CapDemat external identifier
esim = new ExternalServiceIdentifierMapping();
esim.setExternalServiceLabel(externalServiceLabel);
esim.setHomeFolderId(xmlHomeFolder.getId());
esim.setExternalCapDematId(UUID.randomUUID().toString());
xmlHomeFolder.setExternalCapdematId(esim.getExternalCapDematId());
for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) {
String externalCapDematId = UUID.randomUUID().toString();
esim.addIndividualMapping(xmlIndividual.getId(), externalCapDematId, "");
xmlIndividual.setExternalCapdematId(externalCapDematId);
}
externalServiceMappingDAO.create(esim);
}
ExternalServiceTrace est = null;
if (!externalProviderService.handlesTraces()) {
est = new ExternalServiceTrace(new Date(), String.valueOf(xmlRequest.getId()),
null, "capdemat", null, externalServiceLabel, null);
}
try {
logger.debug("sendRequest() routing request to external service "
+ externalServiceLabel);
String externalId = externalProviderService.sendRequest(xmlRequest);
if (externalId != null && !externalId.equals("")) {
esim.setExternalId(externalId);
externalServiceMappingDAO.update(esim);
}
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.SENT);
}
} catch (CvqException ce) {
logger.error("sendRequest() error while sending request to "
+ externalServiceLabel);
if (!externalProviderService.handlesTraces()) {
est.setStatus(TraceStatusEnum.NOT_SENT);
}
}
if (!externalProviderService.handlesTraces()) {
externalServiceTraceDAO.create(est);
}
}
}
|
diff --git a/src/org/geworkbench/bison/datastructure/biocollections/GoAnalysisResult.java b/src/org/geworkbench/bison/datastructure/biocollections/GoAnalysisResult.java
index 9ba39311..b911be62 100644
--- a/src/org/geworkbench/bison/datastructure/biocollections/GoAnalysisResult.java
+++ b/src/org/geworkbench/bison/datastructure/biocollections/GoAnalysisResult.java
@@ -1,422 +1,423 @@
/**
*
*/
package org.geworkbench.bison.datastructure.biocollections;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.bioobjects.markers.goterms.GOTerm;
import org.geworkbench.bison.datastructure.bioobjects.markers.goterms.GeneOntologyTree;
import org.geworkbench.bison.datastructure.bioobjects.microarray.CSMicroarray;
/**
* Go Terms Analysis Result.
* interface DSAncillaryDataSet is the minimal requirement to fit in to geWorkbench analysis's result output framework
*
* wrapping for the result from ontologizer 2.0.
*
* @author zji
* @version $Id$
*/
public class GoAnalysisResult extends CSAncillaryDataSet<CSMicroarray> {
private static final long serialVersionUID = -337000604982427702L;
static Log log = LogFactory.getLog(GoAnalysisResult.class);
Set<String> changedGenes;
Set<String> referenceGenes;
static class ResultRow implements Serializable {
private static final long serialVersionUID = 8340126713281389148L;
String name;
String namespace;
double p;
double pAdjusted;
int popCount;
int studyCount;
ResultRow(String name, String namespace, double p, double pAdjusted, int popCount, int studyCount) {
this.name = name;
this.namespace = namespace;
this.p = p;
this.pAdjusted = pAdjusted;
this.popCount = popCount;
this.studyCount = studyCount;
}
public String toString() {
return name+"|"+namespace+"|"+p+"|"+pAdjusted+"|"+popCount+"|"+studyCount;
}
}
ResultRow getRow(Integer goId) {
return result.get(goId);
}
private Map<Integer, ResultRow> result = null;
Map<Integer, ResultRow> getResult() {return result; }
public int getCount() {
if(result!=null)
return result.size();
else return 0;
}
/**
* Constructor for a result not populated yet.
* @param parent
* @param label
*/
public GoAnalysisResult(DSDataSet<CSMicroarray> parent, String label) {
super(parent, label);
referenceGenes = new HashSet<String>();
changedGenes = new HashSet<String>();
result = new HashMap<Integer, ResultRow>();
}
void addResultRow(int goId, ResultRow row) {
result.put(goId, row);
}
public File getDataSetFile() {
// no use. required by the interface
return null;
}
public void setDataSetFile(File file) {
// no use. required by the interface
}
/**
* return gene detail for a give gene symbol
*/
static public String getGeneDetail(String geneSymbol) {
if(geneDetails==null || geneDetails.get(geneSymbol)==null)
return "";
return geneDetails.get(geneSymbol).toString();
}
/**
* return entrez ID for a given gene symbol
* @param geneSymbol
* @return
*/
static public int getEntrezId(String geneSymbol) {
if(geneDetails==null || geneDetails.get(geneSymbol)==null)
return 0;
return geneDetails.get(geneSymbol).getEntrezId();
}
/**
* return list of child IDs for a GO term ID
* @param goTermId
* @return
*/
static public List<Integer> getOntologyChildren(int goTermId) {
List<Integer> list = new ArrayList<Integer>();
if(goTermId==0) {
for(Integer id: getNamespaceIds()) {
list.add(id);
}
return list;
}
GeneOntologyTree geneOntologyTree = GeneOntologyTree.getInstanceUntilAvailable();
for(GOTerm g: geneOntologyTree.getTerm(goTermId).getChildren()) {
list.add(g.getId());
}
return list;
}
/**
* return GO term name for a given GO term ID
*
*/
static public String getGoTermName(int goTermId) {
GeneOntologyTree geneOntologyTree = GeneOntologyTree.getInstanceUntilAvailable();
GOTerm goTerm = geneOntologyTree.getTerm(goTermId);
if(goTerm!=null)
return goTerm.getName();
else
return null;
}
public static boolean isAnnotationParsed() {
if(term2Gene.size()==0)return false;
else return true;
}
/**
* return the set of gene annotated to the given Go Term ID
* @param goId
* @return
*/
static public Set<String> getAnnotatedGenes(int goTermId) {
return term2Gene.get(goTermId);
}
static public Set<Integer> getNamespaceIds() {
if(namespaceIds.size()>0) {
return namespaceIds;
} else {
GeneOntologyTree geneOntologyTree = GeneOntologyTree.getInstanceUntilAvailable();
for(int i=0; i<geneOntologyTree.getNumberOfRoots(); i++)
namespaceIds.add(geneOntologyTree.getRoot(i).getId());
return namespaceIds;
}
}
private static HashMap<Integer, Set<String>> term2Gene = new HashMap<Integer, Set<String> >();
private static Set<Integer> namespaceIds = new TreeSet<Integer>();
private static final Set<String> namespace;
static {
namespace = new TreeSet<String>();
namespace.add("molecular_function");
namespace.add("biological_process");
namespace.add("cellular_component");
};
private static int countUnexpectedEntrezId = 0;
- public static void parseAnnotation(String annotationFileName) {
+ public static void parseAnnotation(String annotationFileName) throws IOException {
term2Gene.clear();
geneDetails.clear();
try {
BufferedReader br = new BufferedReader(new FileReader(annotationFileName));
String line = br.readLine();
int count = 0;
countUnexpectedEntrezId = 0;
while(line!=null) {
while(line.startsWith("#"))
line = br.readLine();
line = line.substring(1, line.length()-2); // trimming the leading and trailing quotation mark
String[] fields = line.split("\",\"");
+ final int AFFY_COLUMN_COUNT = 41;
+ if(fields.length!=AFFY_COLUMN_COUNT) {
+ throw new IOException("Annotation file "+annotationFileName+" not recognized.");
+ }
String geneSymbolField = fields[ANNOTATION_INDEX_GENE_SYMBOL];
String biologicalProcess = fields[ANNOTATION_INDEX_BIOLOGICAL_PROCESS];
String cellularComponent = fields[ANNOTATION_INDEX_CELLULAR_COMPONENT];
String molecularFunction = fields[ANNOTATION_INDEX_MOLECULAR_FUNCTION];
if (count > 0 && !geneSymbolField.equals("---") ) {
String[] geneSymbols = geneSymbolField.split("///");
String[] geneTitles = fields[ANNOTATION_INDEX_GENE_TITLE].trim().split("///");
String[] entrezIds = fields[ANNOTATION_INDEX_ENTREZ_ID].trim().split("///");
for(int i=0; i<geneSymbols.length; i++)
geneSymbols[i] = geneSymbols[i].trim();
parseOneNameSpace(biologicalProcess, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(cellularComponent, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(molecularFunction, geneSymbols, geneTitles, entrezIds);
}
count++;
line = br.readLine();
}
br.close();
log.debug("total records in annotation file is "+count);
if(countUnexpectedEntrezId>0)
log.warn("total count of unexpected entrezId "+countUnexpectedEntrezId);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("Annotation map is not successfullly created due to FileNotException: "+e.getMessage());
- } catch (IOException e) {
- e.printStackTrace();
- log.error("Annotation map is not successfullly created due to IOException: "+e.getMessage());
}
staticAnnotationFileName = annotationFileName;
}
private final static int ANNOTATION_INDEX_ENTREZ_ID = 18;
private final static int ANNOTATION_INDEX_GENE_TITLE = 13;
private final static int ANNOTATION_INDEX_GENE_SYMBOL = 14;
private final static int ANNOTATION_INDEX_BIOLOGICAL_PROCESS = 30;
private final static int ANNOTATION_INDEX_CELLULAR_COMPONENT = 31;
private final static int ANNOTATION_INDEX_MOLECULAR_FUNCTION = 32;
private static void parseOneNameSpace(String namespaceAnnotation, String[] geneSymbols, String[] geneTitles, String[] entrezIds) {
for (Integer goId : getGoId(namespaceAnnotation)) {
Set<String> genes = term2Gene.get(goId);
if (genes == null) {
genes = new HashSet<String>();
term2Gene.put(goId, genes);
}
for(int i=0; i<geneSymbols.length; i++) {
String geneSymbol = geneSymbols[i];
String geneTitle = "";
if(i<geneTitles.length)
geneTitle = geneTitles[i];
int entrezId = 0;
if(i<entrezIds.length) {
try {
entrezId = Integer.parseInt(entrezIds[i].trim());
} catch (NumberFormatException e) {
log.debug("unexpected entrezId field "+entrezIds[i]);
countUnexpectedEntrezId++;
continue;
}
}
genes.add(geneSymbol);
if(!geneDetails.containsKey(geneSymbol) && entrezId!=0) {
GeneDetails details = new GeneDetails(geneTitle, entrezId);
geneDetails.put(geneSymbol, details);
}
}
}
}
private static List<Integer> getGoId(String annotationField) {
List<Integer> ids = new ArrayList<Integer>();
String[] goTerm = annotationField.split("///");
for(String g: goTerm) {
String[] f = g.split("//");
try {
ids.add( Integer.valueOf(f[0].trim()) );
} catch (NumberFormatException e) {
// do nothing for non-number case, like "---"
// log.debug("non-number in annotation "+f[0]);
}
}
return ids;
}
private static Map<String, GeneDetails> geneDetails = new HashMap<String, GeneDetails>();
// this is necessary because there may be need to include more details
private static class GeneDetails {
public GeneDetails(String geneTitle, int entrezId) {
this.geneTitle = geneTitle;
this.entrezId = entrezId;
}
private String geneTitle;
private int entrezId;
public int getEntrezId() {return entrezId; }
public String toString() {return geneTitle; }
}
// used by GoAnalysis to build up the result object
public void addChangedGenes(String gene) {
changedGenes.add(gene);
}
// used by GoAnalysis to build up the result object
public void addReferenceGenes(String gene) {
referenceGenes.add(gene);
}
// used by GoAnalysis to build up the result object
public void addResultRow(int termId, String termName, String namespace, double p, double adjustedP, int popCount, int studyCount) {
if(termId==0)return;
ResultRow row = new ResultRow(termName, namespace, p, adjustedP, popCount, studyCount);
result.put(termId, row);
}
public String getRowAsString(int goId) {
GoAnalysisResult.ResultRow row = getRow(goId);
if(row==null)return null;
return row.name+" ("+row.studyCount+"/"+row.popCount+") ("+row.pAdjusted+")";
}
public Set<String> getChangedGenes() {
return changedGenes;
}
public Set<String> getReferenceGenes() {
return referenceGenes;
}
public Object[][] getResultAsArray() {
int rowCount = getCount();
List<Object[]> rows = new ArrayList<Object[]>();
for(Integer goId: result.keySet()) {
GoAnalysisResult.ResultRow resultRow = getRow(goId);
Object[] array = new Object[COLUMN_COUNT];
array[TABLE_COLUMN_INDEX_GO_ID] = goId;
array[TABLE_COLUMN_INDEX_GO_TERM_NAME] = resultRow.name;
array[TABLE_COLUMN_INDEX_NAMESPACE] = resultRow.namespace;
array[TABLE_COLUMN_INDEX_P] = resultRow.p;
array[TABLE_COLUMN_INDEX_ADJUSTED_P] = resultRow.pAdjusted;
array[TABLE_COLUMN_INDEX_POP_COUNT] = resultRow.popCount;
array[TABLE_COLUMN_INDEX_STUDY_COUNT] = resultRow.studyCount;
rows.add(array);
}
log.debug("total rows: "+rowCount);
Collections.sort(rows, new AdjustedPComparator());
int row = 0;
Object[][] data = new Object[rowCount][COLUMN_COUNT];
for(Object[] array: rows) {
data[row] = array;
row++;
}
return data;
}
// only used for getRwoAsArray
private static final int COLUMN_COUNT = 7;
private static final int TABLE_COLUMN_INDEX_GO_ID = 0;
private static final int TABLE_COLUMN_INDEX_GO_TERM_NAME = 1;
private static final int TABLE_COLUMN_INDEX_NAMESPACE = 2;
private static final int TABLE_COLUMN_INDEX_P = 3;
private static final int TABLE_COLUMN_INDEX_ADJUSTED_P = 4;
private static final int TABLE_COLUMN_INDEX_POP_COUNT = 5;
private static final int TABLE_COLUMN_INDEX_STUDY_COUNT = 6;
private static class AdjustedPComparator implements Comparator<Object[]> {
public int compare(Object[] o1, Object[] o2) {
Double d1 = (Double) o1[TABLE_COLUMN_INDEX_ADJUSTED_P];
Double d2 = (Double) o2[TABLE_COLUMN_INDEX_ADJUSTED_P];
if(d1<d2)return -1;
else if(d1>d2)return 1;
else return 0;
}
}
// implement saving workspace
private String annotationFileName = null;
private static String staticAnnotationFileName = null;
private void writeObject(ObjectOutputStream out) throws IOException {
annotationFileName = staticAnnotationFileName;
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
parseAnnotation(annotationFileName);
}
public static void parseOboFile(String oboFilename2) {
// TODO place holder for future feature of multiple gene ontology trees
}
}
| false | true | public static void parseAnnotation(String annotationFileName) {
term2Gene.clear();
geneDetails.clear();
try {
BufferedReader br = new BufferedReader(new FileReader(annotationFileName));
String line = br.readLine();
int count = 0;
countUnexpectedEntrezId = 0;
while(line!=null) {
while(line.startsWith("#"))
line = br.readLine();
line = line.substring(1, line.length()-2); // trimming the leading and trailing quotation mark
String[] fields = line.split("\",\"");
String geneSymbolField = fields[ANNOTATION_INDEX_GENE_SYMBOL];
String biologicalProcess = fields[ANNOTATION_INDEX_BIOLOGICAL_PROCESS];
String cellularComponent = fields[ANNOTATION_INDEX_CELLULAR_COMPONENT];
String molecularFunction = fields[ANNOTATION_INDEX_MOLECULAR_FUNCTION];
if (count > 0 && !geneSymbolField.equals("---") ) {
String[] geneSymbols = geneSymbolField.split("///");
String[] geneTitles = fields[ANNOTATION_INDEX_GENE_TITLE].trim().split("///");
String[] entrezIds = fields[ANNOTATION_INDEX_ENTREZ_ID].trim().split("///");
for(int i=0; i<geneSymbols.length; i++)
geneSymbols[i] = geneSymbols[i].trim();
parseOneNameSpace(biologicalProcess, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(cellularComponent, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(molecularFunction, geneSymbols, geneTitles, entrezIds);
}
count++;
line = br.readLine();
}
br.close();
log.debug("total records in annotation file is "+count);
if(countUnexpectedEntrezId>0)
log.warn("total count of unexpected entrezId "+countUnexpectedEntrezId);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("Annotation map is not successfullly created due to FileNotException: "+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
log.error("Annotation map is not successfullly created due to IOException: "+e.getMessage());
}
staticAnnotationFileName = annotationFileName;
}
| public static void parseAnnotation(String annotationFileName) throws IOException {
term2Gene.clear();
geneDetails.clear();
try {
BufferedReader br = new BufferedReader(new FileReader(annotationFileName));
String line = br.readLine();
int count = 0;
countUnexpectedEntrezId = 0;
while(line!=null) {
while(line.startsWith("#"))
line = br.readLine();
line = line.substring(1, line.length()-2); // trimming the leading and trailing quotation mark
String[] fields = line.split("\",\"");
final int AFFY_COLUMN_COUNT = 41;
if(fields.length!=AFFY_COLUMN_COUNT) {
throw new IOException("Annotation file "+annotationFileName+" not recognized.");
}
String geneSymbolField = fields[ANNOTATION_INDEX_GENE_SYMBOL];
String biologicalProcess = fields[ANNOTATION_INDEX_BIOLOGICAL_PROCESS];
String cellularComponent = fields[ANNOTATION_INDEX_CELLULAR_COMPONENT];
String molecularFunction = fields[ANNOTATION_INDEX_MOLECULAR_FUNCTION];
if (count > 0 && !geneSymbolField.equals("---") ) {
String[] geneSymbols = geneSymbolField.split("///");
String[] geneTitles = fields[ANNOTATION_INDEX_GENE_TITLE].trim().split("///");
String[] entrezIds = fields[ANNOTATION_INDEX_ENTREZ_ID].trim().split("///");
for(int i=0; i<geneSymbols.length; i++)
geneSymbols[i] = geneSymbols[i].trim();
parseOneNameSpace(biologicalProcess, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(cellularComponent, geneSymbols, geneTitles, entrezIds);
parseOneNameSpace(molecularFunction, geneSymbols, geneTitles, entrezIds);
}
count++;
line = br.readLine();
}
br.close();
log.debug("total records in annotation file is "+count);
if(countUnexpectedEntrezId>0)
log.warn("total count of unexpected entrezId "+countUnexpectedEntrezId);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("Annotation map is not successfullly created due to FileNotException: "+e.getMessage());
}
staticAnnotationFileName = annotationFileName;
}
|
diff --git a/wings/src/java/org/wings/plaf/css/DialogCG.java b/wings/src/java/org/wings/plaf/css/DialogCG.java
index 01324a1..5ac3366 100644
--- a/wings/src/java/org/wings/plaf/css/DialogCG.java
+++ b/wings/src/java/org/wings/plaf/css/DialogCG.java
@@ -1,68 +1,68 @@
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.wings.*;
import org.wings.io.Device;
import org.wings.plaf.css.script.OnPageRenderedScript;
import org.wings.session.ScriptManager;
import java.io.IOException;
public class DialogCG extends WindowCG implements org.wings.plaf.DialogCG {
public void writeInternal(Device device, SComponent component) throws IOException {
SDialog dialog = (SDialog) component;
SRootContainer owner = dialog.getOwner();
String name = dialog.getName();
device.print("\n\n" +
"<div id=\"" + name + "\">\n" +
" <div class=\"hd\">" + (dialog.getTitle() != null ? dialog.getTitle() : " ") + "</div>\n" +
- " <div class=\"bd\" style=\"padding:0;\">");
+ " <div class=\"bd\" style=\"padding:0; overflow:auto;\">");
super.writeInternal(device, dialog);
device.print(" </div>\n" +
"</div>\n");
StringBuilder sb = new StringBuilder();
sb.append("dialog_").append(name).append(" = new wingS.dialog.SDialog(\"").append(name).append("\"")
.append(", {");
if (dialog.getX() > -1 && dialog.getY() > -1) {
sb.append("x:").append(dialog.getX()).append(",")
.append("y:").append(dialog.getY()).append(",");
}
else {
sb.append("fixedcenter:true").append(",");
}
if (!(owner instanceof SFrame))
sb.append("viewportelement:\"").append(owner.getName()).append("\",");
sb.append("visible:").append(dialog.isVisible()).append(",")
.append("modal:").append(dialog.isModal()).append(",")
.append("draggable:").append(dialog.isDraggable()).append(",")
.append("close:").append(dialog.isClosable()).append(",")
.append("constraintoviewport:true").append("});\n")
.append("dialog_").append(name).append(".render();\n");
//sb.append("var resize = new YAHOO.util.Resize(\"").append(name).append("\");");
ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(sb.toString()));
}
}
| true | true | public void writeInternal(Device device, SComponent component) throws IOException {
SDialog dialog = (SDialog) component;
SRootContainer owner = dialog.getOwner();
String name = dialog.getName();
device.print("\n\n" +
"<div id=\"" + name + "\">\n" +
" <div class=\"hd\">" + (dialog.getTitle() != null ? dialog.getTitle() : " ") + "</div>\n" +
" <div class=\"bd\" style=\"padding:0;\">");
super.writeInternal(device, dialog);
device.print(" </div>\n" +
"</div>\n");
StringBuilder sb = new StringBuilder();
sb.append("dialog_").append(name).append(" = new wingS.dialog.SDialog(\"").append(name).append("\"")
.append(", {");
if (dialog.getX() > -1 && dialog.getY() > -1) {
sb.append("x:").append(dialog.getX()).append(",")
.append("y:").append(dialog.getY()).append(",");
}
else {
sb.append("fixedcenter:true").append(",");
}
if (!(owner instanceof SFrame))
sb.append("viewportelement:\"").append(owner.getName()).append("\",");
sb.append("visible:").append(dialog.isVisible()).append(",")
.append("modal:").append(dialog.isModal()).append(",")
.append("draggable:").append(dialog.isDraggable()).append(",")
.append("close:").append(dialog.isClosable()).append(",")
.append("constraintoviewport:true").append("});\n")
.append("dialog_").append(name).append(".render();\n");
//sb.append("var resize = new YAHOO.util.Resize(\"").append(name).append("\");");
ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(sb.toString()));
}
| public void writeInternal(Device device, SComponent component) throws IOException {
SDialog dialog = (SDialog) component;
SRootContainer owner = dialog.getOwner();
String name = dialog.getName();
device.print("\n\n" +
"<div id=\"" + name + "\">\n" +
" <div class=\"hd\">" + (dialog.getTitle() != null ? dialog.getTitle() : " ") + "</div>\n" +
" <div class=\"bd\" style=\"padding:0; overflow:auto;\">");
super.writeInternal(device, dialog);
device.print(" </div>\n" +
"</div>\n");
StringBuilder sb = new StringBuilder();
sb.append("dialog_").append(name).append(" = new wingS.dialog.SDialog(\"").append(name).append("\"")
.append(", {");
if (dialog.getX() > -1 && dialog.getY() > -1) {
sb.append("x:").append(dialog.getX()).append(",")
.append("y:").append(dialog.getY()).append(",");
}
else {
sb.append("fixedcenter:true").append(",");
}
if (!(owner instanceof SFrame))
sb.append("viewportelement:\"").append(owner.getName()).append("\",");
sb.append("visible:").append(dialog.isVisible()).append(",")
.append("modal:").append(dialog.isModal()).append(",")
.append("draggable:").append(dialog.isDraggable()).append(",")
.append("close:").append(dialog.isClosable()).append(",")
.append("constraintoviewport:true").append("});\n")
.append("dialog_").append(name).append(".render();\n");
//sb.append("var resize = new YAHOO.util.Resize(\"").append(name).append("\");");
ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(sb.toString()));
}
|
diff --git a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java
index ab476056..fadf3567 100644
--- a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java
+++ b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java
@@ -1,328 +1,330 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
package org.opensolaris.opengrok.history;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import org.opensolaris.opengrok.OpenGrokLogger;
/**
* Access to a ClearCase repository.
*
*/
public class ClearCaseRepository extends Repository {
private boolean verbose;
/**
* Creates a new instance of ClearCaseRepository
*/
public ClearCaseRepository() {
}
/**
* Get the name of the ClearCase command that should be used
* @return the name of the cleartool command in use
*/
private String getCommand() {
return System.getProperty("org.opensolaris.opengrok.history.ClearCase", "cleartool");
}
/**
* Use verbose log messages, or just the summary
* @return true if verbose log messages are used for this repository
*/
public boolean isVerbose() {
return verbose;
}
/**
* Specify if verbose log messages or just the summary should be used
* @param verbose set to true if verbose messages should be used
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
Process getHistoryLogProcess(File file) throws IOException {
String abs = file.getAbsolutePath();
String filename = "";
String directoryName = getDirectoryName();
if (abs.length() > directoryName.length()) {
filename = abs.substring(directoryName.length() + 1);
}
ArrayList<String> argv = new ArrayList<String>();
argv.add(getCommand());
argv.add("lshistory");
if (file.isDirectory()) {
argv.add("-dir");
}
argv.add("-fmt");
argv.add("%e\n%Nd\n%Fu (%u)\n%Vn\n%Nc\n.\n");
argv.add(filename);
ProcessBuilder pb = new ProcessBuilder(argv);
File directory = new File(getDirectoryName());
pb.directory(directory);
return pb.start();
}
public InputStream getHistoryGet(String parent, String basename, String rev) {
InputStream ret = null;
String directoryName = getDirectoryName();
File directory = new File(directoryName);
String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1);
Process process = null;
try {
final File tmp = File.createTempFile("opengrok", "tmp");
String tmpName = tmp.getAbsolutePath();
// cleartool can't get to a previously existing file
if (tmp.exists()) {
if (!tmp.delete()) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache");
}
}
String decorated = filename + "@@" + rev;
String argv[] = {getCommand(), "get", "-to", tmpName, decorated};
process = Runtime.getRuntime().exec(argv, null, directory);
drainStream(process.getInputStream());
- process.exitValue();
+ if(waitFor(process) != 0) {
+ return null;
+ }
ret = new BufferedInputStream(new FileInputStream(tmp) {
public void close() throws IOException {
super.close();
// delete the temporary file on close
if (!tmp.delete()) {
// failed, lets do the next best thing then ..
// delete it on JVM exit
tmp.deleteOnExit();
}
}
});
} catch (Exception exp) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp);
} finally {
// Clean up zombie-processes...
if (process != null) {
try {
process.exitValue();
} catch (IllegalThreadStateException exp) {
// the process is still running??? just kill it..
process.destroy();
}
}
}
return ret;
}
/**
* Drain all data from a stream and close it.
* @param in the stream to drain
* @throws IOException if an I/O error occurs
*/
private static void drainStream(InputStream in) throws IOException {
while (true) {
long skipped = in.skip(32768L);
if (skipped == 0) {
// No bytes skipped, check if we've reached EOF with read()
if (in.read() == -1) {
break;
}
}
}
in.close();
}
public Class<? extends HistoryParser> getHistoryParser() {
return ClearCaseHistoryParser.class;
}
public Class<? extends HistoryParser> getDirectoryHistoryParser() {
return ClearCaseHistoryParser.class;
}
/**
* Annotate the specified file/revision.
*
* @param file file to annotate
* @param revision revision to annotate
* @return file annotation
*/
public Annotation annotate(File file, String revision) throws Exception {
ArrayList<String> argv = new ArrayList<String>();
argv.add(getCommand());
argv.add("annotate");
argv.add("-nheader");
argv.add("-out");
argv.add("-");
argv.add("-f");
argv.add("-fmt");
argv.add("%u|%Vn|");
if (revision != null) {
argv.add(revision);
}
argv.add(file.getName());
ProcessBuilder pb = new ProcessBuilder(argv);
pb.directory(file.getParentFile());
Process process = null;
BufferedReader in = null;
try {
process = pb.start();
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
Annotation a = new Annotation(file.getName());
String line;
int lineno = 0;
while ((line = in.readLine()) != null) {
++lineno;
String parts[] = line.split("\\|");
String aAuthor = parts[0];
String aRevision = parts[1];
aRevision = aRevision.replace('\\', '/');
a.addLine(aRevision, aAuthor, true);
}
return a;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException exp) {
// ignore
}
}
if (process != null) {
try {
process.exitValue();
} catch (IllegalThreadStateException e) {
process.destroy();
}
}
}
}
public boolean fileHasAnnotation(File file) {
return true;
}
public boolean isCacheable() {
return true;
}
private int waitFor(Process process) {
do {
try {
return process.waitFor();
} catch (InterruptedException exp) {
}
} while (true);
}
public void update() throws Exception {
Process process = null;
BufferedReader in = null;
try {
File directory = new File(getDirectoryName());
// Check if this is a snapshot view
String[] argv = {getCommand(), "catcs"};
process = Runtime.getRuntime().exec(argv, null, directory);
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
boolean snapshot = false;
String line;
while (!snapshot && (line = in.readLine()) != null) {
snapshot = line.startsWith("load");
}
if (waitFor(process) != 0) {
return;
}
in.close();
in = null; // To avoid double close in finally clause
if (snapshot) {
// It is a snapshot view, we need to update it manually
argv = new String[]{getCommand(), "update", "-overwrite", "-f"};
process = Runtime.getRuntime().exec(argv, null, directory);
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
// consume output
while ((line = in.readLine()) != null) {
// do nothing
}
if (waitFor(process) != 0) {
return;
}
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
if (process != null) {
try {
process.exitValue();
} catch (IllegalThreadStateException e) {
process.destroy();
}
}
}
}
public boolean fileHasHistory(File file) {
// Todo: is there a cheap test for whether ClearCase has history
// available for a file?
// Otherwise, this is harmless, since ClearCase's commands will just
// print nothing if there is no history.
return true;
}
@Override
boolean isRepositoryFor( File file) {
// if the parent contains a file named "view.dat" or
// the parent is named "vobs"
File f = new File(file, "view.dat");
if (f.exists() && f.isDirectory()) {
return true;
} else {
return file.isDirectory() && file.getName().equalsIgnoreCase("vobs");
}
}
}
| true | true | public InputStream getHistoryGet(String parent, String basename, String rev) {
InputStream ret = null;
String directoryName = getDirectoryName();
File directory = new File(directoryName);
String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1);
Process process = null;
try {
final File tmp = File.createTempFile("opengrok", "tmp");
String tmpName = tmp.getAbsolutePath();
// cleartool can't get to a previously existing file
if (tmp.exists()) {
if (!tmp.delete()) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache");
}
}
String decorated = filename + "@@" + rev;
String argv[] = {getCommand(), "get", "-to", tmpName, decorated};
process = Runtime.getRuntime().exec(argv, null, directory);
drainStream(process.getInputStream());
process.exitValue();
ret = new BufferedInputStream(new FileInputStream(tmp) {
public void close() throws IOException {
super.close();
// delete the temporary file on close
if (!tmp.delete()) {
// failed, lets do the next best thing then ..
// delete it on JVM exit
tmp.deleteOnExit();
}
}
});
} catch (Exception exp) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp);
} finally {
// Clean up zombie-processes...
if (process != null) {
try {
process.exitValue();
} catch (IllegalThreadStateException exp) {
// the process is still running??? just kill it..
process.destroy();
}
}
}
return ret;
}
| public InputStream getHistoryGet(String parent, String basename, String rev) {
InputStream ret = null;
String directoryName = getDirectoryName();
File directory = new File(directoryName);
String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1);
Process process = null;
try {
final File tmp = File.createTempFile("opengrok", "tmp");
String tmpName = tmp.getAbsolutePath();
// cleartool can't get to a previously existing file
if (tmp.exists()) {
if (!tmp.delete()) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache");
}
}
String decorated = filename + "@@" + rev;
String argv[] = {getCommand(), "get", "-to", tmpName, decorated};
process = Runtime.getRuntime().exec(argv, null, directory);
drainStream(process.getInputStream());
if(waitFor(process) != 0) {
return null;
}
ret = new BufferedInputStream(new FileInputStream(tmp) {
public void close() throws IOException {
super.close();
// delete the temporary file on close
if (!tmp.delete()) {
// failed, lets do the next best thing then ..
// delete it on JVM exit
tmp.deleteOnExit();
}
}
});
} catch (Exception exp) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp);
} finally {
// Clean up zombie-processes...
if (process != null) {
try {
process.exitValue();
} catch (IllegalThreadStateException exp) {
// the process is still running??? just kill it..
process.destroy();
}
}
}
return ret;
}
|
diff --git a/sandbox-providers/tmrk-enterprisecloud/src/test/java/org/jclouds/tmrk/enterprisecloud/xml/ComputePoolCpuUsageJAXBParsingTest.java b/sandbox-providers/tmrk-enterprisecloud/src/test/java/org/jclouds/tmrk/enterprisecloud/xml/ComputePoolCpuUsageJAXBParsingTest.java
index 919d561bd6..7291b5ff58 100644
--- a/sandbox-providers/tmrk-enterprisecloud/src/test/java/org/jclouds/tmrk/enterprisecloud/xml/ComputePoolCpuUsageJAXBParsingTest.java
+++ b/sandbox-providers/tmrk-enterprisecloud/src/test/java/org/jclouds/tmrk/enterprisecloud/xml/ComputePoolCpuUsageJAXBParsingTest.java
@@ -1,145 +1,145 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.tmrk.enterprisecloud.xml;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.Provides;
import org.jclouds.crypto.Crypto;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.BaseRestClientTest;
import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.tmrk.enterprisecloud.domain.Link;
import org.jclouds.tmrk.enterprisecloud.domain.resource.cpu.ComputePoolCpuUsage;
import org.jclouds.tmrk.enterprisecloud.domain.resource.cpu.ComputePoolCpuUsageDetailSummaryEntry;
import org.jclouds.tmrk.enterprisecloud.domain.resource.cpu.CpuUsageDetails;
import org.jclouds.tmrk.enterprisecloud.features.ResourceAsyncClient;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Named;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Set;
import static org.jclouds.io.Payloads.newInputStreamPayload;
import static org.jclouds.rest.RestContextFactory.contextSpec;
import static org.jclouds.rest.RestContextFactory.createContextBuilder;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* Tests behavior of JAXB parsing for ComputePoolCpuUsage
*
* @author Jason King
*/
@Test(groups = "unit", testName = "ComputePoolCpuUsageJAXBParsingTest")
public class ComputePoolCpuUsageJAXBParsingTest extends BaseRestClientTest {
private SimpleDateFormatDateService dateService;
@BeforeMethod
public void setUp() {
dateService = new SimpleDateFormatDateService();
}
@BeforeClass
void setupFactory() {
RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", "userfoo",
"credentialFoo", String.class, Integer.class,
ImmutableSet.<Module>of(new MockModule(), new NullLoggingModule(), new AbstractModule() {
@Override
protected void configure() {
}
@SuppressWarnings("unused")
@Provides
@Named("exception")
Set<String> exception() {
throw new AuthorizationException();
}
}));
injector = createContextBuilder(contextSpec).buildInjector();
parserFactory = injector.getInstance(ParseSax.Factory.class);
crypto = injector.getInstance(Crypto.class);
}
public void testParseWithJAXB() throws Exception {
Method method = ResourceAsyncClient.class.getMethod("getComputePoolCpuUsage", URI.class);
HttpRequest request = factory(ResourceAsyncClient.class).createRequest(method,new URI("/1"));
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
Function<HttpResponse, ComputePoolCpuUsage> parser = (Function<HttpResponse, ComputePoolCpuUsage>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request);
- InputStream is = getClass().getResourceAsStream("/computePoolsCpuUsage.xml");
+ InputStream is = getClass().getResourceAsStream("/computePoolCpuUsage.xml");
ComputePoolCpuUsage cpuUsage = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
assertLinks(cpuUsage.getLinks());
assertEquals(cpuUsage.getStartTime(), dateService.iso8601DateParse("2011-12-05T09:45:00.0Z"));
assertEquals(cpuUsage.getEndTime(), dateService.iso8601DateParse("2011-12-06T09:45:00.0Z"));
assertDetails(cpuUsage.getDetails());
Set<ComputePoolCpuUsageDetailSummaryEntry> entries = cpuUsage.getDetails().getEntries();
ComputePoolCpuUsageDetailSummaryEntry first = Iterables.getFirst(entries, null);
assertEquals(cpuUsage.getStartTime(),first.getTime());
ComputePoolCpuUsageDetailSummaryEntry last = Iterables.getLast(entries, null);
assertEquals(cpuUsage.getEndTime(),last.getTime());
}
private void assertLinks(Set<Link> links) {
assertEquals(links.size(),2);
Link link = Iterables.get(links, 0);
assertEquals(link.getName(),"Default Compute Pool");
assertEquals(link.getRelationship(), Link.Relationship.UP);
Link link2 = Iterables.get(links, 1);
assertEquals(link2.getHref(), URI.create("/cloudapi/ecloud/computepools/89/usage/cpu/details?time=2011-12-05t09%3a45%3a00z"));
assertEquals(link2.getType(), "application/vnd.tmrk.cloud.computePoolCpuUsageDetail");
assertEquals(link2.getRelationship(), Link.Relationship.DOWN);
}
private void assertDetails(CpuUsageDetails details) {
assertEquals(details.getEntries().size(), 289);
for(ComputePoolCpuUsageDetailSummaryEntry entry: details.getEntries()) {
assertDetail(entry);
}
}
private void assertDetail(ComputePoolCpuUsageDetailSummaryEntry entry) {
assertNotNull(entry.getTime());
assertNotNull(entry.getValue());
}
}
| true | true | public void testParseWithJAXB() throws Exception {
Method method = ResourceAsyncClient.class.getMethod("getComputePoolCpuUsage", URI.class);
HttpRequest request = factory(ResourceAsyncClient.class).createRequest(method,new URI("/1"));
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
Function<HttpResponse, ComputePoolCpuUsage> parser = (Function<HttpResponse, ComputePoolCpuUsage>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request);
InputStream is = getClass().getResourceAsStream("/computePoolsCpuUsage.xml");
ComputePoolCpuUsage cpuUsage = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
assertLinks(cpuUsage.getLinks());
assertEquals(cpuUsage.getStartTime(), dateService.iso8601DateParse("2011-12-05T09:45:00.0Z"));
assertEquals(cpuUsage.getEndTime(), dateService.iso8601DateParse("2011-12-06T09:45:00.0Z"));
assertDetails(cpuUsage.getDetails());
Set<ComputePoolCpuUsageDetailSummaryEntry> entries = cpuUsage.getDetails().getEntries();
ComputePoolCpuUsageDetailSummaryEntry first = Iterables.getFirst(entries, null);
assertEquals(cpuUsage.getStartTime(),first.getTime());
ComputePoolCpuUsageDetailSummaryEntry last = Iterables.getLast(entries, null);
assertEquals(cpuUsage.getEndTime(),last.getTime());
}
| public void testParseWithJAXB() throws Exception {
Method method = ResourceAsyncClient.class.getMethod("getComputePoolCpuUsage", URI.class);
HttpRequest request = factory(ResourceAsyncClient.class).createRequest(method,new URI("/1"));
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
Function<HttpResponse, ComputePoolCpuUsage> parser = (Function<HttpResponse, ComputePoolCpuUsage>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request);
InputStream is = getClass().getResourceAsStream("/computePoolCpuUsage.xml");
ComputePoolCpuUsage cpuUsage = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
assertLinks(cpuUsage.getLinks());
assertEquals(cpuUsage.getStartTime(), dateService.iso8601DateParse("2011-12-05T09:45:00.0Z"));
assertEquals(cpuUsage.getEndTime(), dateService.iso8601DateParse("2011-12-06T09:45:00.0Z"));
assertDetails(cpuUsage.getDetails());
Set<ComputePoolCpuUsageDetailSummaryEntry> entries = cpuUsage.getDetails().getEntries();
ComputePoolCpuUsageDetailSummaryEntry first = Iterables.getFirst(entries, null);
assertEquals(cpuUsage.getStartTime(),first.getTime());
ComputePoolCpuUsageDetailSummaryEntry last = Iterables.getLast(entries, null);
assertEquals(cpuUsage.getEndTime(),last.getTime());
}
|
diff --git a/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/util/ParticipantSearchDecorator.java b/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/util/ParticipantSearchDecorator.java
index 212782b9..2c983f2c 100644
--- a/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/util/ParticipantSearchDecorator.java
+++ b/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/util/ParticipantSearchDecorator.java
@@ -1,60 +1,60 @@
package gov.nih.nci.caxchange.ctom.viewer.util;
import gov.nih.nci.caxchange.ctom.viewer.viewobjects.ParticipantSearchResult;
import org.displaytag.decorator.TableDecorator;
/**
* @author Anupama Sharma
*/
public class ParticipantSearchDecorator extends TableDecorator
{
private static final String NBSP = " ";
public ParticipantSearchDecorator()
{
super();
}
- public final String getFristName()
+ public final String getFirstName()
{
ParticipantSearchResult partSearchResult = (ParticipantSearchResult) getCurrentRowObject();
String fName = NBSP;
if (partSearchResult.getFirstName() != null && !partSearchResult.getFirstName().equals("")
&& !partSearchResult.getFirstName().equals("null"))
{
fName = partSearchResult.getFirstName();
}
return fName;
}
public final String getLastName()
{
ParticipantSearchResult partSearchResult = (ParticipantSearchResult) getCurrentRowObject();
String lName = NBSP;
if (partSearchResult.getLastName() != null && !partSearchResult.getLastName().equals("")
&& !partSearchResult.getLastName().equals("null"))
{
lName = partSearchResult.getLastName();
}
return lName;
}
public final String getStudyId()
{
ParticipantSearchResult partSearchResult = (ParticipantSearchResult) getCurrentRowObject();
String studyId = NBSP;
if (partSearchResult.getStudyId() != null && !partSearchResult.getStudyId().equals("")
&& !partSearchResult.getStudyId().equals("null"))
{
studyId = partSearchResult.getStudyId();
}
return studyId;
}
}
| true | true | public final String getFristName()
{
ParticipantSearchResult partSearchResult = (ParticipantSearchResult) getCurrentRowObject();
String fName = NBSP;
if (partSearchResult.getFirstName() != null && !partSearchResult.getFirstName().equals("")
&& !partSearchResult.getFirstName().equals("null"))
{
fName = partSearchResult.getFirstName();
}
return fName;
}
| public final String getFirstName()
{
ParticipantSearchResult partSearchResult = (ParticipantSearchResult) getCurrentRowObject();
String fName = NBSP;
if (partSearchResult.getFirstName() != null && !partSearchResult.getFirstName().equals("")
&& !partSearchResult.getFirstName().equals("null"))
{
fName = partSearchResult.getFirstName();
}
return fName;
}
|
diff --git a/src/com/shreyaschand/MEDIC/Doctor/Display.java b/src/com/shreyaschand/MEDIC/Doctor/Display.java
index 7e47394..d832356 100644
--- a/src/com/shreyaschand/MEDIC/Doctor/Display.java
+++ b/src/com/shreyaschand/MEDIC/Doctor/Display.java
@@ -1,103 +1,102 @@
package com.shreyaschand.MEDIC.Doctor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ScrollView;
import android.widget.TextView;
public class Display extends Activity implements OnClickListener {
private TextView output = null;
private ScrollView scroller = null;
private Socket socket = null;
private String user;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
findViewById(R.id.display_back_button).setOnClickListener(this);
output = ((TextView) findViewById(R.id.test_output));
scroller = (ScrollView) findViewById(R.id.display_scroller);
user = getIntent().getExtras().getString("com.shreyaschand.MEDIC.Doctor.user");
}
public void onStart() {
super.onStart();
new ConnectSocket().execute();
}
public void onClick(View arg0) {
finish();
}
private class ConnectSocket extends AsyncTask<Void, String, Boolean> {
protected Boolean doInBackground(Void... params) {
try {
publishProgress("Establishing connection...\n");
socket = new Socket("chands.dyndns-server.com", 1028);
publishProgress("Connected.\n");
return true;
} catch (IOException e) {return false;}
}
protected void onProgressUpdate(String... updates) {
output.append(updates[0]);
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
protected void onPostExecute(Boolean result) {
if (result) {
new SocketCommunicator().execute(socket);
} else {
output.append("Error connecting.");
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
}
}
private class SocketCommunicator extends AsyncTask<Socket, String, Boolean> {
protected Boolean doInBackground(Socket... socket) {
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(
- socket[0].getInputStream()));
+ BufferedReader in = new BufferedReader(new InputStreamReader(socket[0].getInputStream()));
PrintWriter out = new PrintWriter(socket[0].getOutputStream());
out.println("$DOC$" + user);
out.flush();
- out.close();
+// out.close();
String message = in.readLine();
while (message != null) {
publishProgress(new String[] { message });
message = in.readLine();
}
- } catch (IOException e) {return false;}
+ } catch (IOException e) {e.printStackTrace();return false;}
return true;
}
protected void onProgressUpdate(String... update) {
output.append("\n" + update[0]);
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
protected void onPostExecute(Boolean result) {
if(result) {
output.append("\nConnection closed.");
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}else {
output.append("\nConnection lost unexepectedly.");
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
}
}
}
| false | true | protected Boolean doInBackground(Socket... socket) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket[0].getInputStream()));
PrintWriter out = new PrintWriter(socket[0].getOutputStream());
out.println("$DOC$" + user);
out.flush();
out.close();
String message = in.readLine();
while (message != null) {
publishProgress(new String[] { message });
message = in.readLine();
}
} catch (IOException e) {return false;}
return true;
}
| protected Boolean doInBackground(Socket... socket) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket[0].getInputStream()));
PrintWriter out = new PrintWriter(socket[0].getOutputStream());
out.println("$DOC$" + user);
out.flush();
// out.close();
String message = in.readLine();
while (message != null) {
publishProgress(new String[] { message });
message = in.readLine();
}
} catch (IOException e) {e.printStackTrace();return false;}
return true;
}
|
diff --git a/src/joshua/decoder/DecoderThread.java b/src/joshua/decoder/DecoderThread.java
index a25891e9..4f471410 100644
--- a/src/joshua/decoder/DecoderThread.java
+++ b/src/joshua/decoder/DecoderThread.java
@@ -1,151 +1,151 @@
package joshua.decoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import joshua.decoder.chart_parser.Chart;
import joshua.decoder.ff.FeatureFunction;
import joshua.decoder.ff.FeatureVector;
import joshua.decoder.ff.SourceDependentFF;
import joshua.decoder.ff.state_maintenance.StateComputer;
import joshua.decoder.ff.tm.Grammar;
import joshua.decoder.ff.tm.GrammarFactory;
import joshua.decoder.hypergraph.ForestWalker;
import joshua.decoder.hypergraph.GrammarBuilderWalkerFunction;
import joshua.decoder.hypergraph.HyperGraph;
import joshua.decoder.segment_file.Sentence;
import joshua.corpus.Vocabulary;
/**
* This class handles decoding of individual Sentence objects (which can represent plain sentences
* or lattices). A single sentence can be decoded by a call to translate() and, if an InputHandler
* is used, many sentences can be decoded in a thread-safe manner via a single call to
* translateAll(), which continually queries the InputHandler for sentences until they have all been
* consumed and translated.
*
* The DecoderFactory class is responsible for launching the threads.
*
* @author Matt Post <[email protected]>
* @author Zhifei Li, <[email protected]>
*/
public class DecoderThread extends Thread {
/*
* these variables may be the same across all threads (e.g., just copy from DecoderFactory), or
* differ from thread to thread
*/
private final List<GrammarFactory> grammarFactories;
private final List<FeatureFunction> featureFunctions;
private final List<StateComputer> stateComputers;
private static final Logger logger = Logger.getLogger(DecoderThread.class.getName());
// ===============================================================
// Constructor
// ===============================================================
public DecoderThread(List<GrammarFactory> grammarFactories, FeatureVector weights,
List<FeatureFunction> featureFunctions, List<StateComputer> stateComputers)
throws IOException {
this.grammarFactories = grammarFactories;
this.stateComputers = stateComputers;
this.featureFunctions = new ArrayList<FeatureFunction>();
for (FeatureFunction ff : featureFunctions) {
if (ff instanceof SourceDependentFF) {
this.featureFunctions.add(((SourceDependentFF) ff).clone());
} else {
this.featureFunctions.add(ff);
}
}
}
// ===============================================================
// Methods
// ===============================================================
@Override
public void run() {
// Nothing to do but wait.
}
/**
* Translate a sentence.
*
* @param sentence The sentence to be translated.
*/
public Translation translate(Sentence sentence) {
logger.info("Translating sentence #" + sentence.id() + " [thread " + getId() + "]\n"
+ sentence.source());
if (sentence.target() != null)
logger.info("Constraining to target sentence '" + sentence.target() + "'");
// skip blank sentences
if (sentence.isEmpty()) {
logger.info("translation of sentence " + sentence.id() + " took 0 seconds [" + getId() + "]");
return new Translation(sentence, null, featureFunctions);
}
long startTime = System.currentTimeMillis();
int numGrammars = grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i < grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence);
/* Seeding: the chart only sees the grammars, not the factories */
Chart chart = new Chart(sentence, this.featureFunctions, this.stateComputers, grammars,
JoshuaConfiguration.goal_symbol);
/* Parsing */
HyperGraph hypergraph = chart.expand();
float seconds = (System.currentTimeMillis() - startTime) / 1000.0f;
logger.info(String.format("translation of sentence %d took %.3f seconds [thread %d]",
sentence.id(), seconds, getId()));
if (!JoshuaConfiguration.parse || hypergraph == null) {
return new Translation(sentence, hypergraph, featureFunctions);
}
/*
* Synchronous parsing.
*
* Step 1. Traverse the hypergraph to create a grammar for the second-pass parse.
*/
Grammar newGrammar = getGrammarFromHyperGraph(JoshuaConfiguration.goal_symbol, hypergraph);
newGrammar.sortGrammar(this.featureFunctions);
long sortTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: New grammar has %d rules.", sentence.id(), newGrammar.getNumRules()));
/* Step 2. Create a new chart and parse with the instantiated grammar. */
Grammar[] newGrammarArray = new Grammar[] { newGrammar };
Sentence targetSentence = new Sentence(sentence.target(), sentence.id());
chart = new Chart(targetSentence, featureFunctions, stateComputers, newGrammarArray, "GOAL");
int goalSymbol = GrammarBuilderWalkerFunction.goalSymbol(hypergraph);
- String goalSymbolString = Vocabulary.word(goalSymbol);
+ String goalSymbolString = Vocabulary.word(goalSymbol);
logger.info(String.format("Sentence %d: goal symbol is %s (%d).", sentence.id(), goalSymbolString, goalSymbol));
chart.setGoalSymbolID(goalSymbol);
/* Parsing */
HyperGraph englishParse = chart.expand();
long secondParseTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: Finished second chart expansion (%d seconds).", sentence.id(),
(secondParseTime - sortTime) / 1000));
logger.info(String.format("Sentence %d total time: %d seconds.\n", sentence.id(), (secondParseTime - startTime) / 1000));
return new Translation(sentence, englishParse, featureFunctions); // or do something else
}
private static Grammar getGrammarFromHyperGraph(String goal, HyperGraph hg) {
GrammarBuilderWalkerFunction f = new GrammarBuilderWalkerFunction(goal);
ForestWalker walker = new ForestWalker();
walker.walk(hg.goalNode, f);
return f.getGrammar();
}
}
| true | true | public Translation translate(Sentence sentence) {
logger.info("Translating sentence #" + sentence.id() + " [thread " + getId() + "]\n"
+ sentence.source());
if (sentence.target() != null)
logger.info("Constraining to target sentence '" + sentence.target() + "'");
// skip blank sentences
if (sentence.isEmpty()) {
logger.info("translation of sentence " + sentence.id() + " took 0 seconds [" + getId() + "]");
return new Translation(sentence, null, featureFunctions);
}
long startTime = System.currentTimeMillis();
int numGrammars = grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i < grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence);
/* Seeding: the chart only sees the grammars, not the factories */
Chart chart = new Chart(sentence, this.featureFunctions, this.stateComputers, grammars,
JoshuaConfiguration.goal_symbol);
/* Parsing */
HyperGraph hypergraph = chart.expand();
float seconds = (System.currentTimeMillis() - startTime) / 1000.0f;
logger.info(String.format("translation of sentence %d took %.3f seconds [thread %d]",
sentence.id(), seconds, getId()));
if (!JoshuaConfiguration.parse || hypergraph == null) {
return new Translation(sentence, hypergraph, featureFunctions);
}
/*
* Synchronous parsing.
*
* Step 1. Traverse the hypergraph to create a grammar for the second-pass parse.
*/
Grammar newGrammar = getGrammarFromHyperGraph(JoshuaConfiguration.goal_symbol, hypergraph);
newGrammar.sortGrammar(this.featureFunctions);
long sortTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: New grammar has %d rules.", sentence.id(), newGrammar.getNumRules()));
/* Step 2. Create a new chart and parse with the instantiated grammar. */
Grammar[] newGrammarArray = new Grammar[] { newGrammar };
Sentence targetSentence = new Sentence(sentence.target(), sentence.id());
chart = new Chart(targetSentence, featureFunctions, stateComputers, newGrammarArray, "GOAL");
int goalSymbol = GrammarBuilderWalkerFunction.goalSymbol(hypergraph);
String goalSymbolString = Vocabulary.word(goalSymbol);
logger.info(String.format("Sentence %d: goal symbol is %s (%d).", sentence.id(), goalSymbolString, goalSymbol));
chart.setGoalSymbolID(goalSymbol);
/* Parsing */
HyperGraph englishParse = chart.expand();
long secondParseTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: Finished second chart expansion (%d seconds).", sentence.id(),
(secondParseTime - sortTime) / 1000));
logger.info(String.format("Sentence %d total time: %d seconds.\n", sentence.id(), (secondParseTime - startTime) / 1000));
return new Translation(sentence, englishParse, featureFunctions); // or do something else
}
| public Translation translate(Sentence sentence) {
logger.info("Translating sentence #" + sentence.id() + " [thread " + getId() + "]\n"
+ sentence.source());
if (sentence.target() != null)
logger.info("Constraining to target sentence '" + sentence.target() + "'");
// skip blank sentences
if (sentence.isEmpty()) {
logger.info("translation of sentence " + sentence.id() + " took 0 seconds [" + getId() + "]");
return new Translation(sentence, null, featureFunctions);
}
long startTime = System.currentTimeMillis();
int numGrammars = grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i < grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence);
/* Seeding: the chart only sees the grammars, not the factories */
Chart chart = new Chart(sentence, this.featureFunctions, this.stateComputers, grammars,
JoshuaConfiguration.goal_symbol);
/* Parsing */
HyperGraph hypergraph = chart.expand();
float seconds = (System.currentTimeMillis() - startTime) / 1000.0f;
logger.info(String.format("translation of sentence %d took %.3f seconds [thread %d]",
sentence.id(), seconds, getId()));
if (!JoshuaConfiguration.parse || hypergraph == null) {
return new Translation(sentence, hypergraph, featureFunctions);
}
/*
* Synchronous parsing.
*
* Step 1. Traverse the hypergraph to create a grammar for the second-pass parse.
*/
Grammar newGrammar = getGrammarFromHyperGraph(JoshuaConfiguration.goal_symbol, hypergraph);
newGrammar.sortGrammar(this.featureFunctions);
long sortTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: New grammar has %d rules.", sentence.id(), newGrammar.getNumRules()));
/* Step 2. Create a new chart and parse with the instantiated grammar. */
Grammar[] newGrammarArray = new Grammar[] { newGrammar };
Sentence targetSentence = new Sentence(sentence.target(), sentence.id());
chart = new Chart(targetSentence, featureFunctions, stateComputers, newGrammarArray, "GOAL");
int goalSymbol = GrammarBuilderWalkerFunction.goalSymbol(hypergraph);
String goalSymbolString = Vocabulary.word(goalSymbol);
logger.info(String.format("Sentence %d: goal symbol is %s (%d).", sentence.id(), goalSymbolString, goalSymbol));
chart.setGoalSymbolID(goalSymbol);
/* Parsing */
HyperGraph englishParse = chart.expand();
long secondParseTime = System.currentTimeMillis();
logger.info(String.format("Sentence %d: Finished second chart expansion (%d seconds).", sentence.id(),
(secondParseTime - sortTime) / 1000));
logger.info(String.format("Sentence %d total time: %d seconds.\n", sentence.id(), (secondParseTime - startTime) / 1000));
return new Translation(sentence, englishParse, featureFunctions); // or do something else
}
|
diff --git a/src/ch/epfl/ad/milestone2/app/Query3.java b/src/ch/epfl/ad/milestone2/app/Query3.java
index 32e5c8a..5ece1dd 100644
--- a/src/ch/epfl/ad/milestone2/app/Query3.java
+++ b/src/ch/epfl/ad/milestone2/app/Query3.java
@@ -1,85 +1,85 @@
package ch.epfl.ad.milestone2.app;
import java.sql.ResultSet;
import java.sql.SQLException;
import ch.epfl.ad.AbstractQuery;
import ch.epfl.ad.db.DatabaseManager;
public class Query3 extends AbstractQuery {
@Override
public void run(String[] args) throws SQLException, InterruptedException {
if (args.length < 1) {
System.out.println("Arguments: config-file [SEGMENT [DATE]]");
System.exit(1);
}
// Segment enum: AUTOMOBILE, BUILDING, FURNITURE, MACHINERY, HOUSEHOLD
String querySegment = "BUILDING";
String queryDate = "1995-03-15";
if (args.length >= 2) {
querySegment = args[1];
}
if (args.length >= 3) {
queryDate = args[2];
}
System.out.println(String.format("Executing Q3 with segment: %s and date: %s",
querySegment, queryDate));
DatabaseManager dbManager = createDatabaseManager(args[0]);
dbManager.setResultShipmentBatchSize(5000);
// ensure that temporary tables do not exist
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
- dbManager.execute("CREATE TABLE temp_col(l_orderkey INTEGER, revenue FLOAT, o_orderdate DATE, o_shippriority INTEGER, KEY (l_orderkey, o_orderdate, o_shippriority))", "node0");
+ dbManager.execute("CREATE TABLE temp_col(l_orderkey INTEGER, revenue FLOAT, o_orderdate DATE, o_shippriority INTEGER, PRIMARY KEY (l_orderkey, o_orderdate, o_shippriority))", "node0");
dbManager.execute(
"SELECT l_orderkey, " +
"sum(l_extendedprice * (1 - l_discount)) as revenue, " +
"o_orderdate, " +
"o_shippriority " +
"FROM customer, orders, lineitem " +
String.format("WHERE o_orderkey = l_orderkey AND c_custkey = o_custkey " +
"AND c_mktsegment = '%s' AND o_orderdate < '%s' AND " +
"l_shipdate > '%s'", querySegment, queryDate, queryDate) +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
allNodes,
"temp_col",
"node0"
);
ResultSet result = dbManager.fetch(
"SELECT l_orderkey, sum(revenue) AS revenue, o_orderdate, o_shippriority " +
"FROM temp_col " +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
"node0");
while(result.next()) {
System.out.print(result.getString(1));
System.out.print("|");
System.out.print(result.getString(2));
System.out.print("|");
System.out.print(result.getString(3));
System.out.print("|");
System.out.print(result.getString(4));
System.out.print("\n");
}
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
dbManager.shutDown();
}
public static void main(String[] args) throws SQLException, InterruptedException {
new Query3().run(args);
}
}
| true | true | public void run(String[] args) throws SQLException, InterruptedException {
if (args.length < 1) {
System.out.println("Arguments: config-file [SEGMENT [DATE]]");
System.exit(1);
}
// Segment enum: AUTOMOBILE, BUILDING, FURNITURE, MACHINERY, HOUSEHOLD
String querySegment = "BUILDING";
String queryDate = "1995-03-15";
if (args.length >= 2) {
querySegment = args[1];
}
if (args.length >= 3) {
queryDate = args[2];
}
System.out.println(String.format("Executing Q3 with segment: %s and date: %s",
querySegment, queryDate));
DatabaseManager dbManager = createDatabaseManager(args[0]);
dbManager.setResultShipmentBatchSize(5000);
// ensure that temporary tables do not exist
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
dbManager.execute("CREATE TABLE temp_col(l_orderkey INTEGER, revenue FLOAT, o_orderdate DATE, o_shippriority INTEGER, KEY (l_orderkey, o_orderdate, o_shippriority))", "node0");
dbManager.execute(
"SELECT l_orderkey, " +
"sum(l_extendedprice * (1 - l_discount)) as revenue, " +
"o_orderdate, " +
"o_shippriority " +
"FROM customer, orders, lineitem " +
String.format("WHERE o_orderkey = l_orderkey AND c_custkey = o_custkey " +
"AND c_mktsegment = '%s' AND o_orderdate < '%s' AND " +
"l_shipdate > '%s'", querySegment, queryDate, queryDate) +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
allNodes,
"temp_col",
"node0"
);
ResultSet result = dbManager.fetch(
"SELECT l_orderkey, sum(revenue) AS revenue, o_orderdate, o_shippriority " +
"FROM temp_col " +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
"node0");
while(result.next()) {
System.out.print(result.getString(1));
System.out.print("|");
System.out.print(result.getString(2));
System.out.print("|");
System.out.print(result.getString(3));
System.out.print("|");
System.out.print(result.getString(4));
System.out.print("\n");
}
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
dbManager.shutDown();
}
| public void run(String[] args) throws SQLException, InterruptedException {
if (args.length < 1) {
System.out.println("Arguments: config-file [SEGMENT [DATE]]");
System.exit(1);
}
// Segment enum: AUTOMOBILE, BUILDING, FURNITURE, MACHINERY, HOUSEHOLD
String querySegment = "BUILDING";
String queryDate = "1995-03-15";
if (args.length >= 2) {
querySegment = args[1];
}
if (args.length >= 3) {
queryDate = args[2];
}
System.out.println(String.format("Executing Q3 with segment: %s and date: %s",
querySegment, queryDate));
DatabaseManager dbManager = createDatabaseManager(args[0]);
dbManager.setResultShipmentBatchSize(5000);
// ensure that temporary tables do not exist
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
dbManager.execute("CREATE TABLE temp_col(l_orderkey INTEGER, revenue FLOAT, o_orderdate DATE, o_shippriority INTEGER, PRIMARY KEY (l_orderkey, o_orderdate, o_shippriority))", "node0");
dbManager.execute(
"SELECT l_orderkey, " +
"sum(l_extendedprice * (1 - l_discount)) as revenue, " +
"o_orderdate, " +
"o_shippriority " +
"FROM customer, orders, lineitem " +
String.format("WHERE o_orderkey = l_orderkey AND c_custkey = o_custkey " +
"AND c_mktsegment = '%s' AND o_orderdate < '%s' AND " +
"l_shipdate > '%s'", querySegment, queryDate, queryDate) +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
allNodes,
"temp_col",
"node0"
);
ResultSet result = dbManager.fetch(
"SELECT l_orderkey, sum(revenue) AS revenue, o_orderdate, o_shippriority " +
"FROM temp_col " +
"GROUP BY l_orderkey, o_orderdate, o_shippriority " +
"ORDER BY revenue desc, o_orderdate " +
"LIMIT 10",
"node0");
while(result.next()) {
System.out.print(result.getString(1));
System.out.print("|");
System.out.print(result.getString(2));
System.out.print("|");
System.out.print(result.getString(3));
System.out.print("|");
System.out.print(result.getString(4));
System.out.print("\n");
}
dbManager.execute("DROP TABLE IF EXISTS temp_col", allNodes);
dbManager.shutDown();
}
|
diff --git a/DataExtractionOSM/src/net/osmand/data/index/IndexBatchCreator.java b/DataExtractionOSM/src/net/osmand/data/index/IndexBatchCreator.java
index f89f664b..a809920b 100644
--- a/DataExtractionOSM/src/net/osmand/data/index/IndexBatchCreator.java
+++ b/DataExtractionOSM/src/net/osmand/data/index/IndexBatchCreator.java
@@ -1,503 +1,507 @@
package net.osmand.data.index;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import net.osmand.Algoritms;
import net.osmand.LogUtil;
import net.osmand.binary.BinaryMapIndexReader;
import net.osmand.data.preparation.IndexCreator;
import net.osmand.data.preparation.MapZooms;
import net.osmand.impl.ConsoleProgressImplementation;
import net.osmand.osm.MapRenderingTypes;
import org.apache.commons.logging.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import rtree.RTree;
public class IndexBatchCreator {
protected static final Log log = LogUtil.getLog(IndexBatchCreator.class);
public static class RegionCountries {
String namePrefix = ""; // for states of the country
String nameSuffix = "";
Set<String> regionNames = new LinkedHashSet<String>();
String siteToDownload = "";
}
// process atributtes
boolean downloadFiles = false;
boolean generateIndexes = false;
boolean uploadIndexes = false;
MapZooms mapZooms = null;
MapRenderingTypes types = MapRenderingTypes.getDefault();
boolean deleteFilesAfterUploading = true;
File osmDirFiles;
File indexDirFiles;
boolean indexPOI = false;
boolean indexTransport = false;
boolean indexAddress = false;
boolean indexMap = false;
String user;
String password;
String cookieHSID = "";
String cookieSID = "";
String pagegen = "";
String token = "";
public static void main(String[] args) {
IndexBatchCreator creator = new IndexBatchCreator();
if(args == null || args.length == 0){
System.out.println("Please specify -local parameter or path to batch.xml configuration file as 1 argument.");
throw new IllegalArgumentException("Please specify -local parameter or path to batch.xml configuration file as 1 argument.");
}
String name = args[0];
InputStream stream;
if(name.equals("-local")){
stream = IndexBatchCreator.class.getResourceAsStream("batch.xml");
} else {
try {
stream = new FileInputStream(name);
} catch (FileNotFoundException e) {
System.out.println("XML configuration file not found : " + name);
return;
}
}
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);
creator.runBatch(doc);
} catch (SAXException e) {
System.out.println("XML configuration file could not be read from " + name);
e.printStackTrace();
log.error("XML configuration file could not be read from " + name, e);
} catch (IOException e) {
System.out.println("XML configuration file could not be read from " + name);
e.printStackTrace();
log.error("XML configuration file could not be read from " + name, e);
} catch (ParserConfigurationException e) {
System.out.println("XML configuration file could not be read from " + name);
e.printStackTrace();
log.error("XML configuration file could not be read from " + name, e);
}
}
public void runBatch(Document doc){
NodeList list = doc.getElementsByTagName("process");
if(list.getLength() != 1){
throw new IllegalArgumentException("You should specify exactly 1 process element!");
}
Element process = (Element) list.item(0);
downloadFiles = Boolean.parseBoolean(process.getAttribute("downloadOsmFiles"));
generateIndexes = Boolean.parseBoolean(process.getAttribute("generateIndexes"));
uploadIndexes = Boolean.parseBoolean(process.getAttribute("uploadIndexes"));
deleteFilesAfterUploading = Boolean.parseBoolean(process.getAttribute("deleteFilesAfterUploading"));
indexPOI = Boolean.parseBoolean(process.getAttribute("indexPOI"));
indexMap = Boolean.parseBoolean(process.getAttribute("indexMap"));
indexTransport = Boolean.parseBoolean(process.getAttribute("indexTransport"));
indexAddress = Boolean.parseBoolean(process.getAttribute("indexAddress"));
String zooms = process.getAttribute("mapZooms");
if(zooms == null || zooms.length() == 0){
mapZooms = MapZooms.getDefault();
} else {
mapZooms = MapZooms.parseZooms(zooms);
}
String f = process.getAttribute("renderingTypesFile");
if(f == null || f.length() == 0){
types = MapRenderingTypes.getDefault();
} else {
types = new MapRenderingTypes(f);
}
String dir = process.getAttribute("directory_for_osm_files");
if(dir == null || !new File(dir).exists()) {
throw new IllegalArgumentException("Please specify directory with .osm or .osm.bz2 files as directory_for_osm_files (attribute)"); //$NON-NLS-1$
}
osmDirFiles = new File(dir);
dir = process.getAttribute("directory_for_index_files");
if(dir == null || !new File(dir).exists()) {
throw new IllegalArgumentException("Please specify directory with generated index files as directory_for_index_files (attribute)"); //$NON-NLS-1$
}
indexDirFiles = new File(dir);
if(uploadIndexes){
list = doc.getElementsByTagName("authorization_info");
if(list.getLength() != 1){
throw new IllegalArgumentException("You should specify exactly 1 authorization_info element to upload indexes!");
}
Element authorization = (Element) list.item(0);
cookieHSID = authorization.getAttribute("cookieHSID");
cookieSID = authorization.getAttribute("cookieSID");
pagegen = authorization.getAttribute("pagegen");
token = authorization.getAttribute("token");
user = authorization.getAttribute("google_code_user");
password = authorization.getAttribute("google_code_password");
}
List<RegionCountries> countriesToDownload = new ArrayList<RegionCountries>();
NodeList regions = doc.getElementsByTagName("regions");
for(int i=0; i< regions.getLength(); i++){
Element el = (Element) regions.item(i);
if(!Boolean.parseBoolean(el.getAttribute("skip"))){
RegionCountries countries = new RegionCountries();
countries.siteToDownload = el.getAttribute("siteToDownload");
if(countries.siteToDownload == null){
continue;
}
countries.namePrefix = el.getAttribute("region_prefix");
if(countries.namePrefix == null){
countries.namePrefix = "";
}
countries.nameSuffix = el.getAttribute("region_suffix");
if(countries.nameSuffix == null){
countries.nameSuffix = "";
}
NodeList ncountries = el.getElementsByTagName("region");
for(int j=0; j< ncountries.getLength(); j++){
Element ncountry = (Element) ncountries.item(j);
String name = ncountry.getAttribute("name");
if(name != null && !Boolean.parseBoolean(ncountry.getAttribute("skip"))){
countries.regionNames.add(name);
}
}
countriesToDownload.add(countries);
}
}
runBatch(countriesToDownload);
}
public void runBatch(List<RegionCountries> countriesToDownload ){
Set<String> alreadyUploadedFiles = new LinkedHashSet<String>();
Set<String> alreadyGeneratedFiles = new LinkedHashSet<String>();
if(downloadFiles){
downloadFiles(countriesToDownload, alreadyGeneratedFiles, alreadyUploadedFiles);
}
if(generateIndexes){
generatedIndexes(alreadyGeneratedFiles, alreadyUploadedFiles);
}
if(uploadIndexes){
uploadIndexes(alreadyUploadedFiles);
}
}
protected void downloadFiles(List<RegionCountries> countriesToDownload, Set<String> alreadyGeneratedFiles, Set<String> alreadyUploadedFiles){
// clean before downloading
// for(File f : osmDirFiles.listFiles()){
// log.info("Delete old file " + f.getName()); //$NON-NLS-1$
// f.delete();
// }
for(RegionCountries regionCountries : countriesToDownload){
String prefix = regionCountries.namePrefix;
String site = regionCountries.siteToDownload;
String suffix = regionCountries.nameSuffix;
for(String name : regionCountries.regionNames){
name = name.toLowerCase();
String url = MessageFormat.format(site, name);
downloadFile(url, prefix+name, suffix,alreadyGeneratedFiles, alreadyUploadedFiles);
}
}
System.out.println("DOWNLOADING FILES FINISHED");
}
private final static int DOWNLOAD_DEBUG = 1 << 20;
private final static int MB = 1 << 20;
private final static int BUFFER_SIZE = 1 << 15;
protected void downloadFile(String url, String country, String suffix, Set<String> alreadyGeneratedFiles, Set<String> alreadyUploadedFiles) {
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
int downloaded = 0;
int mbDownloaded = 0;
String ext = ".osm";
if(url.endsWith(".osm.bz2")){
ext = ".osm.bz2";
} else if(url.endsWith(".osm.pbf")){
ext = ".osm.pbf";
}
File toSave = new File(osmDirFiles, country + suffix + ext);
try {
log.info("Downloading country " + country + " from " + url); //$NON-NLS-1$//$NON-NLS-2$
FileOutputStream ostream = new FileOutputStream(toSave);
InputStream stream = new URL(url).openStream();
while ((count = stream.read(buffer)) != -1) {
ostream.write(buffer, 0, count);
downloaded += count;
if(downloaded > DOWNLOAD_DEBUG){
downloaded -= DOWNLOAD_DEBUG;
mbDownloaded += (DOWNLOAD_DEBUG>>20);
log.info(mbDownloaded +" megabytes downloaded of " + toSave.getName());
}
}
ostream.close();
stream.close();
generateIndex(toSave, country, alreadyGeneratedFiles, alreadyUploadedFiles);
} catch (IOException e) {
log.error("Input/output exception " + toSave.getName() + " downloading from " + url, e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
protected void generatedIndexes(Set<String> alreadyGeneratedFiles, Set<String> alreadyUploadedFiles) {
for (File f : getSortedFiles(osmDirFiles)) {
if (alreadyGeneratedFiles.contains(f.getName())) {
continue;
}
if (f.getName().endsWith(".osm.bz2") || f.getName().endsWith(".osm") || f.getName().endsWith(".osm.pbf")) {
generateIndex(f, null, alreadyGeneratedFiles, alreadyUploadedFiles);
}
}
System.out.println("GENERATING INDEXES FINISHED ");
}
protected void generateIndex(File f, String rName, Set<String> alreadyGeneratedFiles, Set<String> alreadyUploadedFiles) {
if (!generateIndexes) {
return;
}
try {
// be independent of previous results
RTree.clearCache();
String regionName = f.getName();
int i = f.getName().indexOf('.');
if (i > -1) {
regionName = Algoritms.capitalizeFirstLetterAndLowercase(f.getName().substring(0, i));
}
if(Algoritms.isEmpty(rName)){
rName = regionName;
} else {
rName = Algoritms.capitalizeFirstLetterAndLowercase(rName);
}
IndexCreator indexCreator = new IndexCreator(indexDirFiles);
indexCreator.setIndexAddress(indexAddress);
indexCreator.setIndexPOI(indexPOI);
indexCreator.setIndexTransport(indexTransport);
indexCreator.setIndexMap(indexMap);
indexCreator.setLastModifiedDate(f.lastModified());
indexCreator.setNormalizeStreets(true);
indexCreator.setSaveAddressWays(true);
indexCreator.setRegionName(rName);
String poiFileName = regionName + "_" + IndexConstants.POI_TABLE_VERSION + IndexConstants.POI_INDEX_EXT;
indexCreator.setPoiFileName(poiFileName);
String mapFileName = regionName + "_" + IndexConstants.BINARY_MAP_VERSION + IndexConstants.BINARY_MAP_INDEX_EXT;
indexCreator.setMapFileName(mapFileName);
try {
alreadyGeneratedFiles.add(f.getName());
indexCreator.generateIndexes(f, new ConsoleProgressImplementation(3), null, mapZooms, types);
if (indexPOI) {
uploadIndex(new File(indexDirFiles, poiFileName), alreadyUploadedFiles);
}
if (indexMap || indexAddress || indexTransport) {
uploadIndex(new File(indexDirFiles, mapFileName), alreadyUploadedFiles);
}
} catch (Exception e) {
log.error("Exception generating indexes for " + f.getName(), e); //$NON-NLS-1$
}
} catch (OutOfMemoryError e) {
System.gc();
log.error("OutOfMemory", e);
}
System.gc();
}
protected File[] getSortedFiles(File dir){
File[] listFiles = dir.listFiles();
Arrays.sort(listFiles, new Comparator<File>(){
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
return listFiles;
}
protected void uploadIndexes(Set<String> alreadyUploadedFiles){
for(File f : getSortedFiles(indexDirFiles)){
if(!alreadyUploadedFiles.contains(f.getName())){
uploadIndex(f, alreadyUploadedFiles);
if(!alreadyUploadedFiles.contains(f.getName())){
System.out.println("! NOT UPLOADED " + f.getName());
}
}
}
System.out.println("UPLOADING INDEXES FINISHED ");
}
protected void uploadIndex(File f, Set<String> alreadyUploadedFiles){
if(!uploadIndexes){
return;
}
MessageFormat format = new MessageFormat("{0,date,dd.MM.yyyy} : {1, number,##.#} MB", Locale.US);
String summary;
double mbLengh = (double)f.length() / MB;
boolean zip = true;
String regionName;
if(f.getName().endsWith(IndexConstants.POI_INDEX_EXT) || f.getName().endsWith(IndexConstants.POI_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.POI_INDEX_EXT.length() - 2);
summary = "POI index for " ;
} else if(f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT) || f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.ADDRESS_INDEX_EXT.length() - 2);
summary = "Address index for " ;
} else if(f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT) || f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.TRANSPORT_INDEX_EXT.length() - 2);
summary = "Transport index for ";
} else if(f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT) || f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.BINARY_MAP_INDEX_EXT.length() - 2);
boolean addr = indexAddress;
boolean trans = indexTransport;
boolean map = indexMap;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(f, "r");
BinaryMapIndexReader reader = new BinaryMapIndexReader(raf);
trans = reader.hasTransportData();
map = reader.containsMapData();
addr = reader.containsAddressData();
reader.close();
} catch (Exception e) {
log.info("Exception", e);
if (raf != null) {
try {
raf.close();
} catch (IOException e1) {
}
}
}
summary = " index for ";
boolean fir = true;
if (addr) {
summary = "Address" + (fir ? "" : ", ") + summary;
fir = false;
}
if (trans) {
summary = "Transport" + (fir ? "" : ", ") + summary;
fir = false;
}
if (map) {
summary = "Map" + (fir ? "" : ", ") + summary;
fir = false;
}
} else {
return;
}
if(mbLengh < 0.015){
// do not upload small files
return;
}
if(mbLengh > 3 && (f.getName().endsWith(".odb") || f.getName().endsWith(".obf")) && zip){
- String zipFileName = f.getName().subSequence(0, f.getName().length() - 4)+".zip";
+ String n = f.getName();
+ if(f.getName().endsWith(".odb")){
+ n = f.getName().substring(0, f.getName().length() - 4);
+ }
+ String zipFileName = n+".zip";
File zFile = new File(f.getParentFile(), zipFileName);
log.info("Zipping file " + f.getName());
try {
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zFile));
zout.setLevel(9);
zout.putNextEntry(new ZipEntry(f.getName()));
FileInputStream is = new FileInputStream(f);
byte[] BUFFER = new byte[8192];
int read = 0;
while((read = is.read(BUFFER)) != -1){
zout.write(BUFFER, 0, read);
}
is.close();
zout.close();
} catch (IOException e) {
log.error("Exception while zipping file", e);
}
if(f.delete()){
log.info("Source odb file was deleted");
}
f = zFile;
}
try {
DownloaderIndexFromGoogleCode.deleteFileFromGoogleDownloads(f.getName(), token, pagegen, cookieHSID, cookieSID);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// wait 5 seconds
}
} catch (IOException e) {
log.warn("Deleting file from downloads" + f.getName() + " " + e.getMessage());
}
mbLengh = (double)f.length() / MB;
if(mbLengh > 100){
System.err.println("ERROR : file " + f.getName() + " exceeded 100 mb!!! Could not be uploaded.");
return; // restriction for google code
}
String descriptionFile = "{"+format.format(new Object[]{new Date(f.lastModified()), mbLengh})+"}";
summary += regionName + " " + descriptionFile;
GoogleCodeUploadIndex uploader = new GoogleCodeUploadIndex();
uploader.setFileName(f.getAbsolutePath());
uploader.setTargetFileName(f.getName());
uploader.setProjectName("osmand");
uploader.setUserName(user);
uploader.setPassword(password);
uploader.setLabels("Type-Archive, Testdata");
uploader.setSummary(summary.replace('_', ' '));
try {
uploader.upload();
if(deleteFilesAfterUploading){
f.delete();
}
alreadyUploadedFiles.add(f.getName());
} catch (IOException e) {
log.error("Input/output exception uploading " + f.getName(), e);
}
}
}
| true | true | protected void uploadIndex(File f, Set<String> alreadyUploadedFiles){
if(!uploadIndexes){
return;
}
MessageFormat format = new MessageFormat("{0,date,dd.MM.yyyy} : {1, number,##.#} MB", Locale.US);
String summary;
double mbLengh = (double)f.length() / MB;
boolean zip = true;
String regionName;
if(f.getName().endsWith(IndexConstants.POI_INDEX_EXT) || f.getName().endsWith(IndexConstants.POI_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.POI_INDEX_EXT.length() - 2);
summary = "POI index for " ;
} else if(f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT) || f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.ADDRESS_INDEX_EXT.length() - 2);
summary = "Address index for " ;
} else if(f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT) || f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.TRANSPORT_INDEX_EXT.length() - 2);
summary = "Transport index for ";
} else if(f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT) || f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.BINARY_MAP_INDEX_EXT.length() - 2);
boolean addr = indexAddress;
boolean trans = indexTransport;
boolean map = indexMap;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(f, "r");
BinaryMapIndexReader reader = new BinaryMapIndexReader(raf);
trans = reader.hasTransportData();
map = reader.containsMapData();
addr = reader.containsAddressData();
reader.close();
} catch (Exception e) {
log.info("Exception", e);
if (raf != null) {
try {
raf.close();
} catch (IOException e1) {
}
}
}
summary = " index for ";
boolean fir = true;
if (addr) {
summary = "Address" + (fir ? "" : ", ") + summary;
fir = false;
}
if (trans) {
summary = "Transport" + (fir ? "" : ", ") + summary;
fir = false;
}
if (map) {
summary = "Map" + (fir ? "" : ", ") + summary;
fir = false;
}
} else {
return;
}
if(mbLengh < 0.015){
// do not upload small files
return;
}
if(mbLengh > 3 && (f.getName().endsWith(".odb") || f.getName().endsWith(".obf")) && zip){
String zipFileName = f.getName().subSequence(0, f.getName().length() - 4)+".zip";
File zFile = new File(f.getParentFile(), zipFileName);
log.info("Zipping file " + f.getName());
try {
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zFile));
zout.setLevel(9);
zout.putNextEntry(new ZipEntry(f.getName()));
FileInputStream is = new FileInputStream(f);
byte[] BUFFER = new byte[8192];
int read = 0;
while((read = is.read(BUFFER)) != -1){
zout.write(BUFFER, 0, read);
}
is.close();
zout.close();
} catch (IOException e) {
log.error("Exception while zipping file", e);
}
if(f.delete()){
log.info("Source odb file was deleted");
}
f = zFile;
}
try {
DownloaderIndexFromGoogleCode.deleteFileFromGoogleDownloads(f.getName(), token, pagegen, cookieHSID, cookieSID);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// wait 5 seconds
}
} catch (IOException e) {
log.warn("Deleting file from downloads" + f.getName() + " " + e.getMessage());
}
mbLengh = (double)f.length() / MB;
if(mbLengh > 100){
System.err.println("ERROR : file " + f.getName() + " exceeded 100 mb!!! Could not be uploaded.");
return; // restriction for google code
}
String descriptionFile = "{"+format.format(new Object[]{new Date(f.lastModified()), mbLengh})+"}";
summary += regionName + " " + descriptionFile;
GoogleCodeUploadIndex uploader = new GoogleCodeUploadIndex();
uploader.setFileName(f.getAbsolutePath());
uploader.setTargetFileName(f.getName());
uploader.setProjectName("osmand");
uploader.setUserName(user);
uploader.setPassword(password);
uploader.setLabels("Type-Archive, Testdata");
uploader.setSummary(summary.replace('_', ' '));
try {
uploader.upload();
if(deleteFilesAfterUploading){
f.delete();
}
alreadyUploadedFiles.add(f.getName());
} catch (IOException e) {
log.error("Input/output exception uploading " + f.getName(), e);
}
}
| protected void uploadIndex(File f, Set<String> alreadyUploadedFiles){
if(!uploadIndexes){
return;
}
MessageFormat format = new MessageFormat("{0,date,dd.MM.yyyy} : {1, number,##.#} MB", Locale.US);
String summary;
double mbLengh = (double)f.length() / MB;
boolean zip = true;
String regionName;
if(f.getName().endsWith(IndexConstants.POI_INDEX_EXT) || f.getName().endsWith(IndexConstants.POI_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.POI_INDEX_EXT.length() - 2);
summary = "POI index for " ;
} else if(f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT) || f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.ADDRESS_INDEX_EXT.length() - 2);
summary = "Address index for " ;
} else if(f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT) || f.getName().endsWith(IndexConstants.TRANSPORT_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.TRANSPORT_INDEX_EXT.length() - 2);
summary = "Transport index for ";
} else if(f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT) || f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)){
regionName = f.getName().substring(0, f.getName().length() - IndexConstants.BINARY_MAP_INDEX_EXT.length() - 2);
boolean addr = indexAddress;
boolean trans = indexTransport;
boolean map = indexMap;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(f, "r");
BinaryMapIndexReader reader = new BinaryMapIndexReader(raf);
trans = reader.hasTransportData();
map = reader.containsMapData();
addr = reader.containsAddressData();
reader.close();
} catch (Exception e) {
log.info("Exception", e);
if (raf != null) {
try {
raf.close();
} catch (IOException e1) {
}
}
}
summary = " index for ";
boolean fir = true;
if (addr) {
summary = "Address" + (fir ? "" : ", ") + summary;
fir = false;
}
if (trans) {
summary = "Transport" + (fir ? "" : ", ") + summary;
fir = false;
}
if (map) {
summary = "Map" + (fir ? "" : ", ") + summary;
fir = false;
}
} else {
return;
}
if(mbLengh < 0.015){
// do not upload small files
return;
}
if(mbLengh > 3 && (f.getName().endsWith(".odb") || f.getName().endsWith(".obf")) && zip){
String n = f.getName();
if(f.getName().endsWith(".odb")){
n = f.getName().substring(0, f.getName().length() - 4);
}
String zipFileName = n+".zip";
File zFile = new File(f.getParentFile(), zipFileName);
log.info("Zipping file " + f.getName());
try {
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zFile));
zout.setLevel(9);
zout.putNextEntry(new ZipEntry(f.getName()));
FileInputStream is = new FileInputStream(f);
byte[] BUFFER = new byte[8192];
int read = 0;
while((read = is.read(BUFFER)) != -1){
zout.write(BUFFER, 0, read);
}
is.close();
zout.close();
} catch (IOException e) {
log.error("Exception while zipping file", e);
}
if(f.delete()){
log.info("Source odb file was deleted");
}
f = zFile;
}
try {
DownloaderIndexFromGoogleCode.deleteFileFromGoogleDownloads(f.getName(), token, pagegen, cookieHSID, cookieSID);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// wait 5 seconds
}
} catch (IOException e) {
log.warn("Deleting file from downloads" + f.getName() + " " + e.getMessage());
}
mbLengh = (double)f.length() / MB;
if(mbLengh > 100){
System.err.println("ERROR : file " + f.getName() + " exceeded 100 mb!!! Could not be uploaded.");
return; // restriction for google code
}
String descriptionFile = "{"+format.format(new Object[]{new Date(f.lastModified()), mbLengh})+"}";
summary += regionName + " " + descriptionFile;
GoogleCodeUploadIndex uploader = new GoogleCodeUploadIndex();
uploader.setFileName(f.getAbsolutePath());
uploader.setTargetFileName(f.getName());
uploader.setProjectName("osmand");
uploader.setUserName(user);
uploader.setPassword(password);
uploader.setLabels("Type-Archive, Testdata");
uploader.setSummary(summary.replace('_', ' '));
try {
uploader.upload();
if(deleteFilesAfterUploading){
f.delete();
}
alreadyUploadedFiles.add(f.getName());
} catch (IOException e) {
log.error("Input/output exception uploading " + f.getName(), e);
}
}
|
diff --git a/src/controller/CandyMonsterController.java b/src/controller/CandyMonsterController.java
index dda49cb..7901427 100644
--- a/src/controller/CandyMonsterController.java
+++ b/src/controller/CandyMonsterController.java
@@ -1,52 +1,52 @@
package controller;
import org.newdawn.slick.Color;
import org.newdawn.slick.SlickException;
import model.CandyMonster;
import model.Item;
import view.CandyMonsterView;
public class CandyMonsterController {
private CandyMonsterView candyMonsterView;
private CandyMonster candyMonster;
private InGameController inGameController;
boolean isSoundPlayed = false;
public CandyMonsterController(InGameController inGameController, int candyNumber, int index) throws SlickException{
this.inGameController = inGameController;
this.candyMonster = new CandyMonster(this.inGameController.getBlockMapController().getCandyMonsterMap().getBlockList().get(index).getPosX(),
this.inGameController.getBlockMapController().getCandyMonsterMap().getBlockList().get(index).getPosY(),
candyNumber); //x, y, candyNumber
this.candyMonsterView = new CandyMonsterView(this.candyMonster);
}
public CandyMonster getCandyMonster(){
return this.candyMonster;
}
public CandyMonsterView getCandyMonsterView(){
return this.candyMonsterView;
}
/*Checks if the item is dropped correctly by checking if: the item is picked up, the candynumbers are the same
* and if the item contains/intersects with the character*/
public boolean isDroppedOnMonster(Item item){
if(!item.isPickedUp() && item.CANDY_NUMBER == candyMonster.CANDY_NUMBER &&
(candyMonsterView.getShape().contains(inGameController.getItemControllers().
- get(inGameController.getBlockMapController().getBlockMapView().getCandyMonsterNbrMap().
+ get(inGameController.getBlockMapController().getBlockMapView().getItemNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())) ||
candyMonsterView.getShape().intersects(inGameController.getItemControllers().
- get(inGameController.getBlockMapController().getBlockMapView().getCandyMonsterNbrMap().
+ get(inGameController.getBlockMapController().getBlockMapView().getItemNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())){
//kolla isDelivered
item.setDelivered(true);
this.inGameController.getInGame().increaseItemsDelivered();
return true;
}
return false;
}
public boolean isSoundPlayed() {
return isSoundPlayed;
}
}
| false | true | public boolean isDroppedOnMonster(Item item){
if(!item.isPickedUp() && item.CANDY_NUMBER == candyMonster.CANDY_NUMBER &&
(candyMonsterView.getShape().contains(inGameController.getItemControllers().
get(inGameController.getBlockMapController().getBlockMapView().getCandyMonsterNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())) ||
candyMonsterView.getShape().intersects(inGameController.getItemControllers().
get(inGameController.getBlockMapController().getBlockMapView().getCandyMonsterNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())){
//kolla isDelivered
item.setDelivered(true);
this.inGameController.getInGame().increaseItemsDelivered();
return true;
}
return false;
}
| public boolean isDroppedOnMonster(Item item){
if(!item.isPickedUp() && item.CANDY_NUMBER == candyMonster.CANDY_NUMBER &&
(candyMonsterView.getShape().contains(inGameController.getItemControllers().
get(inGameController.getBlockMapController().getBlockMapView().getItemNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())) ||
candyMonsterView.getShape().intersects(inGameController.getItemControllers().
get(inGameController.getBlockMapController().getBlockMapView().getItemNbrMap().
indexOf(candyMonster.CANDY_NUMBER)).getItemView().getShape())){
//kolla isDelivered
item.setDelivered(true);
this.inGameController.getInGame().increaseItemsDelivered();
return true;
}
return false;
}
|
diff --git a/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/src/main/java/org/elasticsearch/percolator/PercolatorService.java
index a132548c81d..7d274398368 100644
--- a/src/main/java/org/elasticsearch/percolator/PercolatorService.java
+++ b/src/main/java/org/elasticsearch/percolator/PercolatorService.java
@@ -1,849 +1,851 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.elasticsearch.percolator;
import com.carrotsearch.hppc.ByteObjectOpenHashMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.memory.ExtendedMemoryIndex;
import org.apache.lucene.index.memory.MemoryIndex;
import org.apache.lucene.search.*;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CloseableThreadLocal;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.ElasticSearchParseException;
import org.elasticsearch.action.percolate.PercolateResponse;
import org.elasticsearch.action.percolate.PercolateShardRequest;
import org.elasticsearch.action.percolate.PercolateShardResponse;
import org.elasticsearch.cache.recycler.CacheRecycler;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.lucene.HashedBytesRef;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.search.XCollector;
import org.elasticsearch.common.lucene.search.XConstantScoreQuery;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.BytesText;
import org.elasticsearch.common.text.StringText;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.fielddata.BytesValues;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.internal.IdFieldMapper;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;
import org.elasticsearch.index.percolator.stats.ShardPercolateService;
import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.percolator.QueryCollector.*;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.AggregationPhase;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.FacetPhase;
import org.elasticsearch.search.facet.InternalFacet;
import org.elasticsearch.search.facet.InternalFacets;
import org.elasticsearch.search.highlight.HighlightField;
import org.elasticsearch.search.highlight.HighlightPhase;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.index.mapper.SourceToParse.source;
import static org.elasticsearch.percolator.QueryCollector.*;
/**
*/
public class PercolatorService extends AbstractComponent {
public final static float NO_SCORE = Float.NEGATIVE_INFINITY;
public final static String TYPE_NAME = ".percolator";
private final CloseableThreadLocal<MemoryIndex> cache;
private final IndicesService indicesService;
private final ByteObjectOpenHashMap<PercolatorType> percolatorTypes;
private final CacheRecycler cacheRecycler;
private final ClusterService clusterService;
private final FacetPhase facetPhase;
private final HighlightPhase highlightPhase;
private final AggregationPhase aggregationPhase;
@Inject
public PercolatorService(Settings settings, IndicesService indicesService, CacheRecycler cacheRecycler,
HighlightPhase highlightPhase, ClusterService clusterService, FacetPhase facetPhase,
AggregationPhase aggregationPhase) {
super(settings);
this.indicesService = indicesService;
this.cacheRecycler = cacheRecycler;
this.clusterService = clusterService;
this.highlightPhase = highlightPhase;
this.facetPhase = facetPhase;
this.aggregationPhase = aggregationPhase;
final long maxReuseBytes = settings.getAsBytesSize("indices.memory.memory_index.size_per_thread", new ByteSizeValue(1, ByteSizeUnit.MB)).bytes();
cache = new CloseableThreadLocal<MemoryIndex>() {
@Override
protected MemoryIndex initialValue() {
return new ExtendedMemoryIndex(true, maxReuseBytes);
}
};
percolatorTypes = new ByteObjectOpenHashMap<PercolatorType>(6);
percolatorTypes.put(countPercolator.id(), countPercolator);
percolatorTypes.put(queryCountPercolator.id(), queryCountPercolator);
percolatorTypes.put(matchPercolator.id(), matchPercolator);
percolatorTypes.put(queryPercolator.id(), queryPercolator);
percolatorTypes.put(scoringPercolator.id(), scoringPercolator);
percolatorTypes.put(topMatchingPercolator.id(), topMatchingPercolator);
}
public ReduceResult reduce(byte percolatorTypeId, List<PercolateShardResponse> shardResults) {
PercolatorType percolatorType = percolatorTypes.get(percolatorTypeId);
return percolatorType.reduce(shardResults);
}
public PercolateShardResponse percolate(PercolateShardRequest request) {
IndexService percolateIndexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = percolateIndexService.shardSafe(request.shardId());
ShardPercolateService shardPercolateService = indexShard.shardPercolateService();
shardPercolateService.prePercolate();
long startTime = System.nanoTime();
SearchShardTarget searchShardTarget = new SearchShardTarget(clusterService.localNode().id(), request.index(), request.shardId());
final PercolateContext context = new PercolateContext(
request, searchShardTarget, indexShard, percolateIndexService, cacheRecycler
);
try {
ParsedDocument parsedDocument = parseRequest(percolateIndexService, request, context);
if (context.percolateQueries().isEmpty()) {
return new PercolateShardResponse(context, request.index(), request.shardId());
}
if (request.docSource() != null && request.docSource().length() != 0) {
parsedDocument = parseFetchedDoc(request.docSource(), percolateIndexService, request.documentType());
} else if (parsedDocument == null) {
throw new ElasticSearchIllegalArgumentException("Nothing to percolate");
}
if (context.percolateQuery() == null && (context.score || context.sort || context.facets() != null || context.aggregations() != null)) {
context.percolateQuery(new MatchAllDocsQuery());
}
if (context.sort && !context.limit) {
throw new ElasticSearchIllegalArgumentException("Can't sort if size isn't specified");
}
if (context.highlight() != null && !context.limit) {
throw new ElasticSearchIllegalArgumentException("Can't highlight if size isn't specified");
}
if (context.size < 0) {
context.size = 0;
}
// first, parse the source doc into a MemoryIndex
final MemoryIndex memoryIndex = cache.get();
// TODO: This means percolation does not support nested docs...
// So look into: ByteBufferDirectory
for (IndexableField field : parsedDocument.rootDoc().getFields()) {
if (!field.fieldType().indexed() && field.name().equals(UidFieldMapper.NAME)) {
continue;
}
try {
TokenStream tokenStream = field.tokenStream(parsedDocument.analyzer());
if (tokenStream != null) {
memoryIndex.addField(field.name(), tokenStream, field.boost());
}
} catch (IOException e) {
throw new ElasticSearchException("Failed to create token stream", e);
}
}
PercolatorType action;
if (request.onlyCount()) {
action = context.percolateQuery() != null ? queryCountPercolator : countPercolator;
} else {
if (context.sort) {
action = topMatchingPercolator;
} else if (context.percolateQuery() != null) {
action = context.score ? scoringPercolator : queryPercolator;
} else {
action = matchPercolator;
}
}
context.percolatorTypeId = action.id();
context.initialize(memoryIndex, parsedDocument);
indexShard.readAllowed();
return action.doPercolate(request, context);
} finally {
context.release();
shardPercolateService.postPercolate(System.nanoTime() - startTime);
}
}
private ParsedDocument parseRequest(IndexService documentIndexService, PercolateShardRequest request, PercolateContext context) throws ElasticSearchException {
BytesReference source = request.source();
if (source == null || source.length() == 0) {
return null;
}
// TODO: combine all feature parse elements into one map
Map<String, ? extends SearchParseElement> hlElements = highlightPhase.parseElements();
Map<String, ? extends SearchParseElement> facetElements = facetPhase.parseElements();
Map<String, ? extends SearchParseElement> aggregationElements = aggregationPhase.parseElements();
ParsedDocument doc = null;
XContentParser parser = null;
// Some queries (function_score query when for decay functions) rely on a SearchContext being set:
// We switch types because this context needs to be in the context of the percolate queries in the shard and
// not the in memory percolate doc
String[] previousTypes = context.types();
context.types(new String[]{TYPE_NAME});
SearchContext.setCurrent(context);
try {
parser = XContentFactory.xContent(source).createParser(source);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
// we need to check the "doc" here, so the next token will be START_OBJECT which is
// the actual document starting
if ("doc".equals(currentFieldName)) {
if (doc != null) {
throw new ElasticSearchParseException("Either specify doc or get, not both");
}
MapperService mapperService = documentIndexService.mapperService();
DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(request.documentType());
doc = docMapper.parse(source(parser).type(request.documentType()).flyweight(true));
+ // the document parsing exists the "doc" object, so we need to set the new current field.
+ currentFieldName = parser.currentName();
}
} else if (token == XContentParser.Token.START_OBJECT) {
SearchParseElement element = hlElements.get(currentFieldName);
if (element == null) {
element = facetElements.get(currentFieldName);
if (element == null) {
element = aggregationElements.get(currentFieldName);
}
}
if ("query".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
context.percolateQuery(documentIndexService.queryParserService().parse(parser).query());
} else if ("filter".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
Filter filter = documentIndexService.queryParserService().parseInnerFilter(parser).filter();
context.percolateQuery(new XConstantScoreQuery(filter));
} else if (element != null) {
element.parse(parser, context);
}
} else if (token == null) {
break;
} else if (token.isValue()) {
if ("size".equals(currentFieldName)) {
context.limit = true;
context.size = parser.intValue();
if (context.size < 0) {
throw new ElasticSearchParseException("size is set to [" + context.size + "] and is expected to be higher or equal to 0");
}
} else if ("sort".equals(currentFieldName)) {
context.sort = parser.booleanValue();
} else if ("score".equals(currentFieldName)) {
context.score = parser.booleanValue();
}
}
}
// We need to get the actual source from the request body for highlighting, so parse the request body again
// and only get the doc source.
if (context.highlight() != null) {
parser.close();
currentFieldName = null;
parser = XContentFactory.xContent(source).createParser(source);
token = parser.nextToken();
assert token == XContentParser.Token.START_OBJECT;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("doc".equals(currentFieldName)) {
BytesStreamOutput bStream = new BytesStreamOutput();
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.SMILE, bStream);
builder.copyCurrentStructure(parser);
builder.close();
doc.setSource(bStream.bytes());
break;
} else {
parser.skipChildren();
}
} else if (token == null) {
break;
}
}
}
} catch (Throwable e) {
throw new ElasticSearchParseException("failed to parse request", e);
} finally {
context.types(previousTypes);
SearchContext.removeCurrent();
if (parser != null) {
parser.close();
}
}
return doc;
}
private ParsedDocument parseFetchedDoc(BytesReference fetchedDoc, IndexService documentIndexService, String type) {
ParsedDocument doc = null;
XContentParser parser = null;
try {
parser = XContentFactory.xContent(fetchedDoc).createParser(fetchedDoc);
MapperService mapperService = documentIndexService.mapperService();
DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(type);
doc = docMapper.parse(source(parser).type(type).flyweight(true));
} catch (Throwable e) {
throw new ElasticSearchParseException("failed to parse request", e);
} finally {
if (parser != null) {
parser.close();
}
}
if (doc == null) {
throw new ElasticSearchParseException("No doc to percolate in the request");
}
return doc;
}
public void close() {
cache.close();
}
interface PercolatorType {
// 0x00 is reserved for empty type.
byte id();
ReduceResult reduce(List<PercolateShardResponse> shardResults);
PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context);
}
private final PercolatorType countPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x01;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
long finalCount = 0;
for (PercolateShardResponse shardResponse : shardResults) {
finalCount += shardResponse.count();
}
assert !shardResults.isEmpty();
InternalFacets reducedFacets = reduceFacets(shardResults);
InternalAggregations reducedAggregations = reduceAggregations(shardResults);
return new ReduceResult(finalCount, reducedFacets, reducedAggregations);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
long count = 0;
Lucene.ExistsCollector collector = new Lucene.ExistsCollector();
for (Map.Entry<HashedBytesRef, Query> entry : context.percolateQueries().entrySet()) {
collector.reset();
try {
context.docSearcher().search(entry.getValue(), collector);
} catch (IOException e) {
logger.warn("[" + entry.getKey() + "] failed to execute query", e);
}
if (collector.exists()) {
count++;
}
}
return new PercolateShardResponse(count, context, request.index(), request.shardId());
}
};
private final PercolatorType queryCountPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x02;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
return countPercolator.reduce(shardResults);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
long count = 0;
Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
try {
Count countCollector = count(logger, context);
queryBasedPercolating(percolatorSearcher, context, countCollector);
count = countCollector.counter();
} catch (Throwable e) {
logger.warn("failed to execute", e);
} finally {
percolatorSearcher.release();
}
return new PercolateShardResponse(count, context, request.index(), request.shardId());
}
};
private final PercolatorType matchPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x03;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
long foundMatches = 0;
int numMatches = 0;
for (PercolateShardResponse response : shardResults) {
foundMatches += response.count();
numMatches += response.matches().length;
}
int requestedSize = shardResults.get(0).requestedSize();
// Use a custom impl of AbstractBigArray for Object[]?
List<PercolateResponse.Match> finalMatches = new ArrayList<PercolateResponse.Match>(requestedSize == 0 ? numMatches : requestedSize);
outer:
for (PercolateShardResponse response : shardResults) {
Text index = new StringText(response.getIndex());
for (int i = 0; i < response.matches().length; i++) {
float score = response.scores().length == 0 ? NO_SCORE : response.scores()[i];
Text match = new BytesText(new BytesArray(response.matches()[i]));
Map<String, HighlightField> hl = response.hls().isEmpty() ? null : response.hls().get(i);
finalMatches.add(new PercolateResponse.Match(index, match, score, hl));
if (requestedSize != 0 && finalMatches.size() == requestedSize) {
break outer;
}
}
}
assert !shardResults.isEmpty();
InternalFacets reducedFacets = reduceFacets(shardResults);
InternalAggregations reducedAggregations = reduceAggregations(shardResults);
return new ReduceResult(foundMatches, finalMatches.toArray(new PercolateResponse.Match[finalMatches.size()]), reducedFacets, reducedAggregations);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
long count = 0;
List<BytesRef> matches = new ArrayList<BytesRef>();
List<Map<String, HighlightField>> hls = new ArrayList<Map<String, HighlightField>>();
Lucene.ExistsCollector collector = new Lucene.ExistsCollector();
for (Map.Entry<HashedBytesRef, Query> entry : context.percolateQueries().entrySet()) {
collector.reset();
if (context.highlight() != null) {
context.parsedQuery(new ParsedQuery(entry.getValue(), ImmutableMap.<String, Filter>of()));
context.hitContext().cache().clear();
}
try {
context.docSearcher().search(entry.getValue(), collector);
} catch (Throwable e) {
logger.warn("[" + entry.getKey() + "] failed to execute query", e);
}
if (collector.exists()) {
if (!context.limit || count < context.size) {
matches.add(entry.getKey().bytes);
if (context.highlight() != null) {
highlightPhase.hitExecute(context, context.hitContext());
hls.add(context.hitContext().hit().getHighlightFields());
}
}
count++;
}
}
BytesRef[] finalMatches = matches.toArray(new BytesRef[matches.size()]);
return new PercolateShardResponse(finalMatches, hls, count, context, request.index(), request.shardId());
}
};
private final PercolatorType queryPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x04;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
return matchPercolator.reduce(shardResults);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
try {
Match match = match(logger, context, highlightPhase);
queryBasedPercolating(percolatorSearcher, context, match);
List<BytesRef> matches = match.matches();
List<Map<String, HighlightField>> hls = match.hls();
long count = match.counter();
BytesRef[] finalMatches = matches.toArray(new BytesRef[matches.size()]);
return new PercolateShardResponse(finalMatches, hls, count, context, request.index(), request.shardId());
} catch (Throwable e) {
logger.debug("failed to execute", e);
throw new PercolateException(context.indexShard().shardId(), "failed to execute", e);
} finally {
percolatorSearcher.release();
}
}
};
private final PercolatorType scoringPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x05;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
return matchPercolator.reduce(shardResults);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
try {
MatchAndScore matchAndScore = matchAndScore(logger, context, highlightPhase);
queryBasedPercolating(percolatorSearcher, context, matchAndScore);
List<BytesRef> matches = matchAndScore.matches();
List<Map<String, HighlightField>> hls = matchAndScore.hls();
float[] scores = matchAndScore.scores().toArray();
long count = matchAndScore.counter();
BytesRef[] finalMatches = matches.toArray(new BytesRef[matches.size()]);
return new PercolateShardResponse(finalMatches, hls, count, scores, context, request.index(), request.shardId());
} catch (Throwable e) {
logger.debug("failed to execute", e);
throw new PercolateException(context.indexShard().shardId(), "failed to execute", e);
} finally {
percolatorSearcher.release();
}
}
};
private final PercolatorType topMatchingPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x06;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
long foundMatches = 0;
int nonEmptyResponses = 0;
int firstNonEmptyIndex = 0;
for (int i = 0; i < shardResults.size(); i++) {
PercolateShardResponse response = shardResults.get(i);
foundMatches += response.count();
if (response.matches().length != 0) {
if (firstNonEmptyIndex == 0) {
firstNonEmptyIndex = i;
}
nonEmptyResponses++;
}
}
int requestedSize = shardResults.get(0).requestedSize();
// Use a custom impl of AbstractBigArray for Object[]?
List<PercolateResponse.Match> finalMatches = new ArrayList<PercolateResponse.Match>(requestedSize);
if (nonEmptyResponses == 1) {
PercolateShardResponse response = shardResults.get(firstNonEmptyIndex);
Text index = new StringText(response.getIndex());
for (int i = 0; i < response.matches().length; i++) {
float score = response.scores().length == 0 ? Float.NaN : response.scores()[i];
Text match = new BytesText(new BytesArray(response.matches()[i]));
if (!response.hls().isEmpty()) {
Map<String, HighlightField> hl = response.hls().get(i);
finalMatches.add(new PercolateResponse.Match(index, match, score, hl));
} else {
finalMatches.add(new PercolateResponse.Match(index, match, score));
}
}
} else {
int[] slots = new int[shardResults.size()];
while (true) {
float lowestScore = Float.NEGATIVE_INFINITY;
int requestIndex = -1;
int itemIndex = -1;
for (int i = 0; i < shardResults.size(); i++) {
int scoreIndex = slots[i];
float[] scores = shardResults.get(i).scores();
if (scoreIndex >= scores.length) {
continue;
}
float score = scores[scoreIndex];
int cmp = Float.compare(lowestScore, score);
// TODO: Maybe add a tie?
if (cmp < 0) {
requestIndex = i;
itemIndex = scoreIndex;
lowestScore = score;
}
}
// This means the shard matches have been exhausted and we should bail
if (requestIndex == -1) {
break;
}
slots[requestIndex]++;
PercolateShardResponse shardResponse = shardResults.get(requestIndex);
Text index = new StringText(shardResponse.getIndex());
Text match = new BytesText(new BytesArray(shardResponse.matches()[itemIndex]));
float score = shardResponse.scores()[itemIndex];
if (!shardResponse.hls().isEmpty()) {
Map<String, HighlightField> hl = shardResponse.hls().get(itemIndex);
finalMatches.add(new PercolateResponse.Match(index, match, score, hl));
} else {
finalMatches.add(new PercolateResponse.Match(index, match, score));
}
if (finalMatches.size() == requestedSize) {
break;
}
}
}
assert !shardResults.isEmpty();
InternalFacets reducedFacets = reduceFacets(shardResults);
InternalAggregations reducedAggregations = reduceAggregations(shardResults);
return new ReduceResult(foundMatches, finalMatches.toArray(new PercolateResponse.Match[finalMatches.size()]), reducedFacets, reducedAggregations);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
try {
MatchAndSort matchAndSort = QueryCollector.matchAndSort(logger, context);
queryBasedPercolating(percolatorSearcher, context, matchAndSort);
TopDocs topDocs = matchAndSort.topDocs();
long count = topDocs.totalHits;
List<BytesRef> matches = new ArrayList<BytesRef>(topDocs.scoreDocs.length);
float[] scores = new float[topDocs.scoreDocs.length];
List<Map<String, HighlightField>> hls = null;
if (context.highlight() != null) {
hls = new ArrayList<Map<String, HighlightField>>(topDocs.scoreDocs.length);
}
final FieldMapper<?> idMapper = context.mapperService().smartNameFieldMapper(IdFieldMapper.NAME);
final IndexFieldData<?> idFieldData = context.fieldData().getForField(idMapper);
int i = 0;
final HashedBytesRef spare = new HashedBytesRef(new BytesRef());
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
int segmentIdx = ReaderUtil.subIndex(scoreDoc.doc, percolatorSearcher.reader().leaves());
AtomicReaderContext atomicReaderContext = percolatorSearcher.reader().leaves().get(segmentIdx);
BytesValues values = idFieldData.load(atomicReaderContext).getBytesValues(true);
final int localDocId = scoreDoc.doc - atomicReaderContext.docBase;
final int numValues = values.setDocument(localDocId);
assert numValues == 1;
spare.bytes = values.nextValue();
spare.hash = values.currentValueHash();
matches.add(values.copyShared());
if (hls != null) {
Query query = context.percolateQueries().get(spare);
context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of()));
context.hitContext().cache().clear();
highlightPhase.hitExecute(context, context.hitContext());
hls.add(i, context.hitContext().hit().getHighlightFields());
}
scores[i++] = scoreDoc.score;
}
if (hls != null) {
return new PercolateShardResponse(matches.toArray(new BytesRef[matches.size()]), hls, count, scores, context, request.index(), request.shardId());
} else {
return new PercolateShardResponse(matches.toArray(new BytesRef[matches.size()]), count, scores, context, request.index(), request.shardId());
}
} catch (Throwable e) {
logger.debug("failed to execute", e);
throw new PercolateException(context.indexShard().shardId(), "failed to execute", e);
} finally {
percolatorSearcher.release();
}
}
};
private void queryBasedPercolating(Engine.Searcher percolatorSearcher, PercolateContext context, QueryCollector percolateCollector) throws IOException {
Filter percolatorTypeFilter = context.indexService().mapperService().documentMapper(TYPE_NAME).typeFilter();
percolatorTypeFilter = context.indexService().cache().filter().cache(percolatorTypeFilter);
FilteredQuery query = new FilteredQuery(context.percolateQuery(), percolatorTypeFilter);
percolatorSearcher.searcher().search(query, percolateCollector);
for (Collector queryCollector : percolateCollector.facetCollectors) {
if (queryCollector instanceof XCollector) {
((XCollector) queryCollector).postCollection();
}
}
if (context.facets() != null) {
facetPhase.execute(context);
}
if (context.aggregations() != null) {
aggregationPhase.execute(context);
}
}
public final static class ReduceResult {
private static PercolateResponse.Match[] EMPTY = new PercolateResponse.Match[0];
private final long count;
private final PercolateResponse.Match[] matches;
private final InternalFacets reducedFacets;
private final InternalAggregations reducedAggregations;
ReduceResult(long count, PercolateResponse.Match[] matches, InternalFacets reducedFacets, InternalAggregations reducedAggregations) {
this.count = count;
this.matches = matches;
this.reducedFacets = reducedFacets;
this.reducedAggregations = reducedAggregations;
}
public ReduceResult(long count, InternalFacets reducedFacets, InternalAggregations reducedAggregations) {
this.count = count;
this.matches = EMPTY;
this.reducedFacets = reducedFacets;
this.reducedAggregations = reducedAggregations;
}
public long count() {
return count;
}
public PercolateResponse.Match[] matches() {
return matches;
}
public InternalFacets reducedFacets() {
return reducedFacets;
}
public InternalAggregations reducedAggregations() {
return reducedAggregations;
}
}
private InternalFacets reduceFacets(List<PercolateShardResponse> shardResults) {
if (shardResults.get(0).facets() == null) {
return null;
}
if (shardResults.size() == 1) {
return shardResults.get(0).facets();
}
PercolateShardResponse firstShardResponse = shardResults.get(0);
List<Facet> aggregatedFacets = Lists.newArrayList();
List<Facet> namedFacets = Lists.newArrayList();
for (Facet facet : firstShardResponse.facets()) {
// aggregate each facet name into a single list, and aggregate it
namedFacets.clear();
for (PercolateShardResponse entry : shardResults) {
for (Facet facet1 : entry.facets()) {
if (facet.getName().equals(facet1.getName())) {
namedFacets.add(facet1);
}
}
}
if (!namedFacets.isEmpty()) {
Facet aggregatedFacet = ((InternalFacet) namedFacets.get(0)).reduce(new InternalFacet.ReduceContext(cacheRecycler, namedFacets));
aggregatedFacets.add(aggregatedFacet);
}
}
return new InternalFacets(aggregatedFacets);
}
private InternalAggregations reduceAggregations(List<PercolateShardResponse> shardResults) {
if (shardResults.get(0).aggregations() == null) {
return null;
}
if (shardResults.size() == 1) {
return shardResults.get(0).aggregations();
}
List<InternalAggregations> aggregationsList = new ArrayList<InternalAggregations>(shardResults.size());
for (PercolateShardResponse shardResult : shardResults) {
aggregationsList.add(shardResult.aggregations());
}
return InternalAggregations.reduce(aggregationsList, cacheRecycler);
}
}
| true | true | private ParsedDocument parseRequest(IndexService documentIndexService, PercolateShardRequest request, PercolateContext context) throws ElasticSearchException {
BytesReference source = request.source();
if (source == null || source.length() == 0) {
return null;
}
// TODO: combine all feature parse elements into one map
Map<String, ? extends SearchParseElement> hlElements = highlightPhase.parseElements();
Map<String, ? extends SearchParseElement> facetElements = facetPhase.parseElements();
Map<String, ? extends SearchParseElement> aggregationElements = aggregationPhase.parseElements();
ParsedDocument doc = null;
XContentParser parser = null;
// Some queries (function_score query when for decay functions) rely on a SearchContext being set:
// We switch types because this context needs to be in the context of the percolate queries in the shard and
// not the in memory percolate doc
String[] previousTypes = context.types();
context.types(new String[]{TYPE_NAME});
SearchContext.setCurrent(context);
try {
parser = XContentFactory.xContent(source).createParser(source);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
// we need to check the "doc" here, so the next token will be START_OBJECT which is
// the actual document starting
if ("doc".equals(currentFieldName)) {
if (doc != null) {
throw new ElasticSearchParseException("Either specify doc or get, not both");
}
MapperService mapperService = documentIndexService.mapperService();
DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(request.documentType());
doc = docMapper.parse(source(parser).type(request.documentType()).flyweight(true));
}
} else if (token == XContentParser.Token.START_OBJECT) {
SearchParseElement element = hlElements.get(currentFieldName);
if (element == null) {
element = facetElements.get(currentFieldName);
if (element == null) {
element = aggregationElements.get(currentFieldName);
}
}
if ("query".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
context.percolateQuery(documentIndexService.queryParserService().parse(parser).query());
} else if ("filter".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
Filter filter = documentIndexService.queryParserService().parseInnerFilter(parser).filter();
context.percolateQuery(new XConstantScoreQuery(filter));
} else if (element != null) {
element.parse(parser, context);
}
} else if (token == null) {
break;
} else if (token.isValue()) {
if ("size".equals(currentFieldName)) {
context.limit = true;
context.size = parser.intValue();
if (context.size < 0) {
throw new ElasticSearchParseException("size is set to [" + context.size + "] and is expected to be higher or equal to 0");
}
} else if ("sort".equals(currentFieldName)) {
context.sort = parser.booleanValue();
} else if ("score".equals(currentFieldName)) {
context.score = parser.booleanValue();
}
}
}
// We need to get the actual source from the request body for highlighting, so parse the request body again
// and only get the doc source.
if (context.highlight() != null) {
parser.close();
currentFieldName = null;
parser = XContentFactory.xContent(source).createParser(source);
token = parser.nextToken();
assert token == XContentParser.Token.START_OBJECT;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("doc".equals(currentFieldName)) {
BytesStreamOutput bStream = new BytesStreamOutput();
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.SMILE, bStream);
builder.copyCurrentStructure(parser);
builder.close();
doc.setSource(bStream.bytes());
break;
} else {
parser.skipChildren();
}
} else if (token == null) {
break;
}
}
}
} catch (Throwable e) {
throw new ElasticSearchParseException("failed to parse request", e);
} finally {
context.types(previousTypes);
SearchContext.removeCurrent();
if (parser != null) {
parser.close();
}
}
return doc;
}
| private ParsedDocument parseRequest(IndexService documentIndexService, PercolateShardRequest request, PercolateContext context) throws ElasticSearchException {
BytesReference source = request.source();
if (source == null || source.length() == 0) {
return null;
}
// TODO: combine all feature parse elements into one map
Map<String, ? extends SearchParseElement> hlElements = highlightPhase.parseElements();
Map<String, ? extends SearchParseElement> facetElements = facetPhase.parseElements();
Map<String, ? extends SearchParseElement> aggregationElements = aggregationPhase.parseElements();
ParsedDocument doc = null;
XContentParser parser = null;
// Some queries (function_score query when for decay functions) rely on a SearchContext being set:
// We switch types because this context needs to be in the context of the percolate queries in the shard and
// not the in memory percolate doc
String[] previousTypes = context.types();
context.types(new String[]{TYPE_NAME});
SearchContext.setCurrent(context);
try {
parser = XContentFactory.xContent(source).createParser(source);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
// we need to check the "doc" here, so the next token will be START_OBJECT which is
// the actual document starting
if ("doc".equals(currentFieldName)) {
if (doc != null) {
throw new ElasticSearchParseException("Either specify doc or get, not both");
}
MapperService mapperService = documentIndexService.mapperService();
DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(request.documentType());
doc = docMapper.parse(source(parser).type(request.documentType()).flyweight(true));
// the document parsing exists the "doc" object, so we need to set the new current field.
currentFieldName = parser.currentName();
}
} else if (token == XContentParser.Token.START_OBJECT) {
SearchParseElement element = hlElements.get(currentFieldName);
if (element == null) {
element = facetElements.get(currentFieldName);
if (element == null) {
element = aggregationElements.get(currentFieldName);
}
}
if ("query".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
context.percolateQuery(documentIndexService.queryParserService().parse(parser).query());
} else if ("filter".equals(currentFieldName)) {
if (context.percolateQuery() != null) {
throw new ElasticSearchParseException("Either specify query or filter, not both");
}
Filter filter = documentIndexService.queryParserService().parseInnerFilter(parser).filter();
context.percolateQuery(new XConstantScoreQuery(filter));
} else if (element != null) {
element.parse(parser, context);
}
} else if (token == null) {
break;
} else if (token.isValue()) {
if ("size".equals(currentFieldName)) {
context.limit = true;
context.size = parser.intValue();
if (context.size < 0) {
throw new ElasticSearchParseException("size is set to [" + context.size + "] and is expected to be higher or equal to 0");
}
} else if ("sort".equals(currentFieldName)) {
context.sort = parser.booleanValue();
} else if ("score".equals(currentFieldName)) {
context.score = parser.booleanValue();
}
}
}
// We need to get the actual source from the request body for highlighting, so parse the request body again
// and only get the doc source.
if (context.highlight() != null) {
parser.close();
currentFieldName = null;
parser = XContentFactory.xContent(source).createParser(source);
token = parser.nextToken();
assert token == XContentParser.Token.START_OBJECT;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("doc".equals(currentFieldName)) {
BytesStreamOutput bStream = new BytesStreamOutput();
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.SMILE, bStream);
builder.copyCurrentStructure(parser);
builder.close();
doc.setSource(bStream.bytes());
break;
} else {
parser.skipChildren();
}
} else if (token == null) {
break;
}
}
}
} catch (Throwable e) {
throw new ElasticSearchParseException("failed to parse request", e);
} finally {
context.types(previousTypes);
SearchContext.removeCurrent();
if (parser != null) {
parser.close();
}
}
return doc;
}
|
diff --git a/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerApplet.java b/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerApplet.java
index 58ca3b58..1e6acdf6 100644
--- a/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerApplet.java
+++ b/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerApplet.java
@@ -1,117 +1,119 @@
/*
* CustomizerApplet.java
*
* Created on June 17, 2008, 7:26 PM
*/
package org.netbeans.modules.javafx.project.ui.customizer;
/**
*
* @author alex
*/
public class CustomizerApplet extends javax.swing.JPanel {
/** Creates new form CustomizerApplet */
public CustomizerApplet(JavaFXProjectProperties uiProperties) {
initComponents();
widthSpinner.setModel(uiProperties.widthModel);
heightSpinner.setModel(uiProperties.heightModel);
jCheckBox1.setModel(uiProperties.draggableModel);
noteLabel.setVisible(false);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
descriptionLabel = new javax.swing.JLabel();
noteLabel = new javax.swing.JLabel();
widthLabel = new javax.swing.JLabel();
widthSpinner = new javax.swing.JSpinner();
heightLabel = new javax.swing.JLabel();
heightSpinner = new javax.swing.JSpinner();
jCheckBox1 = new javax.swing.JCheckBox();
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.descriptionLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 9, 0);
add(descriptionLabel, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(noteLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.noteLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(28, 2, 2, 2);
add(noteLabel, gridBagConstraints);
+ widthLabel.setLabelFor(widthSpinner);
org.openide.awt.Mnemonics.setLocalizedText(widthLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
add(widthLabel, gridBagConstraints);
widthSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 60, 0, 10);
add(widthSpinner, gridBagConstraints);
+ heightLabel.setLabelFor(heightSpinner);
org.openide.awt.Mnemonics.setLocalizedText(heightLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(heightLabel, gridBagConstraints);
heightSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 60, 0, 10);
add(heightSpinner, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.jCheckBox1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0);
add(jCheckBox1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel descriptionLabel;
private javax.swing.JLabel heightLabel;
private javax.swing.JSpinner heightSpinner;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JLabel noteLabel;
private javax.swing.JLabel widthLabel;
private javax.swing.JSpinner widthSpinner;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
descriptionLabel = new javax.swing.JLabel();
noteLabel = new javax.swing.JLabel();
widthLabel = new javax.swing.JLabel();
widthSpinner = new javax.swing.JSpinner();
heightLabel = new javax.swing.JLabel();
heightSpinner = new javax.swing.JSpinner();
jCheckBox1 = new javax.swing.JCheckBox();
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.descriptionLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 9, 0);
add(descriptionLabel, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(noteLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.noteLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(28, 2, 2, 2);
add(noteLabel, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(widthLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
add(widthLabel, gridBagConstraints);
widthSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 60, 0, 10);
add(widthSpinner, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(heightLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(heightLabel, gridBagConstraints);
heightSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 60, 0, 10);
add(heightSpinner, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.jCheckBox1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0);
add(jCheckBox1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
descriptionLabel = new javax.swing.JLabel();
noteLabel = new javax.swing.JLabel();
widthLabel = new javax.swing.JLabel();
widthSpinner = new javax.swing.JSpinner();
heightLabel = new javax.swing.JLabel();
heightSpinner = new javax.swing.JSpinner();
jCheckBox1 = new javax.swing.JCheckBox();
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.descriptionLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 9, 0);
add(descriptionLabel, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(noteLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.noteLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(28, 2, 2, 2);
add(noteLabel, gridBagConstraints);
widthLabel.setLabelFor(widthSpinner);
org.openide.awt.Mnemonics.setLocalizedText(widthLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
add(widthLabel, gridBagConstraints);
widthSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.widthSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 60, 0, 10);
add(widthSpinner, gridBagConstraints);
heightLabel.setLabelFor(heightSpinner);
org.openide.awt.Mnemonics.setLocalizedText(heightLabel, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(heightLabel, gridBagConstraints);
heightSpinner.setToolTipText(org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.heightSpinner.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 60, 0, 10);
add(heightSpinner, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerApplet.class, "CustomizerApplet.jCheckBox1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 0);
add(jCheckBox1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/net/floodlightcontroller/perfmon/PerfMonToggleResource.java b/src/main/java/net/floodlightcontroller/perfmon/PerfMonToggleResource.java
index 7bd31382..32af054d 100644
--- a/src/main/java/net/floodlightcontroller/perfmon/PerfMonToggleResource.java
+++ b/src/main/java/net/floodlightcontroller/perfmon/PerfMonToggleResource.java
@@ -1,44 +1,48 @@
/**
* Copyright 2013, Big Switch Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.perfmon;
import org.restlet.data.Status;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class PerfMonToggleResource extends ServerResource {
@Get("json")
public String retrieve() {
IPktInProcessingTimeService pktinProcTime =
(IPktInProcessingTimeService)getContext().getAttributes().
get(IPktInProcessingTimeService.class.getCanonicalName());
String param = ((String)getRequestAttributes().get("perfmonstate")).toLowerCase();
if (param.equals("reset")) {
+ // We cannot reset something that is disabled, so enable it first.
+ if(!pktinProcTime.isEnabled()){
+ pktinProcTime.setEnabled(true);
+ }
pktinProcTime.getCtb().reset();
} else {
if (param.equals("enable") || param.equals("true")) {
pktinProcTime.setEnabled(true);
} else if (param.equals("disable") || param.equals("false")) {
pktinProcTime.setEnabled(false);
}
}
setStatus(Status.SUCCESS_OK, "OK");
return "{ \"enabled\" : " + pktinProcTime.isEnabled() + " }";
}
}
| true | true | public String retrieve() {
IPktInProcessingTimeService pktinProcTime =
(IPktInProcessingTimeService)getContext().getAttributes().
get(IPktInProcessingTimeService.class.getCanonicalName());
String param = ((String)getRequestAttributes().get("perfmonstate")).toLowerCase();
if (param.equals("reset")) {
pktinProcTime.getCtb().reset();
} else {
if (param.equals("enable") || param.equals("true")) {
pktinProcTime.setEnabled(true);
} else if (param.equals("disable") || param.equals("false")) {
pktinProcTime.setEnabled(false);
}
}
setStatus(Status.SUCCESS_OK, "OK");
return "{ \"enabled\" : " + pktinProcTime.isEnabled() + " }";
}
| public String retrieve() {
IPktInProcessingTimeService pktinProcTime =
(IPktInProcessingTimeService)getContext().getAttributes().
get(IPktInProcessingTimeService.class.getCanonicalName());
String param = ((String)getRequestAttributes().get("perfmonstate")).toLowerCase();
if (param.equals("reset")) {
// We cannot reset something that is disabled, so enable it first.
if(!pktinProcTime.isEnabled()){
pktinProcTime.setEnabled(true);
}
pktinProcTime.getCtb().reset();
} else {
if (param.equals("enable") || param.equals("true")) {
pktinProcTime.setEnabled(true);
} else if (param.equals("disable") || param.equals("false")) {
pktinProcTime.setEnabled(false);
}
}
setStatus(Status.SUCCESS_OK, "OK");
return "{ \"enabled\" : " + pktinProcTime.isEnabled() + " }";
}
|
diff --git a/src/main/java/com/gitblit/manager/GitblitManager.java b/src/main/java/com/gitblit/manager/GitblitManager.java
index 95d50ac1..9d096ddf 100644
--- a/src/main/java/com/gitblit/manager/GitblitManager.java
+++ b/src/main/java/com/gitblit/manager/GitblitManager.java
@@ -1,1115 +1,1116 @@
/*
* Copyright 2013 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.manager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitblit.Constants;
import com.gitblit.Constants.AccessPermission;
import com.gitblit.Constants.AccessRestrictionType;
import com.gitblit.Constants.FederationRequest;
import com.gitblit.Constants.FederationToken;
import com.gitblit.GitBlitException;
import com.gitblit.IStoredSettings;
import com.gitblit.Keys;
import com.gitblit.models.FederationModel;
import com.gitblit.models.FederationProposal;
import com.gitblit.models.FederationSet;
import com.gitblit.models.ForkModel;
import com.gitblit.models.GitClientApplication;
import com.gitblit.models.Metric;
import com.gitblit.models.ProjectModel;
import com.gitblit.models.RegistrantAccessPermission;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.RepositoryUrl;
import com.gitblit.models.SearchResult;
import com.gitblit.models.ServerSettings;
import com.gitblit.models.ServerStatus;
import com.gitblit.models.SettingModel;
import com.gitblit.models.TeamModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.HttpUtils;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.JsonUtils;
import com.gitblit.utils.ObjectCache;
import com.gitblit.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
/**
* GitblitManager is an aggregate interface delegate. It implements all the manager
* interfaces and delegates most methods calls to the proper manager implementation.
* It's primary purpose is to provide complete management control to the git
* upload and receive pack functions.
*
* GitblitManager also implements several integration methods when it is required
* to manipulate several manages for one operation.
*
* @author James Moger
*
*/
public class GitblitManager implements IGitblit {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final ObjectCache<Collection<GitClientApplication>> clientApplications = new ObjectCache<Collection<GitClientApplication>>();
protected final IStoredSettings settings;
protected final IRuntimeManager runtimeManager;
protected final INotificationManager notificationManager;
protected final IUserManager userManager;
protected final IAuthenticationManager authenticationManager;
protected final IRepositoryManager repositoryManager;
protected final IProjectManager projectManager;
protected final IFederationManager federationManager;
public GitblitManager(
IRuntimeManager runtimeManager,
INotificationManager notificationManager,
IUserManager userManager,
IAuthenticationManager authenticationManager,
IRepositoryManager repositoryManager,
IProjectManager projectManager,
IFederationManager federationManager) {
this.settings = runtimeManager.getSettings();
this.runtimeManager = runtimeManager;
this.notificationManager = notificationManager;
this.userManager = userManager;
this.authenticationManager = authenticationManager;
this.repositoryManager = repositoryManager;
this.projectManager = projectManager;
this.federationManager = federationManager;
}
@Override
public GitblitManager start() {
loadSettingModels(runtimeManager.getSettingsModel());
return this;
}
@Override
public GitblitManager stop() {
return this;
}
/*
* IGITBLIT
*/
/**
* Creates a personal fork of the specified repository. The clone is view
* restricted by default and the owner of the source repository is given
* access to the clone.
*
* @param repository
* @param user
* @return the repository model of the fork, if successful
* @throws GitBlitException
*/
@Override
public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(), StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
String fromUrl = MessageFormat.format("file://{0}/{1}", repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);
// clone the repository
try {
JGitUtils.cloneRepository(repositoryManager.getRepositoriesFolder(), cloneName, fromUrl, true, null);
} catch (Exception e) {
throw new GitBlitException(e);
}
// create a Gitblit repository model for the clone
RepositoryModel cloneModel = repository.cloneAs(cloneName);
// owner has REWIND/RW+ permissions
cloneModel.addOwner(user.username);
repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);
// add the owner of the source repository to the clone's access list
if (!ArrayUtils.isEmpty(repository.owners)) {
for (String owner : repository.owners) {
UserModel originOwner = userManager.getUserModel(owner);
- if (originOwner != null) {
+ if (originOwner != null && !originOwner.canClone(cloneModel)) {
+ // origin owner can't yet clone fork, grant explicit clone access
originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
reviseUser(originOwner.username, originOwner);
}
}
}
// grant origin's user list clone permission to fork
List<String> users = repositoryManager.getRepositoryUsers(repository);
List<UserModel> cloneUsers = new ArrayList<UserModel>();
for (String name : users) {
if (!name.equalsIgnoreCase(user.username)) {
UserModel cloneUser = userManager.getUserModel(name);
- if (cloneUser.canClone(repository)) {
- // origin user can clone origin, grant clone access to fork
+ if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) {
+ // origin user can't yet clone fork, grant explicit clone access
cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneUsers.add(cloneUser);
}
}
userManager.updateUserModels(cloneUsers);
// grant origin's team list clone permission to fork
List<String> teams = repositoryManager.getRepositoryTeams(repository);
List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
for (String name : teams) {
TeamModel cloneTeam = userManager.getTeamModel(name);
- if (cloneTeam.canClone(repository)) {
- // origin team can clone origin, grant clone access to fork
+ if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) {
+ // origin team can't yet clone fork, grant explicit clone access
cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneTeams.add(cloneTeam);
}
userManager.updateTeamModels(cloneTeams);
// add this clone to the cached model
repositoryManager.addToCachedRepositoryList(cloneModel);
return cloneModel;
}
/**
* Adds a TeamModel object.
*
* @param team
*/
@Override
public void addTeam(TeamModel team) throws GitBlitException {
if (!userManager.updateTeamModel(team)) {
throw new GitBlitException("Failed to add team!");
}
}
/**
* Updates the TeamModel object for the specified name.
*
* @param teamname
* @param team
*/
@Override
public void reviseTeam(String teamname, TeamModel team) throws GitBlitException {
if (!teamname.equalsIgnoreCase(team.name)) {
if (userManager.getTeamModel(team.name) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
team.name));
}
}
if (!userManager.updateTeamModel(teamname, team)) {
throw new GitBlitException("Failed to update team!");
}
}
/**
* Adds a user object.
*
* @param user
* @throws GitBlitException
*/
@Override
public void addUser(UserModel user) throws GitBlitException {
if (!userManager.updateUserModel(user)) {
throw new GitBlitException("Failed to add user!");
}
}
/**
* Updates a user object keyed by username. This method allows
* for renaming a user.
*
* @param username
* @param user
* @throws GitBlitException
*/
@Override
public void reviseUser(String username, UserModel user) throws GitBlitException {
if (!username.equalsIgnoreCase(user.username)) {
if (userManager.getUserModel(user.username) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", username,
user.username));
}
// rename repositories and owner fields for all repositories
for (RepositoryModel model : repositoryManager.getRepositoryModels(user)) {
if (model.isUsersPersonalRepository(username)) {
// personal repository
model.addOwner(user.username);
String oldRepositoryName = model.name;
model.name = user.getPersonalPath() + model.name.substring(model.projectPath.length());
model.projectPath = user.getPersonalPath();
repositoryManager.updateRepositoryModel(oldRepositoryName, model, false);
} else if (model.isOwner(username)) {
// common/shared repo
model.addOwner(user.username);
repositoryManager.updateRepositoryModel(model.name, model, false);
}
}
}
if (!userManager.updateUserModel(username, user)) {
throw new GitBlitException("Failed to update user!");
}
}
/**
* Returns a list of repository URLs and the user access permission.
*
* @param request
* @param user
* @param repository
* @return a list of repository urls
*/
@Override
public List<RepositoryUrl> getRepositoryUrls(HttpServletRequest request, UserModel user, RepositoryModel repository) {
if (user == null) {
user = UserModel.ANONYMOUS;
}
String username = StringUtils.encodeUsername(UserModel.ANONYMOUS.equals(user) ? "" : user.username);
List<RepositoryUrl> list = new ArrayList<RepositoryUrl>();
// http/https url
if (settings.getBoolean(Keys.git.enableGitServlet, true)) {
AccessPermission permission = user.getRepositoryPermission(repository).permission;
if (permission.exceeds(AccessPermission.NONE)) {
list.add(new RepositoryUrl(getRepositoryUrl(request, username, repository), permission));
}
}
// add all other urls
// {0} = repository
// {1} = username
for (String url : settings.getStrings(Keys.web.otherUrls)) {
if (url.contains("{1}")) {
// external url requires username, only add url IF we have one
if (!StringUtils.isEmpty(username)) {
list.add(new RepositoryUrl(MessageFormat.format(url, repository.name, username), null));
}
} else {
// external url does not require username
list.add(new RepositoryUrl(MessageFormat.format(url, repository.name), null));
}
}
return list;
}
protected String getRepositoryUrl(HttpServletRequest request, String username, RepositoryModel repository) {
String gitblitUrl = settings.getString(Keys.web.canonicalUrl, null);
if (StringUtils.isEmpty(gitblitUrl)) {
gitblitUrl = HttpUtils.getGitblitURL(request);
}
StringBuilder sb = new StringBuilder();
sb.append(gitblitUrl);
sb.append(Constants.R_PATH);
sb.append(repository.name);
// inject username into repository url if authentication is required
if (repository.accessRestriction.exceeds(AccessRestrictionType.NONE)
&& !StringUtils.isEmpty(username)) {
sb.insert(sb.indexOf("://") + 3, username + "@");
}
return sb.toString();
}
/**
* Returns the list of custom client applications to be used for the
* repository url panel;
*
* @return a collection of client applications
*/
@Override
public Collection<GitClientApplication> getClientApplications() {
// prefer user definitions, if they exist
File userDefs = new File(runtimeManager.getBaseFolder(), "clientapps.json");
if (userDefs.exists()) {
Date lastModified = new Date(userDefs.lastModified());
if (clientApplications.hasCurrent("user", lastModified)) {
return clientApplications.getObject("user");
} else {
// (re)load user definitions
try {
InputStream is = new FileInputStream(userDefs);
Collection<GitClientApplication> clients = readClientApplications(is);
is.close();
if (clients != null) {
clientApplications.updateObject("user", lastModified, clients);
return clients;
}
} catch (IOException e) {
logger.error("Failed to deserialize " + userDefs.getAbsolutePath(), e);
}
}
}
// no user definitions, use system definitions
if (!clientApplications.hasCurrent("system", new Date(0))) {
try {
InputStream is = getClass().getResourceAsStream("/clientapps.json");
Collection<GitClientApplication> clients = readClientApplications(is);
is.close();
if (clients != null) {
clientApplications.updateObject("system", new Date(0), clients);
}
} catch (IOException e) {
logger.error("Failed to deserialize clientapps.json resource!", e);
}
}
return clientApplications.getObject("system");
}
private Collection<GitClientApplication> readClientApplications(InputStream is) {
try {
Type type = new TypeToken<Collection<GitClientApplication>>() {
}.getType();
InputStreamReader reader = new InputStreamReader(is);
Gson gson = JsonUtils.gson();
Collection<GitClientApplication> links = gson.fromJson(reader, type);
return links;
} catch (JsonIOException e) {
logger.error("Error deserializing client applications!", e);
} catch (JsonSyntaxException e) {
logger.error("Error deserializing client applications!", e);
}
return null;
}
/**
* Parse the properties file and aggregate all the comments by the setting
* key. A setting model tracks the current value, the default value, the
* description of the setting and and directives about the setting.
*
* @return Map<String, SettingModel>
*/
private void loadSettingModels(ServerSettings settingsModel) {
try {
// Read bundled Gitblit properties to extract setting descriptions.
// This copy is pristine and only used for populating the setting
// models map.
InputStream is = getClass().getResourceAsStream("/reference.properties");
BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
StringBuilder description = new StringBuilder();
SettingModel setting = new SettingModel();
String line = null;
while ((line = propertiesReader.readLine()) != null) {
if (line.length() == 0) {
description.setLength(0);
setting = new SettingModel();
} else {
if (line.charAt(0) == '#') {
if (line.length() > 1) {
String text = line.substring(1).trim();
if (SettingModel.CASE_SENSITIVE.equals(text)) {
setting.caseSensitive = true;
} else if (SettingModel.RESTART_REQUIRED.equals(text)) {
setting.restartRequired = true;
} else if (SettingModel.SPACE_DELIMITED.equals(text)) {
setting.spaceDelimited = true;
} else if (text.startsWith(SettingModel.SINCE)) {
try {
setting.since = text.split(" ")[1];
} catch (Exception e) {
setting.since = text;
}
} else {
description.append(text);
description.append('\n');
}
}
} else {
String[] kvp = line.split("=", 2);
String key = kvp[0].trim();
setting.name = key;
setting.defaultValue = kvp[1].trim();
setting.currentValue = setting.defaultValue;
setting.description = description.toString().trim();
settingsModel.add(setting);
description.setLength(0);
setting = new SettingModel();
}
}
}
propertiesReader.close();
} catch (NullPointerException e) {
logger.error("Failed to find resource copy of gitblit.properties");
} catch (IOException e) {
logger.error("Failed to load resource copy of gitblit.properties");
}
}
/*
* ISTOREDSETTINGS
*
* these methods are necessary for (nearly) seamless Groovy hook operation
* after the massive refactor.
*/
public boolean getBoolean(String key, boolean defaultValue) {
return runtimeManager.getSettings().getBoolean(key, defaultValue);
}
public String getString(String key, String defaultValue) {
return runtimeManager.getSettings().getString(key, defaultValue);
}
public int getInteger(String key, int defaultValue) {
return runtimeManager.getSettings().getInteger(key, defaultValue);
}
public List<String> getStrings(String key) {
return runtimeManager.getSettings().getStrings(key);
}
/*
* RUNTIME MANAGER
*/
@Override
public File getBaseFolder() {
return runtimeManager.getBaseFolder();
}
@Override
public void setBaseFolder(File folder) {
runtimeManager.setBaseFolder(folder);
}
@Override
public Date getBootDate() {
return runtimeManager.getBootDate();
}
@Override
public ServerSettings getSettingsModel() {
return runtimeManager.getSettingsModel();
}
@Override
public boolean isServingRepositories() {
return runtimeManager.isServingRepositories();
}
@Override
public TimeZone getTimezone() {
return runtimeManager.getTimezone();
}
@Override
public boolean isDebugMode() {
return runtimeManager.isDebugMode();
}
@Override
public File getFileOrFolder(String key, String defaultFileOrFolder) {
return runtimeManager.getFileOrFolder(key, defaultFileOrFolder);
}
@Override
public File getFileOrFolder(String fileOrFolder) {
return runtimeManager.getFileOrFolder(fileOrFolder);
}
@Override
public IStoredSettings getSettings() {
return runtimeManager.getSettings();
}
@Override
public boolean updateSettings(Map<String, String> updatedSettings) {
return runtimeManager.updateSettings(updatedSettings);
}
@Override
public ServerStatus getStatus() {
return runtimeManager.getStatus();
}
/*
* NOTIFICATION MANAGER
*/
@Override
public void sendMailToAdministrators(String subject, String message) {
notificationManager.sendMailToAdministrators(subject, message);
}
@Override
public void sendMail(String subject, String message, Collection<String> toAddresses) {
notificationManager.sendMail(subject, message, toAddresses);
}
@Override
public void sendMail(String subject, String message, String... toAddresses) {
notificationManager.sendMail(subject, message, toAddresses);
}
@Override
public void sendHtmlMail(String subject, String message, Collection<String> toAddresses) {
notificationManager.sendHtmlMail(subject, message, toAddresses);
}
@Override
public void sendHtmlMail(String subject, String message, String... toAddresses) {
notificationManager.sendHtmlMail(subject, message, toAddresses);
}
@Override
public void sendHtmlMail(String from, String subject, String message, Collection<String> toAddresses) {
notificationManager.sendHtmlMail(from, subject, message, toAddresses);
}
@Override
public void sendHtmlMail(String from, String subject, String message, String... toAddresses) {
notificationManager.sendHtmlMail(from, subject, message, toAddresses);
}
/*
* SESSION MANAGER
*/
@Override
public UserModel authenticate(String username, char[] password) {
return authenticationManager.authenticate(username, password);
}
@Override
public UserModel authenticate(HttpServletRequest httpRequest) {
UserModel user = authenticationManager.authenticate(httpRequest, false);
if (user == null) {
user = federationManager.authenticate(httpRequest);
}
return user;
}
@Override
public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
UserModel user = authenticationManager.authenticate(httpRequest, requiresCertificate);
if (user == null) {
user = federationManager.authenticate(httpRequest);
}
return user;
}
@Override
public String getCookie(HttpServletRequest request) {
return authenticationManager.getCookie(request);
}
@Override
public void setCookie(HttpServletResponse response, UserModel user) {
authenticationManager.setCookie(response, user);
}
@Override
public void logout(HttpServletResponse response, UserModel user) {
authenticationManager.logout(response, user);
}
@Override
public boolean supportsCredentialChanges(UserModel user) {
return authenticationManager.supportsCredentialChanges(user);
}
@Override
public boolean supportsDisplayNameChanges(UserModel user) {
return authenticationManager.supportsDisplayNameChanges(user);
}
@Override
public boolean supportsEmailAddressChanges(UserModel user) {
return authenticationManager.supportsEmailAddressChanges(user);
}
@Override
public boolean supportsTeamMembershipChanges(UserModel user) {
return authenticationManager.supportsTeamMembershipChanges(user);
}
@Override
public boolean supportsTeamMembershipChanges(TeamModel team) {
return authenticationManager.supportsTeamMembershipChanges(team);
}
/*
* USER MANAGER
*/
@Override
public void setup(IRuntimeManager runtimeManager) {
}
@Override
public boolean isInternalAccount(String username) {
return userManager.isInternalAccount(username);
}
@Override
public List<String> getAllUsernames() {
return userManager.getAllUsernames();
}
@Override
public List<UserModel> getAllUsers() {
return userManager.getAllUsers();
}
@Override
public boolean deleteUser(String username) {
return userManager.deleteUser(username);
}
@Override
public UserModel getUserModel(String username) {
return userManager.getUserModel(username);
}
@Override
public List<TeamModel> getAllTeams() {
return userManager.getAllTeams();
}
@Override
public TeamModel getTeamModel(String teamname) {
return userManager.getTeamModel(teamname);
}
@Override
public String getCookie(UserModel model) {
return userManager.getCookie(model);
}
@Override
public UserModel getUserModel(char[] cookie) {
return userManager.getUserModel(cookie);
}
@Override
public boolean updateUserModel(UserModel model) {
return userManager.updateUserModel(model);
}
@Override
public boolean updateUserModels(Collection<UserModel> models) {
return userManager.updateUserModels(models);
}
@Override
public boolean updateUserModel(String username, UserModel model) {
return userManager.updateUserModel(username, model);
}
@Override
public boolean deleteUserModel(UserModel model) {
return userManager.deleteUserModel(model);
}
@Override
public List<String> getAllTeamNames() {
return userManager.getAllTeamNames();
}
@Override
public List<String> getTeamNamesForRepositoryRole(String role) {
return userManager.getTeamNamesForRepositoryRole(role);
}
@Override
public boolean updateTeamModel(TeamModel model) {
return userManager.updateTeamModel(model);
}
@Override
public boolean updateTeamModels(Collection<TeamModel> models) {
return userManager.updateTeamModels(models);
}
@Override
public boolean updateTeamModel(String teamname, TeamModel model) {
return userManager.updateTeamModel(teamname, model);
}
@Override
public boolean deleteTeamModel(TeamModel model) {
return userManager.deleteTeamModel(model);
}
@Override
public List<String> getUsernamesForRepositoryRole(String role) {
return userManager.getUsernamesForRepositoryRole(role);
}
@Override
public boolean renameRepositoryRole(String oldRole, String newRole) {
return userManager.renameRepositoryRole(oldRole, newRole);
}
@Override
public boolean deleteRepositoryRole(String role) {
return userManager.deleteRepositoryRole(role);
}
@Override
public boolean deleteTeam(String teamname) {
return userManager.deleteTeam(teamname);
}
/*
* REPOSITORY MANAGER
*/
@Override
public Date getLastActivityDate() {
return repositoryManager.getLastActivityDate();
}
@Override
public File getRepositoriesFolder() {
return repositoryManager.getRepositoriesFolder();
}
@Override
public File getHooksFolder() {
return repositoryManager.getHooksFolder();
}
@Override
public File getGrapesFolder() {
return repositoryManager.getGrapesFolder();
}
@Override
public List<RegistrantAccessPermission> getUserAccessPermissions(UserModel user) {
return repositoryManager.getUserAccessPermissions(user);
}
@Override
public List<RegistrantAccessPermission> getUserAccessPermissions(RepositoryModel repository) {
return repositoryManager.getUserAccessPermissions(repository);
}
@Override
public boolean setUserAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
return repositoryManager.setUserAccessPermissions(repository, permissions);
}
@Override
public List<String> getRepositoryUsers(RepositoryModel repository) {
return repositoryManager.getRepositoryUsers(repository);
}
@Override
public List<RegistrantAccessPermission> getTeamAccessPermissions(RepositoryModel repository) {
return repositoryManager.getTeamAccessPermissions(repository);
}
@Override
public boolean setTeamAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
return repositoryManager.setTeamAccessPermissions(repository, permissions);
}
@Override
public List<String> getRepositoryTeams(RepositoryModel repository) {
return repositoryManager.getRepositoryTeams(repository);
}
@Override
public void addToCachedRepositoryList(RepositoryModel model) {
repositoryManager.addToCachedRepositoryList(model);
}
@Override
public void resetRepositoryListCache() {
repositoryManager.resetRepositoryListCache();
}
@Override
public List<String> getRepositoryList() {
return repositoryManager.getRepositoryList();
}
@Override
public Repository getRepository(String repositoryName) {
return repositoryManager.getRepository(repositoryName);
}
@Override
public Repository getRepository(String repositoryName, boolean logError) {
return repositoryManager.getRepository(repositoryName, logError);
}
@Override
public List<RepositoryModel> getRepositoryModels(UserModel user) {
return repositoryManager.getRepositoryModels(user);
}
@Override
public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
return repositoryManager.getRepositoryModel(repositoryName);
}
@Override
public RepositoryModel getRepositoryModel(String repositoryName) {
return repositoryManager.getRepositoryModel(repositoryName);
}
@Override
public long getStarCount(RepositoryModel repository) {
return repositoryManager.getStarCount(repository);
}
@Override
public boolean hasRepository(String repositoryName) {
return repositoryManager.hasRepository(repositoryName);
}
@Override
public boolean hasRepository(String repositoryName, boolean caseSensitiveCheck) {
return repositoryManager.hasRepository(repositoryName, caseSensitiveCheck);
}
@Override
public boolean hasFork(String username, String origin) {
return repositoryManager.hasFork(username, origin);
}
@Override
public String getFork(String username, String origin) {
return repositoryManager.getFork(username, origin);
}
@Override
public ForkModel getForkNetwork(String repository) {
return repositoryManager.getForkNetwork(repository);
}
@Override
public long updateLastChangeFields(Repository r, RepositoryModel model) {
return repositoryManager.updateLastChangeFields(r, model);
}
@Override
public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
return repositoryManager.getRepositoryDefaultMetrics(model, repository);
}
@Override
public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
repositoryManager.updateRepositoryModel(repositoryName, repository, isCreate);
}
@Override
public void updateConfiguration(Repository r, RepositoryModel repository) {
repositoryManager.updateConfiguration(r, repository);
}
@Override
public boolean deleteRepositoryModel(RepositoryModel model) {
return repositoryManager.deleteRepositoryModel(model);
}
@Override
public boolean deleteRepository(String repositoryName) {
return repositoryManager.deleteRepository(repositoryName);
}
@Override
public List<String> getAllScripts() {
return repositoryManager.getAllScripts();
}
@Override
public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
return repositoryManager.getPreReceiveScriptsInherited(repository);
}
@Override
public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
return repositoryManager.getPreReceiveScriptsUnused(repository);
}
@Override
public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
return repositoryManager.getPostReceiveScriptsInherited(repository);
}
@Override
public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
return repositoryManager.getPostReceiveScriptsUnused(repository);
}
@Override
public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {
return repositoryManager.search(query, page, pageSize, repositories);
}
@Override
public boolean isCollectingGarbage() {
return repositoryManager.isCollectingGarbage();
}
@Override
public boolean isCollectingGarbage(String repositoryName) {
return repositoryManager.isCollectingGarbage(repositoryName);
}
/*
* PROJECT MANAGER
*/
@Override
public List<ProjectModel> getProjectModels(UserModel user, boolean includeUsers) {
return projectManager.getProjectModels(user, includeUsers);
}
@Override
public ProjectModel getProjectModel(String name, UserModel user) {
return projectManager.getProjectModel(name, user);
}
@Override
public ProjectModel getProjectModel(String name) {
return projectManager.getProjectModel(name);
}
@Override
public List<ProjectModel> getProjectModels(List<RepositoryModel> repositoryModels, boolean includeUsers) {
return projectManager.getProjectModels(repositoryModels, includeUsers);
}
/*
* FEDERATION MANAGER
*/
@Override
public File getProposalsFolder() {
return federationManager.getProposalsFolder();
}
@Override
public boolean canFederate() {
return federationManager.canFederate();
}
@Override
public UserModel getFederationUser() {
return federationManager.getFederationUser();
}
@Override
public List<FederationModel> getFederationRegistrations() {
return federationManager.getFederationRegistrations();
}
@Override
public FederationModel getFederationRegistration(String url, String name) {
return federationManager.getFederationRegistration(url, name);
}
@Override
public List<FederationSet> getFederationSets(String gitblitUrl) {
return federationManager.getFederationSets(gitblitUrl);
}
@Override
public List<String> getFederationTokens() {
return federationManager.getFederationTokens();
}
@Override
public String getFederationToken(FederationToken type) {
return federationManager.getFederationToken(type);
}
@Override
public String getFederationToken(String value) {
return federationManager.getFederationToken(value);
}
@Override
public boolean validateFederationRequest(FederationRequest req, String token) {
return federationManager.validateFederationRequest(req, token);
}
@Override
public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
return federationManager.acknowledgeFederationStatus(identification, registration);
}
@Override
public List<FederationModel> getFederationResultRegistrations() {
return federationManager.getFederationResultRegistrations();
}
@Override
public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
return federationManager.submitFederationProposal(proposal, gitblitUrl);
}
@Override
public List<FederationProposal> getPendingFederationProposals() {
return federationManager.getPendingFederationProposals();
}
@Override
public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
return federationManager.getRepositories(gitblitUrl, token);
}
@Override
public FederationProposal createFederationProposal(String gitblitUrl, String token) {
return federationManager.createFederationProposal(gitblitUrl, token);
}
@Override
public FederationProposal getPendingFederationProposal(String token) {
return federationManager.getPendingFederationProposal(token);
}
@Override
public boolean deletePendingFederationProposal(FederationProposal proposal) {
return federationManager.deletePendingFederationProposal(proposal);
}
}
| false | true | public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(), StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
String fromUrl = MessageFormat.format("file://{0}/{1}", repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);
// clone the repository
try {
JGitUtils.cloneRepository(repositoryManager.getRepositoriesFolder(), cloneName, fromUrl, true, null);
} catch (Exception e) {
throw new GitBlitException(e);
}
// create a Gitblit repository model for the clone
RepositoryModel cloneModel = repository.cloneAs(cloneName);
// owner has REWIND/RW+ permissions
cloneModel.addOwner(user.username);
repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);
// add the owner of the source repository to the clone's access list
if (!ArrayUtils.isEmpty(repository.owners)) {
for (String owner : repository.owners) {
UserModel originOwner = userManager.getUserModel(owner);
if (originOwner != null) {
originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
reviseUser(originOwner.username, originOwner);
}
}
}
// grant origin's user list clone permission to fork
List<String> users = repositoryManager.getRepositoryUsers(repository);
List<UserModel> cloneUsers = new ArrayList<UserModel>();
for (String name : users) {
if (!name.equalsIgnoreCase(user.username)) {
UserModel cloneUser = userManager.getUserModel(name);
if (cloneUser.canClone(repository)) {
// origin user can clone origin, grant clone access to fork
cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneUsers.add(cloneUser);
}
}
userManager.updateUserModels(cloneUsers);
// grant origin's team list clone permission to fork
List<String> teams = repositoryManager.getRepositoryTeams(repository);
List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
for (String name : teams) {
TeamModel cloneTeam = userManager.getTeamModel(name);
if (cloneTeam.canClone(repository)) {
// origin team can clone origin, grant clone access to fork
cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneTeams.add(cloneTeam);
}
userManager.updateTeamModels(cloneTeams);
// add this clone to the cached model
repositoryManager.addToCachedRepositoryList(cloneModel);
return cloneModel;
}
| public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(), StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
String fromUrl = MessageFormat.format("file://{0}/{1}", repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);
// clone the repository
try {
JGitUtils.cloneRepository(repositoryManager.getRepositoriesFolder(), cloneName, fromUrl, true, null);
} catch (Exception e) {
throw new GitBlitException(e);
}
// create a Gitblit repository model for the clone
RepositoryModel cloneModel = repository.cloneAs(cloneName);
// owner has REWIND/RW+ permissions
cloneModel.addOwner(user.username);
repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);
// add the owner of the source repository to the clone's access list
if (!ArrayUtils.isEmpty(repository.owners)) {
for (String owner : repository.owners) {
UserModel originOwner = userManager.getUserModel(owner);
if (originOwner != null && !originOwner.canClone(cloneModel)) {
// origin owner can't yet clone fork, grant explicit clone access
originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
reviseUser(originOwner.username, originOwner);
}
}
}
// grant origin's user list clone permission to fork
List<String> users = repositoryManager.getRepositoryUsers(repository);
List<UserModel> cloneUsers = new ArrayList<UserModel>();
for (String name : users) {
if (!name.equalsIgnoreCase(user.username)) {
UserModel cloneUser = userManager.getUserModel(name);
if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) {
// origin user can't yet clone fork, grant explicit clone access
cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneUsers.add(cloneUser);
}
}
userManager.updateUserModels(cloneUsers);
// grant origin's team list clone permission to fork
List<String> teams = repositoryManager.getRepositoryTeams(repository);
List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
for (String name : teams) {
TeamModel cloneTeam = userManager.getTeamModel(name);
if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) {
// origin team can't yet clone fork, grant explicit clone access
cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneTeams.add(cloneTeam);
}
userManager.updateTeamModels(cloneTeams);
// add this clone to the cached model
repositoryManager.addToCachedRepositoryList(cloneModel);
return cloneModel;
}
|
diff --git a/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java b/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
index e3cf2dcb..55bd66b8 100644
--- a/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
+++ b/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
@@ -1,179 +1,179 @@
package test.cli.cloudify;
import static org.testng.AssertJUnit.fail;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpStatus;
import org.cloudifysource.dsl.internal.packaging.PackagingException;
import org.cloudifysource.dsl.utils.ServiceUtils;
import org.cloudifysource.usm.USMException;
import org.cloudifysource.usm.shutdown.DefaultProcessKiller;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.machine.Machine;
import org.openspaces.admin.pu.DeploymentStatus;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.pu.events.ProcessingUnitInstanceLifecycleEventListener;
import org.openspaces.pu.service.CustomServiceMonitors;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import test.usm.USMTestUtils;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import framework.utils.LogUtils;
import framework.utils.ProcessingUnitUtils;
import framework.utils.ScriptUtils;
import groovy.util.ConfigObject;
import groovy.util.ConfigSlurper;
public class InternalUSMPuServiceDownTest extends AbstractLocalCloudTest {
ProcessingUnit tomcat;
Long tomcatPId;
Machine machineA;
WebClient client;
private final String TOMCAT_URL = "http://127.0.0.1:8080";
@Override
@BeforeMethod
public void beforeTest() {
super.beforeTest();
client = new WebClient(BrowserVersion.getDefault());
}
@SuppressWarnings("deprecation")
@Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, groups = "1", enabled = true)
public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
tomcatPId = (Long) customServiceDetails.getMonitors().get("Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
- String catalinaPath = "/work/processing-units/default_tomcat_1/install/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
+ String catalinaPath = "/work/processing-units/default_tomcat_1/ext/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
private boolean isWindows() {
return (System.getenv("windir") != null);
}
private void assertTomcatPageExists(WebClient client) {
HtmlPage page = null;
try {
page = client.getPage("http://" + machineA.getHostAddress() + ":8080");
} catch (IOException e) {
fail(e.getMessage());
}
assertEquals("OK", page.getWebResponse().getStatusMessage());
}
//if service is down, this method will return a 404 not found exception.
private int getResponseCode(String urlString) throws IOException{
URL url = new URL ( urlString );
URLConnection connection = url.openConnection();
try {
connection.connect();
}catch (ConnectException e){
LogUtils.log("The connection to " + urlString + " has failed.");
return HttpStatus.SC_NOT_FOUND;
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
return code;
}
}
| true | true | public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
tomcatPId = (Long) customServiceDetails.getMonitors().get("Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
String catalinaPath = "/work/processing-units/default_tomcat_1/install/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
| public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
tomcatPId = (Long) customServiceDetails.getMonitors().get("Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
String catalinaPath = "/work/processing-units/default_tomcat_1/ext/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
|
diff --git a/jOOQ-test/src/org/jooq/test/_/testcases/ExecuteListenerTests.java b/jOOQ-test/src/org/jooq/test/_/testcases/ExecuteListenerTests.java
index 1cec066e7..37dea0dbc 100644
--- a/jOOQ-test/src/org/jooq/test/_/testcases/ExecuteListenerTests.java
+++ b/jOOQ-test/src/org/jooq/test/_/testcases/ExecuteListenerTests.java
@@ -1,1106 +1,1106 @@
/**
* Copyright (c) 2009-2012, Lukas Eder, [email protected]
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.test._.testcases;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.jooq.conf.SettingsTools.executePreparedStatements;
import static org.jooq.impl.Factory.param;
import static org.jooq.impl.Factory.val;
import static org.jooq.tools.reflect.Reflect.on;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.jooq.Cursor;
import org.jooq.ExecuteContext;
import org.jooq.ExecuteListener;
import org.jooq.ExecuteType;
import org.jooq.Field;
import org.jooq.Result;
import org.jooq.TableRecord;
import org.jooq.UpdatableRecord;
import org.jooq.conf.Settings;
import org.jooq.conf.SettingsTools;
import org.jooq.impl.DefaultExecuteListener;
import org.jooq.impl.Factory;
import org.jooq.test.BaseTest;
import org.jooq.test.jOOQAbstractTest;
import org.junit.Test;
public class ExecuteListenerTests<
A extends UpdatableRecord<A>,
AP,
B extends UpdatableRecord<B>,
S extends UpdatableRecord<S>,
B2S extends UpdatableRecord<B2S>,
BS extends UpdatableRecord<BS>,
L extends TableRecord<L>,
X extends TableRecord<X>,
DATE extends UpdatableRecord<DATE>,
BOOL extends UpdatableRecord<BOOL>,
D extends UpdatableRecord<D>,
T extends UpdatableRecord<T>,
U extends TableRecord<U>,
I extends TableRecord<I>,
IPK extends UpdatableRecord<IPK>,
T658 extends TableRecord<T658>,
T725 extends UpdatableRecord<T725>,
T639 extends UpdatableRecord<T639>,
T785 extends TableRecord<T785>>
extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, I, IPK, T658, T725, T639, T785> {
public ExecuteListenerTests(jOOQAbstractTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, I, IPK, T658, T725, T639, T785> delegate) {
super(delegate);
}
@Test
public void testExecuteListenerCustomException() throws Exception {
Factory create = create(new Settings()
.withExecuteListeners(CustomExceptionListener.class.getName()));
try {
create.fetch("invalid sql");
}
catch (E e) {
assertEquals("ERROR", e.getMessage());
}
}
public static class CustomExceptionListener extends DefaultExecuteListener {
@Override
public void exception(ExecuteContext ctx) {
ctx.exception(new E("ERROR"));
}
}
@Test
public void testExecuteListenerOnResultQuery() throws Exception {
Factory create = create(new Settings()
.withExecuteListeners(ResultQueryListener.class.getName()));
create.setData("Foo", "Bar");
create.setData("Bar", "Baz");
Result<?> result =
create.select(TBook_ID(), val("Hello"))
.from(TBook())
.where(TBook_ID().in(1, 2))
.fetch();
// [#1145] When inlining variables, no bind events are triggered
int plus = (SettingsTools.executePreparedStatements(create.getSettings()) ? 2 : 0);
// Check correct order of listener method invocation
assertEquals(1, ResultQueryListener.start);
assertEquals(2, ResultQueryListener.renderStart);
assertEquals(3, ResultQueryListener.renderEnd);
assertEquals(4, ResultQueryListener.prepareStart);
assertEquals(5, ResultQueryListener.prepareEnd);
assertEquals(plus > 0 ? 6 : 0, ResultQueryListener.bindStart);
assertEquals(plus > 0 ? 7 : 0, ResultQueryListener.bindEnd);
assertEquals(6 + plus, ResultQueryListener.executeStart);
assertEquals(7 + plus, ResultQueryListener.executeEnd);
assertEquals(8 + plus, ResultQueryListener.fetchStart);
assertEquals(9 + plus, ResultQueryListener.resultStart);
assertEquals(asList(10 + plus, 12 + plus), ResultQueryListener.recordStart);
assertEquals(asList(11 + plus, 13 + plus), ResultQueryListener.recordEnd);
assertEquals(14 + plus, ResultQueryListener.resultEnd);
assertEquals(15 + plus, ResultQueryListener.fetchEnd);
assertEquals(16 + plus, ResultQueryListener.end);
assertEquals(2, result.size());
}
public static class ResultQueryListener extends DefaultExecuteListener {
// A counter that is incremented in callback methods
private static int callbackCount = 0;
// Fields that are used to check whether callback methods were called
// in the expected order
public static int start;
public static int renderStart;
public static int renderEnd;
public static int prepareStart;
public static int prepareEnd;
public static int bindStart;
public static int bindEnd;
public static int executeStart;
public static int executeEnd;
public static int fetchStart;
public static int resultStart;
public static List<Integer> recordStart = new ArrayList<Integer>();
public static List<Integer> recordEnd = new ArrayList<Integer>();
public static int resultEnd;
public static int fetchEnd;
public static int end;
public static Queue<Integer> ids = new LinkedList<Integer>(asList(1, 2));
@SuppressWarnings("serial")
private void checkBase(ExecuteContext ctx) {
assertNotNull(ctx.query());
assertNotNull(ctx.batchQueries());
assertTrue(ctx.query().toString().toLowerCase().contains("select"));
assertTrue(ctx.batchQueries()[0].toString().toLowerCase().contains("select"));
assertEquals(ctx.query(), ctx.batchQueries()[0]);
assertEquals(1, ctx.batchSQL().length);
assertEquals("Bar", ctx.getData("Foo"));
assertEquals("Baz", ctx.getData("Bar"));
assertEquals(new HashMap<String, String>() {{
put("Foo", "Bar");
put("Bar", "Baz");
}}, ctx.getData());
assertNull(ctx.routine());
assertEquals(ExecuteType.READ, ctx.type());
}
private void checkSQL(ExecuteContext ctx, boolean patched) {
assertTrue(ctx.batchSQL()[0].toLowerCase().contains("select"));
assertTrue(ctx.sql().toLowerCase().contains("select"));
assertEquals(ctx.sql(), ctx.batchSQL()[0]);
if (patched) {
assertTrue(ctx.sql().toLowerCase().contains("as my_field"));
}
}
@SuppressWarnings("unused")
private void checkStatement(ExecuteContext ctx, boolean patched) {
assertNotNull(ctx.statement());
}
@SuppressWarnings("unused")
private void checkResultSet(ExecuteContext ctx, boolean patched) {
assertNotNull(ctx.resultSet());
}
@Override
public void start(ExecuteContext ctx) {
start = ++callbackCount;
checkBase(ctx);
assertNull(ctx.batchSQL()[0]);
assertNull(ctx.sql());
assertNull(ctx.statement());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void renderStart(ExecuteContext ctx) {
renderStart = ++callbackCount;
checkBase(ctx);
assertNull(ctx.batchSQL()[0]);
assertNull(ctx.sql());
assertNull(ctx.statement());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void renderEnd(ExecuteContext ctx) {
renderEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, false);
assertNull(ctx.statement());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
ctx.sql(ctx.sql().replaceFirst("(?i:from)", "as my_field from"));
checkSQL(ctx, true);
}
@Override
public void prepareStart(ExecuteContext ctx) {
prepareStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
assertNull(ctx.statement());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void prepareEnd(ExecuteContext ctx) {
prepareEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, false);
// TODO Patch statement
checkStatement(ctx, true);
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void bindStart(ExecuteContext ctx) {
bindStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void bindEnd(ExecuteContext ctx) {
bindEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void executeStart(ExecuteContext ctx) {
executeStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void executeEnd(ExecuteContext ctx) {
executeEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, false);
// TODO patch result set
checkResultSet(ctx, true);
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void fetchStart(ExecuteContext ctx) {
fetchStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNull(ctx.record());
assertNull(ctx.result());
}
@Override
public void resultStart(ExecuteContext ctx) {
resultStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNull(ctx.record());
assertNotNull(ctx.result());
assertTrue(ctx.result().isEmpty());
}
@Override
public void recordStart(ExecuteContext ctx) {
recordStart.add(++callbackCount);
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNotNull(ctx.record());
assertEquals(2, ctx.record().getFields().size());
assertNull(ctx.record().getValue(0));
assertNull(ctx.record().getValue(1));
}
@Override
public void recordEnd(ExecuteContext ctx) {
recordEnd.add(++callbackCount);
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNotNull(ctx.record());
assertEquals(2, ctx.record().getFields().size());
assertEquals(ids.remove(), ctx.record().getValue(0));
assertEquals("Hello", ctx.record().getValue(1));
}
@Override
public void resultEnd(ExecuteContext ctx) {
resultEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNotNull(ctx.record());
assertEquals(2, ctx.record().getFields().size());
assertNotNull(ctx.result());
assertEquals(2, ctx.result().size());
}
@Override
public void fetchEnd(ExecuteContext ctx) {
fetchEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNotNull(ctx.record());
assertEquals(2, ctx.record().getFields().size());
assertNotNull(ctx.result());
assertEquals(2, ctx.result().size());
}
@Override
public void end(ExecuteContext ctx) {
end = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
checkResultSet(ctx, true);
assertNotNull(ctx.record());
assertEquals(2, ctx.record().getFields().size());
assertNotNull(ctx.result());
assertEquals(2, ctx.result().size());
}
}
static class E extends RuntimeException {
/**
* Generated UID
*/
private static final long serialVersionUID = 594781555404278995L;
public E(String message) {
super(message);
}
}
@Test
public void testExecuteListenerOnBatchSingle() {
if (!executePreparedStatements(create().getSettings())) {
log.info("SKIPPINT", "Single batch tests with statement type = STATEMENT");
return;
}
jOOQAbstractTest.reset = false;
Factory create = create(new Settings()
.withExecuteListeners(BatchSingleListener.class.getName()));
create.setData("Foo", "Bar");
create.setData("Bar", "Baz");
int[] result = create.batch(create().insertInto(TAuthor())
.set(TAuthor_ID(), param("id", Integer.class))
.set(TAuthor_LAST_NAME(), param("name", String.class)))
.bind(8, "Gamma")
.bind(9, "Helm")
.bind(10, "Johnson")
.execute();
assertEquals(3, result.length);
// Check correct order of listener method invocation
assertEquals(1, BatchSingleListener.start);
assertEquals(2, BatchSingleListener.renderStart);
assertEquals(3, BatchSingleListener.renderEnd);
assertEquals(4, BatchSingleListener.prepareStart);
assertEquals(5, BatchSingleListener.prepareEnd);
assertEquals(asList(6, 8, 10), BatchSingleListener.bindStart);
assertEquals(asList(7, 9, 11), BatchSingleListener.bindEnd);
assertEquals(12, BatchSingleListener.executeStart);
assertEquals(13, BatchSingleListener.executeEnd);
assertEquals(14, BatchSingleListener.end);
}
public static class BatchSingleListener extends DefaultExecuteListener {
// A counter that is incremented in callback methods
private static int callbackCount = 0;
// Fields that are used to check whether callback methods were called
// in the expected order
public static int start;
public static int renderStart;
public static int renderEnd;
public static int prepareStart;
public static int prepareEnd;
public static List<Integer> bindStart = new ArrayList<Integer>();
public static List<Integer> bindEnd = new ArrayList<Integer>();
public static int executeStart;
public static int executeEnd;
public static int end;
@SuppressWarnings("serial")
private void checkBase(ExecuteContext ctx) {
assertNull(ctx.query());
assertNotNull(ctx.batchQueries());
assertTrue(ctx.batchQueries()[0].toString().toLowerCase().contains("insert"));
assertEquals(1, ctx.batchSQL().length);
assertEquals("Bar", ctx.getData("Foo"));
assertEquals("Baz", ctx.getData("Bar"));
assertEquals(new HashMap<String, String>() {{
put("Foo", "Bar");
put("Bar", "Baz");
}}, ctx.getData());
assertNull(ctx.routine());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
assertEquals(ExecuteType.BATCH, ctx.type());
}
private void checkSQL(ExecuteContext ctx, boolean patched) {
assertTrue(ctx.batchSQL()[0].toLowerCase().contains("insert"));
if (patched) {
assertTrue(ctx.batchSQL()[0].toLowerCase().contains("values ("));
}
}
@SuppressWarnings("unused")
private void checkStatement(ExecuteContext ctx, boolean patched) {
assertNotNull(ctx.statement());
}
@Override
public void start(ExecuteContext ctx) {
start = ++callbackCount;
checkBase(ctx);
assertNull(ctx.batchSQL()[0]);
assertNull(ctx.sql());
assertNull(ctx.statement());
}
@Override
public void renderStart(ExecuteContext ctx) {
renderStart = ++callbackCount;
checkBase(ctx);
assertNull(ctx.batchSQL()[0]);
assertNull(ctx.sql());
assertNull(ctx.statement());
}
@Override
public void renderEnd(ExecuteContext ctx) {
renderEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, false);
assertNull(ctx.statement());
ctx.sql(ctx.sql().replaceFirst("(?i:values\\s+)", "values "));
checkSQL(ctx, true);
}
@Override
public void prepareStart(ExecuteContext ctx) {
prepareStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
assertNull(ctx.statement());
}
@Override
public void prepareEnd(ExecuteContext ctx) {
prepareEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, false);
// TODO Patch statement
checkStatement(ctx, true);
}
@Override
public void bindStart(ExecuteContext ctx) {
bindStart.add(++callbackCount);
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void bindEnd(ExecuteContext ctx) {
bindEnd.add(++callbackCount);
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void executeStart(ExecuteContext ctx) {
executeStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void executeEnd(ExecuteContext ctx) {
executeEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void fetchStart(ExecuteContext ctx) {
fail();
}
@Override
public void resultStart(ExecuteContext ctx) {
fail();
}
@Override
public void recordStart(ExecuteContext ctx) {
fail();
}
@Override
public void recordEnd(ExecuteContext ctx) {
fail();
}
@Override
public void resultEnd(ExecuteContext ctx) {
fail();
}
@Override
public void fetchEnd(ExecuteContext ctx) {
fail();
}
@Override
public void end(ExecuteContext ctx) {
end = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
}
@Test
public void testExecuteListenerOnBatchMultiple() {
jOOQAbstractTest.reset = false;
Factory create = create(new Settings()
.withExecuteListeners(BatchMultipleListener.class.getName()));
create.setData("Foo", "Bar");
create.setData("Bar", "Baz");
int[] result = create.batch(
create().insertInto(TAuthor())
.set(TAuthor_ID(), 8)
.set(TAuthor_LAST_NAME(), "Gamma"),
create().insertInto(TAuthor())
.set(TAuthor_ID(), 9)
.set(TAuthor_LAST_NAME(), "Helm"),
create().insertInto(TBook())
.set(TBook_ID(), 6)
.set(TBook_AUTHOR_ID(), 8)
.set(TBook_PUBLISHED_IN(), 1994)
.set((Field<Object>)TBook_LANGUAGE_ID(), on(TBook_LANGUAGE_ID().getDataType().getType()).get("en"))
.set(TBook_CONTENT_TEXT(), "Design Patterns are awesome")
.set(TBook_TITLE(), "Design Patterns"),
create().insertInto(TAuthor())
.set(TAuthor_ID(), 10)
.set(TAuthor_LAST_NAME(), "Johnson")).execute();
assertEquals(4, result.length);
assertEquals(5, create().fetch(TBook()).size());
assertEquals(1, create().fetch(TBook(), TBook_AUTHOR_ID().equal(8)).size());
// Check correct order of listener method invocation
assertEquals(1, BatchMultipleListener.start);
assertEquals(asList(2, 4, 6, 8), BatchMultipleListener.renderStart);
assertEquals(asList(3, 5, 7, 9), BatchMultipleListener.renderEnd);
assertEquals(asList(10, 12, 14, 16), BatchMultipleListener.prepareStart);
assertEquals(asList(11, 13, 15, 17), BatchMultipleListener.prepareEnd);
assertEquals(18, BatchMultipleListener.executeStart);
assertEquals(19, BatchMultipleListener.executeEnd);
assertEquals(20, BatchMultipleListener.end);
}
public static class BatchMultipleListener extends DefaultExecuteListener {
// A counter that is incremented in callback methods
private static int callbackCount = 0;
private static int rendered = 0;
private static int prepared = 0;
// Fields that are used to check whether callback methods were called
// in the expected order
public static int start;
public static List<Integer> renderStart = new ArrayList<Integer>();
public static List<Integer> renderEnd = new ArrayList<Integer>();
public static List<Integer> prepareStart = new ArrayList<Integer>();
public static List<Integer> prepareEnd = new ArrayList<Integer>();
public static int executeStart;
public static int executeEnd;
public static int end;
public static Queue<Integer> ids = new LinkedList<Integer>(asList(1, 2));
@SuppressWarnings("serial")
private void checkBase(ExecuteContext ctx) {
assertNull(ctx.query());
assertNotNull(ctx.batchQueries());
assertTrue(ctx.batchQueries()[0].toString().toLowerCase().contains("insert"));
assertTrue(ctx.batchQueries()[1].toString().toLowerCase().contains("insert"));
assertTrue(ctx.batchQueries()[2].toString().toLowerCase().contains("insert"));
assertTrue(ctx.batchQueries()[3].toString().toLowerCase().contains("insert"));
assertEquals(4, ctx.batchSQL().length);
assertEquals("Bar", ctx.getData("Foo"));
assertEquals("Baz", ctx.getData("Bar"));
assertEquals(new HashMap<String, String>() {{
put("Foo", "Bar");
put("Bar", "Baz");
}}, ctx.getData());
assertNull(ctx.routine());
assertNull(ctx.resultSet());
assertNull(ctx.record());
assertNull(ctx.result());
assertEquals(ExecuteType.BATCH, ctx.type());
}
private void checkSQL(ExecuteContext ctx, boolean patched) {
for (int i = 0; i < rendered; i++) {
assertTrue(ctx.batchQueries()[i].toString().toLowerCase().contains("insert"));
if (patched) {
assertTrue(ctx.batchSQL()[i].toLowerCase().contains("values ("));
}
}
}
@SuppressWarnings("unused")
private void checkStatement(ExecuteContext ctx, boolean patched) {
assertNotNull(ctx.statement());
}
@Override
public void start(ExecuteContext ctx) {
start = ++callbackCount;
checkBase(ctx);
assertNull(ctx.batchSQL()[0]);
assertNull(ctx.batchSQL()[1]);
assertNull(ctx.batchSQL()[2]);
assertNull(ctx.batchSQL()[3]);
assertNull(ctx.sql());
assertNull(ctx.statement());
}
@Override
public void renderStart(ExecuteContext ctx) {
renderStart.add(++callbackCount);
checkBase(ctx);
checkStatement(ctx, false);
checkSQL(ctx, false);
assertNull(ctx.sql());
}
@Override
public void renderEnd(ExecuteContext ctx) {
renderEnd.add(++callbackCount);
rendered++;
checkBase(ctx);
checkStatement(ctx, false);
checkSQL(ctx, false);
ctx.batchSQL()[rendered - 1] = ctx.batchSQL()[rendered - 1].replaceFirst("(?i:values\\s+)", "values ");
checkSQL(ctx, true);
}
@Override
public void prepareStart(ExecuteContext ctx) {
prepareStart.add(++callbackCount);
checkBase(ctx);
checkStatement(ctx, false);
checkSQL(ctx, true);
}
@Override
public void prepareEnd(ExecuteContext ctx) {
prepareEnd.add(++callbackCount);
prepared++;
checkBase(ctx);
checkStatement(ctx, false);
checkSQL(ctx, true);
}
@Override
public void bindStart(ExecuteContext ctx) {
fail();
}
@Override
public void bindEnd(ExecuteContext ctx) {
fail();
}
@Override
public void executeStart(ExecuteContext ctx) {
executeStart = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void executeEnd(ExecuteContext ctx) {
executeEnd = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
@Override
public void fetchStart(ExecuteContext ctx) {
fail();
}
@Override
public void resultStart(ExecuteContext ctx) {
fail();
}
@Override
public void recordStart(ExecuteContext ctx) {
fail();
}
@Override
public void recordEnd(ExecuteContext ctx) {
fail();
}
@Override
public void resultEnd(ExecuteContext ctx) {
fail();
}
@Override
public void fetchEnd(ExecuteContext ctx) {
fail();
}
@Override
public void end(ExecuteContext ctx) {
end = ++callbackCount;
checkBase(ctx);
checkSQL(ctx, true);
checkStatement(ctx, true);
}
}
@Test
public void testExecuteListenerFetchLazyTest() throws Exception {
Factory create = create(new Settings().withExecuteListeners(FetchLazyListener.class.getName()));
FetchLazyListener.reset();
create.selectFrom(TAuthor()).fetch();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(1, FetchLazyListener.countFetchEnd);
assertEquals(1, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
// [#1868] fetchLazy should behave almost the same as fetch
FetchLazyListener.reset();
Cursor<A> cursor = create.selectFrom(TAuthor()).fetchLazy();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(0, FetchLazyListener.countFetchStart);
assertEquals(0, FetchLazyListener.countResultStart);
assertEquals(0, FetchLazyListener.countRecordStart);
assertEquals(0, FetchLazyListener.countRecordEnd);
assertEquals(0, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(1, FetchLazyListener.countRecordStart);
assertEquals(1, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(2, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(2, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
- assertEquals(2, FetchLazyListener.countResultStart);
+ assertEquals(3, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
- assertEquals(2, FetchLazyListener.countResultEnd);
- assertEquals(0, FetchLazyListener.countFetchEnd);
- assertEquals(0, FetchLazyListener.countEnd);
+ assertEquals(3, FetchLazyListener.countResultEnd);
+ assertEquals(1, FetchLazyListener.countFetchEnd);
+ assertEquals(1, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
}
public static class FetchLazyListener implements ExecuteListener {
static int countStart;
static int countRenderStart;
static int countRenderEnd;
static int countPrepareStart;
static int countPrepareEnd;
static int countBindStart;
static int countBindEnd;
static int countExecuteStart;
static int countExecuteEnd;
static int countFetchStart;
static int countResultStart;
static int countRecordStart;
static int countRecordEnd;
static int countResultEnd;
static int countFetchEnd;
static int countEnd;
static int countException;
static void reset() {
for (java.lang.reflect.Field f : FetchLazyListener.class.getDeclaredFields()) {
f.setAccessible(true);
try {
f.set(FetchLazyListener.class, 0);
}
catch (Exception ignore) {}
}
}
@Override
public void start(ExecuteContext ctx) {
countStart++;
}
@Override
public void renderStart(ExecuteContext ctx) {
countRenderStart++;
}
@Override
public void renderEnd(ExecuteContext ctx) {
countRenderEnd++;
}
@Override
public void prepareStart(ExecuteContext ctx) {
countPrepareStart++;
}
@Override
public void prepareEnd(ExecuteContext ctx) {
countPrepareEnd++;
}
@Override
public void bindStart(ExecuteContext ctx) {
countBindStart++;
}
@Override
public void bindEnd(ExecuteContext ctx) {
countBindEnd++;
}
@Override
public void executeStart(ExecuteContext ctx) {
countExecuteStart++;
}
@Override
public void executeEnd(ExecuteContext ctx) {
countExecuteEnd++;
}
@Override
public void fetchStart(ExecuteContext ctx) {
countFetchStart++;
}
@Override
public void resultStart(ExecuteContext ctx) {
countResultStart++;
}
@Override
public void recordStart(ExecuteContext ctx) {
countRecordStart++;
}
@Override
public void recordEnd(ExecuteContext ctx) {
countRecordEnd++;
}
@Override
public void resultEnd(ExecuteContext ctx) {
countResultEnd++;
}
@Override
public void fetchEnd(ExecuteContext ctx) {
countFetchEnd++;
}
@Override
public void exception(ExecuteContext ctx) {
countException++;
}
@Override
public void end(ExecuteContext ctx) {
countEnd++;
}
}
}
| false | true | public void testExecuteListenerFetchLazyTest() throws Exception {
Factory create = create(new Settings().withExecuteListeners(FetchLazyListener.class.getName()));
FetchLazyListener.reset();
create.selectFrom(TAuthor()).fetch();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(1, FetchLazyListener.countFetchEnd);
assertEquals(1, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
// [#1868] fetchLazy should behave almost the same as fetch
FetchLazyListener.reset();
Cursor<A> cursor = create.selectFrom(TAuthor()).fetchLazy();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(0, FetchLazyListener.countFetchStart);
assertEquals(0, FetchLazyListener.countResultStart);
assertEquals(0, FetchLazyListener.countRecordStart);
assertEquals(0, FetchLazyListener.countRecordEnd);
assertEquals(0, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(1, FetchLazyListener.countRecordStart);
assertEquals(1, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(2, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(2, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(2, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(2, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
}
| public void testExecuteListenerFetchLazyTest() throws Exception {
Factory create = create(new Settings().withExecuteListeners(FetchLazyListener.class.getName()));
FetchLazyListener.reset();
create.selectFrom(TAuthor()).fetch();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(1, FetchLazyListener.countFetchEnd);
assertEquals(1, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
// [#1868] fetchLazy should behave almost the same as fetch
FetchLazyListener.reset();
Cursor<A> cursor = create.selectFrom(TAuthor()).fetchLazy();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(0, FetchLazyListener.countFetchStart);
assertEquals(0, FetchLazyListener.countResultStart);
assertEquals(0, FetchLazyListener.countRecordStart);
assertEquals(0, FetchLazyListener.countRecordEnd);
assertEquals(0, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(1, FetchLazyListener.countResultStart);
assertEquals(1, FetchLazyListener.countRecordStart);
assertEquals(1, FetchLazyListener.countRecordEnd);
assertEquals(1, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(2, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(2, FetchLazyListener.countResultEnd);
assertEquals(0, FetchLazyListener.countFetchEnd);
assertEquals(0, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
cursor.fetchOne();
assertEquals(1, FetchLazyListener.countStart);
assertEquals(1, FetchLazyListener.countRenderStart);
assertEquals(1, FetchLazyListener.countRenderEnd);
assertEquals(1, FetchLazyListener.countPrepareStart);
assertEquals(1, FetchLazyListener.countPrepareEnd);
assertEquals(1, FetchLazyListener.countBindStart);
assertEquals(1, FetchLazyListener.countBindEnd);
assertEquals(1, FetchLazyListener.countExecuteStart);
assertEquals(1, FetchLazyListener.countExecuteEnd);
assertEquals(1, FetchLazyListener.countFetchStart);
assertEquals(3, FetchLazyListener.countResultStart);
assertEquals(2, FetchLazyListener.countRecordStart);
assertEquals(2, FetchLazyListener.countRecordEnd);
assertEquals(3, FetchLazyListener.countResultEnd);
assertEquals(1, FetchLazyListener.countFetchEnd);
assertEquals(1, FetchLazyListener.countEnd);
assertEquals(0, FetchLazyListener.countException);
}
|
diff --git a/src/main/java/org/vamdc/validator/gui/mainframe/QueryField.java b/src/main/java/org/vamdc/validator/gui/mainframe/QueryField.java
index e54ea13..eb105c0 100644
--- a/src/main/java/org/vamdc/validator/gui/mainframe/QueryField.java
+++ b/src/main/java/org/vamdc/validator/gui/mainframe/QueryField.java
@@ -1,86 +1,89 @@
package org.vamdc.validator.gui.mainframe;
import javax.swing.text.JTextComponent;
import org.vamdc.tapservice.vss2.VSSParser;
import org.vamdc.validator.Setting;
import org.vamdc.validator.gui.HistoryComboBox;
import org.vamdc.validator.interfaces.XSAMSIOModel;
public class QueryField extends HistoryComboBox implements ComponentUpdateInterface{
private static final long serialVersionUID = -9123198309241131479L;
private XSAMSIOModel data;
public QueryField(){
super(Setting.GUIQueryHistory,";",10);
}
@Override
protected void loadValues(){
super.loadValues();
if (data!=null && data.getSampleQueries()!=null)
for (String query:data.getSampleQueries()){
- if (query.length()>1){
- validateQuery(query);
- this.addItem(query+";");
+ String trq=query.trim();
+ if (trq.length()>1){
+ validateQuery(trq);
+ if (!trq.endsWith(";"))
+ trq=trq+";";
+ this.addItem(trq);
}
}
}
public static boolean validateQuery(String query) {
try{
VSSParser.parse(query);
return true;
}catch (IllegalArgumentException e){
System.out.println("Warning! Query '"+query+"' was not valid:");
System.out.println(e.getMessage());
return false;
}
}
/**
* Add query to history. If query is already present, move it up the list.
* @param query query string
*/
private void saveQuery(String query) {
this.saveValue(query);
this.removeAllItems();
this.loadValues();
}
public String getText() {
return this.getEditor().getItem().toString();
}
public JTextComponent getTextComponent() {
return (JTextComponent)this.getEditor().getEditorComponent();
}
@Override
public void resetComponent() {
loadValues();
}
@Override
public void setModel(XSAMSIOModel data) {
this.data = data;
loadValues();
}
@Override
public void updateFromModel(boolean isFinal) {
if (isFinal && data!=null){
if (data.getLineCount() > 10)
saveQuery(data.getQuery());
else
loadValues();
}
}
}
| true | true | protected void loadValues(){
super.loadValues();
if (data!=null && data.getSampleQueries()!=null)
for (String query:data.getSampleQueries()){
if (query.length()>1){
validateQuery(query);
this.addItem(query+";");
}
}
}
| protected void loadValues(){
super.loadValues();
if (data!=null && data.getSampleQueries()!=null)
for (String query:data.getSampleQueries()){
String trq=query.trim();
if (trq.length()>1){
validateQuery(trq);
if (!trq.endsWith(";"))
trq=trq+";";
this.addItem(trq);
}
}
}
|
diff --git a/src/com/arantius/tivocommander/Explore.java b/src/com/arantius/tivocommander/Explore.java
index 287eee5..3d13815 100644
--- a/src/com/arantius/tivocommander/Explore.java
+++ b/src/com/arantius/tivocommander/Explore.java
@@ -1,476 +1,477 @@
/*
DVR Commander for TiVo allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.RecordingSearch;
import com.arantius.tivocommander.rpc.request.RecordingUpdate;
import com.arantius.tivocommander.rpc.request.SubscriptionSearch;
import com.arantius.tivocommander.rpc.request.UiNavigate;
import com.arantius.tivocommander.rpc.request.Unsubscribe;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
import com.fasterxml.jackson.databind.JsonNode;
public class Explore extends ExploreCommon {
enum RecordActions {
DONT_RECORD("Don't record"), RECORD("Record this episode"), RECORD_STOP(
"Stop recording in progress"), SP_ADD("Add season pass"), SP_CANCEL(
"Cancel season pass"), SP_MODIFY("Modify season pass");
private final String mText;
private RecordActions(String text) {
mText = text;
}
@Override
public String toString() {
return mText;
}
}
private final MindRpcResponseListener mDeleteListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
getParent().setProgressBarIndeterminateVisibility(false);
if (!("success".equals(response.getRespType()))) {
Utils.logError("Delete attempt failed!");
Utils.toast(Explore.this, "Delete failed!.", Toast.LENGTH_SHORT);
return;
}
// .. and tell the show list to refresh itself.
Intent resultIntent = new Intent();
resultIntent.putExtra("refresh", true);
getParent().setResult(Activity.RESULT_OK, resultIntent);
finish();
}
};
private final MindRpcResponseListener mRecordingListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mRecording = response.getBody().path("recording").path(0);
mRecordingState = mRecording.path("state").asText();
mSubscriptionType = Utils.subscriptionTypeForRecording(mRecording);
finishRequest();
}
};
private final MindRpcResponseListener mSubscriptionListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
mSubscription = response.getBody().path("subscription").path(0);
if (mSubscription.isMissingNode()) {
mSubscription = null;
mSubscriptionId = null;
} else {
mSubscriptionId = mSubscription.path("subscriptionId").asText();
final String subType =
mSubscription.path("idSetSource").path("type").asText();
if ("seasonPassSource".equals(subType)) {
mSubscriptionType = SubscriptionType.SEASON_PASS;
} else if ("wishListSource".equals(subType)) {
mSubscriptionType = SubscriptionType.WISHLIST;
}
}
finishRequest();
}
};
private final ArrayList<String> mChoices = new ArrayList<String>();
private JsonNode mRecording = null;
private String mRecordingState = null;
private int mRequestCount = 0;
private SubscriptionType mSubscriptionType = null;
private JsonNode mSubscription = null;
private String mSubscriptionId = null;
public void doDelete(View v) {
// FIXME: Fails when deleting the currently-playing show.
getParent().setProgressBarIndeterminateVisibility(true);
String newState = "deleted";
if (v.getId() == R.id.explore_btn_undelete) {
newState = "complete";
}
// (Un-)Delete the recording ...
final RecordingUpdate req = new RecordingUpdate(mRecordingId, newState);
MindRpc.addRequest(req, mDeleteListener);
}
public void doRecord(View v) {
ArrayAdapter<String> choicesAdapter =
new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
mChoices);
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Operation?");
dialogBuilder.setAdapter(choicesAdapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
String label = mChoices.get(position);
if (RecordActions.DONT_RECORD.toString().equals(label)) {
getParent().setProgressBarIndeterminateVisibility(true);
MindRpc.addRequest(
new RecordingUpdate(mRecordingId, "cancelled"),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
getParent().setProgressBarIndeterminateVisibility(false);
ImageView iconSubType =
(ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType =
(TextView) findViewById(R.id.text_sub_type);
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
});
} else if (RecordActions.RECORD.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeOffer.class);
intent.putExtra("contentId", mContentId);
intent.putExtra("offerId", mOfferId);
startActivity(intent);
} else if (RecordActions.RECORD_STOP.toString().equals(label)) {
getParent().setProgressBarIndeterminateVisibility(true);
MindRpc.addRequest(new RecordingUpdate(mRecordingId, "complete"),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
getParent().setProgressBarIndeterminateVisibility(false);
mRecordingId = null;
}
});
} else if (RecordActions.SP_ADD.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeCollection.class);
intent.putExtra("collectionId", mCollectionId);
startActivity(intent);
// TODO: Start for result, get subscription ID.
} else if (RecordActions.SP_CANCEL.toString().equals(label)) {
getParent().setProgressBarIndeterminateVisibility(true);
MindRpc.addRequest(new Unsubscribe(mSubscriptionId),
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
getParent().setProgressBarIndeterminateVisibility(false);
mSubscriptionId = null;
}
});
} else if (RecordActions.SP_MODIFY.toString().equals(label)) {
Intent intent =
new Intent(getBaseContext(), SubscribeCollection.class);
intent.putExtra("collectionId", mCollectionId);
intent.putExtra("subscriptionId", mSubscriptionId);
intent.putExtra("subscriptionJson",
Utils.stringifyToJson(mSubscription));
startActivity(intent);
}
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
public void doUpcoming(View v) {
Intent intent = new Intent(getBaseContext(), Upcoming.class);
intent.putExtra("collectionId", mCollectionId);
startActivity(intent);
}
public void doWatch(View v) {
MindRpc.addRequest(new UiNavigate(mRecordingId), null);
Intent intent = new Intent(this, NowShowing.class);
startActivity(intent);
}
protected void finishRequest() {
if (--mRequestCount != 0) {
return;
}
getParent().setProgressBarIndeterminateVisibility(false);
if (mRecordingId == null) {
for (JsonNode recording : mContent.path("recordingForContentId")) {
String state = recording.path("state").asText();
if ("inProgress".equals(state) || "complete".equals(state)
|| "scheduled".equals(state)) {
mRecordingId = recording.path("recordingId").asText();
mRecordingState = state;
break;
}
}
}
// Fill mChoices based on the data we now have.
if ("scheduled".equals(mRecordingState)) {
mChoices.add(RecordActions.DONT_RECORD.toString());
} else if ("inProgress".equals(mRecordingState)) {
mChoices.add(RecordActions.RECORD_STOP.toString());
} else if (mOfferId != null) {
mChoices.add(RecordActions.RECORD.toString());
}
if (mSubscriptionId != null) {
mChoices.add(RecordActions.SP_MODIFY.toString());
mChoices.add(RecordActions.SP_CANCEL.toString());
} else if (mCollectionId != null
- && !"movie".equals(mContent.path("collectionType").asText())) {
+ && !"movie".equals(mContent.path("collectionType").asText())
+ && !mContent.has("movieYear")) {
mChoices.add(RecordActions.SP_ADD.toString());
}
setContentView(R.layout.explore);
// Show only appropriate buttons.
findViewById(R.id.explore_btn_watch).setVisibility(
"complete".equals(mRecordingState)
|| "inprogress".equals(mRecordingState)
? View.VISIBLE : View.GONE);
hideViewIfNull(R.id.explore_btn_upcoming, mCollectionId);
if (mChoices.size() == 0) {
findViewById(R.id.explore_btn_record).setVisibility(View.GONE);
}
// Delete / undelete buttons visible only if appropriate.
findViewById(R.id.explore_btn_delete).setVisibility(
"complete".equals(mRecordingState) ? View.VISIBLE : View.GONE);
findViewById(R.id.explore_btn_undelete).setVisibility(
"deleted".equals(mRecordingState) ? View.VISIBLE : View.GONE);
// Display titles.
String title = mContent.path("title").asText();
String subtitle = mContent.path("subtitle").asText();
((TextView) findViewById(R.id.content_title)).setText(title);
TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle));
if ("".equals(subtitle)) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setText(subtitle);
}
// Display (only the proper) badges.
if (mRecording == null || mRecording.path("repeat").asBoolean()) {
findViewById(R.id.badge_new).setVisibility(View.GONE);
}
if (mRecording == null || !mRecording.path("hdtv").asBoolean()) {
findViewById(R.id.badge_hd).setVisibility(View.GONE);
}
ImageView iconSubType = (ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType = (TextView) findViewById(R.id.text_sub_type);
// TODO: Downloading state?
if ("complete".equals(mRecordingState)) {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
} else if ("inProgress".equals(mRecordingState)) {
iconSubType.setImageResource(R.drawable.recording_recording);
textSubType.setText(R.string.sub_recording);
} else if (mSubscriptionType != null) {
switch (mSubscriptionType) {
case SEASON_PASS:
iconSubType.setImageResource(R.drawable.todo_seasonpass);
textSubType.setText(R.string.sub_season_pass);
break;
case SINGLE_OFFER:
iconSubType.setImageResource(R.drawable.todo_single_offer);
textSubType.setText(R.string.sub_single_offer);
break;
case WISHLIST:
iconSubType.setImageResource(R.drawable.todo_wishlist);
textSubType.setText(R.string.sub_wishlist);
break;
default:
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
} else {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
// Display channel and time.
if (mRecording != null) {
String channelStr = "";
JsonNode channel = mRecording.path("channel");
if (!channel.isMissingNode()) {
channelStr =
String.format("%s %s, ", channel.path("channelNumber")
.asText(),
channel.path("callSign").asText());
}
// Lots of shows seem to be a few seconds short, add padding so that
// rounding down works as expected. Magic number.
final int minutes = (30 + mRecording.path("duration").asInt()) / 60;
String durationStr =
minutes >= 60 ? String.format(Locale.US, "%d hr", minutes / 60)
: String.format(Locale.US, "%d min", minutes);
if (isRecordingPartial()) {
durationStr += " (partial)";
}
((TextView) findViewById(R.id.content_time)).setText(channelStr
+ durationStr);
} else {
((TextView) findViewById(R.id.content_time)).setVisibility(View.GONE);
}
// Construct and display details.
ArrayList<String> detailParts = new ArrayList<String>();
int season = mContent.path("seasonNumber").asInt();
int epNum = mContent.path("episodeNum").path(0).asInt();
if (season != 0 && epNum != 0) {
detailParts.add(String.format("Sea %d Ep %d", season, epNum));
}
if (mContent.has("mpaaRating")) {
detailParts.add(mContent.path("mpaaRating").asText()
.toUpperCase(Locale.US));
} else if (mContent.has("tvRating")) {
detailParts.add("TV-"
+ mContent.path("tvRating").asText().toUpperCase(Locale.US));
}
detailParts.add(mContent.path("category").path(0).path("label")
.asText());
int year = mContent.path("originalAirYear").asInt();
if (year != 0) {
detailParts.add(Integer.toString(year));
}
// Filter empty strings.
for (int i = detailParts.size() - 1; i >= 0; i--) {
if ("".equals(detailParts.get(i)) || null == detailParts.get(i)) {
detailParts.remove(i);
}
}
// Then format the parts into one string.
String detail1 = "(" + Utils.join(", ", detailParts) + ") ";
if ("() ".equals(detail1)) {
detail1 = "";
}
String detail2 = mContent.path("description").asText();
TextView detailView = ((TextView) findViewById(R.id.content_details));
if (detail2 == null) {
detailView.setText(detail1);
} else {
Spannable details = new SpannableString(detail1 + detail2);
details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(),
details.length(), 0);
detailView.setText(details);
}
// Add credits.
ArrayList<String> credits = new ArrayList<String>();
for (JsonNode credit : mContent.path("credit")) {
String role = credit.path("role").asText();
if ("actor".equals(role) || "host".equals(role)
|| "guestStar".equals(role)) {
credits.add(credit.path("first").asText() + " "
+ credit.path("last").asText());
}
}
TextView creditsView = (TextView) findViewById(R.id.content_credits);
creditsView.setText(Utils.join(", ", credits));
// Find and set the banner image if possible.
ImageView imageView = (ImageView) findViewById(R.id.content_image);
View progressView = findViewById(R.id.content_image_progress);
String imageUrl = Utils.findImageUrl(mContent);
new DownloadImageTask(this, imageView, progressView).execute(imageUrl);
}
private void hideViewIfNull(int viewId, Object condition) {
if (condition != null)
return;
findViewById(viewId).setVisibility(View.GONE);
}
private Boolean isRecordingPartial() {
final Date actualStart =
Utils.parseDateTimeStr(mRecording.path("actualStartTime")
.asText());
final Date scheduledStart =
Utils.parseDateTimeStr(mRecording.path("scheduledStartTime")
.asText());
final Date actualEnd =
Utils.parseDateTimeStr(mRecording.path("actualEndTime").asText());
final Date scheduledEnd =
Utils.parseDateTimeStr(mRecording.path("scheduledEndTime")
.asText());
return actualStart.getTime() - scheduledStart.getTime() >= 30000
|| scheduledEnd.getTime() - actualEnd.getTime() >= 30000;
}
@Override
protected void onContent() {
finishRequest();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.log(String.format("Explore: "
+ "contentId:%s collectionId:%s offerId:%s recordingId:%s", mContentId,
mCollectionId, mOfferId, mRecordingId));
// The one from ExploreCommon.
mRequestCount = 1;
if (mCollectionId != null) {
mRequestCount++;
MindRpc.addRequest(new SubscriptionSearch(mCollectionId),
mSubscriptionListener);
}
if (mRecordingId != null) {
mRequestCount++;
MindRpc.addRequest(new RecordingSearch(mRecordingId), mRecordingListener);
}
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Explore");
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Explore");
if (MindRpc.init(this, null)) {
return;
}
}
}
| true | true | protected void finishRequest() {
if (--mRequestCount != 0) {
return;
}
getParent().setProgressBarIndeterminateVisibility(false);
if (mRecordingId == null) {
for (JsonNode recording : mContent.path("recordingForContentId")) {
String state = recording.path("state").asText();
if ("inProgress".equals(state) || "complete".equals(state)
|| "scheduled".equals(state)) {
mRecordingId = recording.path("recordingId").asText();
mRecordingState = state;
break;
}
}
}
// Fill mChoices based on the data we now have.
if ("scheduled".equals(mRecordingState)) {
mChoices.add(RecordActions.DONT_RECORD.toString());
} else if ("inProgress".equals(mRecordingState)) {
mChoices.add(RecordActions.RECORD_STOP.toString());
} else if (mOfferId != null) {
mChoices.add(RecordActions.RECORD.toString());
}
if (mSubscriptionId != null) {
mChoices.add(RecordActions.SP_MODIFY.toString());
mChoices.add(RecordActions.SP_CANCEL.toString());
} else if (mCollectionId != null
&& !"movie".equals(mContent.path("collectionType").asText())) {
mChoices.add(RecordActions.SP_ADD.toString());
}
setContentView(R.layout.explore);
// Show only appropriate buttons.
findViewById(R.id.explore_btn_watch).setVisibility(
"complete".equals(mRecordingState)
|| "inprogress".equals(mRecordingState)
? View.VISIBLE : View.GONE);
hideViewIfNull(R.id.explore_btn_upcoming, mCollectionId);
if (mChoices.size() == 0) {
findViewById(R.id.explore_btn_record).setVisibility(View.GONE);
}
// Delete / undelete buttons visible only if appropriate.
findViewById(R.id.explore_btn_delete).setVisibility(
"complete".equals(mRecordingState) ? View.VISIBLE : View.GONE);
findViewById(R.id.explore_btn_undelete).setVisibility(
"deleted".equals(mRecordingState) ? View.VISIBLE : View.GONE);
// Display titles.
String title = mContent.path("title").asText();
String subtitle = mContent.path("subtitle").asText();
((TextView) findViewById(R.id.content_title)).setText(title);
TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle));
if ("".equals(subtitle)) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setText(subtitle);
}
// Display (only the proper) badges.
if (mRecording == null || mRecording.path("repeat").asBoolean()) {
findViewById(R.id.badge_new).setVisibility(View.GONE);
}
if (mRecording == null || !mRecording.path("hdtv").asBoolean()) {
findViewById(R.id.badge_hd).setVisibility(View.GONE);
}
ImageView iconSubType = (ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType = (TextView) findViewById(R.id.text_sub_type);
// TODO: Downloading state?
if ("complete".equals(mRecordingState)) {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
} else if ("inProgress".equals(mRecordingState)) {
iconSubType.setImageResource(R.drawable.recording_recording);
textSubType.setText(R.string.sub_recording);
} else if (mSubscriptionType != null) {
switch (mSubscriptionType) {
case SEASON_PASS:
iconSubType.setImageResource(R.drawable.todo_seasonpass);
textSubType.setText(R.string.sub_season_pass);
break;
case SINGLE_OFFER:
iconSubType.setImageResource(R.drawable.todo_single_offer);
textSubType.setText(R.string.sub_single_offer);
break;
case WISHLIST:
iconSubType.setImageResource(R.drawable.todo_wishlist);
textSubType.setText(R.string.sub_wishlist);
break;
default:
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
} else {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
// Display channel and time.
if (mRecording != null) {
String channelStr = "";
JsonNode channel = mRecording.path("channel");
if (!channel.isMissingNode()) {
channelStr =
String.format("%s %s, ", channel.path("channelNumber")
.asText(),
channel.path("callSign").asText());
}
// Lots of shows seem to be a few seconds short, add padding so that
// rounding down works as expected. Magic number.
final int minutes = (30 + mRecording.path("duration").asInt()) / 60;
String durationStr =
minutes >= 60 ? String.format(Locale.US, "%d hr", minutes / 60)
: String.format(Locale.US, "%d min", minutes);
if (isRecordingPartial()) {
durationStr += " (partial)";
}
((TextView) findViewById(R.id.content_time)).setText(channelStr
+ durationStr);
} else {
((TextView) findViewById(R.id.content_time)).setVisibility(View.GONE);
}
// Construct and display details.
ArrayList<String> detailParts = new ArrayList<String>();
int season = mContent.path("seasonNumber").asInt();
int epNum = mContent.path("episodeNum").path(0).asInt();
if (season != 0 && epNum != 0) {
detailParts.add(String.format("Sea %d Ep %d", season, epNum));
}
if (mContent.has("mpaaRating")) {
detailParts.add(mContent.path("mpaaRating").asText()
.toUpperCase(Locale.US));
} else if (mContent.has("tvRating")) {
detailParts.add("TV-"
+ mContent.path("tvRating").asText().toUpperCase(Locale.US));
}
detailParts.add(mContent.path("category").path(0).path("label")
.asText());
int year = mContent.path("originalAirYear").asInt();
if (year != 0) {
detailParts.add(Integer.toString(year));
}
// Filter empty strings.
for (int i = detailParts.size() - 1; i >= 0; i--) {
if ("".equals(detailParts.get(i)) || null == detailParts.get(i)) {
detailParts.remove(i);
}
}
// Then format the parts into one string.
String detail1 = "(" + Utils.join(", ", detailParts) + ") ";
if ("() ".equals(detail1)) {
detail1 = "";
}
String detail2 = mContent.path("description").asText();
TextView detailView = ((TextView) findViewById(R.id.content_details));
if (detail2 == null) {
detailView.setText(detail1);
} else {
Spannable details = new SpannableString(detail1 + detail2);
details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(),
details.length(), 0);
detailView.setText(details);
}
// Add credits.
ArrayList<String> credits = new ArrayList<String>();
for (JsonNode credit : mContent.path("credit")) {
String role = credit.path("role").asText();
if ("actor".equals(role) || "host".equals(role)
|| "guestStar".equals(role)) {
credits.add(credit.path("first").asText() + " "
+ credit.path("last").asText());
}
}
TextView creditsView = (TextView) findViewById(R.id.content_credits);
creditsView.setText(Utils.join(", ", credits));
// Find and set the banner image if possible.
ImageView imageView = (ImageView) findViewById(R.id.content_image);
View progressView = findViewById(R.id.content_image_progress);
String imageUrl = Utils.findImageUrl(mContent);
new DownloadImageTask(this, imageView, progressView).execute(imageUrl);
}
| protected void finishRequest() {
if (--mRequestCount != 0) {
return;
}
getParent().setProgressBarIndeterminateVisibility(false);
if (mRecordingId == null) {
for (JsonNode recording : mContent.path("recordingForContentId")) {
String state = recording.path("state").asText();
if ("inProgress".equals(state) || "complete".equals(state)
|| "scheduled".equals(state)) {
mRecordingId = recording.path("recordingId").asText();
mRecordingState = state;
break;
}
}
}
// Fill mChoices based on the data we now have.
if ("scheduled".equals(mRecordingState)) {
mChoices.add(RecordActions.DONT_RECORD.toString());
} else if ("inProgress".equals(mRecordingState)) {
mChoices.add(RecordActions.RECORD_STOP.toString());
} else if (mOfferId != null) {
mChoices.add(RecordActions.RECORD.toString());
}
if (mSubscriptionId != null) {
mChoices.add(RecordActions.SP_MODIFY.toString());
mChoices.add(RecordActions.SP_CANCEL.toString());
} else if (mCollectionId != null
&& !"movie".equals(mContent.path("collectionType").asText())
&& !mContent.has("movieYear")) {
mChoices.add(RecordActions.SP_ADD.toString());
}
setContentView(R.layout.explore);
// Show only appropriate buttons.
findViewById(R.id.explore_btn_watch).setVisibility(
"complete".equals(mRecordingState)
|| "inprogress".equals(mRecordingState)
? View.VISIBLE : View.GONE);
hideViewIfNull(R.id.explore_btn_upcoming, mCollectionId);
if (mChoices.size() == 0) {
findViewById(R.id.explore_btn_record).setVisibility(View.GONE);
}
// Delete / undelete buttons visible only if appropriate.
findViewById(R.id.explore_btn_delete).setVisibility(
"complete".equals(mRecordingState) ? View.VISIBLE : View.GONE);
findViewById(R.id.explore_btn_undelete).setVisibility(
"deleted".equals(mRecordingState) ? View.VISIBLE : View.GONE);
// Display titles.
String title = mContent.path("title").asText();
String subtitle = mContent.path("subtitle").asText();
((TextView) findViewById(R.id.content_title)).setText(title);
TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle));
if ("".equals(subtitle)) {
subtitleView.setVisibility(View.GONE);
} else {
subtitleView.setText(subtitle);
}
// Display (only the proper) badges.
if (mRecording == null || mRecording.path("repeat").asBoolean()) {
findViewById(R.id.badge_new).setVisibility(View.GONE);
}
if (mRecording == null || !mRecording.path("hdtv").asBoolean()) {
findViewById(R.id.badge_hd).setVisibility(View.GONE);
}
ImageView iconSubType = (ImageView) findViewById(R.id.icon_sub_type);
TextView textSubType = (TextView) findViewById(R.id.text_sub_type);
// TODO: Downloading state?
if ("complete".equals(mRecordingState)) {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
} else if ("inProgress".equals(mRecordingState)) {
iconSubType.setImageResource(R.drawable.recording_recording);
textSubType.setText(R.string.sub_recording);
} else if (mSubscriptionType != null) {
switch (mSubscriptionType) {
case SEASON_PASS:
iconSubType.setImageResource(R.drawable.todo_seasonpass);
textSubType.setText(R.string.sub_season_pass);
break;
case SINGLE_OFFER:
iconSubType.setImageResource(R.drawable.todo_single_offer);
textSubType.setText(R.string.sub_single_offer);
break;
case WISHLIST:
iconSubType.setImageResource(R.drawable.todo_wishlist);
textSubType.setText(R.string.sub_wishlist);
break;
default:
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
} else {
iconSubType.setVisibility(View.GONE);
textSubType.setVisibility(View.GONE);
}
// Display channel and time.
if (mRecording != null) {
String channelStr = "";
JsonNode channel = mRecording.path("channel");
if (!channel.isMissingNode()) {
channelStr =
String.format("%s %s, ", channel.path("channelNumber")
.asText(),
channel.path("callSign").asText());
}
// Lots of shows seem to be a few seconds short, add padding so that
// rounding down works as expected. Magic number.
final int minutes = (30 + mRecording.path("duration").asInt()) / 60;
String durationStr =
minutes >= 60 ? String.format(Locale.US, "%d hr", minutes / 60)
: String.format(Locale.US, "%d min", minutes);
if (isRecordingPartial()) {
durationStr += " (partial)";
}
((TextView) findViewById(R.id.content_time)).setText(channelStr
+ durationStr);
} else {
((TextView) findViewById(R.id.content_time)).setVisibility(View.GONE);
}
// Construct and display details.
ArrayList<String> detailParts = new ArrayList<String>();
int season = mContent.path("seasonNumber").asInt();
int epNum = mContent.path("episodeNum").path(0).asInt();
if (season != 0 && epNum != 0) {
detailParts.add(String.format("Sea %d Ep %d", season, epNum));
}
if (mContent.has("mpaaRating")) {
detailParts.add(mContent.path("mpaaRating").asText()
.toUpperCase(Locale.US));
} else if (mContent.has("tvRating")) {
detailParts.add("TV-"
+ mContent.path("tvRating").asText().toUpperCase(Locale.US));
}
detailParts.add(mContent.path("category").path(0).path("label")
.asText());
int year = mContent.path("originalAirYear").asInt();
if (year != 0) {
detailParts.add(Integer.toString(year));
}
// Filter empty strings.
for (int i = detailParts.size() - 1; i >= 0; i--) {
if ("".equals(detailParts.get(i)) || null == detailParts.get(i)) {
detailParts.remove(i);
}
}
// Then format the parts into one string.
String detail1 = "(" + Utils.join(", ", detailParts) + ") ";
if ("() ".equals(detail1)) {
detail1 = "";
}
String detail2 = mContent.path("description").asText();
TextView detailView = ((TextView) findViewById(R.id.content_details));
if (detail2 == null) {
detailView.setText(detail1);
} else {
Spannable details = new SpannableString(detail1 + detail2);
details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(),
details.length(), 0);
detailView.setText(details);
}
// Add credits.
ArrayList<String> credits = new ArrayList<String>();
for (JsonNode credit : mContent.path("credit")) {
String role = credit.path("role").asText();
if ("actor".equals(role) || "host".equals(role)
|| "guestStar".equals(role)) {
credits.add(credit.path("first").asText() + " "
+ credit.path("last").asText());
}
}
TextView creditsView = (TextView) findViewById(R.id.content_credits);
creditsView.setText(Utils.join(", ", credits));
// Find and set the banner image if possible.
ImageView imageView = (ImageView) findViewById(R.id.content_image);
View progressView = findViewById(R.id.content_image_progress);
String imageUrl = Utils.findImageUrl(mContent);
new DownloadImageTask(this, imageView, progressView).execute(imageUrl);
}
|
diff --git a/src/main/java/de/bbe_consulting/mavento/MagentoArtifactMojo.java b/src/main/java/de/bbe_consulting/mavento/MagentoArtifactMojo.java
index c9b82a9..93837cc 100644
--- a/src/main/java/de/bbe_consulting/mavento/MagentoArtifactMojo.java
+++ b/src/main/java/de/bbe_consulting/mavento/MagentoArtifactMojo.java
@@ -1,588 +1,593 @@
/**
* Copyright 2011-2012 BBe Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.bbe_consulting.mavento;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;
import javax.xml.transform.TransformerException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.w3c.dom.Document;
import de.bbe_consulting.mavento.helper.FileUtil;
import de.bbe_consulting.mavento.helper.MagentoSqlUtil;
import de.bbe_consulting.mavento.helper.MagentoUtil;
import de.bbe_consulting.mavento.helper.MagentoXmlUtil;
import de.bbe_consulting.mavento.helper.visitor.CopyFilesVisitor;
import de.bbe_consulting.mavento.helper.visitor.MoveFilesVisitor;
import de.bbe_consulting.mavento.type.MagentoVersion;
import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.name;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;
/**
* Create a magento dependency artifact for magento:setup and unit tests.<br/><br/>
*
* To create a dependency artifact from a running Magento instance:<br/>
*
* <pre>
* mvn magento:artifact -DmagentoPath=/path/to/magento/folder
* </pre>
*
* Per default this will import the source db into a temporary db and clean all
* log tables, except report_viewed_product_index, before creating the final dump.<br/><br/>
*
* Use -DskipTempDb to do all cleaning operations directly on the source db. Disabled per default.
* Not recommended unless you are already working on a backup.<br/><br/>
*
* Use -DtruncateLogs to prune all log tables. Enabled per default.<br/>
* Use -DincludeViewedProduct to also truncate report_viewed_product_index. Disabled per default.<br/>
* Use -DtruncateCustomers to prune all customer/order data. Disabled per default.<br/>
* Use -DtempDb to specify the temporary db name, default is source db name + "_temp"<br/><br/>
*
* To create a dependency artifact from a vanilla Magento zip:<br/>
*
* <pre>
* mvn magento:artifact -DmagentoZip=/path/to/.zip -DdbUser= -DdbPassword= -DdbName=
* </pre>
*
* This goal does not need an active Maven project.<br/>
*
* @goal artifact
* @aggregator false
* @requiresProject false
* @author Erik Dannenberg
*/
public class MagentoArtifactMojo extends AbstractMojo {
/**
* The Maven Project Object
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
protected MavenSession session;
/**
* The Maven PluginManager Object
*
* @component
* @required
*/
protected BuildPluginManager pluginManager;
/**
* Root path of a magento instance you want to create an artifact of.<br/>
*
* @parameter expression="${magentoPath}"
*/
protected String magentoPath;
/**
* Path to a magento vanilla install archive in zip format.<br/>
*
* @parameter expression="${magentoZip}"
*/
protected String magentoZip;
/**
* Database name to use for magento install.<br/>
* Only used when creating an artifact from a vanilla magento zip.
*
* @parameter expression="${dbName}" default-value="mavento_artifact"
*/
protected String dbName;
/**
* Database user for install db.<br/>
* Only used when creating an artifact from a vanilla magento zip.
*
* @parameter expression="${dbUser}"
*/
protected String dbUser;
/**
* Database password for install db.<br/>
* Only used when creating an artifact from a vanilla magento zip.
*
* @parameter expression="${dbPassword}"
*/
protected String dbPassword;
/**
* Database host for install db.<br/>
* Only used when creating an artifact from a vanilla magento zip.
*
* @parameter expression="${dbHost}" default-value="localhost";
*/
protected String dbHost;
/**
* Database port for install db..<br/>
* Only used when creating an artifact from a vanilla magento zip.
*
* @parameter expression="${dbPort}" default-value="3306";
*/
protected String dbPort;
/**
* Temp directory to use while creating the artifact. <br/>
* Defaults to your system's temp directory. (i.e. /tmp with Linux, etc)
*
* @parameter expression="${tempDir}"
*/
protected String tempDir;
/**
* Database to use for cleaning operations before final dump.<br/>
* If left empty the plugin will append _temp to the original database name.<br/>
* Only used when creating an artifact from a running instance.
*
* @parameter expression="${tempDb}"
*/
protected String tempDb;
/**
* Where to write the final artifact file. <br/>
* Default is Magento root foldername+timestamp in the current directory.
*
* @parameter expression="${artifactFile}" default-value=""
*/
protected String artifactFile;
/**
* Db settings in local.xml will not be scrambled if set to true.<br/>
*
* @parameter expression="${keepDbSettings}" default-value="false"
*/
protected Boolean keepDbSettings;
/**
* Use a temporary database for cleaning operations. (log tables, customer data, etc)<br/>
*
* @parameter expression="${skipTempDb}" default-value="false"
*/
protected Boolean skipTempDb;
/**
* Truncate magento log/report tables before final dump.<br/>
*
* @parameter expression="${truncateLogs}" default-value="true"
*/
protected Boolean truncateLogs;
/**
* When truncating magento log tables also inlcude the report_viewed_product_index table.<br/>
* Activating truncateCustomers will truncate the table in any case, making this option irrelevant.
*
* @parameter expression="${includeViewedProduct}" default-value="false"
*/
protected Boolean includeViewedProduct;
/**
* Truncate magento sales/customer tables before final dump.<br/>
*
* @parameter expression="${truncateCustomers}" default-value="false"
*/
protected Boolean truncateCustomers;
/**
* Working dir.
*/
private Path tempDirPath;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (tempDir != null && !tempDir.isEmpty()) {
try {
tempDirPath = Paths.get(tempDir);
Files.createDirectories(tempDirPath);
} catch (IOException e) {
throw new MojoExecutionException("Error creating temp directory: " + e.getMessage(), e);
}
} else {
try {
tempDirPath = Files.createTempDirectory("mavento_artifact_");
} catch (IOException e) {
throw new MojoExecutionException("Could not get tmp dir from underlying os. " + e.getMessage(), e);
}
}
if (magentoPath != null && !magentoPath.isEmpty()) {
createCustomArtifact();
} else if (magentoZip != null && !magentoZip.isEmpty()) {
createVanillaArtifact();
} else {
getLog().error("");
getLog().error("Use -DmagentoPath to create a custom artifact or -DmagentoZip to create a vanilla artifact");
getLog().error("");
throw new MojoExecutionException("Error: missing parameters");
}
}
/**
* Create a maven artifact from a vanilla magento zip.
*
* @throws MojoExecutionException
*/
private void createVanillaArtifact() throws MojoExecutionException {
getLog().info("Working directory is: " + tempDirPath);
try {
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final Path maventoDir = Paths.get(tempDirPath + "/mavento_setup/sql");
try {
Files.createDirectories(maventoDir);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final MagentoVersion mageVersion;
try {
mageVersion = MagentoUtil.getMagentoVersion(Paths.get(tempDirPath+"/magento/app/Mage.php"));
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
String sampleDataVersion = "1.6.1.0";
if (mageVersion.getMajorVersion() <= 1 && mageVersion.getMinorVersion() <=6 && mageVersion.getRevisionVersion() < 1) {
- sampleDataVersion = "1.2.0.0";
+ sampleDataVersion = "1.2.0";
}
// call dependency plugin to resolve and extract sample data
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("2.0")
),
goal("unpack"),
configuration(
element(name("outputDirectory"), maventoDir.getParent() + "/sample_data"),
element(name("markersDirectory"), maventoDir.getParent() +"/dep-marker"),
element("silent", "true"),
element("artifactItems",
element("artifactItem",
element("groupId", "com.varien"),
element("artifactId", "magento-sample-data"),
element("version", sampleDataVersion),
element("type", "jar")
))
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("Magento version: " + mageVersion);
final String sqlDumpEmpty = maventoDir.toString()+"/magento.sql";
final String sqlDumpSample = maventoDir.toString()+"/magento_with_sample_data.sql";
final Path sampleDataPre = Paths.get(maventoDir.getParent()
+ "/sample_data/magento_sample_data_for_" + sampleDataVersion + ".sql");
if (!Files.exists(sampleDataPre)) {
throw new MojoExecutionException ("Could not find magento sample data dump. " + sampleDataPre);
}
// import sample data dump
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
MagentoSqlUtil.importSqlDump(sampleDataPre.toString(), dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// run magento setup and indexer
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
- MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
+ if (mageVersion.getMajorVersion() >= 1 && mageVersion.getMinorVersion() >= 4) {
+ MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
+ }
// dump final sample data db
MagentoSqlUtil.dumpSqlDb(sqlDumpSample, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// one more time without sample data
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
try {
FileUtil.deleteFile(tempDirPath.toString()+"/magento", getLog());
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
+ if (mageVersion.getMajorVersion() >= 1 && mageVersion.getMinorVersion() >= 4) {
+ MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
+ }
// dump final db
MagentoSqlUtil.dumpSqlDb(sqlDumpEmpty, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// move magento files
try {
final MoveFilesVisitor mv = new MoveFilesVisitor(Paths.get(tempDirPath+"/magento"), tempDirPath);
try {
Files.walkFileTree(Paths.get(tempDirPath+"/magento"),
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, mv);
} catch (IOException e) {
throw new MojoExecutionException("Error moving to tmp dir. " + e.getMessage(), e);
}
FileUtil.deleteFile(maventoDir.getParent() + "/sample_data/META-INF", getLog());
FileUtil.deleteFile(maventoDir.getParent() + "/dep-marker", getLog());
FileUtil.deleteFile(sampleDataPre.toString(), getLog());
FileUtil.deleteFile(tempDirPath + "/var/cache", getLog());
FileUtil.deleteFile(tempDirPath + "/var/session", getLog());
} catch (IOException e) {
throw new MojoExecutionException("Error deleting cache or session directories. " + e.getMessage(), e);
}
if (artifactFile == null || artifactFile.isEmpty()) {
artifactFile = "magento-"+mageVersion+".jar";
}
getLog().info("Creating jar file: " + artifactFile + "..");
FileUtil.createJar(artifactFile, tempDirPath.toString());
getLog().info("..done.");
// clean up
try {
MagentoSqlUtil.dropMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
getLog().info("Cleaning up..");
FileUtil.deleteFile(tempDirPath.toString(), getLog());
getLog().info("..done.");
} catch (IOException e) {
throw new MojoExecutionException("Error deleting tmp dir. " + e.getMessage(), e);
}
// finally install the new artifact into the local repository
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-install-plugin"),
version("2.3.1")
),
goal("install-file"),
configuration(
element(name("file"), artifactFile),
element("groupId", "com.varien"),
element("artifactId", "magento"),
element("version", mageVersion.toString()),
element("packaging", "jar")
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("");
getLog().info("Great success! " + artifactFile + " was successfully installed and is ready for use.");
}
/**
* Create a maven artifact from a running magento instance.
*
* @throws MojoExecutionException
*/
private void createCustomArtifact() throws MojoExecutionException {
if (magentoPath.endsWith("/")) {
magentoPath = magentoPath.substring(0, magentoPath.length() - 1);
}
getLog().info("Scanning: " + Paths.get(magentoPath));
// try to find magento version
final Path appMage = Paths.get(magentoPath + "/app/Mage.php");
final MagentoVersion mageVersion;
try {
mageVersion = MagentoUtil.getMagentoVersion(appMage);
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().info("..found Magento " + mageVersion.toString());
// get sql settings from local.xml
final Path localXmlPath = Paths.get(magentoPath + "/app/etc/local.xml");
Document localXml;
if (Files.exists(localXmlPath)) {
localXml = MagentoXmlUtil.readXmlFile(localXmlPath.toAbsolutePath().toString());
} else {
throw new MojoExecutionException("Could not read or parse /app/etc/local.xml");
}
Map<String, String> dbSettings = MagentoXmlUtil.getDbValues(localXml);
getLog().info("..done.");
getLog().info("Working directory is: " + tempDirPath);
// copy magento source to tmp dir
getLog().info("Creating snapshot..");
final CopyFilesVisitor cv = new CopyFilesVisitor(Paths.get(magentoPath), tempDirPath, true);
try {
Files.walkFileTree(Paths.get(magentoPath),
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, cv);
} catch (IOException e) {
throw new MojoExecutionException("Error copying to tmp dir. " + e.getMessage(), e);
} catch (Exception e) {
throw new MojoExecutionException("Error copying to tmp dir. " + e.getMessage(), e);
}
getLog().info("..done.");
// prepare db dump
try {
Files.createDirectories(Paths.get(tempDirPath + "/mavento_setup/sql"));
} catch (IOException e) {
throw new MojoExecutionException("Error creating directory. " + e.getMessage(), e);
}
final String dumpFile = Paths.get(tempDirPath + "/mavento_setup/sql/magento.sql").toString();
// set temp db
if (tempDb == null || tempDb.isEmpty()) {
tempDb = dbSettings.get("dbname") + "_temp";
}
if (!skipTempDb && tempDb.equals(dbSettings.get("dbname"))) {
throw new MojoExecutionException("Error: source and temp database names are the same, aborting..");
}
// do cleaning work on source db?
if (skipTempDb) {
tempDb = dbSettings.get("dbname");
}
if (truncateLogs || truncateCustomers) {
truncateTables(dbSettings, dumpFile);
}
// final dump
MagentoSqlUtil.dumpSqlDb(dumpFile, dbSettings.get("user"),
dbSettings.get("password"), dbSettings.get("host"),
dbSettings.get("port"), tempDb, getLog());
// drop temp db if we created one
if (!skipTempDb && truncateLogs || truncateCustomers) {
MagentoSqlUtil.dropMagentoDb(dbSettings.get("user"),
dbSettings.get("password"), dbSettings.get("host"),
dbSettings.get("port"), tempDb, getLog());
}
// scramble db settings in local.xml
if (!keepDbSettings) {
getLog().info("Scrambling original database settings in local.xml..");
final Path tmpLocalXml = Paths.get(tempDirPath + "/app/etc/local.xml");
localXml = MagentoXmlUtil.readXmlFile(tmpLocalXml.toString());
MagentoXmlUtil.updateDbValues("localhost", "heinzi", "floppel", "db_magento", localXml);
try {
MagentoXmlUtil.writeXmlFile(MagentoXmlUtil.transformXmlToString(localXml), tmpLocalXml.toString());
} catch (TransformerException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().info("..done.");
}
// clean /var before we build the artifact
try {
FileUtil.deleteFile(tempDirPath + "/var/cache", getLog());
FileUtil.deleteFile(tempDirPath + "/var/session", getLog());
} catch (IOException e) {
throw new MojoExecutionException("Error deleting cache or session directories. " + e.getMessage(), e);
}
// create the jar
final SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyyMMddHHmmss");
final String defaultVersion = sdf.format(new Date()) + "-SNAPSHOT";
if (artifactFile == null || artifactFile.equals("")) {
artifactFile = Paths.get(magentoPath).getFileName().toString() + "-" + defaultVersion + ".jar";
} else if (!artifactFile.endsWith(".jar")) {
artifactFile += "-" + defaultVersion + ".jar";
}
getLog().info("Creating jar file: " + artifactFile + "..");
FileUtil.createJar(artifactFile, tempDirPath.toString());
getLog().info("..done.");
// clean up
try {
getLog().info("Cleaning up..");
FileUtil.deleteFile(tempDirPath.toString(), getLog());
getLog().info("..done.");
} catch (IOException e) {
throw new MojoExecutionException("Error deleting tmp dir. " + e.getMessage(), e);
}
getLog().info("");
getLog().info("Great success! " + artifactFile + " is now ready for install.");
getLog().info("Use:\n");
getLog().info("mvn install:install-file -Dpackaging=jar -Dfile="
+ artifactFile + " -Dversion=" + defaultVersion
+ " -DgroupId= -DartifactId= \n");
getLog().info("..to install the jar into your local maven repository.");
}
/**
* Handle table truncating.
*
* @param dbSettings
* @param dumpFile
* @throws MojoExecutionException
*/
private void truncateTables(Map<String,String> dbSettings, String dumpFile) throws MojoExecutionException {
if (!skipTempDb) {
// import dump into temp db
MagentoSqlUtil.dumpSqlDb(dumpFile, dbSettings.get("user"),
dbSettings.get("password"), dbSettings.get("host"),
dbSettings.get("port"), dbSettings.get("dbname"), getLog());
MagentoSqlUtil.recreateMagentoDb(dbSettings.get("user"), dbSettings.get("password"),
dbSettings.get("host"), dbSettings.get("port"), tempDb, getLog());
MagentoSqlUtil.importSqlDump(dumpFile, dbSettings.get("user"), dbSettings.get("password"),
dbSettings.get("host"), dbSettings.get("port"), tempDb, getLog());
}
final String jdbcUrlTempDb = MagentoSqlUtil.getJdbcUrl(dbSettings.get("host"),
dbSettings.get("port"), tempDb);
if (truncateLogs) {
getLog().info("Cleaning log tables..");
MagentoSqlUtil.truncateLogTables(dbSettings.get("user"), dbSettings.get("password"),
jdbcUrlTempDb, includeViewedProduct, getLog());
getLog().info("..done.");
}
if (truncateCustomers) {
getLog().info("Deleting customer/sales data..");
MagentoSqlUtil.truncateSalesTables(dbSettings.get("user"), dbSettings.get("password"),
jdbcUrlTempDb, getLog());
MagentoSqlUtil.truncateCustomerTables(dbSettings.get("user"), dbSettings.get("password"),
jdbcUrlTempDb, getLog());
getLog().info("..done.");
}
}
}
| false | true | private void createVanillaArtifact() throws MojoExecutionException {
getLog().info("Working directory is: " + tempDirPath);
try {
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final Path maventoDir = Paths.get(tempDirPath + "/mavento_setup/sql");
try {
Files.createDirectories(maventoDir);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final MagentoVersion mageVersion;
try {
mageVersion = MagentoUtil.getMagentoVersion(Paths.get(tempDirPath+"/magento/app/Mage.php"));
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
String sampleDataVersion = "1.6.1.0";
if (mageVersion.getMajorVersion() <= 1 && mageVersion.getMinorVersion() <=6 && mageVersion.getRevisionVersion() < 1) {
sampleDataVersion = "1.2.0.0";
}
// call dependency plugin to resolve and extract sample data
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("2.0")
),
goal("unpack"),
configuration(
element(name("outputDirectory"), maventoDir.getParent() + "/sample_data"),
element(name("markersDirectory"), maventoDir.getParent() +"/dep-marker"),
element("silent", "true"),
element("artifactItems",
element("artifactItem",
element("groupId", "com.varien"),
element("artifactId", "magento-sample-data"),
element("version", sampleDataVersion),
element("type", "jar")
))
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("Magento version: " + mageVersion);
final String sqlDumpEmpty = maventoDir.toString()+"/magento.sql";
final String sqlDumpSample = maventoDir.toString()+"/magento_with_sample_data.sql";
final Path sampleDataPre = Paths.get(maventoDir.getParent()
+ "/sample_data/magento_sample_data_for_" + sampleDataVersion + ".sql");
if (!Files.exists(sampleDataPre)) {
throw new MojoExecutionException ("Could not find magento sample data dump. " + sampleDataPre);
}
// import sample data dump
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
MagentoSqlUtil.importSqlDump(sampleDataPre.toString(), dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// run magento setup and indexer
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
// dump final sample data db
MagentoSqlUtil.dumpSqlDb(sqlDumpSample, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// one more time without sample data
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
try {
FileUtil.deleteFile(tempDirPath.toString()+"/magento", getLog());
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
// dump final db
MagentoSqlUtil.dumpSqlDb(sqlDumpEmpty, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// move magento files
try {
final MoveFilesVisitor mv = new MoveFilesVisitor(Paths.get(tempDirPath+"/magento"), tempDirPath);
try {
Files.walkFileTree(Paths.get(tempDirPath+"/magento"),
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, mv);
} catch (IOException e) {
throw new MojoExecutionException("Error moving to tmp dir. " + e.getMessage(), e);
}
FileUtil.deleteFile(maventoDir.getParent() + "/sample_data/META-INF", getLog());
FileUtil.deleteFile(maventoDir.getParent() + "/dep-marker", getLog());
FileUtil.deleteFile(sampleDataPre.toString(), getLog());
FileUtil.deleteFile(tempDirPath + "/var/cache", getLog());
FileUtil.deleteFile(tempDirPath + "/var/session", getLog());
} catch (IOException e) {
throw new MojoExecutionException("Error deleting cache or session directories. " + e.getMessage(), e);
}
if (artifactFile == null || artifactFile.isEmpty()) {
artifactFile = "magento-"+mageVersion+".jar";
}
getLog().info("Creating jar file: " + artifactFile + "..");
FileUtil.createJar(artifactFile, tempDirPath.toString());
getLog().info("..done.");
// clean up
try {
MagentoSqlUtil.dropMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
getLog().info("Cleaning up..");
FileUtil.deleteFile(tempDirPath.toString(), getLog());
getLog().info("..done.");
} catch (IOException e) {
throw new MojoExecutionException("Error deleting tmp dir. " + e.getMessage(), e);
}
// finally install the new artifact into the local repository
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-install-plugin"),
version("2.3.1")
),
goal("install-file"),
configuration(
element(name("file"), artifactFile),
element("groupId", "com.varien"),
element("artifactId", "magento"),
element("version", mageVersion.toString()),
element("packaging", "jar")
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("");
getLog().info("Great success! " + artifactFile + " was successfully installed and is ready for use.");
}
| private void createVanillaArtifact() throws MojoExecutionException {
getLog().info("Working directory is: " + tempDirPath);
try {
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final Path maventoDir = Paths.get(tempDirPath + "/mavento_setup/sql");
try {
Files.createDirectories(maventoDir);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
final MagentoVersion mageVersion;
try {
mageVersion = MagentoUtil.getMagentoVersion(Paths.get(tempDirPath+"/magento/app/Mage.php"));
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
String sampleDataVersion = "1.6.1.0";
if (mageVersion.getMajorVersion() <= 1 && mageVersion.getMinorVersion() <=6 && mageVersion.getRevisionVersion() < 1) {
sampleDataVersion = "1.2.0";
}
// call dependency plugin to resolve and extract sample data
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("2.0")
),
goal("unpack"),
configuration(
element(name("outputDirectory"), maventoDir.getParent() + "/sample_data"),
element(name("markersDirectory"), maventoDir.getParent() +"/dep-marker"),
element("silent", "true"),
element("artifactItems",
element("artifactItem",
element("groupId", "com.varien"),
element("artifactId", "magento-sample-data"),
element("version", sampleDataVersion),
element("type", "jar")
))
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("Magento version: " + mageVersion);
final String sqlDumpEmpty = maventoDir.toString()+"/magento.sql";
final String sqlDumpSample = maventoDir.toString()+"/magento_with_sample_data.sql";
final Path sampleDataPre = Paths.get(maventoDir.getParent()
+ "/sample_data/magento_sample_data_for_" + sampleDataVersion + ".sql");
if (!Files.exists(sampleDataPre)) {
throw new MojoExecutionException ("Could not find magento sample data dump. " + sampleDataPre);
}
// import sample data dump
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
MagentoSqlUtil.importSqlDump(sampleDataPre.toString(), dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// run magento setup and indexer
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
if (mageVersion.getMajorVersion() >= 1 && mageVersion.getMinorVersion() >= 4) {
MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
}
// dump final sample data db
MagentoSqlUtil.dumpSqlDb(sqlDumpSample, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// one more time without sample data
MagentoSqlUtil.recreateMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
try {
FileUtil.deleteFile(tempDirPath.toString()+"/magento", getLog());
FileUtil.unzipFile(magentoZip, tempDirPath.toString());
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
MagentoUtil.execMagentoInstall(tempDirPath, dbUser, dbPassword, dbHost+":"+dbPort, dbName, getLog());
if (mageVersion.getMajorVersion() >= 1 && mageVersion.getMinorVersion() >= 4) {
MagentoSqlUtil.indexDb(tempDirPath.toString()+"/magento", getLog());
}
// dump final db
MagentoSqlUtil.dumpSqlDb(sqlDumpEmpty, dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
// move magento files
try {
final MoveFilesVisitor mv = new MoveFilesVisitor(Paths.get(tempDirPath+"/magento"), tempDirPath);
try {
Files.walkFileTree(Paths.get(tempDirPath+"/magento"),
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, mv);
} catch (IOException e) {
throw new MojoExecutionException("Error moving to tmp dir. " + e.getMessage(), e);
}
FileUtil.deleteFile(maventoDir.getParent() + "/sample_data/META-INF", getLog());
FileUtil.deleteFile(maventoDir.getParent() + "/dep-marker", getLog());
FileUtil.deleteFile(sampleDataPre.toString(), getLog());
FileUtil.deleteFile(tempDirPath + "/var/cache", getLog());
FileUtil.deleteFile(tempDirPath + "/var/session", getLog());
} catch (IOException e) {
throw new MojoExecutionException("Error deleting cache or session directories. " + e.getMessage(), e);
}
if (artifactFile == null || artifactFile.isEmpty()) {
artifactFile = "magento-"+mageVersion+".jar";
}
getLog().info("Creating jar file: " + artifactFile + "..");
FileUtil.createJar(artifactFile, tempDirPath.toString());
getLog().info("..done.");
// clean up
try {
MagentoSqlUtil.dropMagentoDb(dbUser, dbPassword, dbHost, dbPort, dbName, getLog());
getLog().info("Cleaning up..");
FileUtil.deleteFile(tempDirPath.toString(), getLog());
getLog().info("..done.");
} catch (IOException e) {
throw new MojoExecutionException("Error deleting tmp dir. " + e.getMessage(), e);
}
// finally install the new artifact into the local repository
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-install-plugin"),
version("2.3.1")
),
goal("install-file"),
configuration(
element(name("file"), artifactFile),
element("groupId", "com.varien"),
element("artifactId", "magento"),
element("version", mageVersion.toString()),
element("packaging", "jar")
),
executionEnvironment(
project,
session,
pluginManager
)
);
getLog().info("");
getLog().info("Great success! " + artifactFile + " was successfully installed and is ready for use.");
}
|
diff --git a/src/org/cyanogenmod/nemesis/CameraManager.java b/src/org/cyanogenmod/nemesis/CameraManager.java
index 0a1fb86..cfbba3b 100644
--- a/src/org/cyanogenmod/nemesis/CameraManager.java
+++ b/src/org/cyanogenmod/nemesis/CameraManager.java
@@ -1,783 +1,783 @@
/**
* Copyright (C) 2013 The CyanogenMod Project
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.cyanogenmod.nemesis;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.AutoFocusMoveCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* This class is responsible for interacting with the Camera HAL.
* It provides easy open/close, helper methods to set parameters or
* toggle features, etc. in an asynchronous fashion.
*/
public class CameraManager {
private final static String TAG = "CameraManager";
private final static int FOCUS_WIDTH = 80;
private final static int FOCUS_HEIGHT = 80;
private CameraPreview mPreview;
private Camera mCamera;
private boolean mCameraReady;
private int mCurrentFacing;
private Point mTargetSize;
private AutoFocusMoveCallback mAutoFocusMoveCallback;
private Camera.Parameters mParameters;
private int mOrientation;
private MediaRecorder mMediaRecorder;
private PreviewPauseListener mPreviewPauseListener;
private CameraReadyListener mCameraReadyListener;
private Handler mHandler;
private long mLastPreviewFrameTime;
public interface PreviewPauseListener {
/**
* This method is called when the preview is about to pause.
* This allows the CameraActivity to display an animation when the preview
* has to stop.
*/
public void onPreviewPause();
/**
* This method is called when the preview resumes
*/
public void onPreviewResume();
}
public interface CameraReadyListener {
/**
* Called when a camera has been successfully opened. This allows the
* main activity to continue setup operations while the camera
* sets up in a different thread.
*/
public void onCameraReady();
/**
* Called when the camera failed to initialize
*/
public void onCameraFailed();
}
private class AsyncParamRunnable implements Runnable {
private String mKey;
private String mValue;
public AsyncParamRunnable(String key, String value) {
mKey = key;
mValue = value;
}
public void run() {
Log.v(TAG, "Asynchronously setting parameter " + mKey + " to " + mValue);
Camera.Parameters params = getParameters();
params.set(mKey, mValue);
try {
mCamera.setParameters(params);
} catch (RuntimeException e) {
Log.e(TAG, "Could not set parameter " + mKey + " to '" + mValue + "'", e);
// Reset the camera as it likely crashed if we reached here
open(mCurrentFacing);
}
// Read them from sensor next time
mParameters = null;
}
}
;
private class AsyncParamClassRunnable implements Runnable {
private Camera.Parameters mParameters;
public AsyncParamClassRunnable(Camera.Parameters params) {
mParameters = params;
}
public void run() {
try {
mCamera.setParameters(mParameters);
} catch (RuntimeException e) {
Log.e(TAG, "Could not set parameters", e);
// Reset the camera as it likely crashed if we reached here
open(mCurrentFacing);
}
// Read them from sensor next time
mParameters = null;
}
}
public CameraManager(Context context) {
mPreview = new CameraPreview(context);
mMediaRecorder = new MediaRecorder();
mCameraReady = true;
mHandler = new Handler();
}
/**
* Opens the camera and show its preview in the preview
*
* @param cameraId
* @return true if the operation succeeded, false otherwise
*/
public boolean open(final int cameraId) {
if (mCamera != null) {
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewPause();
}
// Close the previous camera
releaseCamera();
}
mCameraReady = false;
// Try to open the camera
new Thread() {
public void run() {
try {
if (mCamera != null) {
Log.e(TAG, "Previous camera not closed! Not opening");
return;
}
mCamera = Camera.open(cameraId);
mCamera.enableShutterSound(false);
mCamera.setPreviewCallback(mPreview);
mCurrentFacing = cameraId;
mParameters = mCamera.getParameters();
String params = mCamera.getParameters().flatten();
- int step = params.length() > 256 ? 256 : params.length();
- for (int i = 0; i < params.length(); i += 256) {
+ final int step = params.length() > 256 ? 256 : params.length();
+ for (int i = 0; i < params.length(); i += step) {
Log.e(TAG, params);
- params = params.substring(256);
+ params = params.substring(step);
}
if (mTargetSize != null)
setPreviewSize(mTargetSize.x, mTargetSize.y);
if (mAutoFocusMoveCallback != null)
mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback);
// Default focus mode to continuous
} catch (Exception e) {
Log.e(TAG, "Error while opening cameras: " + e.getMessage());
StackTraceElement[] st = e.getStackTrace();
for (StackTraceElement elemt : st) {
Log.e(TAG, elemt.toString());
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraFailed();
}
return;
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraReady();
}
// Update the preview surface holder with the new opened camera
mPreview.notifyCameraChanged();
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewResume();
}
mCameraReady = true;
}
}.start();
return true;
}
public void setPreviewPauseListener(PreviewPauseListener listener) {
mPreviewPauseListener = listener;
}
public void setCameraReadyListener(CameraReadyListener listener) {
mCameraReadyListener = listener;
}
/**
* Returns the preview surface used to display the Camera's preview
*
* @return CameraPreview
*/
public CameraPreview getPreviewSurface() {
return mPreview;
}
/**
* @return The facing of the current open camera
*/
public int getCurrentFacing() {
return mCurrentFacing;
}
/**
* Returns the parameters structure of the current running camera
*
* @return Camera.Parameters
*/
public Camera.Parameters getParameters() {
if (mCamera == null)
return null;
if (mParameters == null)
mParameters = mCamera.getParameters();
return mParameters;
}
public void pause() {
releaseCamera();
}
public void resume() {
reconnectToCamera();
}
private void releaseCamera() {
if (mCamera != null && mCameraReady) {
Log.v(TAG, "Releasing camera facing " + mCurrentFacing);
mCamera.release();
mCamera = null;
mParameters = null;
mPreview.notifyCameraChanged();
mCameraReady = true;
}
}
private void reconnectToCamera() {
if (mCameraReady) {
open(mCurrentFacing);
}
}
public void setPreviewSize(int width, int height) {
mTargetSize = new Point(width, height);
if (mCamera != null) {
mParameters.setPreviewSize(width, height);
Log.v(TAG, "Preview size is " + width + "x" + height);
mCamera.stopPreview();
mCamera.setParameters(mParameters);
mPreview.notifyPreviewSize(width, height);
mCamera.startPreview();
}
}
public void setParameterAsync(String key, String value) {
AsyncParamRunnable run = new AsyncParamRunnable(key, value);
new Thread(run).start();
}
public void setParametersAsync(Camera.Parameters params) {
AsyncParamClassRunnable run = new AsyncParamClassRunnable(params);
new Thread(run).start();
}
/**
* Locks the automatic settings of the camera device, like White balance and
* exposure.
*
* @param lock true to lock, false to unlock
*/
public void setLockSetup(boolean lock) {
Camera.Parameters params = getParameters();
if (params == null) {
// Params might be null if we pressed or swipe the shutter button
// while the camera is not ready
return;
}
if (params.isAutoExposureLockSupported()) {
params.setAutoExposureLock(lock);
}
if (params.isAutoWhiteBalanceLockSupported()) {
params.setAutoWhiteBalanceLock(lock);
}
mCamera.setParameters(params);
}
/**
* Returns the last frame of the preview surface
*
* @return Bitmap
*/
public Bitmap getLastPreviewFrame() {
// Decode the last frame bytes
byte[] data = mPreview.getLastFrameBytes();
Camera.Parameters params = getParameters();
if (params == null) {
return null;
}
Camera.Size previewSize = params.getPreviewSize();
if (previewSize == null) {
return null;
}
int previewWidth = previewSize.width;
int previewHeight = previewSize.height;
// Convert YUV420SP preview data to RGB
if (data != null) {
return Util.decodeYUV420SP(mPreview.getContext(),
data, previewWidth, previewHeight);
} else {
return null;
}
}
/**
* Returns the system time of when the last preview frame was received
*
* @return long
*/
public long getLastPreviewFrameTime() {
return mLastPreviewFrameTime;
}
/**
* Defines a new size for the recorded picture
* XXX: Should it update preview size?!
*
* @param sz The new picture size
*/
public void setPictureSize(Camera.Size sz) {
Camera.Parameters params = getParameters();
params.setPictureSize(sz.width, sz.height);
mCamera.setParameters(params);
}
/**
* Takes a snapshot
*/
public void takeSnapshot(Camera.ShutterCallback shutterCallback, Camera.PictureCallback raw,
Camera.PictureCallback jpeg) {
Log.v(TAG, "takePicture");
SoundManager.getSingleton().play(SoundManager.SOUND_SHUTTER);
mCamera.takePicture(shutterCallback, raw, jpeg);
}
/**
* Prepares the MediaRecorder to record a video. This must be called before
* startVideoRecording to setup the recording environment.
*
* @param fileName Target file path
* @param profile Target profile (quality)
*/
public void prepareVideoRecording(String fileName, CamcorderProfile profile) {
// Unlock the camera for use with MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(profile);
mMediaRecorder.setOutputFile(fileName);
// Set maximum file size.
long maxFileSize = Storage.getStorage().getAvailableSpace() - Storage.LOW_STORAGE_THRESHOLD;
mMediaRecorder.setMaxFileSize(maxFileSize);
mMediaRecorder.setMaxDuration(0); // infinite
mMediaRecorder.setPreviewDisplay(mPreview.getSurfaceHolder().getSurface());
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.e(TAG, "Cannot prepare MediaRecorder", e);
} catch (IOException e) {
Log.e(TAG, "Cannot prepare MediaRecorder", e);
}
mPreview.postCallbackBuffer();
}
public void startVideoRecording() {
Log.v(TAG, "startVideoRecording");
mMediaRecorder.start();
mPreview.postCallbackBuffer();
}
public void stopVideoRecording() {
Log.v(TAG, "stopVideoRecording");
mMediaRecorder.stop();
mCamera.lock();
mMediaRecorder.reset();
mPreview.postCallbackBuffer();
}
/**
* Returns the orientation of the device
*
* @return
*/
public int getOrientation() {
return mOrientation;
}
public void setOrientation(int orientation) {
mOrientation = orientation;
}
public void restartPreviewIfNeeded() {
try {
mCamera.startPreview();
} catch (Exception e) {
// ignore
}
}
public void setCameraMode(final int mode) {
if (mPreviewPauseListener != null) {
// mPreviewPauseListener.onPreviewPause();
return;
}
new Thread() {
public void run() {
// We voluntarily sleep the thread here for the animation being done
// in the CameraActivity
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Camera.Parameters params = getParameters();
if (mode == CameraActivity.CAMERA_MODE_VIDEO) {
params.setRecordingHint(true);
} else {
params.setRecordingHint(false);
}
mCamera.stopPreview();
mCamera.setParameters(params);
try {
mCamera.startPreview();
} catch (RuntimeException e) {
Log.e(TAG, "Unable to start preview", e);
}
mPreview.postCallbackBuffer();
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewResume();
}
}
}.start();
}
/**
* Trigger the autofocus function of the device
*
* @param cb The AF callback
* @return true if we could start the AF, false otherwise
*/
public boolean doAutofocus(final AutoFocusCallback cb) {
if (mCamera != null) {
try {
// make sure our auto settings aren't locked
setLockSetup(false);
// trigger af
mCamera.cancelAutoFocus();
mHandler.post(new Runnable() {
public void run() {
mCamera.autoFocus(cb);
}
});
} catch (Exception e) {
return false;
}
return true;
} else {
return false;
}
}
/**
* Returns whether or not the current open camera device supports
* focus area (focus ring)
*
* @return true if supported
*/
public boolean isFocusAreaSupported() {
if (mCamera != null) {
try {
return (getParameters().getMaxNumFocusAreas() > 0);
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
* Returns whether or not the current open camera device supports
* exposure metering area (exposure ring)
*
* @return true if supported
*/
public boolean isExposureAreaSupported() {
if (mCamera != null) {
try {
return (getParameters().getMaxNumMeteringAreas() > 0);
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
* Defines the main focus point of the camera to the provided x and y values.
* Those values must between -1000 and 1000, where -1000 is the top/left, and 1000 the bottom/right
*
* @param x The X position of the focus point
* @param y The Y position of the focus point
*/
public void setFocusPoint(int x, int y) {
Camera.Parameters params = getParameters();
if (params.getMaxNumFocusAreas() > 0) {
List<Camera.Area> focusArea = new ArrayList<Camera.Area>();
focusArea.add(new Camera.Area(new Rect(x, y, x + FOCUS_WIDTH, y + FOCUS_HEIGHT), 1000));
params.setFocusAreas(focusArea);
try {
mCamera.setParameters(params);
} catch (Exception e) {
// ignore, we might be setting it too fast since previous attempt
}
}
}
/**
* Defines the exposure metering point of the camera to the provided x and y values.
* Those values must between -1000 and 1000, where -1000 is the top/left, and 1000 the bottom/right
*
* @param x The X position of the exposure metering point
* @param y The Y position of the exposure metering point
*/
public void setExposurePoint(int x, int y) {
Camera.Parameters params = getParameters();
if (params != null && params.getMaxNumMeteringAreas() > 0) {
List<Camera.Area> exposureArea = new ArrayList<Camera.Area>();
exposureArea.add(new Camera.Area(new Rect(x, y, x + FOCUS_WIDTH, y + FOCUS_HEIGHT), 1000));
params.setMeteringAreas(exposureArea);
try {
mCamera.setParameters(params);
} catch (Exception e) {
// ignore, we might be setting it too fast since previous attempt
}
}
}
public void setAutoFocusMoveCallback(AutoFocusMoveCallback cb) {
mAutoFocusMoveCallback = cb;
if (mCamera != null)
mCamera.setAutoFocusMoveCallback(cb);
}
/**
* Enable the device image stabilization system. Toggle device-specific
* stab as well if they exist and are implemented.
* @param enabled
*/
public void setStabilization(boolean enabled) {
Camera.Parameters params = getParameters();
if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_PHOTO) {
// Sony
if (params.get("sony-is") != null) {
// XXX: on-still-hdr
params.set("sony-is", enabled ? "on" : "off");
}
// HTC
else if (params.get("ois_mode") != null) {
params.set("ois_mode", enabled ? "on" : "off");
}
} else if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_VIDEO) {
if (params.get("sony-vs") != null) {
params.set("sony-vs", enabled ? "on" : "off");
} else {
params.setVideoStabilization(enabled);
}
}
}
/**
* The CameraPreview class handles the Camera preview feed
* and setting the surface holder.
*/
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
private final static String TAG = "CameraManager.CameraPreview";
private SurfaceHolder mHolder;
private byte[] mLastFrameBytes;
public CameraPreview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
}
public void notifyPreviewSize(int width, int height) {
mLastFrameBytes = new byte[(int) (width * height * 1.5 + 0.5)];
}
public byte[] getLastFrameBytes() {
return mLastFrameBytes;
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
public void notifyCameraChanged() {
if (mCamera != null) {
setupCamera();
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
mPreview.postCallbackBuffer();
} catch (IOException e) {
Log.e(TAG, "Error setting camera preview: " + e.getMessage());
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
if (mCamera == null)
return;
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
mPreview.postCallbackBuffer();
} catch (IOException e) {
Log.e(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
setupCamera();
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void postCallbackBuffer() {
mCamera.addCallbackBuffer(mLastFrameBytes);
mCamera.setPreviewCallbackWithBuffer(this);
}
private void setupCamera() {
// Set device-specifics here
try {
Camera.Parameters params = mCamera.getParameters();
if (getResources().getBoolean(R.bool.config_qualcommZslCameraMode)) {
params.set("camera-mode", 1);
}
mCamera.setParameters(params);
postCallbackBuffer();
} catch (Exception e) {
Log.e(TAG, "Could not set device specifics");
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
mLastPreviewFrameTime = System.currentTimeMillis();
if (mCamera != null) {
mCamera.addCallbackBuffer(mLastFrameBytes);
}
}
}
}
| false | true | public boolean open(final int cameraId) {
if (mCamera != null) {
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewPause();
}
// Close the previous camera
releaseCamera();
}
mCameraReady = false;
// Try to open the camera
new Thread() {
public void run() {
try {
if (mCamera != null) {
Log.e(TAG, "Previous camera not closed! Not opening");
return;
}
mCamera = Camera.open(cameraId);
mCamera.enableShutterSound(false);
mCamera.setPreviewCallback(mPreview);
mCurrentFacing = cameraId;
mParameters = mCamera.getParameters();
String params = mCamera.getParameters().flatten();
int step = params.length() > 256 ? 256 : params.length();
for (int i = 0; i < params.length(); i += 256) {
Log.e(TAG, params);
params = params.substring(256);
}
if (mTargetSize != null)
setPreviewSize(mTargetSize.x, mTargetSize.y);
if (mAutoFocusMoveCallback != null)
mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback);
// Default focus mode to continuous
} catch (Exception e) {
Log.e(TAG, "Error while opening cameras: " + e.getMessage());
StackTraceElement[] st = e.getStackTrace();
for (StackTraceElement elemt : st) {
Log.e(TAG, elemt.toString());
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraFailed();
}
return;
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraReady();
}
// Update the preview surface holder with the new opened camera
mPreview.notifyCameraChanged();
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewResume();
}
mCameraReady = true;
}
}.start();
return true;
}
| public boolean open(final int cameraId) {
if (mCamera != null) {
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewPause();
}
// Close the previous camera
releaseCamera();
}
mCameraReady = false;
// Try to open the camera
new Thread() {
public void run() {
try {
if (mCamera != null) {
Log.e(TAG, "Previous camera not closed! Not opening");
return;
}
mCamera = Camera.open(cameraId);
mCamera.enableShutterSound(false);
mCamera.setPreviewCallback(mPreview);
mCurrentFacing = cameraId;
mParameters = mCamera.getParameters();
String params = mCamera.getParameters().flatten();
final int step = params.length() > 256 ? 256 : params.length();
for (int i = 0; i < params.length(); i += step) {
Log.e(TAG, params);
params = params.substring(step);
}
if (mTargetSize != null)
setPreviewSize(mTargetSize.x, mTargetSize.y);
if (mAutoFocusMoveCallback != null)
mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback);
// Default focus mode to continuous
} catch (Exception e) {
Log.e(TAG, "Error while opening cameras: " + e.getMessage());
StackTraceElement[] st = e.getStackTrace();
for (StackTraceElement elemt : st) {
Log.e(TAG, elemt.toString());
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraFailed();
}
return;
}
if (mCameraReadyListener != null) {
mCameraReadyListener.onCameraReady();
}
// Update the preview surface holder with the new opened camera
mPreview.notifyCameraChanged();
if (mPreviewPauseListener != null) {
mPreviewPauseListener.onPreviewResume();
}
mCameraReady = true;
}
}.start();
return true;
}
|
diff --git a/JSynthLib/org/jsynthlib/editorbuilder/widgets/Widget.java b/JSynthLib/org/jsynthlib/editorbuilder/widgets/Widget.java
index d891ba8..070e667 100644
--- a/JSynthLib/org/jsynthlib/editorbuilder/widgets/Widget.java
+++ b/JSynthLib/org/jsynthlib/editorbuilder/widgets/Widget.java
@@ -1,85 +1,87 @@
package org.jsynthlib.editorbuilder.widgets;
import java.awt.Component;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import org.jsynthlib.utils.Writable;
import org.jsynthlib.utils.XMLWriter;
import org.xml.sax.SAXException;
public class Widget extends JPanel implements Writable {
private static int count;
private String name;
private String id;
private String type;
private WidgetPosition position;
public Widget(String name) {
this(name, name + " " + (count++));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
public Widget(String name, String id) {
this.name = name;
this.id = id;
}
public final String getId() {
return id;
}
public final void setId(String _id) {
this.id = _id;
}
public String getWidgetName() {
return name;
}
protected String getType() {
return type;
}
protected void setType(String type) {
this.type = type;
}
public void write(XMLWriter xml) throws SAXException {
startElement(xml);
writeContent(xml);
endElement(xml);
}
protected void startElement(XMLWriter xml) throws SAXException {
String type = getType();
if (type != null)
xml.setAttribute("type", type);
xml.startElement(getWidgetName());
xml.writeProperty("id", getId());
}
protected void writeContent(XMLWriter xml) throws SAXException {
Component kids[] = getComponents();
boolean started = false;
if (kids != null && kids.length > 0) {
for (int i = 0; i < kids.length; i++) {
if (kids[i] instanceof Widget) {
- if (!started)
- xml.startElement("widgets");
+ if (!started) {
+ xml.startElement("widgets");
+ started = true;
+ }
((Widget)kids[i]).write(xml);
}
}
if (started)
xml.endElement("widgets");
}
}
protected void endElement(XMLWriter xml) throws SAXException {
xml.endElement(getWidgetName());
}
}
| true | true | protected void writeContent(XMLWriter xml) throws SAXException {
Component kids[] = getComponents();
boolean started = false;
if (kids != null && kids.length > 0) {
for (int i = 0; i < kids.length; i++) {
if (kids[i] instanceof Widget) {
if (!started)
xml.startElement("widgets");
((Widget)kids[i]).write(xml);
}
}
if (started)
xml.endElement("widgets");
}
}
| protected void writeContent(XMLWriter xml) throws SAXException {
Component kids[] = getComponents();
boolean started = false;
if (kids != null && kids.length > 0) {
for (int i = 0; i < kids.length; i++) {
if (kids[i] instanceof Widget) {
if (!started) {
xml.startElement("widgets");
started = true;
}
((Widget)kids[i]).write(xml);
}
}
if (started)
xml.endElement("widgets");
}
}
|
diff --git a/java/ibrdtnlib/src/ibrdtn/api/object/NodeConnection.java b/java/ibrdtnlib/src/ibrdtn/api/object/NodeConnection.java
index 7798a5ee..b45a9ebe 100644
--- a/java/ibrdtnlib/src/ibrdtn/api/object/NodeConnection.java
+++ b/java/ibrdtnlib/src/ibrdtn/api/object/NodeConnection.java
@@ -1,143 +1,143 @@
package ibrdtn.api.object;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Julian Timpner <[email protected]>
*/
public class NodeConnection {
private int priority;
private Type type = null;
private Protocol protocol = null;
private String connectionData;
private static final Map<String, Protocol> protocolMap;
static {
Map<String, Protocol> aMap = new HashMap<>();
aMap.put("unsupported", Protocol.CONN_UNSUPPORTED);
aMap.put("undefined", Protocol.CONN_UNDEFINED);
aMap.put("UDP", Protocol.CONN_UDPIP);
aMap.put("TCP", Protocol.CONN_TCPIP);
aMap.put("LoWPAN", Protocol.CONN_LOWPAN);
aMap.put("Bluetooth", Protocol.CONN_BLUETOOTH);
aMap.put("HTTP", Protocol.CONN_HTTP);
aMap.put("FILE", Protocol.CONN_FILE);
aMap.put("DGRAM:UDP", Protocol.CONN_DGRAM_UDP);
aMap.put("DGRAM:ETHERNET", Protocol.CONN_DGRAM_ETHERNET);
aMap.put("DGRAM:LOWPAN", Protocol.CONN_DGRAM_LOWPAN);
aMap.put("P2P:WIFI", Protocol.CONN_P2P_WIFI);
aMap.put("P2P:BT", Protocol.CONN_P2P_BT);
protocolMap = Collections.unmodifiableMap(aMap);
}
private static final Map<String, Type> typeMap;
static {
Map<String, Type> aMap = new HashMap<>();
aMap.put("unavailable", Type.NODE_UNAVAILABLE);
aMap.put("discovered", Type.NODE_DISCOVERED);
aMap.put("static global", Type.NODE_STATIC_GLOBAL);
aMap.put("static local", Type.NODE_STATIC_LOCAL);
aMap.put("connected", Type.NODE_CONNECTED);
aMap.put("dht discovered", Type.NODE_DHT_DISCOVERED);
aMap.put("p2p dialup", Type.NODE_P2P_DIALUP);
typeMap = Collections.unmodifiableMap(aMap);
}
public enum Type {
NODE_UNAVAILABLE(0),
NODE_CONNECTED(1),
NODE_DISCOVERED(2),
NODE_STATIC_GLOBAL(3),
NODE_STATIC_LOCAL(4),
NODE_DHT_DISCOVERED(5),
NODE_P2P_DIALUP(6);
Type(int offset) {
this.offset = offset;
}
int offset;
public int getOffset() {
return offset;
}
};
public enum Protocol {
CONN_UNSUPPORTED(-1),
CONN_UNDEFINED(0),
CONN_TCPIP(1),
CONN_UDPIP(2),
CONN_LOWPAN(3),
CONN_BLUETOOTH(4),
CONN_HTTP(5),
CONN_FILE(6),
CONN_DGRAM_UDP(7),
CONN_DGRAM_LOWPAN(8),
CONN_DGRAM_ETHERNET(9),
CONN_P2P_WIFI(10),
CONN_P2P_BT(11);
Protocol(int offset) {
this.offset = offset;
}
int offset;
public int getOffset() {
return offset;
}
};
public NodeConnection(String data) {
parse(data);
}
private void parse(String data) {
final Pattern pattern = Pattern.compile(
"(\\d+)" // priority
+ "#"
+ "(\\w+)" // type
+ "#"
- + "(\\w+)" // protocol
+ + "((\\w|:)+)" // protocol
+ "#"
+ "(.*)" // connection data
);
final Matcher matcher = pattern.matcher(data);
matcher.find();
priority = Integer.parseInt(matcher.group(1));
type = typeMap.get(matcher.group(2));
protocol = protocolMap.get(matcher.group(3));
connectionData = matcher.group(4);
}
public int getPriority() {
return priority;
}
public Type getType() {
return type;
}
public Protocol getProtocol() {
return protocol;
}
public String getConnectionData() {
return connectionData;
}
@Override
public String toString() {
return type + ":" + protocol + "#" + connectionData;
}
}
| true | true | private void parse(String data) {
final Pattern pattern = Pattern.compile(
"(\\d+)" // priority
+ "#"
+ "(\\w+)" // type
+ "#"
+ "(\\w+)" // protocol
+ "#"
+ "(.*)" // connection data
);
final Matcher matcher = pattern.matcher(data);
matcher.find();
priority = Integer.parseInt(matcher.group(1));
type = typeMap.get(matcher.group(2));
protocol = protocolMap.get(matcher.group(3));
connectionData = matcher.group(4);
}
| private void parse(String data) {
final Pattern pattern = Pattern.compile(
"(\\d+)" // priority
+ "#"
+ "(\\w+)" // type
+ "#"
+ "((\\w|:)+)" // protocol
+ "#"
+ "(.*)" // connection data
);
final Matcher matcher = pattern.matcher(data);
matcher.find();
priority = Integer.parseInt(matcher.group(1));
type = typeMap.get(matcher.group(2));
protocol = protocolMap.get(matcher.group(3));
connectionData = matcher.group(4);
}
|
diff --git a/src/com/github/nutomic/controldlna/FileArrayAdapter.java b/src/com/github/nutomic/controldlna/FileArrayAdapter.java
index fa5215c..47efbac 100644
--- a/src/com/github/nutomic/controldlna/FileArrayAdapter.java
+++ b/src/com/github/nutomic/controldlna/FileArrayAdapter.java
@@ -1,103 +1,104 @@
/*
Copyright (c) 2013, Felix Ableitner
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.nutomic.controldlna;
import java.util.Comparator;
import java.util.List;
import org.teleal.cling.support.model.DIDLObject;
import org.teleal.cling.support.model.container.Container;
import org.teleal.cling.support.model.item.Item;
import org.teleal.cling.support.model.item.MusicTrack;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<DIDLObject> {
public FileArrayAdapter(Context context) {
super(context, R.layout.list_item);
sort(new Comparator<DIDLObject>() {
@Override
public int compare(DIDLObject lhs, DIDLObject rhs) {
if (lhs instanceof MusicTrack && rhs instanceof MusicTrack)
return ((MusicTrack) rhs).getOriginalTrackNumber() -
((MusicTrack) lhs).getOriginalTrackNumber();
else if (lhs instanceof Item && rhs instanceof Container)
return 1;
else if (rhs instanceof Item && lhs instanceof Container)
return -1;
else if (lhs instanceof Container && rhs instanceof Container)
return lhs.getTitle().compareTo(rhs.getTitle());
else
return 0;
}
});
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
DIDLObject item = getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView artist = (TextView) convertView.findViewById(R.id.subtitle);
RemoteImageView image = (RemoteImageView) convertView.findViewById(R.id.image);
- MusicTrack track;
if (item instanceof MusicTrack) {
- track = (MusicTrack) item;
- title.setText(Integer.toString(track.getOriginalTrackNumber()) +
- ". " + item.getTitle());
+ MusicTrack track = (MusicTrack) item;
+ String trackNumber = (track.getOriginalTrackNumber() != null)
+ ? Integer.toString(track.getOriginalTrackNumber()) + ". "
+ : "";
+ title.setText(trackNumber + item.getTitle());
artist.setText(track.getArtists()[0].getName());
}
else {
title.setText(item.getTitle());
artist.setText("");
}
image.setImageUri(item.getFirstPropertyValue(
DIDLObject.Property.UPNP.ALBUM_ART_URI.class));
return convertView;
}
/**
* Replacement for addAll, which is not implemented on lower API levels.
*/
public void add(List<Item> playlist) {
for (DIDLObject d : playlist)
add(d);
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
DIDLObject item = getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView artist = (TextView) convertView.findViewById(R.id.subtitle);
RemoteImageView image = (RemoteImageView) convertView.findViewById(R.id.image);
MusicTrack track;
if (item instanceof MusicTrack) {
track = (MusicTrack) item;
title.setText(Integer.toString(track.getOriginalTrackNumber()) +
". " + item.getTitle());
artist.setText(track.getArtists()[0].getName());
}
else {
title.setText(item.getTitle());
artist.setText("");
}
image.setImageUri(item.getFirstPropertyValue(
DIDLObject.Property.UPNP.ALBUM_ART_URI.class));
return convertView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
DIDLObject item = getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView artist = (TextView) convertView.findViewById(R.id.subtitle);
RemoteImageView image = (RemoteImageView) convertView.findViewById(R.id.image);
if (item instanceof MusicTrack) {
MusicTrack track = (MusicTrack) item;
String trackNumber = (track.getOriginalTrackNumber() != null)
? Integer.toString(track.getOriginalTrackNumber()) + ". "
: "";
title.setText(trackNumber + item.getTitle());
artist.setText(track.getArtists()[0].getName());
}
else {
title.setText(item.getTitle());
artist.setText("");
}
image.setImageUri(item.getFirstPropertyValue(
DIDLObject.Property.UPNP.ALBUM_ART_URI.class));
return convertView;
}
|
diff --git a/liveDemo/core/source/org/openfaces/demo/beans/selectbooleancheckbox/PermissionSchema.java b/liveDemo/core/source/org/openfaces/demo/beans/selectbooleancheckbox/PermissionSchema.java
index dbc2a39f2..68c7105e8 100644
--- a/liveDemo/core/source/org/openfaces/demo/beans/selectbooleancheckbox/PermissionSchema.java
+++ b/liveDemo/core/source/org/openfaces/demo/beans/selectbooleancheckbox/PermissionSchema.java
@@ -1,241 +1,241 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2009, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.demo.beans.selectbooleancheckbox;
import org.openfaces.component.select.SelectBooleanCheckbox;
import static org.openfaces.demo.beans.selectbooleancheckbox.Permission.*;
import org.openfaces.demo.beans.util.FacesUtils;
import javax.faces.event.ActionEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class PermissionSchema {
private static final String SEPARATOR = "Separator";
public PermissionSchema() {
setAssigned(Permission.VIEW_POSTS, PermissionGroup.ANONYMOUS, true);
setAssigned(Permission.CREATE_POSTS, PermissionGroup.USER, true);
setAssigned(Permission.EDIT_ANY_POST, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.DELETE_OWN_POST, PermissionGroup.USER, true);
setAssigned(Permission.DELETE_ANY_POST, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.CREATE_ATTACHEMENTS, PermissionGroup.USER, true);
setAssigned(Permission.REMOVE_ATTACHEMENTS, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.CREATE_NEWS, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.VIEW_HIDDEN_TIMED_NEWS, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.DELETE_NEWS, PermissionGroup.ADMINISTRATOR, true);
setAssigned(Permission.ADD_COMMENTS, PermissionGroup.USER, true);
setAssigned(Permission.REMOVE_COMMENTS, PermissionGroup.ADMINISTRATOR, true);
}
private Map<PermissionGroup, Map<Permission, State>> permissionsAssignment;
public Map<PermissionGroup, Map<Permission, State>> getPermissionsAssignment() {
if (permissionsAssignment == null) {
permissionsAssignment = new PermissionAssigmnent();
}
return permissionsAssignment;
}
public Collection<?> getPermissions() {
return Arrays.asList(
VIEW_POSTS,
CREATE_POSTS,
EDIT_ANY_POST,
DELETE_OWN_POST,
DELETE_ANY_POST,
SEPARATOR,
CREATE_ATTACHEMENTS,
REMOVE_ATTACHEMENTS,
SEPARATOR,
CREATE_NEWS,
VIEW_HIDDEN_TIMED_NEWS,
DELETE_NEWS,
SEPARATOR,
ADD_COMMENTS,
REMOVE_COMMENTS);
//return EnumSet.allOf(Permission.class);
}
public HashMap<Object, Boolean> getIsSeparator() {
return new HashMap<Object, Boolean>() {
@Override
public Boolean get(Object permission) {
return permission.equals(SEPARATOR);
}
};
}
public HashMap<String, PermissionGroup> getPermissionGroup() {
return new HashMap<String, PermissionGroup>() {
@Override
public PermissionGroup get(Object permissionGroup) {
return PermissionGroup.valueOf(String.valueOf(permissionGroup));
}
};
}
public boolean isAssigned(Permission permission, PermissionGroup permissionGroup) {
Boolean state = getPermissionsAssignment().get(permissionGroup).get(permission).getState();
return state == null || state;
}
public void setAssigned(Permission permission, PermissionGroup permissionGroup, Boolean state) {
getPermissionsAssignment().get(permissionGroup).get(permission).setState(state);
}
private class PermissionAssigmnent extends HashMap<PermissionGroup, Map<Permission, State>> {
@Override
public Map<Permission, State> get(final Object key) {
if (key == null) {
return null;
}
final PermissionGroup permissionGroup;
if (key instanceof PermissionGroup) {
permissionGroup = (PermissionGroup) key;
} else {
permissionGroup = PermissionGroup.valueOf(String.valueOf(key));
}
Map<Permission, State> value = super.get(permissionGroup);
if (value == null) {
value = new HashMap<Permission, State>() {
@Override
public State get(Object key) {
if (key == null) {
return null;
}
final Permission permission;
if (key instanceof Permission) {
permission = (Permission) key;
} else {
permission = Permission.valueOf(String.valueOf(key));
}
State result = super.get(permission);
if (result == null) {
result = new State() {
@Override
public void setState(Boolean state) {
super.setState(state);
if (state != null) {
setDependentPermissions(state);
}
}
@Override
public void setDependent(boolean dependent) {
super.setDependent(dependent);
setDependentPermissions(dependent);
}
private void setDependentPermissions(boolean value) {
- Collection<Permission> dependendPermissions = permission.getDependent();
- for (Permission dependendPermission : dependendPermissions) {
- get(dependendPermission).setDependent(value);
+ Collection<Permission> dependentPermissions = permission.getDependent();
+ for (Permission dependentPermission : dependentPermissions) {
+ get(dependentPermission).setDependent(value);
}
Collection<PermissionGroup> dependentPermissionGroups = permissionGroup.getDependent();
- for (PermissionGroup dependendPermissionGroup : dependentPermissionGroups) {
- PermissionAssigmnent.this.get(dependendPermissionGroup).get(permission).setDependent(value);
+ for (PermissionGroup dependentPermissionGroup : dependentPermissionGroups) {
+ PermissionAssigmnent.this.get(dependentPermissionGroup).get(permission).setDependent(value);
}
}
};
super.put(permission, result);
}
return result;
}
};
super.put(permissionGroup, value);
}
return value;
}
}
public class State {
private Boolean state = false;
private Boolean outputState = false;
private int dependent = 0;
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
public Boolean getOutputState() {
return state;
}
public void setOutputState(Boolean outputState) {
this.outputState = outputState;
}
private void submitState() {
setState(outputState);
}
public boolean isDependent() {
return dependent != 0;
}
public void setDependent(boolean dependent) {
if (dependent) {
this.dependent++;
} else {
this.dependent--;
}
if (!isDependent()) {
if (state == null) {
state = false;
}
} else {
if (state != null && !state) {
state = null;
}
}
}
}
public void updateAssignment(ActionEvent event) {
String groupString = String.valueOf(FacesUtils.getEventParameter(event, "group"));
PermissionGroup permissionGroup = PermissionGroup.valueOf(groupString);
String permissionString = String.valueOf(FacesUtils.getEventParameter(event, "permission"));
Permission permission = Permission.valueOf(permissionString);
getPermissionsAssignment().get(permissionGroup).get(permission).submitState();
}
public Iterable<String> getDefaultStateList() {
return Arrays.asList(SelectBooleanCheckbox.SELECTED_STATE, SelectBooleanCheckbox.UNSELECTED_STATE);
}
public Iterable<String> getDependentStateList() {
return Arrays.asList(SelectBooleanCheckbox.SELECTED_STATE, SelectBooleanCheckbox.UNDEFINED_STATE);
}
}
| false | true | public Map<Permission, State> get(final Object key) {
if (key == null) {
return null;
}
final PermissionGroup permissionGroup;
if (key instanceof PermissionGroup) {
permissionGroup = (PermissionGroup) key;
} else {
permissionGroup = PermissionGroup.valueOf(String.valueOf(key));
}
Map<Permission, State> value = super.get(permissionGroup);
if (value == null) {
value = new HashMap<Permission, State>() {
@Override
public State get(Object key) {
if (key == null) {
return null;
}
final Permission permission;
if (key instanceof Permission) {
permission = (Permission) key;
} else {
permission = Permission.valueOf(String.valueOf(key));
}
State result = super.get(permission);
if (result == null) {
result = new State() {
@Override
public void setState(Boolean state) {
super.setState(state);
if (state != null) {
setDependentPermissions(state);
}
}
@Override
public void setDependent(boolean dependent) {
super.setDependent(dependent);
setDependentPermissions(dependent);
}
private void setDependentPermissions(boolean value) {
Collection<Permission> dependendPermissions = permission.getDependent();
for (Permission dependendPermission : dependendPermissions) {
get(dependendPermission).setDependent(value);
}
Collection<PermissionGroup> dependentPermissionGroups = permissionGroup.getDependent();
for (PermissionGroup dependendPermissionGroup : dependentPermissionGroups) {
PermissionAssigmnent.this.get(dependendPermissionGroup).get(permission).setDependent(value);
}
}
};
super.put(permission, result);
}
return result;
}
};
super.put(permissionGroup, value);
}
return value;
}
| public Map<Permission, State> get(final Object key) {
if (key == null) {
return null;
}
final PermissionGroup permissionGroup;
if (key instanceof PermissionGroup) {
permissionGroup = (PermissionGroup) key;
} else {
permissionGroup = PermissionGroup.valueOf(String.valueOf(key));
}
Map<Permission, State> value = super.get(permissionGroup);
if (value == null) {
value = new HashMap<Permission, State>() {
@Override
public State get(Object key) {
if (key == null) {
return null;
}
final Permission permission;
if (key instanceof Permission) {
permission = (Permission) key;
} else {
permission = Permission.valueOf(String.valueOf(key));
}
State result = super.get(permission);
if (result == null) {
result = new State() {
@Override
public void setState(Boolean state) {
super.setState(state);
if (state != null) {
setDependentPermissions(state);
}
}
@Override
public void setDependent(boolean dependent) {
super.setDependent(dependent);
setDependentPermissions(dependent);
}
private void setDependentPermissions(boolean value) {
Collection<Permission> dependentPermissions = permission.getDependent();
for (Permission dependentPermission : dependentPermissions) {
get(dependentPermission).setDependent(value);
}
Collection<PermissionGroup> dependentPermissionGroups = permissionGroup.getDependent();
for (PermissionGroup dependentPermissionGroup : dependentPermissionGroups) {
PermissionAssigmnent.this.get(dependentPermissionGroup).get(permission).setDependent(value);
}
}
};
super.put(permission, result);
}
return result;
}
};
super.put(permissionGroup, value);
}
return value;
}
|
diff --git a/src/gool/generator/python/PythonGenerator.java b/src/gool/generator/python/PythonGenerator.java
index 337f249..ccd177b 100644
--- a/src/gool/generator/python/PythonGenerator.java
+++ b/src/gool/generator/python/PythonGenerator.java
@@ -1,768 +1,772 @@
package gool.generator.python;
import gool.ast.constructs.ArrayNew;
import gool.ast.constructs.BinaryOperation;
import gool.ast.constructs.Block;
import gool.ast.constructs.CastExpression;
import gool.ast.constructs.ClassDef;
import gool.ast.constructs.ClassFree;
import gool.ast.constructs.ClassNew;
import gool.ast.constructs.Comment;
import gool.ast.constructs.CompoundAssign;
import gool.ast.constructs.Constant;
import gool.ast.constructs.CustomDependency;
import gool.ast.constructs.Dependency;
import gool.ast.constructs.EnhancedForLoop;
import gool.ast.constructs.EqualsCall;
import gool.ast.constructs.ExpressionUnknown;
import gool.ast.constructs.Field;
import gool.ast.constructs.For;
import gool.ast.constructs.Identifier;
import gool.ast.constructs.If;
import gool.ast.constructs.MainMeth;
import gool.ast.constructs.MapEntryMethCall;
import gool.ast.constructs.MapMethCall;
import gool.ast.constructs.MemberSelect;
import gool.ast.constructs.Meth;
import gool.ast.constructs.MethCall;
import gool.ast.constructs.Modifier;
import gool.ast.constructs.NewInstance;
import gool.ast.constructs.Operator;
import gool.ast.constructs.ParentCall;
import gool.ast.constructs.Return;
import gool.ast.constructs.Statement;
import gool.ast.constructs.This;
import gool.ast.constructs.ThisCall;
import gool.ast.constructs.ToStringCall;
import gool.ast.constructs.TypeDependency;
import gool.ast.constructs.UnaryOperation;
import gool.ast.constructs.VarAccess;
import gool.ast.constructs.VarDeclaration;
import gool.ast.constructs.While;
import gool.ast.list.ListAddCall;
import gool.ast.list.ListContainsCall;
import gool.ast.list.ListGetCall;
import gool.ast.list.ListGetIteratorCall;
import gool.ast.list.ListIsEmptyCall;
import gool.ast.list.ListRemoveAtCall;
import gool.ast.list.ListRemoveCall;
import gool.ast.list.ListSizeCall;
import gool.ast.map.MapContainsKeyCall;
import gool.ast.map.MapEntryGetKeyCall;
import gool.ast.map.MapEntryGetValueCall;
import gool.ast.map.MapGetCall;
import gool.ast.map.MapGetIteratorCall;
import gool.ast.map.MapIsEmptyCall;
import gool.ast.map.MapPutCall;
import gool.ast.map.MapRemoveCall;
import gool.ast.map.MapSizeCall;
import gool.ast.system.SystemCommandDependency;
import gool.ast.system.SystemOutDependency;
import gool.ast.system.SystemOutPrintCall;
import gool.ast.type.TypeArray;
import gool.ast.type.TypeBool;
import gool.ast.type.TypeByte;
import gool.ast.type.TypeChar;
import gool.ast.type.TypeDecimal;
import gool.ast.type.TypeEntry;
import gool.ast.type.TypeInt;
import gool.ast.type.TypeList;
import gool.ast.type.TypeMap;
import gool.ast.type.TypeNone;
import gool.ast.type.TypeNull;
import gool.ast.type.TypeObject;
import gool.ast.type.TypeString;
import gool.ast.type.TypeUnknown;
import gool.ast.type.TypeVoid;
import gool.generator.GeneratorHelper;
import gool.generator.common.CommonCodeGenerator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import logger.Log;
import org.apache.commons.lang.StringUtils;
public class PythonGenerator extends CommonCodeGenerator {
public PythonGenerator() {
super();
indentation = " ";
}
private ArrayList<String> comments = new ArrayList<String>();
private ArrayList<String> paramsMethCurrent = new ArrayList<String>();
private ArrayList<String> privateMeth = new ArrayList<String>();
private void comment(String newcomment) {
comments.add("# " + newcomment + "\n");
}
private String printWithComment(Statement statement) {
String sttmnt = statement.toString().replaceFirst("\\s*\\z", "");
if (comments.size() == 1 && ! sttmnt.contains("\n")) {
sttmnt += " " + comments.get(0);
} else {
sttmnt = StringUtils.join(comments,"") + sttmnt + "\n";
}
comments.clear();
return sttmnt;
}
private static Map<Meth, String> methodsNames = new HashMap<Meth, String>();
private static Map<String, Dependency> customDependencies = new HashMap<String, Dependency>();
private String getName(Meth meth) {
return methodsNames.get(meth);
}
@Override
public void addCustomDependency(String key, Dependency value) {
customDependencies.put(key, value);
}
@Override
public String getCode(ArrayNew arrayNew) {
return String.format("%s[%s]", arrayNew.getType(), StringUtils
.join(arrayNew.getDimesExpressions(), ", "));
}
@Override
public String getCode(Block block) {
StringBuilder result = new StringBuilder();
for (Statement statement : block.getStatements()) {
result.append(printWithComment(statement));
}
return result.toString();
}
@Override
public String getCode(BinaryOperation binaryOp) {
String textualOp;
switch (binaryOp.getOperator()) {
case AND :
textualOp = "and";
break;
case OR :
textualOp = "or";
break;
case DIV :
if (binaryOp.getType().equals(TypeInt.INSTANCE))
textualOp = "//";
else
textualOp = "/";
break;
default :
textualOp = binaryOp.getTextualoperator();
}
if(binaryOp.getOperator().equals(Operator.UNKNOWN))
comment("Unrecognized by GOOL, passed on");
return String.format("(%s %s %s)", binaryOp.getLeft(), textualOp, binaryOp.getRight());
}
@Override
public String getCode(Constant constant) {
if (constant.getType().equals(TypeBool.INSTANCE)) {
return String.valueOf(constant.getValue().toString().equalsIgnoreCase("true") ? "True" : "False");
} else {
return super.getCode(constant);
}
}
@Override
public String getCode(CastExpression cast) {
return String.format("%s(%s)", cast.getType(), cast
.getExpression());
}
@Override
public String getCode(ClassNew classNew) {
return String.format("%s(%s)", classNew.getName(), StringUtils
.join(classNew.getParameters(), ", "));
}
@Override
public String getCode(Comment comment) {
return comment.getValue().replaceAll("(^ *)([^ ])", "$1# $2");
}
@Override
public String getCode(EnhancedForLoop enhancedForLoop) {
if(enhancedForLoop.getExpression().getType() instanceof TypeMap)
return formatIndented("for %s in %s.iteritems():%1", enhancedForLoop.getVarDec().getName(),
enhancedForLoop.getExpression() ,enhancedForLoop.getStatements());
return formatIndented("for %s in %s:%1", enhancedForLoop.getVarDec().getName(),
enhancedForLoop.getExpression() ,enhancedForLoop.getStatements());
}
@Override
public String getCode(EqualsCall equalsCall) {
return String.format("%s == %s", equalsCall.getTarget(), equalsCall.getParameters().get(0));
}
@Override
public String getCode(Field field) {
String value;
if (field.getDefaultValue() != null) {
value = field.getDefaultValue().toString();
}
else {
value = "None";
}
return String.format("%s = %s\n", field.getName(), value);
}
@Override
public String getCode(For forr) {
return formatIndented("%swhile %s:%1%-1%s",
printWithComment(forr.getInitializer()),forr.getCondition(),
forr.getWhileStatement().toString(), printWithComment(forr.getUpdater()));
}
@Override
public String getCode(If pif) {
String out = formatIndented ("if %s:%1", pif.getCondition(), pif.getThenStatement());
if (pif.getElseStatement() != null){
if (pif.getElseStatement() instanceof If) {
out += formatIndented ("el%s", pif.getElseStatement());
} else {
out += formatIndented ("else:%1", pif.getElseStatement());
}
}
return out;
}
@Override
public String getCode(Collection<Modifier> modifiers) {
return "";
}
@Override
public String getCode(ListAddCall lac) {
switch (lac.getParameters().size()) {
case 1:
return String.format("%s.append(%s)",
lac.getExpression(), lac.getParameters().get(0));
case 2:
return String.format("%s.insert(%s, %s)",
lac.getExpression(), lac.getParameters().get(1), lac.getParameters().get(0));
default:
comment ("Unrecognized by GOOL, passed on");
return String.format("%s.add(%s)",
lac.getExpression(), StringUtils.join(lac.getParameters(), ", "));
}
}
@Override
public String getCode(ListContainsCall lcc) {
return String.format("%s in %s", lcc.getParameters().get(0), lcc.getExpression());
}
@Override
public String getCode(ListGetCall lgc) {
return String.format("%s[%s]", lgc.getExpression(), lgc.getParameters().get(0));
}
@Override
public String getCode(ListGetIteratorCall lgic) {
return String.format("iter(%s)", lgic.getExpression());
}
@Override
public String getCode(ListIsEmptyCall liec) {
return String.format("(not %s)", liec.getExpression());
}
@Override
public String getCode(ListRemoveAtCall lrc) {
return String.format("%s.pop(%s)", lrc.getExpression(), StringUtils
.join(lrc.getParameters(), ", "));
}
@Override
public String getCode(ListRemoveCall lrc) {
return String.format("%s.remove(%s)", lrc.getExpression(), StringUtils
.join(lrc.getParameters(), ", "));
}
@Override
public String getCode(ListSizeCall lsc) {
return String.format("len(%s)", lsc.getExpression());
}
@Override
public String getCode(MainMeth mainMeth) {
return mainMeth.getBlock().toString();
}
@Override
public String getCode(MapContainsKeyCall mapContainsKeyCall) {
return String.format("%s in %s",
mapContainsKeyCall.getParameters().get(0), mapContainsKeyCall.getExpression());
}
@Override
public String getCode(MapEntryGetKeyCall mapEntryGetKeyCall) {
return String.format("%s[0]", mapEntryGetKeyCall.getExpression());
}
@Override
public String getCode(MapEntryGetValueCall mapEntryGetKeyCall) {
return String.format("%s[1]", mapEntryGetKeyCall.getExpression());
}
@Override
public String getCode(MapEntryMethCall mapEntryMethCall) {
// TODO Auto-generated method stub
return "";
}
@Override
public String getCode(MapGetCall mapGetCall) {
return String.format("%s[%s]", mapGetCall.getExpression(), mapGetCall.getParameters().get(0));
}
@Override
public String getCode(MapGetIteratorCall mapGetIteratorCall) {
return String.format("iter(%s)", mapGetIteratorCall.getExpression());
}
@Override
public String getCode(MapIsEmptyCall mapIsEmptyCall) {
return String.format("(not %s)", mapIsEmptyCall.getExpression());
}
@Override
public String getCode(MapMethCall mapMethCall) {
return String.format("%s[%s])", mapMethCall.getExpression(),
mapMethCall.getParameters().get(0));
}
@Override
public String getCode(MapPutCall mapPutCall) {
return String.format("%s[%s] = %s", mapPutCall.getExpression(),
mapPutCall.getParameters().get(0), mapPutCall.getParameters().get(1));
}
@Override
public String getCode(MapRemoveCall mapRemoveCall) {
return String.format("%s.pop(%s, None)", mapRemoveCall.getExpression(),
StringUtils.join(mapRemoveCall.getParameters(), ", "));
}
@Override
public String getCode(MapSizeCall mapSizeCall) {
return String.format("len(%s)", mapSizeCall.getExpression());
}
private String printMeth(Meth meth, String prefix){
String params = "";
paramsMethCurrent.clear();
for (VarDeclaration p : meth.getParams()) {
paramsMethCurrent.add(p.getName());
params += ", " + p.getName();
if (p.getInitialValue() != null)
params += " = " + p.getInitialValue();
}
if (prefix == "" && meth.getBlock().getStatements().isEmpty())
prefix = "pass";
return formatIndented("%sdef %s(self%s):%1",
meth.getModifiers().contains(Modifier.STATIC)?"@classmethod\n":"",
methodsNames.get(meth), params,
prefix + meth.getBlock());
}
@Override
public String getCode(Meth meth) {
return printMeth(meth, "");
}
@Override
public String getCode(VarAccess varAccess) {
String name = varAccess.getDec().getName();
if (name.equals("this"))
return "self";
else if (paramsMethCurrent.contains(name))
return name;
else
return "self." + name;
}
@Override
public String getCode(MemberSelect memberSelect) {
return String.format("%s.%s", memberSelect.getTarget().toString().equals("this")?"self":memberSelect.getTarget(), memberSelect
.getIdentifier());
}
@Override
public String getCode(Modifier modifier) {
// TODO Auto-generated method stub
return "";
}
@Override
public String getCode(NewInstance newInstance) {
return String.format("%s = %s( %s )", newInstance.getVariable(),
newInstance.getVariable().getType().toString().replaceAll(
"\\*$", ""), StringUtils.join(newInstance
.getParameters(), ", "));
}
@Override
public String getCode(ParentCall parentCall) {
String out = parentCall.getTarget() + "(";
if (parentCall.getParameters() != null) {
out += StringUtils.join(parentCall.getParameters(), ", ");
}
out += ")";
return out;
}
@Override
public String getCode(Return returnExpr) {
return String.format("return %s", returnExpr.getExpression());
}
@Override
public String getCode(SystemOutDependency systemOutDependency) {
return "noprint";
}
@Override
public String getCode(SystemOutPrintCall systemOutPrintCall) {
return String.format("print %s", StringUtils.join(
systemOutPrintCall.getParameters(), ","));
}
@Override
public String getCode(This pthis) {
return "self";
}
@Override
public String getCode(ThisCall thisCall) {
return String.format("self.__init__(%s)", GeneratorHelper.joinParams(thisCall.getParameters()));
}
@Override
public String getCode(ToStringCall tsc) {
return String.format("str(%s)", tsc.getTarget());
}
@Override
public String getCode(TypeBool typeBool) {
return "bool";
}
@Override
public String getCode(TypeByte typeByte) {
return "bytearray";
}
@Override
public String getCode(TypeDecimal typeReal) {
return "float";
}
@Override
public String getCode(TypeDependency typeDependency) {
// TODO Auto-generated method stub
if(typeDependency.getType() instanceof TypeInt)
return "noprint";
if(typeDependency.getType() instanceof TypeString)
return "noprint";
if(typeDependency.getType() instanceof TypeList)
return "noprint";
if(typeDependency.getType() instanceof TypeMap)
return "noprint";
return super.getCode(typeDependency);
}
@Override
public String getCode(TypeEntry typeEntry) {
return String.format("(%s, %s)",typeEntry.getKeyType(), typeEntry.getElementType() );
}
@Override
public String getCode(TypeInt typeInt) {
return "int";
}
@Override
public String getCode(TypeList typeList) {
return "list";
}
@Override
public String getCode(TypeMap typeMap) {
return "dict";
}
@Override
public String getCode(TypeNone type) {
return "None";
}
@Override
public String getCode(TypeNull type) {
return "None";
}
@Override
public String getCode(TypeObject typeObject) {
return "object";
}
@Override
public String getCode(TypeString typeString) {
return "str";
}
@Override
public String getCode(TypeVoid typeVoid) {
// TODO Auto-generated method stub
return "";
}
@Override
public String getCode(UnaryOperation unaryOperation) {
switch (unaryOperation.getOperator()){
case POSTFIX_INCREMENT:
comment("GOOL warning: post-incrementation became pre-incrementation");
// no break: follow to the next case
case PREFIX_INCREMENT:
return String.format("goolHelper.increment(%s)", unaryOperation.getExpression());
case POSTFIX_DECREMENT:
comment("GOOL warning: post-decrementation became pre-decrementation");
// no break: follow to the next case
case PREFIX_DECREMENT:
return String.format("goolHelper.decrement(%s)", unaryOperation.getExpression());
case UNKNOWN:
comment("Unrecognized by GOOL, passed on");
// no break: follow to the next case
default:
return String.format("%s%s", unaryOperation.getTextualoperator(), unaryOperation.getExpression());
}
}
@Override
public String getCode(VarDeclaration varDec) {
String value;
if(varDec.getInitialValue() != null) {
value = varDec.getInitialValue().toString();
}
else {
value = "None";
}
paramsMethCurrent.add(varDec.getName());
return String.format("%s = %s", varDec.getName(), value);
}
@Override
public String getCode(While whilee) {
return formatIndented("while %s:%1", whilee.getCondition(), whilee.getWhileStatement());
}
@Override
public String getCode(TypeArray typeArray) {
return "list";
}
@Override
public String getCode(CustomDependency customDependency) {
if (!customDependencies.containsKey(customDependency.getName())) {
Log.e(String.format("Custom dependencies: %s, Desired: %s", customDependencies, customDependency.getName()));
throw new IllegalArgumentException(String.format("There is no equivalent type in Python for the GOOL type '%s'.", customDependency.getName()));
}
return customDependencies.get(customDependency.getName()).toString();
}
@Override
public String getCode(TypeUnknown typeUnknown) {
// TODO Auto-generated method stub
return "";
}
@Override
public String getCode(CompoundAssign compoundAssign) {
String textualOp;
switch (compoundAssign.getOperator()) {
case AND :
textualOp = "&";
break;
case OR :
textualOp = "|";
break;
case DIV :
if (compoundAssign.getType().equals(TypeInt.INSTANCE))
textualOp = "//";
else
textualOp = "/";
break;
default :
textualOp = compoundAssign.getTextualoperator();
}
if (compoundAssign.getOperator().equals(Operator.UNKNOWN))
comment("Unrecognized by GOOL, passed on");
return String.format("%s %s= %s", compoundAssign.getLValue(), textualOp,
compoundAssign.getValue());
}
@Override
public String getCode(ExpressionUnknown unknownExpression) {
comment ("Unrecognized by GOOL, passed on");
return unknownExpression.getTextual();
}
@Override
public String getCode(ClassFree classFree) {
// TODO Auto-generated method stub
return "";
}
@Override
public String getCode(SystemCommandDependency systemCommandDependency) {
// a verifier car de partout à null et je ne sais pas ce que ça fait
return null;
}
@Override
public String printClass(ClassDef classDef) {
//StringBuilder code = new StringBuilder ("#!/usr/bin/env python\n\nimport goolHelper\n\n");
StringBuilder code = new StringBuilder (String.format("# Platform: %s\n\n", classDef.getPlatform()));
code.append("import goolHelper\n");
Set<String> dependencies = GeneratorHelper.printDependencies(classDef);
if (! dependencies.isEmpty()) {
for (String dependency : dependencies) {
if(!dependency.isEmpty())
if(dependency != "noprint")
code = code.append(String.format("import %s\n", dependency));
}
}
code = code.append(String.format("\nclass %s(%s):\n", classDef.getName(),
(classDef.getParentClass() != null) ? classDef.getParentClass().getName() : "object"));
String dynamicAttributs = "";
for(Field f : classDef.getFields()) {
if (f.getModifiers().contains(Modifier.STATIC))
code = code.append(formatIndented("%1", f));
else
dynamicAttributs += String.format("self.%s\n", f);
}
- dynamicAttributs = dynamicAttributs.replaceFirst("\\s*\\z", "\n");
+ dynamicAttributs = dynamicAttributs.replaceFirst("\\s+\\z", "\n");
List<Meth> meths = new ArrayList<Meth>();
Meth mainMeth = null;
for(Meth method : classDef.getMethods()) { //On parcourt les méthodes
// the main method will be printed outside of the class later
if (method.isMainMethod()) {
mainMeth = method;
}
// we register all private method to be able to rename them
if (method.getModifiers().contains(Modifier.PRIVATE)) {
privateMeth.add(method.getName());
}
else if(getName(method) == null) { //Si la méthode n'a pas encore été renommée
meths.clear();
for(Meth m : classDef.getMethods()) { //On récupère les méthodes de mêmes noms
if(m.getName().equals(method.getName())) {
meths.add(m);
}
}
if(meths.size()>1) { //Si il y a plusieurs méthodes de même nom
- code = code.append(formatIndented("\n%-1# Wrapper generated by GOOL\n"));
+ code = code.append(formatIndented("\n%-1# wrapper generated by GOOL\n"));
String block = "";
String newName = method.getName();
int i = 0;
boolean first = true;
boolean someStatics = false;
boolean someDynamics = false;
for(Meth m2 : meths) {
if (m2.getModifiers().contains(Modifier.STATIC))
someStatics = true;
else
someDynamics = true;
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
while(methodsNames.containsValue(newName)) {
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
}
methodsNames.put(m2, newName);
String types = "";
for(VarDeclaration p : m2.getParams()) {
types += ", " + p.getType();
}
block += formatIndented("%sif goolHelper.test_args(args%s):\n%-1self.%s(*args)\n",
first?"":"el", types, newName);
first = false;
}
if (someStatics && someDynamics) {
code = code.append(formatIndented(
- "%-1# GOOL warning: some methods are statics, they can't be used as-is. Rename them.\n"));
+ "%-1# GOOL warning: static and dynamic methods under a same wrapper\n" +
+ "%-1# impossible to call static methods\n"));
} else if (someStatics) {
code = code.append(formatIndented("%-1@classmethod\n"));
}
String name = method.getName();
if(method.isConstructor()) {
name = "__init__";
block = dynamicAttributs + block;
}
code = code.append(formatIndented("%-1def %s(self, *args):%2", name, block));
}
else {
if(method.isConstructor()) {
methodsNames.put(method, "__init__");
}
else {
methodsNames.put(method, method.getName());
}
}
}
}
for(Meth method : classDef.getMethods()) {
if (! method.isMainMethod()) {
+ if (! methodsNames.get(method).equals(method.getName()) && ! methodsNames.get(method).equals("__init__"))
+ code = code.append(formatIndented("\n%-1# used in wrapper '%s'",
+ method.isConstructor()?"__init__":method.getName()));
if (methodsNames.get(method).equals("__init__"))
- code = code.append(formatIndented("%1", printMeth(method, dynamicAttributs)));
+ code = code.append(formatIndented("\n%-1# constructor%1", printMeth(method, dynamicAttributs)));
else
code = code.append(formatIndented("%1", method));
}
}
if (mainMeth != null) {
paramsMethCurrent.clear();
code = code.append(formatIndented("\n# main program\nif __name__ == '__main__':%1",
mainMeth.getBlock().toString().replaceAll("self", classDef.getName())));
}
return code.toString();
}
@Override
public String getCode(TypeChar typeChar) {
return "str";
}
}
| false | true | public String printClass(ClassDef classDef) {
//StringBuilder code = new StringBuilder ("#!/usr/bin/env python\n\nimport goolHelper\n\n");
StringBuilder code = new StringBuilder (String.format("# Platform: %s\n\n", classDef.getPlatform()));
code.append("import goolHelper\n");
Set<String> dependencies = GeneratorHelper.printDependencies(classDef);
if (! dependencies.isEmpty()) {
for (String dependency : dependencies) {
if(!dependency.isEmpty())
if(dependency != "noprint")
code = code.append(String.format("import %s\n", dependency));
}
}
code = code.append(String.format("\nclass %s(%s):\n", classDef.getName(),
(classDef.getParentClass() != null) ? classDef.getParentClass().getName() : "object"));
String dynamicAttributs = "";
for(Field f : classDef.getFields()) {
if (f.getModifiers().contains(Modifier.STATIC))
code = code.append(formatIndented("%1", f));
else
dynamicAttributs += String.format("self.%s\n", f);
}
dynamicAttributs = dynamicAttributs.replaceFirst("\\s*\\z", "\n");
List<Meth> meths = new ArrayList<Meth>();
Meth mainMeth = null;
for(Meth method : classDef.getMethods()) { //On parcourt les méthodes
// the main method will be printed outside of the class later
if (method.isMainMethod()) {
mainMeth = method;
}
// we register all private method to be able to rename them
if (method.getModifiers().contains(Modifier.PRIVATE)) {
privateMeth.add(method.getName());
}
else if(getName(method) == null) { //Si la méthode n'a pas encore été renommée
meths.clear();
for(Meth m : classDef.getMethods()) { //On récupère les méthodes de mêmes noms
if(m.getName().equals(method.getName())) {
meths.add(m);
}
}
if(meths.size()>1) { //Si il y a plusieurs méthodes de même nom
code = code.append(formatIndented("\n%-1# Wrapper generated by GOOL\n"));
String block = "";
String newName = method.getName();
int i = 0;
boolean first = true;
boolean someStatics = false;
boolean someDynamics = false;
for(Meth m2 : meths) {
if (m2.getModifiers().contains(Modifier.STATIC))
someStatics = true;
else
someDynamics = true;
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
while(methodsNames.containsValue(newName)) {
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
}
methodsNames.put(m2, newName);
String types = "";
for(VarDeclaration p : m2.getParams()) {
types += ", " + p.getType();
}
block += formatIndented("%sif goolHelper.test_args(args%s):\n%-1self.%s(*args)\n",
first?"":"el", types, newName);
first = false;
}
if (someStatics && someDynamics) {
code = code.append(formatIndented(
"%-1# GOOL warning: some methods are statics, they can't be used as-is. Rename them.\n"));
} else if (someStatics) {
code = code.append(formatIndented("%-1@classmethod\n"));
}
String name = method.getName();
if(method.isConstructor()) {
name = "__init__";
block = dynamicAttributs + block;
}
code = code.append(formatIndented("%-1def %s(self, *args):%2", name, block));
}
else {
if(method.isConstructor()) {
methodsNames.put(method, "__init__");
}
else {
methodsNames.put(method, method.getName());
}
}
}
}
for(Meth method : classDef.getMethods()) {
if (! method.isMainMethod()) {
if (methodsNames.get(method).equals("__init__"))
code = code.append(formatIndented("%1", printMeth(method, dynamicAttributs)));
else
code = code.append(formatIndented("%1", method));
}
}
if (mainMeth != null) {
paramsMethCurrent.clear();
code = code.append(formatIndented("\n# main program\nif __name__ == '__main__':%1",
mainMeth.getBlock().toString().replaceAll("self", classDef.getName())));
}
return code.toString();
}
| public String printClass(ClassDef classDef) {
//StringBuilder code = new StringBuilder ("#!/usr/bin/env python\n\nimport goolHelper\n\n");
StringBuilder code = new StringBuilder (String.format("# Platform: %s\n\n", classDef.getPlatform()));
code.append("import goolHelper\n");
Set<String> dependencies = GeneratorHelper.printDependencies(classDef);
if (! dependencies.isEmpty()) {
for (String dependency : dependencies) {
if(!dependency.isEmpty())
if(dependency != "noprint")
code = code.append(String.format("import %s\n", dependency));
}
}
code = code.append(String.format("\nclass %s(%s):\n", classDef.getName(),
(classDef.getParentClass() != null) ? classDef.getParentClass().getName() : "object"));
String dynamicAttributs = "";
for(Field f : classDef.getFields()) {
if (f.getModifiers().contains(Modifier.STATIC))
code = code.append(formatIndented("%1", f));
else
dynamicAttributs += String.format("self.%s\n", f);
}
dynamicAttributs = dynamicAttributs.replaceFirst("\\s+\\z", "\n");
List<Meth> meths = new ArrayList<Meth>();
Meth mainMeth = null;
for(Meth method : classDef.getMethods()) { //On parcourt les méthodes
// the main method will be printed outside of the class later
if (method.isMainMethod()) {
mainMeth = method;
}
// we register all private method to be able to rename them
if (method.getModifiers().contains(Modifier.PRIVATE)) {
privateMeth.add(method.getName());
}
else if(getName(method) == null) { //Si la méthode n'a pas encore été renommée
meths.clear();
for(Meth m : classDef.getMethods()) { //On récupère les méthodes de mêmes noms
if(m.getName().equals(method.getName())) {
meths.add(m);
}
}
if(meths.size()>1) { //Si il y a plusieurs méthodes de même nom
code = code.append(formatIndented("\n%-1# wrapper generated by GOOL\n"));
String block = "";
String newName = method.getName();
int i = 0;
boolean first = true;
boolean someStatics = false;
boolean someDynamics = false;
for(Meth m2 : meths) {
if (m2.getModifiers().contains(Modifier.STATIC))
someStatics = true;
else
someDynamics = true;
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
while(methodsNames.containsValue(newName)) {
newName = String.format("__%s_%d", method.getName().replaceFirst("^_*", ""), i++);
}
methodsNames.put(m2, newName);
String types = "";
for(VarDeclaration p : m2.getParams()) {
types += ", " + p.getType();
}
block += formatIndented("%sif goolHelper.test_args(args%s):\n%-1self.%s(*args)\n",
first?"":"el", types, newName);
first = false;
}
if (someStatics && someDynamics) {
code = code.append(formatIndented(
"%-1# GOOL warning: static and dynamic methods under a same wrapper\n" +
"%-1# impossible to call static methods\n"));
} else if (someStatics) {
code = code.append(formatIndented("%-1@classmethod\n"));
}
String name = method.getName();
if(method.isConstructor()) {
name = "__init__";
block = dynamicAttributs + block;
}
code = code.append(formatIndented("%-1def %s(self, *args):%2", name, block));
}
else {
if(method.isConstructor()) {
methodsNames.put(method, "__init__");
}
else {
methodsNames.put(method, method.getName());
}
}
}
}
for(Meth method : classDef.getMethods()) {
if (! method.isMainMethod()) {
if (! methodsNames.get(method).equals(method.getName()) && ! methodsNames.get(method).equals("__init__"))
code = code.append(formatIndented("\n%-1# used in wrapper '%s'",
method.isConstructor()?"__init__":method.getName()));
if (methodsNames.get(method).equals("__init__"))
code = code.append(formatIndented("\n%-1# constructor%1", printMeth(method, dynamicAttributs)));
else
code = code.append(formatIndented("%1", method));
}
}
if (mainMeth != null) {
paramsMethCurrent.clear();
code = code.append(formatIndented("\n# main program\nif __name__ == '__main__':%1",
mainMeth.getBlock().toString().replaceAll("self", classDef.getName())));
}
return code.toString();
}
|
diff --git a/src/java/LGDEditTool/Templates/TemplatesUnmappedTags.java b/src/java/LGDEditTool/Templates/TemplatesUnmappedTags.java
index dbaf39e..f1b4830 100644
--- a/src/java/LGDEditTool/Templates/TemplatesUnmappedTags.java
+++ b/src/java/LGDEditTool/Templates/TemplatesUnmappedTags.java
@@ -1,134 +1,134 @@
/*
* This file is part of LGDEditTool (LGDET).
*
* LGDET is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* LGDET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LGDET. If not, see <http://www.gnu.org/licenses/>.
*/
package LGDEditTool.Templates;
import LGDEditTool.db.DatabaseBremen;
import java.util.ArrayList;
/**
*
* @author Alexander Richter
*/
public class TemplatesUnmappedTags {
//k,usage_count , distinct_value_count
static ArrayList<String> al = new ArrayList<String>();
/**
* template Unmapped Tags
* @param ksite site k-mappings
* @param kvsite site kv-mappings
* @return sitecontent
*/
static public String unmappedTags(String ksite,String kvsite){
String s = new String();
//kmapping table
String tableHead = "\t\t\t\t<h2>List of all Unmapped Tags</h2>\n";
tableHead += "\t\t\t\t<table class=\"table\">\n";
tableHead += "\t\t\t\t\t<tr class=mapping>\n";
tableHead += "\t\t\t\t\t\t<th>k</th>\n";
tableHead += "\t\t\t\t\t\t<th>usage_count</th>\n";
tableHead += "\t\t\t\t\t\t<th>distinct_value_count</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
try{
listAllk(Integer.valueOf(ksite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(ksite)>1){
Integer prevsite=Integer.valueOf(ksite)-1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ prevsite.toString() + "&kvsite="+kvsite+"\"><prev</a> "));
}
Integer nextsite=Integer.valueOf(ksite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ nextsite.toString() + "&kvsite="+kvsite+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
- //kmapping table
+ //kvmapping table
String tableHead2 = "\t\t\t\t<table class=\"table\">\n";
tableHead2 += "\t\t\t\t\t<tr class=mapping>\n";
tableHead2 += "\t\t\t\t\t\t<th>k</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>v</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>dusage_count</th>\n";
tableHead2 += "\t\t\t\t\t</tr>\n";
- al.add(tableHead);
+ al.add(tableHead2);
try{
listAllkv(Integer.valueOf(kvsite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(kvsite)>1){
Integer prevsite=Integer.valueOf(kvsite)-1;
al.add(new String(" \t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+prevsite.toString()+"\"><prev</a> "));
}
Integer nextsite2=Integer.valueOf(kvsite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+nextsite2.toString()+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
for(int i=0;i<al.size();i++){s+=al.get(i);}
al.clear();
return s;
}
static private void listAllk(int ksite) throws Exception {
String s = new String();
DatabaseBremen database = new DatabaseBremen();
database.connect();
Object[][] a = database.execute("SELECT k, usage_count , distinct_value_count FROM lgd_stat_tags_k a WHERE NOT EXISTS (Select b.k FROM ( Select k FROM lgd_map_datatype UNION ALL SELECT k FROM lgd_map_label UNION ALL SELECT k FROM lgd_map_literal UNION ALL SELECT k FROM lgd_map_property UNION ALL SELECT k FROM lgd_map_resource_k UNION ALL SELECT k FROM lgd_map_resource_kv UNION ALL SELECT k FROM lgd_map_resource_prefix ) b WHERE a.k=b.k) LIMIT 20 OFFSET " + (ksite-1)*20);
int count=0;
for (int i=0;i<a.length;i++) {
s += "\t\t\t\t\t<tr>\n";
s += "\t\t\t\t\t<td>"+a[i][0]+"</td>\n";
s += "\t\t\t\t\t<td>"+a[i][1]+"</td>\n";
s += "\t\t\t\t\t<td>"+a[i][2]+"</td>\n";
s += "\t\t\t\t\t</tr>\n";
}
al.add(s);
database.disconnect();
}
static private void listAllkv(int kvsite) throws Exception {
String s = new String();
DatabaseBremen database = new DatabaseBremen();
database.connect();
Object[][] a = database.execute("SELECT k,v, usage_count FROM lgd_stat_tags_kv a WHERE NOT EXISTS (Select b.k FROM ( SELECT k,v FROM lgd_map_label UNION ALL SELECT k,v FROM lgd_map_resource_kv ) b WHERE a.k=b.k) LIMIT 20 OFFSET "+(kvsite-1)*20);
int count=0;
for (int i=0;i<a.length;i++) {
s += "\t\t\t\t\t<tr>\n";
s += "\t\t\t\t\t<td>"+a[i][0]+"</td>\n";
s += "\t\t\t\t\t<td>"+a[i][1]+"</td>\n";
s += "\t\t\t\t\t<td>"+a[i][2]+"</td>\n";
s += "\t\t\t\t\t</tr>\n";
}
al.add(s);
database.disconnect();
}
}
| false | true | static public String unmappedTags(String ksite,String kvsite){
String s = new String();
//kmapping table
String tableHead = "\t\t\t\t<h2>List of all Unmapped Tags</h2>\n";
tableHead += "\t\t\t\t<table class=\"table\">\n";
tableHead += "\t\t\t\t\t<tr class=mapping>\n";
tableHead += "\t\t\t\t\t\t<th>k</th>\n";
tableHead += "\t\t\t\t\t\t<th>usage_count</th>\n";
tableHead += "\t\t\t\t\t\t<th>distinct_value_count</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
try{
listAllk(Integer.valueOf(ksite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(ksite)>1){
Integer prevsite=Integer.valueOf(ksite)-1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ prevsite.toString() + "&kvsite="+kvsite+"\"><prev</a> "));
}
Integer nextsite=Integer.valueOf(ksite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ nextsite.toString() + "&kvsite="+kvsite+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
//kmapping table
String tableHead2 = "\t\t\t\t<table class=\"table\">\n";
tableHead2 += "\t\t\t\t\t<tr class=mapping>\n";
tableHead2 += "\t\t\t\t\t\t<th>k</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>v</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>dusage_count</th>\n";
tableHead2 += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
try{
listAllkv(Integer.valueOf(kvsite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(kvsite)>1){
Integer prevsite=Integer.valueOf(kvsite)-1;
al.add(new String(" \t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+prevsite.toString()+"\"><prev</a> "));
}
Integer nextsite2=Integer.valueOf(kvsite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+nextsite2.toString()+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
for(int i=0;i<al.size();i++){s+=al.get(i);}
al.clear();
return s;
}
| static public String unmappedTags(String ksite,String kvsite){
String s = new String();
//kmapping table
String tableHead = "\t\t\t\t<h2>List of all Unmapped Tags</h2>\n";
tableHead += "\t\t\t\t<table class=\"table\">\n";
tableHead += "\t\t\t\t\t<tr class=mapping>\n";
tableHead += "\t\t\t\t\t\t<th>k</th>\n";
tableHead += "\t\t\t\t\t\t<th>usage_count</th>\n";
tableHead += "\t\t\t\t\t\t<th>distinct_value_count</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
try{
listAllk(Integer.valueOf(ksite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(ksite)>1){
Integer prevsite=Integer.valueOf(ksite)-1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ prevsite.toString() + "&kvsite="+kvsite+"\"><prev</a> "));
}
Integer nextsite=Integer.valueOf(ksite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ nextsite.toString() + "&kvsite="+kvsite+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
//kvmapping table
String tableHead2 = "\t\t\t\t<table class=\"table\">\n";
tableHead2 += "\t\t\t\t\t<tr class=mapping>\n";
tableHead2 += "\t\t\t\t\t\t<th>k</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>v</th>\n";
tableHead2 += "\t\t\t\t\t\t<th>dusage_count</th>\n";
tableHead2 += "\t\t\t\t\t</tr>\n";
al.add(tableHead2);
try{
listAllkv(Integer.valueOf(kvsite));
}catch(Exception e){}
al.add(new String("\t\t\t\t</table>\n<br />"));
//show more
al.add(new String("\t\t\t\t<div style=\"float: right;\">\n"));
if(Integer.valueOf(kvsite)>1){
Integer prevsite=Integer.valueOf(kvsite)-1;
al.add(new String(" \t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+prevsite.toString()+"\"><prev</a> "));
}
Integer nextsite2=Integer.valueOf(kvsite)+1;
al.add(new String("\t\t\t\t\t<a href=\"?tab=unmapped&ksite="+ ksite + "&kvsite="+nextsite2.toString()+"\">next</a>\n"));
al.add(new String("\t\t\t\t</div>\n"));
for(int i=0;i<al.size();i++){s+=al.get(i);}
al.clear();
return s;
}
|
diff --git a/src/org/windycityrails/activities/SponsorDetail.java b/src/org/windycityrails/activities/SponsorDetail.java
index caacc15..5a19685 100644
--- a/src/org/windycityrails/activities/SponsorDetail.java
+++ b/src/org/windycityrails/activities/SponsorDetail.java
@@ -1,57 +1,57 @@
package org.windycityrails.activities;
import org.windycityrails.Constants;
import org.windycityrails.R;
import org.windycityrails.WindyCityRailsApplication;
import org.windycityrails.model.Sponsor;
import org.windycityrails.ui.WebImageView;
import org.windycityrails.util.Network;
import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SponsorDetail extends RoboActivity {
private static final String CLASSTAG = SponsorDetail.class.getSimpleName();
@InjectView(R.id.sponsor_image_detail) private WebImageView logo;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(Constants.LOGTAG, " " + SponsorDetail.CLASSTAG + " onCreate");
WindyCityRailsApplication app = (WindyCityRailsApplication) getApplication();
final Sponsor sponsor = app.getCurrentSponsor();
setContentView(R.layout.sponsor_detail);
TextView name = (TextView) findViewById(R.id.sponsor_name_detail);
name.setText("About " + sponsor.name);
TextView description = (TextView) findViewById(R.id.sponsor_description_detail);
description.setText(sponsor.description);
- Button url = (Button) findViewById(R.id.sponsor_url_detail);
+ TextView url = (TextView) findViewById(R.id.sponsor_website);
url.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse(sponsor.url));
startActivity(i);
}
});
if (Network.isNetworkAvailable(this) && sponsor.logo != null
&& sponsor.logo != "") {
logo.setImageUrl(sponsor.logo);
logo.loadImage();
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(Constants.LOGTAG, " " + SponsorDetail.CLASSTAG + " onCreate");
WindyCityRailsApplication app = (WindyCityRailsApplication) getApplication();
final Sponsor sponsor = app.getCurrentSponsor();
setContentView(R.layout.sponsor_detail);
TextView name = (TextView) findViewById(R.id.sponsor_name_detail);
name.setText("About " + sponsor.name);
TextView description = (TextView) findViewById(R.id.sponsor_description_detail);
description.setText(sponsor.description);
Button url = (Button) findViewById(R.id.sponsor_url_detail);
url.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse(sponsor.url));
startActivity(i);
}
});
if (Network.isNetworkAvailable(this) && sponsor.logo != null
&& sponsor.logo != "") {
logo.setImageUrl(sponsor.logo);
logo.loadImage();
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(Constants.LOGTAG, " " + SponsorDetail.CLASSTAG + " onCreate");
WindyCityRailsApplication app = (WindyCityRailsApplication) getApplication();
final Sponsor sponsor = app.getCurrentSponsor();
setContentView(R.layout.sponsor_detail);
TextView name = (TextView) findViewById(R.id.sponsor_name_detail);
name.setText("About " + sponsor.name);
TextView description = (TextView) findViewById(R.id.sponsor_description_detail);
description.setText(sponsor.description);
TextView url = (TextView) findViewById(R.id.sponsor_website);
url.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse(sponsor.url));
startActivity(i);
}
});
if (Network.isNetworkAvailable(this) && sponsor.logo != null
&& sponsor.logo != "") {
logo.setImageUrl(sponsor.logo);
logo.loadImage();
}
}
|
diff --git a/template/source/Template.java b/template/source/Template.java
index 8dd834a..fabd1d5 100644
--- a/template/source/Template.java
+++ b/template/source/Template.java
@@ -1,149 +1,149 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class Template {
private static final String INPUT = null; // override to use a specific input (i.e. "small-1", "large-2", "sample", "stdin").
public static void main(String[] args) throws Exception {
new Template().run();
}
private final PrintStream out;
private final BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public Template() throws Exception {
String problem = getClass().getSimpleName();
if (INPUT == null) {
File input = findInput(problem);
if (input == null) {
throw new IOException("No input file found");
}
File output = new File(input.getParent(), input.getName().replace(".in", ".out"));
System.err.println("input: " + input.getPath());
System.err.println("output: " + output.getPath());
out = new PrintStream(new FileOutputStream(output));
reader = new BufferedReader(new FileReader(input));
} else if (INPUT.equals("stdin")) {
System.err.println("input: stdin");
System.err.println("output: stdout");
out = System.out;
reader = new BufferedReader(new InputStreamReader(System.in));
} else {
System.err.println("input: " + problem + "-" + INPUT + ".in");
System.err.println("output: " + problem + "-" + INPUT + ".out");
- out = new PrintStream(new FileOutputStream(problem + "-" + INPUT + ".out"));
- reader = new BufferedReader(new FileReader(problem + "-" + INPUT + ".in"));
+ out = new PrintStream(new FileOutputStream("source/" + problem + "-" + INPUT + ".out"));
+ reader = new BufferedReader(new FileReader("source/" + problem + "-" + INPUT + ".in"));
}
}
public static File findInput(String problem) throws Exception {
File dir = new File("source");
long bestTimestamp = -1;
File bestFile = null;
for (File file : dir.listFiles()) {
if (file.getName().startsWith(problem + "-") && file.getName().endsWith(".in")) {
long timestamp = file.lastModified();
if (timestamp > bestTimestamp) {
bestTimestamp = timestamp;
bestFile = file;
}
}
}
return bestFile;
}
public void run() {
try {
runCases();
} finally {
out.close();
}
}
public void debug(String s, Object... args) {
System.err.printf("DEBUG: " + s + "\n", args);
}
private void runCases() {
try {
int cases = getInt();
for (int c = 1; c <= cases; c++) {
try {
String answer = new Solver(c).solve();
String s = "Case #" + c + ": " + answer;
out.println(s);
if (out != System.out) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
debug("done with all!");
}
}
public String readLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getToken() {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s, " \t\n\r");
}
}
public double getDouble() {
return Double.parseDouble(getToken());
}
public int getInt() {
return Integer.parseInt(getToken());
}
public long getLong() {
return Long.parseLong(getToken());
}
public BigInteger getBigInt() {
return new BigInteger(getToken());
}
public BigDecimal getBigDec() {
return new BigDecimal(getToken());
}
public class Solver {
private final int caseNumber;
public Solver(int caseNumber) {
this.caseNumber = caseNumber;
}
public String solve() throws Exception {
debug("solving case %d", caseNumber);
return "not implemented";
}
}
}
| true | true | public Template() throws Exception {
String problem = getClass().getSimpleName();
if (INPUT == null) {
File input = findInput(problem);
if (input == null) {
throw new IOException("No input file found");
}
File output = new File(input.getParent(), input.getName().replace(".in", ".out"));
System.err.println("input: " + input.getPath());
System.err.println("output: " + output.getPath());
out = new PrintStream(new FileOutputStream(output));
reader = new BufferedReader(new FileReader(input));
} else if (INPUT.equals("stdin")) {
System.err.println("input: stdin");
System.err.println("output: stdout");
out = System.out;
reader = new BufferedReader(new InputStreamReader(System.in));
} else {
System.err.println("input: " + problem + "-" + INPUT + ".in");
System.err.println("output: " + problem + "-" + INPUT + ".out");
out = new PrintStream(new FileOutputStream(problem + "-" + INPUT + ".out"));
reader = new BufferedReader(new FileReader(problem + "-" + INPUT + ".in"));
}
}
| public Template() throws Exception {
String problem = getClass().getSimpleName();
if (INPUT == null) {
File input = findInput(problem);
if (input == null) {
throw new IOException("No input file found");
}
File output = new File(input.getParent(), input.getName().replace(".in", ".out"));
System.err.println("input: " + input.getPath());
System.err.println("output: " + output.getPath());
out = new PrintStream(new FileOutputStream(output));
reader = new BufferedReader(new FileReader(input));
} else if (INPUT.equals("stdin")) {
System.err.println("input: stdin");
System.err.println("output: stdout");
out = System.out;
reader = new BufferedReader(new InputStreamReader(System.in));
} else {
System.err.println("input: " + problem + "-" + INPUT + ".in");
System.err.println("output: " + problem + "-" + INPUT + ".out");
out = new PrintStream(new FileOutputStream("source/" + problem + "-" + INPUT + ".out"));
reader = new BufferedReader(new FileReader("source/" + problem + "-" + INPUT + ".in"));
}
}
|
diff --git a/webui/portal/src/main/java/org/exoplatform/portal/webui/page/UIPageActionListener.java b/webui/portal/src/main/java/org/exoplatform/portal/webui/page/UIPageActionListener.java
index de8427e3a..a65164312 100644
--- a/webui/portal/src/main/java/org/exoplatform/portal/webui/page/UIPageActionListener.java
+++ b/webui/portal/src/main/java/org/exoplatform/portal/webui/page/UIPageActionListener.java
@@ -1,383 +1,385 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.portal.webui.page;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.config.DataStorage;
import org.exoplatform.portal.config.UserPortalConfig;
import org.exoplatform.portal.config.model.Container;
import org.exoplatform.portal.config.model.ModelObject;
import org.exoplatform.portal.config.model.Page;
import org.exoplatform.portal.config.model.PageNavigation;
import org.exoplatform.portal.config.model.PageNode;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.portal.webui.application.UIGadget;
import org.exoplatform.portal.webui.portal.PageNodeEvent;
import org.exoplatform.portal.webui.portal.UIPortal;
import org.exoplatform.portal.webui.util.PortalDataMapper;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.portal.webui.workspace.UIPortalApplication;
import org.exoplatform.portal.webui.workspace.UIWorkingWorkspace;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.core.UIComponent;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import java.util.ArrayList;
import java.util.List;
/**
* Created by The eXo Platform SAS Author : Tran The Trong [email protected] Jun
* 14, 2006
*/
public class UIPageActionListener
{
static public class ChangePageNodeActionListener extends EventListener<UIPortal>
{
@Override
public void execute(Event<UIPortal> event) throws Exception
{
UIPortal showedUIPortal = event.getSource();
UIPortalApplication uiPortalApp = showedUIPortal.getAncestorOfType(UIPortalApplication.class);
//This code snippet is to make sure that Javascript/Skin is fully loaded at the first request
UIWorkingWorkspace uiWorkingWS = uiPortalApp.getChildById(UIPortalApplication.UI_WORKING_WS_ID);
PortalRequestContext pcontext = Util.getPortalRequestContext();
pcontext.addUIComponentToUpdateByAjax(uiWorkingWS);
- uiWorkingWS.setRenderedChild(UIPortalApplication.UI_VIEWING_WS_ID);
- pcontext.setFullRender(true);
PageNavigation currentNav = showedUIPortal.getSelectedNavigation();
String currentUri = showedUIPortal.getSelectedNode().getUri();
if(currentUri.startsWith("/"))
{
currentUri = currentUri.substring(1);
}
//This if branche is to make sure that the first time user logs in, showedUIPortal has selectedPaths
//Otherwise, there will be NPE on BreadcumbsPortlet
if(showedUIPortal.getSelectedPath() == null)
{
List<PageNode> currentSelectedPath = findPath(currentNav, currentUri.split("/"));
showedUIPortal.setSelectedPath(currentSelectedPath);
}
String targetedUri = ((PageNodeEvent<UIPortal>)event).getTargetNodeUri();
if(targetedUri.startsWith("/"))
{
targetedUri = targetedUri.substring(1);
}
PageNavigation targetedNav = getTargetedNav(uiPortalApp, targetedUri);
if(targetedNav == null)
{
return;
}
String formerNavType = currentNav.getOwnerType();
String formerNavId = currentNav.getOwnerId();
String newNavType = targetedNav.getOwnerType();
String newNavId = targetedNav.getOwnerId();
String[] targetPath = targetedUri.split("/");
PageNode targetPageNode = getTargetedNode(targetedNav, targetPath);
List<PageNode> targetedPathNodes = findPath(targetedNav, targetPath);
if(formerNavType.equals(newNavType) && formerNavId.equals(newNavId))
{
//Case 1: Both navigation type and id are not changed, but current page node is changed
if(!currentUri.equals(targetedUri))
{
showedUIPortal.setSelectedNode(targetPageNode);
showedUIPortal.setSelectedPath(targetedPathNodes);
showedUIPortal.refreshUIPage();
+ pcontext.setFullRender(true);
return;
}
}
else
{
// Case 2: Either navigation type or id has been changed
// First, we try to find a cached UIPortal
+ uiWorkingWS.setRenderedChild(UIPortalApplication.UI_VIEWING_WS_ID);
+ uiPortalApp.setModeState(UIPortalApplication.NORMAL_MODE);
+ pcontext.setFullRender(true);
UIPortal cachedUIPortal = uiPortalApp.getCachedUIPortal(newNavType, newNavId);
if (cachedUIPortal != null)
{
// System.out.println("Found UIPortal with OWNERTYPE: " + newNavType + " OWNERID " + newNavId);
cachedUIPortal.setSelectedNode(targetPageNode);
cachedUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(cachedUIPortal);
//Temporary solution to fix edit inline error while switching between navigations
DataStorage storageService = uiPortalApp.getApplicationComponent(DataStorage.class);
PortalConfig associatedPortalConfig = storageService.getPortalConfig(newNavType, newNavId);
uiPortalApp.getUserPortalConfig().setPortal(associatedPortalConfig);
cachedUIPortal.refreshUIPage();
return;
}
else
{
UIPortal newUIPortal = buildUIPortal(targetedNav, uiPortalApp, uiPortalApp.getUserPortalConfig());
if(newUIPortal == null)
{
return;
}
newUIPortal.setSelectedNode(targetPageNode);
newUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(newUIPortal);
uiPortalApp.addUIPortal(newUIPortal);
newUIPortal.refreshUIPage();
return;
}
}
}
/**
* Get the targeted <code>PageNavigation</code>
*
* @param uiPortalApp
* @param targetedUri
* @return
*/
private PageNavigation getTargetedNav(UIPortalApplication uiPortalApp, String targetedUri)
{
List<PageNavigation> allNavs = uiPortalApp.getUserPortalConfig().getNavigations();
//That happens when user browses to an empty-nodeUri URL like ../portal/public/classic/
//In this case, we returns default navigation
if(targetedUri.length() == 0)
{
return uiPortalApp.getNavigations().get(0);
}
String[] pathNodes = targetedUri.split("/");
//We check the first navigation in the list containing all descendants corresponding to pathNodes
for(PageNavigation nav : allNavs)
{
if(containingDescendantNodes(nav, pathNodes))
{
return nav;
}
}
return null;
}
/**
* Check if a given <code>PageNavigation</code> contains all the descendants corresponding to the pathNodes
*
* @param navigation
* @param pathNodes
* @return
*/
private static boolean containingDescendantNodes(PageNavigation navigation, String[] pathNodes)
{
PageNode firstLevelNode = navigation.getNode(pathNodes[0]);
if(firstLevelNode == null)
{
return false;
}
//Recursive code snippet with two variables
PageNode tempNode = firstLevelNode;
PageNode currentNode;
for(int i = 1; i < pathNodes.length; i++)
{
currentNode = tempNode.getChild(pathNodes[i]);
//If the navigation does not support an intermediate pathNode, then returns false
if (currentNode == null)
{
return false;
}
else
{
tempNode = currentNode;
}
}
return true;
}
/**
* Fetch the currently selected pageNode under a PageNavigation. It is the last node encountered
* while descending the pathNodes
*
* @param targetedNav
* @param pathNodes
* @return
*/
private static PageNode getTargetedNode(PageNavigation targetedNav, String[] pathNodes)
{
//Case users browses to a URL of the form */portal/public/classic
if(pathNodes.length == 0)
{
return targetedNav.getNodes().get(0);
}
PageNode currentNode = targetedNav.getNode(pathNodes[0]);
PageNode tempNode = null;
for(int i = 1; i < pathNodes.length; i++)
{
tempNode = currentNode.getChild(pathNodes[i]);
if (tempNode == null)
{
return null;
}
else
{
currentNode = tempNode;
}
}
return currentNode;
}
private static List<PageNode> findPath(PageNavigation nav, String[] pathNodes)
{
List<PageNode> nodes = new ArrayList<PageNode>(4);
//That happens when user browses to a URL like */portal/public/classic
if(pathNodes.length == 0)
{
nodes.add(nav.getNodes().get(0));
return nodes;
}
PageNode startNode = nav.getNode(pathNodes[0]);
if (startNode == null)
{
return nodes;
}
nodes.add(startNode);
for (int i = 1; i < pathNodes.length; i++)
{
startNode = startNode.getChild(pathNodes[i]);
if (startNode == null)
{
return nodes;
}
else
{
nodes.add(startNode);
}
}
return nodes;
}
private static UIPortal buildUIPortal(PageNavigation newPageNav, UIPortalApplication uiPortalApp, UserPortalConfig userPortalConfig) throws Exception
{
DataStorage storage = uiPortalApp.getApplicationComponent(DataStorage.class);
if(storage == null){
return null;
}
PortalConfig portalConfig = storage.getPortalConfig(newPageNav.getOwnerType(), newPageNav.getOwnerId());
Container layout = portalConfig.getPortalLayout();
if(layout != null)
{
userPortalConfig.setPortal(portalConfig);
}
UIPortal uiPortal = uiPortalApp.createUIComponent(UIPortal.class, null, null);
//Reset selected navigation on userPortalConfig
userPortalConfig.setSelectedNavigation(newPageNav);
// System.out.println("Build new UIPortal with OWNERTYPE: " + newPageNav.getOwnerType() + " OWNERID: " + newPageNav.getOwnerId());
PortalDataMapper.toUIPortal(uiPortal, userPortalConfig);
return uiPortal;
}
}
static public class DeleteGadgetActionListener extends EventListener<UIPage>
{
public void execute(Event<UIPage> event) throws Exception
{
WebuiRequestContext pContext = event.getRequestContext();
String id = pContext.getRequestParameter(UIComponent.OBJECTID);
UIPage uiPage = event.getSource();
List<UIGadget> uiWidgets = new ArrayList<UIGadget>();
uiPage.findComponentOfType(uiWidgets, UIGadget.class);
for (UIGadget uiWidget : uiWidgets)
{
if (uiWidget.getId().equals(id))
{
uiPage.getChildren().remove(uiWidget);
String userName = pContext.getRemoteUser();
if (userName != null && userName.trim().length() > 0)
{
// Julien : commented as normally removing the gadget should
// remove the state associated with it
// in the MOP
// UserGadgetStorage widgetDataService =
// uiPage.getApplicationComponent(UserGadgetStorage.class) ;
// widgetDataService.delete(userName,
// uiWidget.getApplicationName(), uiWidget.getId()) ;
}
if (uiPage.isModifiable())
{
Page page = (Page)PortalDataMapper.buildModelObject(uiPage);
if (page.getChildren() == null)
{
page.setChildren(new ArrayList<ModelObject>());
}
DataStorage dataService = uiPage.getApplicationComponent(DataStorage.class);
dataService.save(page);
}
break;
}
}
PortalRequestContext pcontext = (PortalRequestContext)event.getRequestContext();
pcontext.setFullRender(false);
pcontext.setResponseComplete(true);
pcontext.getWriter().write(EventListener.RESULT_OK);
}
}
static public class RemoveChildActionListener extends EventListener<UIPage>
{
public void execute(Event<UIPage> event) throws Exception
{
UIPage uiPage = event.getSource();
String id = event.getRequestContext().getRequestParameter(UIComponent.OBJECTID);
PortalRequestContext pcontext = (PortalRequestContext)event.getRequestContext();
if (uiPage.isModifiable())
{
uiPage.removeChildById(id);
Page page = (Page)PortalDataMapper.buildModelObject(uiPage);
if (page.getChildren() == null)
{
page.setChildren(new ArrayList<ModelObject>());
}
DataStorage dataService = uiPage.getApplicationComponent(DataStorage.class);
dataService.save(page);
pcontext.setFullRender(false);
pcontext.setResponseComplete(true);
pcontext.getWriter().write(EventListener.RESULT_OK);
}
else
{
org.exoplatform.webui.core.UIApplication uiApp = pcontext.getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIPage.msg.EditPermission.null", null));
}
}
}
}
| false | true | public void execute(Event<UIPortal> event) throws Exception
{
UIPortal showedUIPortal = event.getSource();
UIPortalApplication uiPortalApp = showedUIPortal.getAncestorOfType(UIPortalApplication.class);
//This code snippet is to make sure that Javascript/Skin is fully loaded at the first request
UIWorkingWorkspace uiWorkingWS = uiPortalApp.getChildById(UIPortalApplication.UI_WORKING_WS_ID);
PortalRequestContext pcontext = Util.getPortalRequestContext();
pcontext.addUIComponentToUpdateByAjax(uiWorkingWS);
uiWorkingWS.setRenderedChild(UIPortalApplication.UI_VIEWING_WS_ID);
pcontext.setFullRender(true);
PageNavigation currentNav = showedUIPortal.getSelectedNavigation();
String currentUri = showedUIPortal.getSelectedNode().getUri();
if(currentUri.startsWith("/"))
{
currentUri = currentUri.substring(1);
}
//This if branche is to make sure that the first time user logs in, showedUIPortal has selectedPaths
//Otherwise, there will be NPE on BreadcumbsPortlet
if(showedUIPortal.getSelectedPath() == null)
{
List<PageNode> currentSelectedPath = findPath(currentNav, currentUri.split("/"));
showedUIPortal.setSelectedPath(currentSelectedPath);
}
String targetedUri = ((PageNodeEvent<UIPortal>)event).getTargetNodeUri();
if(targetedUri.startsWith("/"))
{
targetedUri = targetedUri.substring(1);
}
PageNavigation targetedNav = getTargetedNav(uiPortalApp, targetedUri);
if(targetedNav == null)
{
return;
}
String formerNavType = currentNav.getOwnerType();
String formerNavId = currentNav.getOwnerId();
String newNavType = targetedNav.getOwnerType();
String newNavId = targetedNav.getOwnerId();
String[] targetPath = targetedUri.split("/");
PageNode targetPageNode = getTargetedNode(targetedNav, targetPath);
List<PageNode> targetedPathNodes = findPath(targetedNav, targetPath);
if(formerNavType.equals(newNavType) && formerNavId.equals(newNavId))
{
//Case 1: Both navigation type and id are not changed, but current page node is changed
if(!currentUri.equals(targetedUri))
{
showedUIPortal.setSelectedNode(targetPageNode);
showedUIPortal.setSelectedPath(targetedPathNodes);
showedUIPortal.refreshUIPage();
return;
}
}
else
{
// Case 2: Either navigation type or id has been changed
// First, we try to find a cached UIPortal
UIPortal cachedUIPortal = uiPortalApp.getCachedUIPortal(newNavType, newNavId);
if (cachedUIPortal != null)
{
// System.out.println("Found UIPortal with OWNERTYPE: " + newNavType + " OWNERID " + newNavId);
cachedUIPortal.setSelectedNode(targetPageNode);
cachedUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(cachedUIPortal);
//Temporary solution to fix edit inline error while switching between navigations
DataStorage storageService = uiPortalApp.getApplicationComponent(DataStorage.class);
PortalConfig associatedPortalConfig = storageService.getPortalConfig(newNavType, newNavId);
uiPortalApp.getUserPortalConfig().setPortal(associatedPortalConfig);
cachedUIPortal.refreshUIPage();
return;
}
else
{
UIPortal newUIPortal = buildUIPortal(targetedNav, uiPortalApp, uiPortalApp.getUserPortalConfig());
if(newUIPortal == null)
{
return;
}
newUIPortal.setSelectedNode(targetPageNode);
newUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(newUIPortal);
uiPortalApp.addUIPortal(newUIPortal);
newUIPortal.refreshUIPage();
return;
}
}
}
| public void execute(Event<UIPortal> event) throws Exception
{
UIPortal showedUIPortal = event.getSource();
UIPortalApplication uiPortalApp = showedUIPortal.getAncestorOfType(UIPortalApplication.class);
//This code snippet is to make sure that Javascript/Skin is fully loaded at the first request
UIWorkingWorkspace uiWorkingWS = uiPortalApp.getChildById(UIPortalApplication.UI_WORKING_WS_ID);
PortalRequestContext pcontext = Util.getPortalRequestContext();
pcontext.addUIComponentToUpdateByAjax(uiWorkingWS);
PageNavigation currentNav = showedUIPortal.getSelectedNavigation();
String currentUri = showedUIPortal.getSelectedNode().getUri();
if(currentUri.startsWith("/"))
{
currentUri = currentUri.substring(1);
}
//This if branche is to make sure that the first time user logs in, showedUIPortal has selectedPaths
//Otherwise, there will be NPE on BreadcumbsPortlet
if(showedUIPortal.getSelectedPath() == null)
{
List<PageNode> currentSelectedPath = findPath(currentNav, currentUri.split("/"));
showedUIPortal.setSelectedPath(currentSelectedPath);
}
String targetedUri = ((PageNodeEvent<UIPortal>)event).getTargetNodeUri();
if(targetedUri.startsWith("/"))
{
targetedUri = targetedUri.substring(1);
}
PageNavigation targetedNav = getTargetedNav(uiPortalApp, targetedUri);
if(targetedNav == null)
{
return;
}
String formerNavType = currentNav.getOwnerType();
String formerNavId = currentNav.getOwnerId();
String newNavType = targetedNav.getOwnerType();
String newNavId = targetedNav.getOwnerId();
String[] targetPath = targetedUri.split("/");
PageNode targetPageNode = getTargetedNode(targetedNav, targetPath);
List<PageNode> targetedPathNodes = findPath(targetedNav, targetPath);
if(formerNavType.equals(newNavType) && formerNavId.equals(newNavId))
{
//Case 1: Both navigation type and id are not changed, but current page node is changed
if(!currentUri.equals(targetedUri))
{
showedUIPortal.setSelectedNode(targetPageNode);
showedUIPortal.setSelectedPath(targetedPathNodes);
showedUIPortal.refreshUIPage();
pcontext.setFullRender(true);
return;
}
}
else
{
// Case 2: Either navigation type or id has been changed
// First, we try to find a cached UIPortal
uiWorkingWS.setRenderedChild(UIPortalApplication.UI_VIEWING_WS_ID);
uiPortalApp.setModeState(UIPortalApplication.NORMAL_MODE);
pcontext.setFullRender(true);
UIPortal cachedUIPortal = uiPortalApp.getCachedUIPortal(newNavType, newNavId);
if (cachedUIPortal != null)
{
// System.out.println("Found UIPortal with OWNERTYPE: " + newNavType + " OWNERID " + newNavId);
cachedUIPortal.setSelectedNode(targetPageNode);
cachedUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(cachedUIPortal);
//Temporary solution to fix edit inline error while switching between navigations
DataStorage storageService = uiPortalApp.getApplicationComponent(DataStorage.class);
PortalConfig associatedPortalConfig = storageService.getPortalConfig(newNavType, newNavId);
uiPortalApp.getUserPortalConfig().setPortal(associatedPortalConfig);
cachedUIPortal.refreshUIPage();
return;
}
else
{
UIPortal newUIPortal = buildUIPortal(targetedNav, uiPortalApp, uiPortalApp.getUserPortalConfig());
if(newUIPortal == null)
{
return;
}
newUIPortal.setSelectedNode(targetPageNode);
newUIPortal.setSelectedPath(targetedPathNodes);
uiPortalApp.setShowedUIPortal(newUIPortal);
uiPortalApp.addUIPortal(newUIPortal);
newUIPortal.refreshUIPage();
return;
}
}
}
|
diff --git a/src/jumble/fast/SeanResultPrinter.java b/src/jumble/fast/SeanResultPrinter.java
index 00ad09a..c9619e4 100644
--- a/src/jumble/fast/SeanResultPrinter.java
+++ b/src/jumble/fast/SeanResultPrinter.java
@@ -1,76 +1,76 @@
package jumble.fast;
import java.io.PrintStream;
import jumble.Mutation;
/**
* Class outputting jumble results in Sean's original jumble format
*
* @author Tin Pavlinic
* @version $Revision$
*/
public class SeanResultPrinter extends AbstractResultPrinter {
/**
* Constructor.
*
* @param p
* the output stream to print to.
*/
public SeanResultPrinter(PrintStream p) {
super(p);
}
/**
* Displays the result.
*
* @param res
* the Jumble result to print
* @throws Exception if something goes wrong
*/
public void printResult(JumbleResult res) throws Exception {
PrintStream out = getStream();
out.println("Mutating " + res.getClassName());
- if (Class.forName(res.getClassName()).isInterface()) {
+ if (res.isInterface()) {
out.println("Score: 100 (INTERFACE)");
return;
}
String[] testClasses = res.getTestClasses();
out.print("Tests: ");
for (int i = 0; i < testClasses.length; i++) {
out.print((i == 0 ? "" : ", ") + testClasses[i]);
}
out.println();
if (!res.getInitialTestResult().wasSuccessful()) {
out.println("Score: 0 (TEST CLASS IS BROKEN)");
return;
}
out.print("Mutation points = " + res.getAllMutations().length);
out.println(", unit test time limit " + (double) res.getTimeoutLength()
/ 1000 + "s");
for (int i = 0; i < res.getAllMutations().length; i++) {
Mutation currentMutation = res.getAllMutations()[i];
if (currentMutation.isPassed()) {
out.print(".");
} else if (currentMutation.isTimedOut()) {
out.print("T");
} else {
out.println("M " + currentMutation.getDescription());
}
}
out.println();
if (res.getAllMutations().length == 0) {
out.println("Score: 100 (NO MUTATIONS POSSIBLE)");
} else {
out.println("Score: " + res.getCovered().length
* 100 / res.getAllMutations().length);
}
}
}
| true | true | public void printResult(JumbleResult res) throws Exception {
PrintStream out = getStream();
out.println("Mutating " + res.getClassName());
if (Class.forName(res.getClassName()).isInterface()) {
out.println("Score: 100 (INTERFACE)");
return;
}
String[] testClasses = res.getTestClasses();
out.print("Tests: ");
for (int i = 0; i < testClasses.length; i++) {
out.print((i == 0 ? "" : ", ") + testClasses[i]);
}
out.println();
if (!res.getInitialTestResult().wasSuccessful()) {
out.println("Score: 0 (TEST CLASS IS BROKEN)");
return;
}
out.print("Mutation points = " + res.getAllMutations().length);
out.println(", unit test time limit " + (double) res.getTimeoutLength()
/ 1000 + "s");
for (int i = 0; i < res.getAllMutations().length; i++) {
Mutation currentMutation = res.getAllMutations()[i];
if (currentMutation.isPassed()) {
out.print(".");
} else if (currentMutation.isTimedOut()) {
out.print("T");
} else {
out.println("M " + currentMutation.getDescription());
}
}
out.println();
if (res.getAllMutations().length == 0) {
out.println("Score: 100 (NO MUTATIONS POSSIBLE)");
} else {
out.println("Score: " + res.getCovered().length
* 100 / res.getAllMutations().length);
}
}
| public void printResult(JumbleResult res) throws Exception {
PrintStream out = getStream();
out.println("Mutating " + res.getClassName());
if (res.isInterface()) {
out.println("Score: 100 (INTERFACE)");
return;
}
String[] testClasses = res.getTestClasses();
out.print("Tests: ");
for (int i = 0; i < testClasses.length; i++) {
out.print((i == 0 ? "" : ", ") + testClasses[i]);
}
out.println();
if (!res.getInitialTestResult().wasSuccessful()) {
out.println("Score: 0 (TEST CLASS IS BROKEN)");
return;
}
out.print("Mutation points = " + res.getAllMutations().length);
out.println(", unit test time limit " + (double) res.getTimeoutLength()
/ 1000 + "s");
for (int i = 0; i < res.getAllMutations().length; i++) {
Mutation currentMutation = res.getAllMutations()[i];
if (currentMutation.isPassed()) {
out.print(".");
} else if (currentMutation.isTimedOut()) {
out.print("T");
} else {
out.println("M " + currentMutation.getDescription());
}
}
out.println();
if (res.getAllMutations().length == 0) {
out.println("Score: 100 (NO MUTATIONS POSSIBLE)");
} else {
out.println("Score: " + res.getCovered().length
* 100 / res.getAllMutations().length);
}
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index 3fb497a..c8c560f 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,382 +1,382 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
// Leave data urls alone to increase parse performance.
protected String extractDataUrls(String css, ArrayList preservedTokens) {
int maxIndex = css.length() - 1;
int appendIndex = 0;
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("url\\(\\s*([\"']?)data\\:");
Matcher m = p.matcher(css);
/*
* Since we need to account for non-base64 data urls, we need to handle
* ' and ) being part of the data string. Hence switching to indexOf,
* to determine whether or not we have matching string terminators and
* handling sb appends directly, instead of using matcher.append* methods.
*/
while (m.find()) {
int startIndex = m.start() + 4; // "url(".length()
String terminator = m.group(1); // ', " or empty (not quoted)
if (terminator.length() == 0) {
terminator = ")";
}
boolean foundTerminator = false;
int endIndex = m.end() - 1;
while(foundTerminator == false && endIndex+1 <= maxIndex) {
endIndex = css.indexOf(terminator, endIndex+1);
if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) {
foundTerminator = true;
if (!")".equals(terminator)) {
endIndex = css.indexOf(")", endIndex);
}
}
}
// Enough searching, start moving stuff over to the buffer
sb.append(css.substring(appendIndex, m.start()));
if (foundTerminator) {
String token = css.substring(startIndex, endIndex);
token = token.replaceAll("\\s+", "");
preservedTokens.add(token);
String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)";
sb.append(preserver);
appendIndex = endIndex + 1;
} else {
// No end terminator found, re-add the whole match. Should we throw/warn here?
sb.append(css.substring(m.start(), m.end()));
appendIndex = m.end();
}
}
sb.append(css.substring(appendIndex));
return sb.toString();
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
- p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
+ p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| true | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/src/es/jafs/jaiberdroid/QueryManager.java b/src/es/jafs/jaiberdroid/QueryManager.java
index 873bc85..2396d04 100644
--- a/src/es/jafs/jaiberdroid/QueryManager.java
+++ b/src/es/jafs/jaiberdroid/QueryManager.java
@@ -1,312 +1,312 @@
package es.jafs.jaiberdroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Class that execute and control the querys.
* @author Jose Antonio Fuentes Santiago
* @version 0.5
* @todo This class must receive only one query method, and analyzes whats method call.
*/
final class QueryManager extends SQLiteOpenHelper {
/** Database version. */
private static int version = 0;
/** Database name. */
private static String name = "";
/** Instance of Entity Manager. */
private EntityManager entityManager;
/**
* Default constructor of the class.
* @throws JaiberdroidException
*/
public QueryManager(final Context context, final EntityManager entityManager) throws JaiberdroidException {
super(context, name, null, version);
this.entityManager = entityManager;
}
/**
* Called when the database is created for the first time.
* @param database The database
*/
@Override
public void onCreate(final SQLiteDatabase database) {
if (!executeUpdates(entityManager.getCreateQueries(), true, database)) {
Log.e(JaiberdroidInstance.LOG_TAG, "Problem creating database.");
}
}
/**
* Called when the database needs to be upgraded. This method executes within a transaction. If an
* exception is thrown, all changes will automatically be rolled back.
* @param database The database.
* @param oldVersion Old version id.
* @param newVersion New version id.
*/
@Override
public void onUpgrade(final SQLiteDatabase database, final int oldVersion, final int newVersion) {
// The false value in if executeUpdates call, is because this method creates automatically a
// transaction.
if (!executeUpdates(entityManager.getDropQueries(), false, database)) {
Log.e(JaiberdroidInstance.LOG_TAG, "Problem upgrading database.");
}
onCreate(database);
}
/**
* Executes an update with received query.
* @param query Query to execute.
* @return Number of rows affected. -1 if there an error.
* @throws JaiberdroidException
*/
public long executeUpdate(final Query query) throws JaiberdroidException {
long rows = -1;
try {
final SQLiteDatabase database = getWritableDatabase();
if (query.isTransactional()) {
database.beginTransaction();
}
switch (query.getType()) {
// Inserts a value into the database.
case INSERT:
// Returns the row id of inserted data.
rows = (int) database.insert(query.getEntity().getTableName(), null, query.getValues());
if (-1 != rows) {
JaiberdroidReflection.executeSetMethod(JaiberdroidReflection.SET_ID, query.getObject(),
int.class, (int) rows);
rows = 1; // Affected 1 row.
}
break;
// Updates existing values into database.
case UPDATE:
rows = database.update(query.getEntity().getTableName(), query.getValues(),
query.getCondition(), query.getArgsArray());
break;
// Delete values of database.
case DELETE:
- database.delete(query.getEntity().getTableName(), query.getCondition(),
- query.getArgsArray());
+ rows = database.delete(query.getEntity().getTableName(), query.getCondition(),
+ query.getArgsArray());
break;
default:
- Log.d(JaiberdroidInstance.LOG_TAG, "Only Insert, Update, Delete are supported");
+ Log.w(JaiberdroidInstance.LOG_TAG, "Only Insert, Update, Delete are supported");
}
if (database.inTransaction()) {
if (rows != -1) {
database.setTransactionSuccessful();
}
database.endTransaction();
}
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing update: " + e.getMessage(), e);
throw new JaiberdroidException("Executing SQL" + e.getMessage());
}
return rows;
}
/**
* Execute a query in database.
* @param query String with query to execute.
* @param transaction Boolean value that sets if the queries are executed in transacction.
* @param database Database into execute queries.
* @return Boolean value that indicates if all it's ok.
*/
public void executeUpdate(final String query, final SQLiteDatabase database) throws SQLException {
database.execSQL(query);
}
/**
* Execute a list of queries in database.
* @param database Database into execute queries.
* @param queries List of String with queries to execute.
* @param transaction Boolean value that sets if the queries are executed in transacction.
*/
private boolean executeUpdates(final List<String> queries, final boolean transaction,
final SQLiteDatabase database) {
boolean ok = false;
if (null != queries) {
try {
if (transaction) {
database.beginTransaction();
}
try {
for (String query : queries) {
executeUpdate(query, database);
}
if (database.inTransaction()) {
database.setTransactionSuccessful();
}
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing SQL: " + e.getMessage(), e);
}
if (database.inTransaction()) {
database.endTransaction();
}
ok = true;
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "Opening database: " + e.getMessage(), e);
}
}
return ok;
}
/**
* Executes a query that returns data of an entity.
* @param query Query to execute.
* @return List of results or null is there an error.
* @throws JaiberdroidException
*/
public List<Object> executeQueryEntity(final Query query) throws JaiberdroidException {
List<Object> results = null;
// Checks if query is SELECT type.
if (Query.Type.SELECT.equals(query.getType())) {
try {
final SQLiteDatabase database = getWritableDatabase();
final Cursor cursor = database.query(query.getEntity().getTableName(), query.getFields(),
query.getCondition(), query.getArgsArray(), null, null,
null);
if (cursor.moveToFirst()) {
results = new ArrayList<Object>();
do {
results.add(getObject(cursor, query.getEntity()));
} while (cursor.moveToNext());
}
cursor.close();
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing a query: " + e.getMessage(), e);
}
}
return results;
}
/**
* Executes a query that returns data of an entity.
* @param query Query to execute.
* @return List of results or null is there an error.
* @throws JaiberdroidException
*/
public long executeCountQuery(final Entity entity) throws JaiberdroidException {
long count = 0;
try {
final SQLiteDatabase database = getWritableDatabase();
Cursor mCount= database.rawQuery(JaiberdroidSql.getCountSql(entity.getTableName()), null);
if (mCount.moveToFirst());
count= mCount.getLong(0);
mCount.close();
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing a query: " + e.getMessage(), e);
}
return count;
}
@SuppressWarnings("rawtypes")
private Object getObject(final Cursor cursor, final Entity entity) throws JaiberdroidException {
Object result = null;
if (null != cursor && cursor.getCount() > 0) {
try {
result = entity.getReferenced().newInstance();
for (String column : cursor.getColumnNames()) {
Class type = entity.getFields().getFieldClass(column);
String name = JaiberdroidReflection.getMethodName(JaiberdroidReflection.SET_PREFIX, column);
int pos = cursor.getColumnIndex(column);
if (int.class.equals(type) || Integer.class.equals(type)) {
JaiberdroidReflection.executeSetMethod(name, result, type, cursor.getInt(pos));
} else if (long.class.equals(type) || Long.class.equals(type)) {
JaiberdroidReflection.executeSetMethod(name, result, type, cursor.getLong(pos));
} else if (String.class.equals(type)) {
JaiberdroidReflection.executeSetMethod(name, result, type, cursor.getString(pos));
} else if (float.class.getName().equals(type) || Float.class.getName().equals(type)) {
JaiberdroidReflection.executeSetMethod(name, result, type, cursor.getFloat(pos));
} else if (double.class.getName().equals(type) || Double.class.getName().equals(type)) {
JaiberdroidReflection.executeSetMethod(name, result, type, cursor.getDouble(pos));
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
return result;
}
/**
* Gets the current version of database.
* @return Integer with current version of database.
*/
public static final int getVersion() {
return version;
}
/**
* Sets the current version of database.
* @param version Integer with current version of database.
*/
public static final void setVersion(final int version) {
QueryManager.version = version;
}
/**
* Gets a String with database's name.
* @return String with database's name.
*/
public static final String getName() {
return name;
}
/**
* Sets a String with database's name.
* @param name String with database's name.
*/
public static final void setName(String name) {
QueryManager.name = name;
}
}
| false | true | public long executeUpdate(final Query query) throws JaiberdroidException {
long rows = -1;
try {
final SQLiteDatabase database = getWritableDatabase();
if (query.isTransactional()) {
database.beginTransaction();
}
switch (query.getType()) {
// Inserts a value into the database.
case INSERT:
// Returns the row id of inserted data.
rows = (int) database.insert(query.getEntity().getTableName(), null, query.getValues());
if (-1 != rows) {
JaiberdroidReflection.executeSetMethod(JaiberdroidReflection.SET_ID, query.getObject(),
int.class, (int) rows);
rows = 1; // Affected 1 row.
}
break;
// Updates existing values into database.
case UPDATE:
rows = database.update(query.getEntity().getTableName(), query.getValues(),
query.getCondition(), query.getArgsArray());
break;
// Delete values of database.
case DELETE:
database.delete(query.getEntity().getTableName(), query.getCondition(),
query.getArgsArray());
break;
default:
Log.d(JaiberdroidInstance.LOG_TAG, "Only Insert, Update, Delete are supported");
}
if (database.inTransaction()) {
if (rows != -1) {
database.setTransactionSuccessful();
}
database.endTransaction();
}
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing update: " + e.getMessage(), e);
throw new JaiberdroidException("Executing SQL" + e.getMessage());
}
return rows;
}
| public long executeUpdate(final Query query) throws JaiberdroidException {
long rows = -1;
try {
final SQLiteDatabase database = getWritableDatabase();
if (query.isTransactional()) {
database.beginTransaction();
}
switch (query.getType()) {
// Inserts a value into the database.
case INSERT:
// Returns the row id of inserted data.
rows = (int) database.insert(query.getEntity().getTableName(), null, query.getValues());
if (-1 != rows) {
JaiberdroidReflection.executeSetMethod(JaiberdroidReflection.SET_ID, query.getObject(),
int.class, (int) rows);
rows = 1; // Affected 1 row.
}
break;
// Updates existing values into database.
case UPDATE:
rows = database.update(query.getEntity().getTableName(), query.getValues(),
query.getCondition(), query.getArgsArray());
break;
// Delete values of database.
case DELETE:
rows = database.delete(query.getEntity().getTableName(), query.getCondition(),
query.getArgsArray());
break;
default:
Log.w(JaiberdroidInstance.LOG_TAG, "Only Insert, Update, Delete are supported");
}
if (database.inTransaction()) {
if (rows != -1) {
database.setTransactionSuccessful();
}
database.endTransaction();
}
} catch (final SQLException e) {
Log.e(JaiberdroidInstance.LOG_TAG, "When executing update: " + e.getMessage(), e);
throw new JaiberdroidException("Executing SQL" + e.getMessage());
}
return rows;
}
|
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/libraries/Dojo102Test.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/libraries/Dojo102Test.java
index 21fee424e..51ddf41a3 100644
--- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/libraries/Dojo102Test.java
+++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/libraries/Dojo102Test.java
@@ -1,77 +1,77 @@
/*
* Copyright (c) 2002-2008 Gargoyle Software Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
* SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gargoylesoftware.htmlunit.libraries;
import java.net.URL;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebTestCase;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* Tests for compatibility with version 1.0.2 of the <a href="http://dojotoolkit.org/">Dojo JavaScript library</a>.
*
* @version $Revision$
* @author Ahmed Ashour
*/
public class Dojo102Test extends WebTestCase {
/**
* @param name The name of the test.
*/
public Dojo102Test(final String name) {
super(name);
}
/**
* @throws Exception if an error occurs
*/
public void testDojo() throws Exception {
- if (notYetImplemented()) {
- return;
- }
+ if (notYetImplemented()) {
+ return;
+ }
final WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_7_0);
final URL url = getClass().getClassLoader().getResource("dojo/1.0.2/util/doh/runner.html");
assertNotNull(url);
final HtmlPage page = (HtmlPage) client.getPage(url);
page.getEnclosingWindow().getThreadManager().joinAll(10000);
}
}
| true | true | public void testDojo() throws Exception {
if (notYetImplemented()) {
return;
}
final WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_7_0);
final URL url = getClass().getClassLoader().getResource("dojo/1.0.2/util/doh/runner.html");
assertNotNull(url);
final HtmlPage page = (HtmlPage) client.getPage(url);
page.getEnclosingWindow().getThreadManager().joinAll(10000);
}
| public void testDojo() throws Exception {
if (notYetImplemented()) {
return;
}
final WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_7_0);
final URL url = getClass().getClassLoader().getResource("dojo/1.0.2/util/doh/runner.html");
assertNotNull(url);
final HtmlPage page = (HtmlPage) client.getPage(url);
page.getEnclosingWindow().getThreadManager().joinAll(10000);
}
|
diff --git a/src/helloworld/HelloWorld.java b/src/helloworld/HelloWorld.java
index 6e109aa..475c84b 100644
--- a/src/helloworld/HelloWorld.java
+++ b/src/helloworld/HelloWorld.java
@@ -1,20 +1,20 @@
package helloworld;
/**
*
* @author WASD
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("kuk");
System.out.println("kukar");
NewClass x = new NewClass(5, "Hello World!");
- for(int i = 0; i < x.getX(); i++) {
- System.out.println(i + " of " + x.getX() + ": " + x.getName());
- }
+ for(int i = 0; i < x.getX(); i++) {
+ System.out.println(i + " of " + x.getX() + ": " + x.getName());
+ }
}
}
| true | true | public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("kuk");
System.out.println("kukar");
NewClass x = new NewClass(5, "Hello World!");
for(int i = 0; i < x.getX(); i++) {
System.out.println(i + " of " + x.getX() + ": " + x.getName());
}
}
| public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("kuk");
System.out.println("kukar");
NewClass x = new NewClass(5, "Hello World!");
for(int i = 0; i < x.getX(); i++) {
System.out.println(i + " of " + x.getX() + ": " + x.getName());
}
}
|
diff --git a/de.neo.remote.mediaserver/src/de/neo/remote/mediaserver/impl/AbstractPlayer.java b/de.neo.remote.mediaserver/src/de/neo/remote/mediaserver/impl/AbstractPlayer.java
index 4644dc7..6bf743f 100644
--- a/de.neo.remote.mediaserver/src/de/neo/remote/mediaserver/impl/AbstractPlayer.java
+++ b/de.neo.remote.mediaserver/src/de/neo/remote/mediaserver/impl/AbstractPlayer.java
@@ -1,260 +1,277 @@
package de.neo.remote.mediaserver.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.AbstractID3v2;
import de.neo.remote.mediaserver.api.IPlayer;
import de.neo.remote.mediaserver.api.IPlayerListener;
import de.neo.remote.mediaserver.api.PlayerException;
import de.neo.remote.mediaserver.api.PlayingBean;
import de.neo.remote.mediaserver.api.PlayingBean.STATE;
import de.neo.rmi.protokol.RemoteException;
/**
* the abstract player implements basically functions of an player. this
* contains handling of listeners, current playing file
*
* @author sebastian
*/
public abstract class AbstractPlayer implements IPlayer {
public static final String TATORT_DL_FILE = "/usr/bin/tatort-dl.sh";
public static final String TATORT_TMP_FILE = "tatort_tmp.f4v";
/**
* list of all listeners
*/
private List<IPlayerListener> listeners = new ArrayList<IPlayerListener>();
/**
* current playing file
*/
protected PlayingBean playingBean;
private String tempFolder;
private Process tatortProcess;
private String tatortURL;
public AbstractPlayer(String tempFolder) {
new PlayingTimeCounter().start();
this.tempFolder = tempFolder;
if (!this.tempFolder.endsWith(File.separator))
this.tempFolder += File.separator;
}
@Override
public void addPlayerMessageListener(IPlayerListener listener)
throws RemoteException {
if (!listeners.contains(listener))
listeners.add(listener);
}
@Override
public void removePlayerMessageListener(IPlayerListener listener)
throws RemoteException {
listeners.remove(listener);
}
/**
* read file tags with the ID3 library
*
* @param file
* @return playingbean
* @throws IOException
*/
protected PlayingBean readFileInformations(File file) throws IOException {
PlayingBean bean = new PlayingBean();
try {
MP3File mp3File = new MP3File(file);
bean.setFile(file.getName().trim());
bean.setPath(file.getPath());
AbstractID3v2 id3v2Tag = mp3File.getID3v2Tag();
if (id3v2Tag != null) {
if (id3v2Tag.getAuthorComposer() != null)
bean.setArtist(id3v2Tag.getAuthorComposer().trim());
if (id3v2Tag.getSongTitle() != null)
bean.setTitle(id3v2Tag.getSongTitle().trim());
if (id3v2Tag.getAlbumTitle() != null)
bean.setAlbum(id3v2Tag.getAlbumTitle().trim());
}
} catch (TagException e) {
System.out.println(e);
}
return bean;
}
/**
* inform all listeners about the current playing file. the information
* about the file will be read.
*
* @param bean
* @throws IOException
*/
protected void informFile(File file) throws IOException {
PlayingBean bean = readFileInformations(file);
bean.setState(STATE.PLAY);
informPlayingBean(bean);
}
/**
* inform all listeners about the current playing file. a new bean will be
* created.
*
* @param bean
*/
protected void informPlayingBean(PlayingBean bean) {
this.playingBean = new PlayingBean(bean);
List<IPlayerListener> exceptionList = new ArrayList<IPlayerListener>();
for (IPlayerListener listener : listeners)
try {
listener.playerMessage(playingBean);
} catch (RemoteException e) {
exceptionList.add(listener);
}
listeners.removeAll(exceptionList);
}
@Override
public PlayingBean getPlayingBean() throws RemoteException, PlayerException {
return playingBean;
}
@Override
public void playPause() throws PlayerException {
if (playingBean != null) {
playingBean
.setState((playingBean.getState() == STATE.PLAY) ? STATE.PAUSE
: STATE.PLAY);
informPlayingBean(playingBean);
}
}
protected String getYoutubeStreamUrl(String url) throws RemoteException {
try {
String[] youtubeArgs = new String[] { "/usr/bin/youtube-dl", "-g",
url };
Process youtube = Runtime.getRuntime().exec(youtubeArgs);
InputStreamReader input = new InputStreamReader(
youtube.getInputStream());
BufferedReader reader = new BufferedReader(input);
return reader.readLine();
} catch (IOException e) {
throw new RemoteException("youtube", "Error play youtube stream :"
+ e.getMessage());
}
}
protected String openTemporaryArdFile(String url) throws RemoteException {
if (tatortURL != null && tatortURL.equals(url))
return tempFolder + TATORT_TMP_FILE;
try {
String tempFile = tempFolder + TATORT_TMP_FILE;
File file = new File(tempFile);
System.out.println("-> destroy load process");
if (tatortProcess != null)
tatortProcess.destroy();
if (file.exists())
file.delete();
if (!new File(TATORT_DL_FILE).exists())
throw new IllegalStateException("Missing script: "
+ TATORT_DL_FILE);
System.out.println("-> start load process");
- String[] tatortArgs = new String[] { TATORT_DL_FILE, url, tempFile };
- tatortProcess = Runtime.getRuntime().exec(tatortArgs);
+ List<String> tatortArgs = new ArrayList<String>();
+ tatortArgs.add(TATORT_DL_FILE);
+ tatortArgs.add(url);
+ tatortArgs.add(tempFile);
+ ProcessBuilder pb = new ProcessBuilder(tatortArgs);
+ tatortProcess = pb.start();
InputStreamReader input = new InputStreamReader(
tatortProcess.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = null;
System.out.println("-> read request");
while ((line = reader.readLine()) != null) {
System.out.println("-> read line: " + line);
if (line.contains("Error"))
throw new RemoteException("", "Stream ARD: " + line);
if (line.contains("Connected")) {
Thread.sleep(2000);
tatortURL = tempFile;
return tempFile;
}
}
+ input = new InputStreamReader(tatortProcess.getErrorStream());
+ reader = new BufferedReader(input);
+ System.out.println("-> read error request");
+ while ((line = reader.readLine()) != null) {
+ System.out.println("-> read line: " + line);
+ if (line.contains("Error"))
+ throw new RemoteException("", "Stream ARD: " + line);
+ if (line.contains("Connected")) {
+ Thread.sleep(2000);
+ tatortURL = tempFile;
+ return tempFile;
+ }
+ }
System.out.println("-> end of request");
throw new RemoteException("", "Stream ARD: not Connected");
} catch (Exception e) {
throw new RemoteException("youtube", "Error play youtube stream :"
+ e.getMessage());
}
}
@Override
public void play(String file) {
if (playingBean != null) {
playingBean.setState(STATE.PLAY);
playingBean.setFile(file);
playingBean.setCurrentTime(0);
informPlayingBean(playingBean);
}
}
@Override
public void quit() throws PlayerException {
if (playingBean == null)
playingBean = new PlayingBean();
playingBean.setState(STATE.DOWN);
informPlayingBean(playingBean);
}
@Override
public void next() throws PlayerException {
if (playingBean != null) {
playingBean.setState(STATE.PLAY);
informPlayingBean(playingBean);
}
}
@Override
public void previous() throws PlayerException {
if (playingBean != null) {
playingBean.setState(STATE.PLAY);
informPlayingBean(playingBean);
}
}
@Override
public void playFromYoutube(String url) throws RemoteException,
PlayerException {
}
@Override
public void playFromArdMediathek(String url) throws RemoteException,
PlayerException {
}
class PlayingTimeCounter extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (playingBean != null && playingBean.getState() == STATE.PLAY) {
playingBean.incrementCurrentTime(1);
}
}
}
}
}
| false | true | protected String openTemporaryArdFile(String url) throws RemoteException {
if (tatortURL != null && tatortURL.equals(url))
return tempFolder + TATORT_TMP_FILE;
try {
String tempFile = tempFolder + TATORT_TMP_FILE;
File file = new File(tempFile);
System.out.println("-> destroy load process");
if (tatortProcess != null)
tatortProcess.destroy();
if (file.exists())
file.delete();
if (!new File(TATORT_DL_FILE).exists())
throw new IllegalStateException("Missing script: "
+ TATORT_DL_FILE);
System.out.println("-> start load process");
String[] tatortArgs = new String[] { TATORT_DL_FILE, url, tempFile };
tatortProcess = Runtime.getRuntime().exec(tatortArgs);
InputStreamReader input = new InputStreamReader(
tatortProcess.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = null;
System.out.println("-> read request");
while ((line = reader.readLine()) != null) {
System.out.println("-> read line: " + line);
if (line.contains("Error"))
throw new RemoteException("", "Stream ARD: " + line);
if (line.contains("Connected")) {
Thread.sleep(2000);
tatortURL = tempFile;
return tempFile;
}
}
System.out.println("-> end of request");
throw new RemoteException("", "Stream ARD: not Connected");
} catch (Exception e) {
throw new RemoteException("youtube", "Error play youtube stream :"
+ e.getMessage());
}
}
| protected String openTemporaryArdFile(String url) throws RemoteException {
if (tatortURL != null && tatortURL.equals(url))
return tempFolder + TATORT_TMP_FILE;
try {
String tempFile = tempFolder + TATORT_TMP_FILE;
File file = new File(tempFile);
System.out.println("-> destroy load process");
if (tatortProcess != null)
tatortProcess.destroy();
if (file.exists())
file.delete();
if (!new File(TATORT_DL_FILE).exists())
throw new IllegalStateException("Missing script: "
+ TATORT_DL_FILE);
System.out.println("-> start load process");
List<String> tatortArgs = new ArrayList<String>();
tatortArgs.add(TATORT_DL_FILE);
tatortArgs.add(url);
tatortArgs.add(tempFile);
ProcessBuilder pb = new ProcessBuilder(tatortArgs);
tatortProcess = pb.start();
InputStreamReader input = new InputStreamReader(
tatortProcess.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = null;
System.out.println("-> read request");
while ((line = reader.readLine()) != null) {
System.out.println("-> read line: " + line);
if (line.contains("Error"))
throw new RemoteException("", "Stream ARD: " + line);
if (line.contains("Connected")) {
Thread.sleep(2000);
tatortURL = tempFile;
return tempFile;
}
}
input = new InputStreamReader(tatortProcess.getErrorStream());
reader = new BufferedReader(input);
System.out.println("-> read error request");
while ((line = reader.readLine()) != null) {
System.out.println("-> read line: " + line);
if (line.contains("Error"))
throw new RemoteException("", "Stream ARD: " + line);
if (line.contains("Connected")) {
Thread.sleep(2000);
tatortURL = tempFile;
return tempFile;
}
}
System.out.println("-> end of request");
throw new RemoteException("", "Stream ARD: not Connected");
} catch (Exception e) {
throw new RemoteException("youtube", "Error play youtube stream :"
+ e.getMessage());
}
}
|
diff --git a/Pong/src/pong/PongGameView.java b/Pong/src/pong/PongGameView.java
index b877a93..d77b932 100644
--- a/Pong/src/pong/PongGameView.java
+++ b/Pong/src/pong/PongGameView.java
@@ -1,71 +1,71 @@
package pong;
import java.util.Collection;
import java.util.List;
import jgame.Context;
import jgame.GContainer;
import jgame.GObject;
import jgame.GSprite;
import jgame.ImageCache;
import jgame.controller.ControlScheme;
import jgame.listener.FrameListener;
import jgame.listener.TimerListener;
public class PongGameView extends GContainer {
public PongGameView(){
super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png")));
setSize(640,480);
// Add the paddle to the game view.
PongPaddle paddle = new PongPaddle(ControlScheme.WASD);
add(paddle);
paddle.setLocation(50, 480/2);
// Create a puck.
PongPuck puck = new PongPuck();
// Add the puck.
addAtCenter(puck);
// Create another paddle to add.
PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS);
add(paddle2);
// Set the paddle's location.
paddle2.setLocation(640 - 50, 480 / 2);
TimerListener tl3 = new TimerListener(30*10) {
@Override
public void invoke(GObject target, Context context) {
Collection<GObject> children = getObjects();
for (GObject someChild : children) {
if (someChild instanceof PowerUp) {
someChild.removeSelf();
}
}
PowerUp unpredictable = new PowerUp();
- addAt(unpredictable, (int)(Math.random() * 550 + 90), (int)(Math.random() * 380 + 50));
+ addAt(unpredictable, Math.random() * 550 + 90, Math.random() * 380 + 50);
}
};
FrameListener fl = new FrameListener() {
@Override
public void invoke(GObject target, Context context) {
// Get all the pucks.
List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class);
// Is it empty?
boolean noPucksLeft = pucks.isEmpty();
// Set the current game view.
if (noPucksLeft == true)
{
context.setCurrentGameView(Pong.View.GAME_OVER);
}
}
};
addListener(fl);
addListener(tl3);
}
}
| true | true | public PongGameView(){
super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png")));
setSize(640,480);
// Add the paddle to the game view.
PongPaddle paddle = new PongPaddle(ControlScheme.WASD);
add(paddle);
paddle.setLocation(50, 480/2);
// Create a puck.
PongPuck puck = new PongPuck();
// Add the puck.
addAtCenter(puck);
// Create another paddle to add.
PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS);
add(paddle2);
// Set the paddle's location.
paddle2.setLocation(640 - 50, 480 / 2);
TimerListener tl3 = new TimerListener(30*10) {
@Override
public void invoke(GObject target, Context context) {
Collection<GObject> children = getObjects();
for (GObject someChild : children) {
if (someChild instanceof PowerUp) {
someChild.removeSelf();
}
}
PowerUp unpredictable = new PowerUp();
addAt(unpredictable, (int)(Math.random() * 550 + 90), (int)(Math.random() * 380 + 50));
}
};
FrameListener fl = new FrameListener() {
@Override
public void invoke(GObject target, Context context) {
// Get all the pucks.
List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class);
// Is it empty?
boolean noPucksLeft = pucks.isEmpty();
// Set the current game view.
if (noPucksLeft == true)
{
context.setCurrentGameView(Pong.View.GAME_OVER);
}
}
};
addListener(fl);
addListener(tl3);
}
| public PongGameView(){
super(new GSprite(ImageCache.forClass(Pong.class).get("explosion.png")));
setSize(640,480);
// Add the paddle to the game view.
PongPaddle paddle = new PongPaddle(ControlScheme.WASD);
add(paddle);
paddle.setLocation(50, 480/2);
// Create a puck.
PongPuck puck = new PongPuck();
// Add the puck.
addAtCenter(puck);
// Create another paddle to add.
PongPaddle paddle2 = new PongPaddle(ControlScheme.ARROW_KEYS);
add(paddle2);
// Set the paddle's location.
paddle2.setLocation(640 - 50, 480 / 2);
TimerListener tl3 = new TimerListener(30*10) {
@Override
public void invoke(GObject target, Context context) {
Collection<GObject> children = getObjects();
for (GObject someChild : children) {
if (someChild instanceof PowerUp) {
someChild.removeSelf();
}
}
PowerUp unpredictable = new PowerUp();
addAt(unpredictable, Math.random() * 550 + 90, Math.random() * 380 + 50);
}
};
FrameListener fl = new FrameListener() {
@Override
public void invoke(GObject target, Context context) {
// Get all the pucks.
List<PongPuck> pucks = context.getInstancesOfClass(PongPuck.class);
// Is it empty?
boolean noPucksLeft = pucks.isEmpty();
// Set the current game view.
if (noPucksLeft == true)
{
context.setCurrentGameView(Pong.View.GAME_OVER);
}
}
};
addListener(fl);
addListener(tl3);
}
|
diff --git a/src/main/java/io/github/alshain01/Flags/area/GriefPreventionClaim78.java b/src/main/java/io/github/alshain01/Flags/area/GriefPreventionClaim78.java
index d00ab1f..bedbaa5 100644
--- a/src/main/java/io/github/alshain01/Flags/area/GriefPreventionClaim78.java
+++ b/src/main/java/io/github/alshain01/Flags/area/GriefPreventionClaim78.java
@@ -1,136 +1,136 @@
/* Copyright 2013 Kevin Seiden. All rights reserved.
This works is licensed under the Creative Commons Attribution-NonCommercial 3.0
You are Free to:
to Share: to copy, distribute and transmit the work
to Remix: to adapt the work
Under the following conditions:
Attribution: You must attribute the work in the manner specified by the author (but not in any way that suggests that they endorse you or your use of the work).
Non-commercial: You may not use this work for commercial purposes.
With the understanding that:
Waiver: Any of the above conditions can be waived if you get permission from the copyright holder.
Public Domain: Where the work or any of its elements is in the public domain under applicable law, that status is in no way affected by the license.
Other Rights: In no way are any of the following rights affected by the license:
Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
The author's moral rights;
Rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights.
Notice: For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page.
http://creativecommons.org/licenses/by-nc/3.0/
*/
package io.github.alshain01.Flags.area;
import io.github.alshain01.Flags.Flags;
import me.ryanhamshire.GriefPrevention.Claim;
import org.bukkit.Bukkit;
import org.bukkit.Location;
public class GriefPreventionClaim78 extends GriefPreventionClaim implements Subdivision {
/**
* Creates an instance of GriefPreventionClaim78 based on a Bukkit Location
*
* @param location
* The Bukkit location
*/
public GriefPreventionClaim78(Location location) {
super(location);
}
/**
* Creates an instance of GriefPreventionClaim78 based on a claim ID
*
* @param ID
* The claim ID
*/
public GriefPreventionClaim78(long ID) {
super(ID);
}
/**
* Creates an instance of GriefPreventionClaim78 based on a claim ID and
* sub-claimID
*
* @param ID
* The claim ID
* @param subID
* The sub-claim ID
*/
public GriefPreventionClaim78(long ID, long subID) {
super(ID);
this.claim = (claim == null) ? null : claim.getSubClaim(subID);
}
/**
* 0 if the the claims are the same
* -1 if the claim is a subdivision of the provided claim.
* 1 if the claim is a parent of the provided claim.
* 2 if they are "sister" subdivisions. 3 if they are completely unrelated.
*
* @return The value of the comparison.
*/
@Override
public int compareTo(Area a) {
if (!(a instanceof GriefPreventionClaim78)) {
return 3;
}
Claim testClaim = ((GriefPreventionClaim78)a).getClaim();
if(claim.equals(testClaim)) {
return 0;
- } else if (claim.parent.equals(testClaim)) {
+ } else if (claim.parent != null && claim.parent.equals(testClaim)) {
return -1;
- } else if (testClaim.parent.equals(claim)) {
+ } else if (testClaim.parent != null && testClaim.parent.equals(claim)) {
return 1;
} else if (claim.parent != null && claim.parent.equals(testClaim.parent)) {
return 2;
}
return 3;
}
@Override
public String getSystemSubID() {
return claim != null && claim.parent != null ? String.valueOf(claim.getSubClaimID()) : null;
}
@Override
public org.bukkit.World getWorld() {
return Bukkit.getServer().getWorld(claim.getClaimWorldName());
}
@Override
public boolean isInherited() {
return claim != null && claim.parent != null && Flags.getDataStore().readInheritance(this);
}
@Override
public boolean isSubdivision() {
return claim != null && claim.parent != null;
}
@Override
public void setInherited(Boolean value) {
if (claim == null || claim.parent == null) {
return;
}
Flags.getDataStore().writeInheritance(this, value);
}
@Override
public boolean isParent(Area area) {
return area instanceof GriefPreventionClaim78 && claim.parent != null
&& claim.parent.equals(((GriefPreventionClaim78)area).getClaim());
}
@Override
public Area getParent() {
if(claim.parent == null) { return null; }
return new GriefPreventionClaim78(claim.getID());
}
}
| false | true | public int compareTo(Area a) {
if (!(a instanceof GriefPreventionClaim78)) {
return 3;
}
Claim testClaim = ((GriefPreventionClaim78)a).getClaim();
if(claim.equals(testClaim)) {
return 0;
} else if (claim.parent.equals(testClaim)) {
return -1;
} else if (testClaim.parent.equals(claim)) {
return 1;
} else if (claim.parent != null && claim.parent.equals(testClaim.parent)) {
return 2;
}
return 3;
}
| public int compareTo(Area a) {
if (!(a instanceof GriefPreventionClaim78)) {
return 3;
}
Claim testClaim = ((GriefPreventionClaim78)a).getClaim();
if(claim.equals(testClaim)) {
return 0;
} else if (claim.parent != null && claim.parent.equals(testClaim)) {
return -1;
} else if (testClaim.parent != null && testClaim.parent.equals(claim)) {
return 1;
} else if (claim.parent != null && claim.parent.equals(testClaim.parent)) {
return 2;
}
return 3;
}
|
diff --git a/deepamehta-core/src/test/java/de/deepamehta/core/impl/service/JavaUtilsTest.java b/deepamehta-core/src/test/java/de/deepamehta/core/impl/service/JavaUtilsTest.java
index 80e492852..71bc84d4f 100644
--- a/deepamehta-core/src/test/java/de/deepamehta/core/impl/service/JavaUtilsTest.java
+++ b/deepamehta-core/src/test/java/de/deepamehta/core/impl/service/JavaUtilsTest.java
@@ -1,125 +1,129 @@
package de.deepamehta.core.impl.service;
import de.deepamehta.core.util.JavaUtils;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JavaUtilsTest {
@Test
public void stripHTML() {
String html = "<body><p><i>Hi</i> there!</p><p style=\"margin-top: 10px\">2. paragraph</p></body>";
assertEquals("Hi there!2. paragraph", JavaUtils.stripHTML(html));
}
@Test
public void stripHTMLwithLinebreaks() {
String html = "<p>abc 123</p>\n<p>def</p>\n<p>ghi</p>";
assertEquals("abc 123\ndef\nghi", JavaUtils.stripHTML(html));
}
// ---
@Test
public void stripDriveLetter() {
assertEquals("/my/path", JavaUtils.stripDriveLetter("/my/path"));
assertEquals("/my/path", JavaUtils.stripDriveLetter("A:/my/path"));
assertEquals("/my/A:path", JavaUtils.stripDriveLetter("/my/A:path"));
}
// ---
@Test
public void isInRangeIPv4() {
+ assertTrue(JavaUtils.isInRange("0.0.0.0", "0.0.0.0/0"));
+ assertTrue(JavaUtils.isInRange("255.255.255.255", "0.0.0.0/0"));
+ assertTrue(JavaUtils.isInRange("0.0.0.0", "127.0.0.1/0"));
+ assertTrue(JavaUtils.isInRange("255.255.255.255", "127.0.0.1/0"));
assertTrue(JavaUtils.isInRange("172.68.8.0", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.12", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.255", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.0", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.12", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.255", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange( "100.68.8.113", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.112", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.114", "100.68.8.113/32"));
}
@Test
public void inetAddressIPv4() {
assertEquals(BigInteger.ZERO, JavaUtils.inetAddress("0.0.0.0"));
assertEquals(BigInteger.ONE, JavaUtils.inetAddress("0.0.0.1"));
assertEquals(bigInt(256), JavaUtils.inetAddress("0.0.1.0"));
assertEquals(bigInt(Math.pow(2, 24) - 1), JavaUtils.inetAddress("0.255.255.255"));
assertEquals(bigInt(Math.pow(2, 31) - 1), JavaUtils.inetAddress("127.255.255.255"));
assertEquals(bigInt(Math.pow(2, 31)), JavaUtils.inetAddress("128.0.0.0"));
assertEquals(bigInt(Math.pow(2, 32) - 1), JavaUtils.inetAddress("255.255.255.255"));
}
@Test
public void networkMaskIPv4() {
assertEquals(JavaUtils.inetAddress("0.0.0.0"), JavaUtils.networkMask(0, 32));
assertEquals(JavaUtils.inetAddress("128.0.0.0"), JavaUtils.networkMask(1, 32));
assertEquals(JavaUtils.inetAddress("255.0.0.0"), JavaUtils.networkMask(8, 32));
assertEquals(JavaUtils.inetAddress("255.255.0.0"), JavaUtils.networkMask(16, 32));
assertEquals(JavaUtils.inetAddress("255.255.255.0"), JavaUtils.networkMask(24, 32));
assertEquals(JavaUtils.inetAddress("255.255.255.192"), JavaUtils.networkMask(26, 32));
assertEquals(JavaUtils.inetAddress("255.255.255.255"), JavaUtils.networkMask(32, 32));
}
// ---
@Test
public void isInRangeIPv6() {
assertTrue(JavaUtils.isInRange("::3afe:7a0:c800", "::3afe:7a0:c800/120"));
assertTrue(JavaUtils.isInRange("::3afe:7a0:c880", "::3afe:7a0:c800/120"));
assertTrue(JavaUtils.isInRange("::3afe:7a0:c8ff", "::3afe:7a0:c800/120"));
assertTrue(JavaUtils.isInRange("::3afe:7a0:c800", "::3afe:7a0:c800/121"));
assertTrue(JavaUtils.isInRange("::3afe:7a0:c87f", "::3afe:7a0:c800/121"));
assertFalse(JavaUtils.isInRange("::3afe:7a0:c880", "::3afe:7a0:c800/121"));
assertFalse(JavaUtils.isInRange("::3afe:7a0:c8ff", "::3afe:7a0:c800/121"));
}
@Test
public void inetAddressIPv6() {
assertEquals(BigInteger.ZERO, JavaUtils.inetAddress("::"));
assertEquals(BigInteger.ONE, JavaUtils.inetAddress("::1"));
assertEquals(bigInt(256), JavaUtils.inetAddress("::100"));
assertEquals(bigInt(Math.pow(2, 24) - 1), JavaUtils.inetAddress("::ff:ffff"));
assertEquals(bigInt(Math.pow(2, 31) - 1), JavaUtils.inetAddress("::7fff:ffff"));
assertEquals(bigInt(Math.pow(2, 31)), JavaUtils.inetAddress("::8000:0000"));
assertEquals(bigInt(Math.pow(2, 32) - 1), JavaUtils.inetAddress("::ffff:ffff"));
assertEquals(bigInt(Math.pow(2, 32)), JavaUtils.inetAddress("::1:0000:0000"));
assertEquals(bigInt(Math.pow(2, 63) - 1), JavaUtils.inetAddress("::7fff:ffff:ffff:ffff"));
}
@Test
public void networkMaskIPv6() {
assertEquals(JavaUtils.inetAddress("::"), JavaUtils.networkMask(0, 128));
assertEquals(JavaUtils.inetAddress("8000::"), JavaUtils.networkMask(1, 128));
assertEquals(JavaUtils.inetAddress("ff00::"), JavaUtils.networkMask(8, 128));
assertEquals(JavaUtils.inetAddress("ffff::"), JavaUtils.networkMask(16, 128));
assertEquals(JavaUtils.inetAddress("ffff:ff00::"), JavaUtils.networkMask(24, 128));
assertEquals(JavaUtils.inetAddress("ffff:ffc0::"), JavaUtils.networkMask(26, 128));
assertEquals(JavaUtils.inetAddress("ffff:ffff::"), JavaUtils.networkMask(32, 128));
assertEquals(JavaUtils.inetAddress("ffff:ffff:ffff:ffff::"), JavaUtils.networkMask(64, 128));
assertEquals(JavaUtils.inetAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), JavaUtils.networkMask(128, 128));
}
// ---
private BigInteger bigInt(double val) {
return bigInt((long) val);
}
private BigInteger bigInt(long val) {
return new BigInteger(Long.toString(val));
}
}
| true | true | public void isInRangeIPv4() {
assertTrue(JavaUtils.isInRange("172.68.8.0", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.12", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.255", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.0", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.12", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.255", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange( "100.68.8.113", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.112", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.114", "100.68.8.113/32"));
}
| public void isInRangeIPv4() {
assertTrue(JavaUtils.isInRange("0.0.0.0", "0.0.0.0/0"));
assertTrue(JavaUtils.isInRange("255.255.255.255", "0.0.0.0/0"));
assertTrue(JavaUtils.isInRange("0.0.0.0", "127.0.0.1/0"));
assertTrue(JavaUtils.isInRange("255.255.255.255", "127.0.0.1/0"));
assertTrue(JavaUtils.isInRange("172.68.8.0", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.12", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange("172.68.8.255", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.0", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.12", "172.68.8.0/24"));
assertFalse(JavaUtils.isInRange("172.68.9.255", "172.68.8.0/24"));
assertTrue(JavaUtils.isInRange( "100.68.8.113", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.112", "100.68.8.113/32"));
assertFalse(JavaUtils.isInRange("100.68.8.114", "100.68.8.113/32"));
}
|
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/JavaLogicalStructure.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/JavaLogicalStructure.java
index 926fb89ab..5725562f0 100644
--- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/JavaLogicalStructure.java
+++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/JavaLogicalStructure.java
@@ -1,457 +1,457 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.core.logicalstructures;
import java.text.MessageFormat;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILogicalStructureType;
import org.eclipse.debug.core.IStatusHandler;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.core.model.IThread;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.debug.core.IJavaClassType;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaInterfaceType;
import org.eclipse.jdt.debug.core.IJavaObject;
import org.eclipse.jdt.debug.core.IJavaReferenceType;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.debug.core.IJavaType;
import org.eclipse.jdt.debug.core.IJavaValue;
import org.eclipse.jdt.debug.core.IJavaVariable;
import org.eclipse.jdt.debug.eval.IAstEvaluationEngine;
import org.eclipse.jdt.debug.eval.ICompiledExpression;
import org.eclipse.jdt.debug.eval.IEvaluationListener;
import org.eclipse.jdt.debug.eval.IEvaluationResult;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
import org.eclipse.jdt.internal.debug.core.model.JDIReferenceType;
public class JavaLogicalStructure implements ILogicalStructureType {
// stack frame context provider
public static final int INFO_EVALUATION_STACK_FRAME = 111;
private static IStatus fgNeedStackFrame = new Status(IStatus.INFO, JDIDebugPlugin.getUniqueIdentifier(), INFO_EVALUATION_STACK_FRAME, "Provides thread context for an evaluation", null); //$NON-NLS-1$
private static IStatusHandler fgStackFrameProvider;
/**
* Fully qualified type name.
*/
private String fType;
/**
* Indicate if this java logical structure should be used on object
* instance of subtype of the specified type.
*/
private boolean fSubtypes;
/**
* Code snippet to evaluate to create the logical value.
*/
private String fValue;
/**
* Description of the logical structure.
*/
private String fDescription;
/**
* Name and associated code snippet of the variables of the logical value.
*/
private String[][] fVariables;
/**
* The plugin identifier of the plugin which contributed this logical structure
* or <code>null</code> if this structure was defined by the user.
*/
private String fContributingPluginId= null;
/**
* Performs the evaluations.
*/
private class EvaluationBlock implements IEvaluationListener {
private IJavaObject fEvaluationValue;
private IJavaReferenceType fEvaluationType;
private IJavaThread fThread;
private IAstEvaluationEngine fEvaluationEngine;
private IEvaluationResult fResult;
public EvaluationBlock(IJavaObject value, IJavaReferenceType type, IJavaThread thread, IAstEvaluationEngine evaluationEngine) {
fEvaluationValue= value;
fEvaluationType= type;
fThread= thread;
fEvaluationEngine= evaluationEngine;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.debug.eval.IEvaluationListener#evaluationComplete(org.eclipse.jdt.debug.eval.IEvaluationResult)
*/
public void evaluationComplete(IEvaluationResult result) {
synchronized(this) {
fResult= result;
this.notify();
}
}
public IJavaValue evaluate(String snippet) throws DebugException {
ICompiledExpression compiledExpression= fEvaluationEngine.getCompiledExpression(snippet, fEvaluationType);
if (compiledExpression.hasErrors()) {
String[] errorMessages = compiledExpression.getErrorMessages();
log(errorMessages);
return new JavaStructureErrorValue(errorMessages, fEvaluationValue);
}
fResult= null;
fEvaluationEngine.evaluateExpression(compiledExpression, fEvaluationValue, fThread, this, DebugEvent.EVALUATION_IMPLICIT, false);
synchronized(this) {
if (fResult == null) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
}
if (fResult == null) {
return new JavaStructureErrorValue(LogicalStructuresMessages.JavaLogicalStructure_1, fEvaluationValue); //$NON-NLS-1$
}
if (fResult.hasErrors()) {
DebugException exception = fResult.getException();
String message;
if (exception != null) {
if (isContributed()) {
JDIDebugPlugin.log(exception);
}
message= MessageFormat.format(LogicalStructuresMessages.JavaLogicalStructure_2, new String[] { exception.getMessage() }); //$NON-NLS-1$
} else {
log(fResult.getErrorMessages());
message= LogicalStructuresMessages.JavaLogicalStructure_3; //$NON-NLS-1$
}
return new JavaStructureErrorValue(message, fEvaluationValue);
}
return fResult.getValue();
}
/**
* Logs the given error messages if this logical structure was contributed
* via extension.
*/
private void log(String[] messages) {
if (isContributed()) {
StringBuffer log= new StringBuffer();
for (int i = 0; i < messages.length; i++) {
log.append(messages[i]).append('\n');
}
JDIDebugPlugin.log(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), IStatus.ERROR, log.toString(),null));
}
}
}
/**
* Constructor from parameters.
*/
public JavaLogicalStructure(String type, boolean subtypes, String value, String description, String[][] variables) {
fType= type;
fSubtypes= subtypes;
fValue= value;
fDescription= description;
fVariables= variables;
}
/**
* Constructor from configuration element.
*/
public JavaLogicalStructure(IConfigurationElement configurationElement) throws CoreException {
fType= configurationElement.getAttribute("type"); //$NON-NLS-1$
if (fType == null) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.JavaLogicalStructures_0, null)); //$NON-NLS-1$
}
fSubtypes= Boolean.valueOf(configurationElement.getAttribute("subtypes")).booleanValue(); //$NON-NLS-1$
fValue= configurationElement.getAttribute("value"); //$NON-NLS-1$
fDescription= configurationElement.getAttribute("description"); //$NON-NLS-1$
if (fDescription == null) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.JavaLogicalStructures_4, null)); //$NON-NLS-1$
}
IConfigurationElement[] variableElements= configurationElement.getChildren("variable"); //$NON-NLS-1$
if (fValue== null && variableElements.length == 0) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.JavaLogicalStructures_1, null)); //$NON-NLS-1$
}
fVariables= new String[variableElements.length][2];
for (int j= 0; j < fVariables.length; j++) {
String variableName= variableElements[j].getAttribute("name"); //$NON-NLS-1$
if (variableName == null) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.JavaLogicalStructures_2, null)); //$NON-NLS-1$
}
fVariables[j][0]= variableName;
String variableValue= variableElements[j].getAttribute("value"); //$NON-NLS-1$
if (variableValue == null) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.JavaLogicalStructures_3, null)); //$NON-NLS-1$
}
fVariables[j][1]= variableValue;
}
fContributingPluginId= configurationElement.getNamespace();
}
/**
* @see org.eclipse.debug.core.model.ILogicalStructureTypeDelegate#providesLogicalStructure(IValue)
*/
public boolean providesLogicalStructure(IValue value) {
if (!(value instanceof IJavaObject)) {
return false;
}
return getType((IJavaObject) value) != null;
}
/**
* @see org.eclipse.debug.core.model.ILogicalStructureTypeDelegate#getLogicalStructure(IValue)
*/
public IValue getLogicalStructure(IValue value) {
if (!(value instanceof IJavaObject)) {
- return null;
+ return value;
}
IJavaObject javaValue= (IJavaObject) value;
try {
IJavaReferenceType type = getType(javaValue);
if (type == null) {
- return null;
+ return value;
}
IJavaStackFrame stackFrame= getStackFrame(javaValue);
if (stackFrame == null) {
- return null;
+ return value;
}
// find the project the snippets will be compiled in.
ISourceLocator locator= javaValue.getLaunch().getSourceLocator();
Object sourceElement= null;
if (locator instanceof ISourceLookupDirector) {
if (type instanceof JDIReferenceType) {
String[] sourcePaths= ((JDIReferenceType) type).getSourcePaths(null);
if (sourcePaths.length > 0) {
sourceElement= ((ISourceLookupDirector) locator).getSourceElement(sourcePaths[0]);
}
}
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
if (sourceElement == null) {
sourceElement = locator.getSourceElement(stackFrame);
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
IJavaProject project= null;
if (sourceElement instanceof IJavaElement) {
project= ((IJavaElement) sourceElement).getJavaProject();
} else if (sourceElement instanceof IResource) {
IJavaProject resourceProject = JavaCore.create(((IResource)sourceElement).getProject());
if (resourceProject.exists()) {
project= resourceProject;
}
}
if (project == null) {
- return null;
+ return value;
}
IAstEvaluationEngine evaluationEngine= JDIDebugPlugin.getDefault().getEvaluationEngine(project, (IJavaDebugTarget)stackFrame.getDebugTarget());
EvaluationBlock evaluationBlock= new EvaluationBlock(javaValue, type, (IJavaThread)stackFrame.getThread(), evaluationEngine);
if (fValue == null) {
// evaluate each variable
IJavaVariable[] variables= new IJavaVariable[fVariables.length];
for (int i= 0; i < fVariables.length; i++) {
variables[i]= new JDIPlaceholderVariable(fVariables[i][0], evaluationBlock.evaluate(fVariables[i][1]));
}
return new LogicalObjectStructureValue(javaValue, variables);
}
// evaluate the logical value
return evaluationBlock.evaluate(fValue);
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
- return null;
+ return value;
}
private IJavaReferenceType getType(IJavaObject value) {
try {
IJavaType type= value.getJavaType();
if (!(type instanceof IJavaClassType)) {
return null;
}
IJavaClassType classType= (IJavaClassType) type;
if (classType.getName().equals(fType)) {
// found the type
return classType;
}
if (!fSubtypes) {
// if not checking the subtypes, stop here
return null;
}
IJavaClassType superClass= classType.getSuperclass();
while (superClass != null) {
if (superClass.getName().equals(fType)) {
// found the type, it's a super class
return superClass;
}
superClass= superClass.getSuperclass();
}
IJavaInterfaceType[] superInterfaces= classType.getAllInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
if (superInterfaces[i].getName().equals(fType)) {
// found the type, it's a super interface
return superInterfaces[i];
}
}
} catch (DebugException e) {
JDIDebugPlugin.log(e);
return null;
}
return null;
}
/**
* Return the current stack frame context, or a valid stack frame for the given value.
*/
private IJavaStackFrame getStackFrame(IValue value) throws CoreException {
IStatusHandler handler = getStackFrameProvider();
if (handler != null) {
IJavaStackFrame stackFrame = (IJavaStackFrame)handler.handleStatus(fgNeedStackFrame, value);
if (stackFrame != null) {
return stackFrame;
}
}
IDebugTarget target = value.getDebugTarget();
IJavaDebugTarget javaTarget = (IJavaDebugTarget) target.getAdapter(IJavaDebugTarget.class);
if (javaTarget != null) {
IThread[] threads = javaTarget.getThreads();
for (int i = 0; i < threads.length; i++) {
IThread thread = threads[i];
if (thread.isSuspended()) {
return (IJavaStackFrame)thread.getTopStackFrame();
}
}
}
return null;
}
private static IStatusHandler getStackFrameProvider() {
if (fgStackFrameProvider == null) {
fgStackFrameProvider = DebugPlugin.getDefault().getStatusHandler(fgNeedStackFrame);
}
return fgStackFrameProvider;
}
/**
* Returns if this logical structure should be used for subtypes too.
*/
public boolean isSubtypes() {
return fSubtypes;
}
/**
* Sets if this logical structure should be used for subtypes or not.
*/
public void setSubtypes(boolean subtypes) {
fSubtypes = subtypes;
}
/**
* Returns the name of the type this logical structure should be used for.
*/
public String getQualifiedTypeName() {
return fType;
}
/**
* Sets the name of the type this logical structure should be used for.
*/
public void setType(String type) {
fType = type;
}
/**
* Returns the code snippet to use to generate the logical structure.
*/
public String getValue() {
return fValue;
}
/**
* Sets the code snippet to use to generate the logical structure.
*/
public void setValue(String value) {
fValue = value;
}
/**
* Returns the variables of this logical structure.
*/
public String[][] getVariables() {
return fVariables;
}
/**
* Sets the variables of this logical structure.
*/
public void setVariables(String[][] variables) {
fVariables = variables;
}
/**
* Set the description of this logical structure.
*/
public void setDescription(String description) {
fDescription = description;
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.model.ILogicalStructureTypeDelegate2#getDescription(org.eclipse.debug.core.model.IValue)
*/
public String getDescription(IValue value) {
return getDescription();
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.ILogicalStructureType#getDescription()
*/
public String getDescription() {
return fDescription;
}
/**
* Indicates if this logical structure was contributed by a plug-in
* or defined by a user.
*/
public boolean isContributed() {
return fContributingPluginId != null;
}
/**
* Returns the plugin identifier of the plugin which contributed this logical
* structure or <code>null</code> if this structure was defined by the user.
* @return the plugin identifier of the plugin which contributed this
* structure or <code>null</code>
*/
public String getContributingPluginId() {
return fContributingPluginId;
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.ILogicalStructureType#getId()
*/
public String getId() {
return JDIDebugPlugin.getUniqueIdentifier() + fType + fDescription;
}
}
| false | true | public IValue getLogicalStructure(IValue value) {
if (!(value instanceof IJavaObject)) {
return null;
}
IJavaObject javaValue= (IJavaObject) value;
try {
IJavaReferenceType type = getType(javaValue);
if (type == null) {
return null;
}
IJavaStackFrame stackFrame= getStackFrame(javaValue);
if (stackFrame == null) {
return null;
}
// find the project the snippets will be compiled in.
ISourceLocator locator= javaValue.getLaunch().getSourceLocator();
Object sourceElement= null;
if (locator instanceof ISourceLookupDirector) {
if (type instanceof JDIReferenceType) {
String[] sourcePaths= ((JDIReferenceType) type).getSourcePaths(null);
if (sourcePaths.length > 0) {
sourceElement= ((ISourceLookupDirector) locator).getSourceElement(sourcePaths[0]);
}
}
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
if (sourceElement == null) {
sourceElement = locator.getSourceElement(stackFrame);
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
IJavaProject project= null;
if (sourceElement instanceof IJavaElement) {
project= ((IJavaElement) sourceElement).getJavaProject();
} else if (sourceElement instanceof IResource) {
IJavaProject resourceProject = JavaCore.create(((IResource)sourceElement).getProject());
if (resourceProject.exists()) {
project= resourceProject;
}
}
if (project == null) {
return null;
}
IAstEvaluationEngine evaluationEngine= JDIDebugPlugin.getDefault().getEvaluationEngine(project, (IJavaDebugTarget)stackFrame.getDebugTarget());
EvaluationBlock evaluationBlock= new EvaluationBlock(javaValue, type, (IJavaThread)stackFrame.getThread(), evaluationEngine);
if (fValue == null) {
// evaluate each variable
IJavaVariable[] variables= new IJavaVariable[fVariables.length];
for (int i= 0; i < fVariables.length; i++) {
variables[i]= new JDIPlaceholderVariable(fVariables[i][0], evaluationBlock.evaluate(fVariables[i][1]));
}
return new LogicalObjectStructureValue(javaValue, variables);
}
// evaluate the logical value
return evaluationBlock.evaluate(fValue);
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
return null;
}
| public IValue getLogicalStructure(IValue value) {
if (!(value instanceof IJavaObject)) {
return value;
}
IJavaObject javaValue= (IJavaObject) value;
try {
IJavaReferenceType type = getType(javaValue);
if (type == null) {
return value;
}
IJavaStackFrame stackFrame= getStackFrame(javaValue);
if (stackFrame == null) {
return value;
}
// find the project the snippets will be compiled in.
ISourceLocator locator= javaValue.getLaunch().getSourceLocator();
Object sourceElement= null;
if (locator instanceof ISourceLookupDirector) {
if (type instanceof JDIReferenceType) {
String[] sourcePaths= ((JDIReferenceType) type).getSourcePaths(null);
if (sourcePaths.length > 0) {
sourceElement= ((ISourceLookupDirector) locator).getSourceElement(sourcePaths[0]);
}
}
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
if (sourceElement == null) {
sourceElement = locator.getSourceElement(stackFrame);
if (!(sourceElement instanceof IJavaElement) && sourceElement instanceof IAdaptable) {
sourceElement = ((IAdaptable)sourceElement).getAdapter(IJavaElement.class);
}
}
IJavaProject project= null;
if (sourceElement instanceof IJavaElement) {
project= ((IJavaElement) sourceElement).getJavaProject();
} else if (sourceElement instanceof IResource) {
IJavaProject resourceProject = JavaCore.create(((IResource)sourceElement).getProject());
if (resourceProject.exists()) {
project= resourceProject;
}
}
if (project == null) {
return value;
}
IAstEvaluationEngine evaluationEngine= JDIDebugPlugin.getDefault().getEvaluationEngine(project, (IJavaDebugTarget)stackFrame.getDebugTarget());
EvaluationBlock evaluationBlock= new EvaluationBlock(javaValue, type, (IJavaThread)stackFrame.getThread(), evaluationEngine);
if (fValue == null) {
// evaluate each variable
IJavaVariable[] variables= new IJavaVariable[fVariables.length];
for (int i= 0; i < fVariables.length; i++) {
variables[i]= new JDIPlaceholderVariable(fVariables[i][0], evaluationBlock.evaluate(fVariables[i][1]));
}
return new LogicalObjectStructureValue(javaValue, variables);
}
// evaluate the logical value
return evaluationBlock.evaluate(fValue);
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
return value;
}
|
diff --git a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/InfoPixelLabelProvider.java b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/InfoPixelLabelProvider.java
index d5c40395d..17ba6ee38 100644
--- a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/InfoPixelLabelProvider.java
+++ b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/InfoPixelLabelProvider.java
@@ -1,156 +1,156 @@
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dawb.workbench.plotting.tools;
import java.util.Collection;
import org.dawb.common.ui.plot.IPlottingSystem;
import org.dawb.common.ui.plot.region.IRegion;
import org.dawb.common.ui.plot.region.IRegion.RegionType;
import org.dawb.common.ui.plot.trace.IImageTrace;
import org.dawb.common.ui.plot.trace.ITrace;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
import uk.ac.diamond.scisoft.analysis.diffraction.DetectorProperties;
import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironment;
import uk.ac.diamond.scisoft.analysis.diffraction.QSpace;
import uk.ac.diamond.scisoft.analysis.io.IDiffractionMetadata;
import uk.ac.diamond.scisoft.analysis.io.IMetaData;
import uk.ac.diamond.scisoft.analysis.rcp.pixelinfoutils.Vector3dutil;
import uk.ac.diamond.scisoft.analysis.roi.PointROI;
public class InfoPixelLabelProvider extends ColumnLabelProvider {
private final int column;
private final InfoPixelTool tool;
private final IPlottingSystem plotSystem;
private static final Logger logger = LoggerFactory.getLogger(InfoPixelLabelProvider.class);
public InfoPixelLabelProvider(InfoPixelTool tool, int i) {
this.column = i;
this.tool = tool;
this.plotSystem = tool.getPlottingSystem();
}
@Override
public String getText(Object element) {
double x = 0.0;
double y = 0.0;
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
x = pr.getPointX();
y = pr.getPointY();
} else {
x = tool.xValues[0];
y = tool.yValues[0];
}
}else {
return null;
}
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
final Collection<ITrace> traces = plotSystem.getTraces(IImageTrace.class);
final IImageTrace trace = traces!=null && traces.size()>0 ? (IImageTrace)traces.iterator().next() : null;
if (trace!=null) {
set = trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, x, y);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return String.format("% 4.4f", x);
case 2: // "Y position"
return String.format("% 4.4f", y);
case 3: // "Data value"
if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", set.getDouble((int)y, (int) x));
case 4: // q X
if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (qSpace == null) return "-";
- return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScaterringAngle(qSpace)));
+ return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace)));
case 8: // resolution
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
@Override
public String getToolTipText(Object element) {
return "Any selection region can be used in information box tool.";
}
}
| true | true | public String getText(Object element) {
double x = 0.0;
double y = 0.0;
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
x = pr.getPointX();
y = pr.getPointY();
} else {
x = tool.xValues[0];
y = tool.yValues[0];
}
}else {
return null;
}
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
final Collection<ITrace> traces = plotSystem.getTraces(IImageTrace.class);
final IImageTrace trace = traces!=null && traces.size()>0 ? (IImageTrace)traces.iterator().next() : null;
if (trace!=null) {
set = trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, x, y);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return String.format("% 4.4f", x);
case 2: // "Y position"
return String.format("% 4.4f", y);
case 3: // "Data value"
if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", set.getDouble((int)y, (int) x));
case 4: // q X
if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (qSpace == null) return "-";
return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScaterringAngle(qSpace)));
case 8: // resolution
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
| public String getText(Object element) {
double x = 0.0;
double y = 0.0;
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
x = pr.getPointX();
y = pr.getPointY();
} else {
x = tool.xValues[0];
y = tool.yValues[0];
}
}else {
return null;
}
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
final Collection<ITrace> traces = plotSystem.getTraces(IImageTrace.class);
final IImageTrace trace = traces!=null && traces.size()>0 ? (IImageTrace)traces.iterator().next() : null;
if (trace!=null) {
set = trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, x, y);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return String.format("% 4.4f", x);
case 2: // "Y position"
return String.format("% 4.4f", y);
case 3: // "Data value"
if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", set.getDouble((int)y, (int) x));
case 4: // q X
if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (qSpace == null) return "-";
return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace)));
case 8: // resolution
if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
|
diff --git a/src/main/java/dungeon/ui/screens/Canvas.java b/src/main/java/dungeon/ui/screens/Canvas.java
index b47ea1d..f088d4a 100644
--- a/src/main/java/dungeon/ui/screens/Canvas.java
+++ b/src/main/java/dungeon/ui/screens/Canvas.java
@@ -1,82 +1,82 @@
package dungeon.ui.screens;
import dungeon.load.messages.LevelLoadedEvent;
import dungeon.messages.Message;
import dungeon.messages.MessageHandler;
import dungeon.models.*;
import dungeon.models.messages.Transform;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
public class Canvas extends JPanel implements MessageHandler {
private final Color blockingTile = new Color(181, 125, 147);
private final Color passableTile = new Color(139, 108, 217);
private final Color victoryTile = new Color(255, 244, 25);
private final Color teleporterTile = new Color(0, 0, 0);
private final Color playerColor = new Color(101, 202, 227);
private final Color enemyColor = new Color(33, 237, 60);
private World world;
public Canvas () {
this.setFocusable(true);
}
@Override
public void handleMessage (Message message) {
if (message instanceof Transform) {
this.world = this.world.apply((Transform) message);
} else if (message instanceof LevelLoadedEvent) {
this.world = ((LevelLoadedEvent) message).getWorld();
}
repaint();
}
@Override
protected void paintComponent (Graphics g) {
super.paintComponent(g);
if (this.world == null) {
return;
}
Room room = this.world.getCurrentRoom();
- int tileWidth = g.getClipBounds().width * Tile.SIZE / (int)room.getXSize();
- int tileHeight = g.getClipBounds().height * Tile.SIZE / (int)room.getYSize();
+ double xPixelPerUnit = (double)g.getClipBounds().width / room.getXSize();
+ double yPixelPerUnit = (double)g.getClipBounds().height / room.getYSize();
for (Tile tile : room.getTiles()) {
if (tile instanceof TeleporterTile) {
g.setColor(this.teleporterTile);
} else if (tile instanceof VictoryTile) {
g.setColor(this.victoryTile);
} else if (tile.isBlocking()) {
g.setColor(this.blockingTile);
} else {
g.setColor(this.passableTile);
}
- g.fillRect(tile.getPosition().getX() * tileWidth / Tile.SIZE, tile.getPosition().getY() * tileHeight / Tile.SIZE, tileWidth, tileHeight);
+ g.fillRect((int)(tile.getPosition().getX() * xPixelPerUnit), (int)(tile.getPosition().getY() * yPixelPerUnit), (int)(Tile.SIZE * xPixelPerUnit), (int)(Tile.SIZE * yPixelPerUnit));
}
for (Enemy enemy : room.getEnemies()) {
Position position = enemy.getPosition();
g.setColor(this.enemyColor);
- g.fillRect(position.getX() * tileWidth / Enemy.SIZE, position.getY() * tileHeight / Enemy.SIZE, tileWidth, tileHeight);
+ g.fillRect((int)(position.getX() * xPixelPerUnit), (int)(position.getY() * yPixelPerUnit), (int)(Enemy.SIZE * xPixelPerUnit), (int)(Enemy.SIZE * yPixelPerUnit));
}
Position playerPosition = this.world.getPlayer().getPosition();
g.setColor(this.playerColor);
- g.fillRect(playerPosition.getX() * tileWidth / Player.SIZE, playerPosition.getY() * tileHeight / Player.SIZE, tileWidth, tileHeight);
+ g.fillRect((int)(playerPosition.getX() * xPixelPerUnit), (int)(playerPosition.getY() * yPixelPerUnit), (int)(Player.SIZE * xPixelPerUnit), (int)(Player.SIZE * yPixelPerUnit));
}
}
| false | true | protected void paintComponent (Graphics g) {
super.paintComponent(g);
if (this.world == null) {
return;
}
Room room = this.world.getCurrentRoom();
int tileWidth = g.getClipBounds().width * Tile.SIZE / (int)room.getXSize();
int tileHeight = g.getClipBounds().height * Tile.SIZE / (int)room.getYSize();
for (Tile tile : room.getTiles()) {
if (tile instanceof TeleporterTile) {
g.setColor(this.teleporterTile);
} else if (tile instanceof VictoryTile) {
g.setColor(this.victoryTile);
} else if (tile.isBlocking()) {
g.setColor(this.blockingTile);
} else {
g.setColor(this.passableTile);
}
g.fillRect(tile.getPosition().getX() * tileWidth / Tile.SIZE, tile.getPosition().getY() * tileHeight / Tile.SIZE, tileWidth, tileHeight);
}
for (Enemy enemy : room.getEnemies()) {
Position position = enemy.getPosition();
g.setColor(this.enemyColor);
g.fillRect(position.getX() * tileWidth / Enemy.SIZE, position.getY() * tileHeight / Enemy.SIZE, tileWidth, tileHeight);
}
Position playerPosition = this.world.getPlayer().getPosition();
g.setColor(this.playerColor);
g.fillRect(playerPosition.getX() * tileWidth / Player.SIZE, playerPosition.getY() * tileHeight / Player.SIZE, tileWidth, tileHeight);
}
| protected void paintComponent (Graphics g) {
super.paintComponent(g);
if (this.world == null) {
return;
}
Room room = this.world.getCurrentRoom();
double xPixelPerUnit = (double)g.getClipBounds().width / room.getXSize();
double yPixelPerUnit = (double)g.getClipBounds().height / room.getYSize();
for (Tile tile : room.getTiles()) {
if (tile instanceof TeleporterTile) {
g.setColor(this.teleporterTile);
} else if (tile instanceof VictoryTile) {
g.setColor(this.victoryTile);
} else if (tile.isBlocking()) {
g.setColor(this.blockingTile);
} else {
g.setColor(this.passableTile);
}
g.fillRect((int)(tile.getPosition().getX() * xPixelPerUnit), (int)(tile.getPosition().getY() * yPixelPerUnit), (int)(Tile.SIZE * xPixelPerUnit), (int)(Tile.SIZE * yPixelPerUnit));
}
for (Enemy enemy : room.getEnemies()) {
Position position = enemy.getPosition();
g.setColor(this.enemyColor);
g.fillRect((int)(position.getX() * xPixelPerUnit), (int)(position.getY() * yPixelPerUnit), (int)(Enemy.SIZE * xPixelPerUnit), (int)(Enemy.SIZE * yPixelPerUnit));
}
Position playerPosition = this.world.getPlayer().getPosition();
g.setColor(this.playerColor);
g.fillRect((int)(playerPosition.getX() * xPixelPerUnit), (int)(playerPosition.getY() * yPixelPerUnit), (int)(Player.SIZE * xPixelPerUnit), (int)(Player.SIZE * yPixelPerUnit));
}
|
diff --git a/src/main/java/com/spartansoftwareinc/globalsight/gscli/WebServiceCommand.java b/src/main/java/com/spartansoftwareinc/globalsight/gscli/WebServiceCommand.java
index df3bff8..84d73d5 100755
--- a/src/main/java/com/spartansoftwareinc/globalsight/gscli/WebServiceCommand.java
+++ b/src/main/java/com/spartansoftwareinc/globalsight/gscli/WebServiceCommand.java
@@ -1,158 +1,161 @@
package com.spartansoftwareinc.globalsight.gscli;
import java.rmi.RemoteException;
import java.util.Date;
import javax.xml.stream.XMLInputFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
@SuppressWarnings("static-access")
public abstract class WebServiceCommand extends Command {
private Profile profile;
// Default implementation that actually wants a webservice.
public void handle(CommandLine command, UserData userData)
throws Exception {
if (command.hasOption(PROFILE)) {
profile = userData.getProfiles()
.getProfile(command.getOptionValue(PROFILE));
+ if (profile == null) {
+ die("Not such profile: '" + command.getOptionValue(PROFILE) + "'");
+ }
}
else {
profile = userData.getProfiles().getDefaultProfile();
if (profile != null) {
verbose("Using default profile '" +
profile.getProfileName() + "'");
}
else {
die("No default profile set; must use --profile");
}
}
String url = null;
if (command.hasOption(URL)) {
url = command.getOptionValue(URL);
}
else if (profile != null){
url = profile.getUrl();
}
if (url == null) {
die("No URL specified. Specify with --url=<url>");
}
WebService ws = new WebService(url, XMLInputFactory.newInstance());
// XXX Ugly
// TODO: also, lazily calculate this -- right now we always do it
// even if the command dies immediately
String token = getAuthToken(userData, profile);
try {
execWithAuth(ws, userData, command, token, profile);
}
catch (RemoteException e) {
ErrorParser parser = new ErrorParser();
Error error = parser.parse(e.getMessage());
if (error instanceof InvalidTokenError) {
try {
execWithAuth(ws, userData, command, null, profile);
}
catch (RemoteException e2) {
dieWithError(parser.parse(e2.getMessage()));
}
}
else {
dieWithError(error);
}
}
}
static final String PROFILE = "profile";
static final Option PROFILE_OPT = OptionBuilder
.withArgName(PROFILE)
.hasArg()
.withDescription("profile name")
.create(PROFILE);
@Override
public Options getOptions() {
Options options = super.getOptions();
options.addOption(PROFILE_OPT);
return options;
}
void execWithAuth(WebService ws, UserData userData, CommandLine command,
String token, Profile profile) throws Exception {
if (token == null) {
token = authorize(ws, userData);
verbose("Received token " + token);
// Update Session cache
Sessions sessions = userData.getSessions();
sessions.setSession(profile.getProfileName(), token);
userData.setSessions(sessions);
}
else {
verbose("Using cached auth token " + token);
}
ws.setToken(token);
execute(command, userData, ws);
}
private void dieWithError(Error error) {
die("Webservice error (" + error.getStatus() + "): " +
error.getError());
}
protected Profile getProfile() {
return profile;
}
protected String authorize(WebService ws, UserData userData)
throws Exception {
String username = null, password = null;
if (getProfile() != null) {
username = getProfile().getUsername();
password = getProfile().getPassword();
}
if (username == null) {
die("No username specified. Specify with --user=<username>");
}
if (password == null) {
die("No password specified. Specify with --password=<password>");
}
return ws.login(username, password);
}
protected String getAuthToken(UserData userData, Profile profile) throws Exception {
if (profile == null) {
return null;
}
Sessions sessions = userData.getSessions();
Session session = sessions.getSession(profile.getProfileName());
if (session == null) {
return null;
}
// XXX Is this the right place to validate the timestamp?
String token = session.getToken();
if (token == null) {
return null;
}
Date timestamp = session.getDate(), now = new Date();
if (!timestamp.before(now)) {
// Strange date corruption
return null;
}
long delta = (now.getTime() - timestamp.getTime());
// Expire the token
if (delta > ONE_HOUR) {
return null;
}
return token;
}
public static final long ONE_HOUR = 1000 * 60 * 60;
protected abstract void execute(CommandLine command, UserData userData,
WebService webService) throws Exception;
}
| true | true | public void handle(CommandLine command, UserData userData)
throws Exception {
if (command.hasOption(PROFILE)) {
profile = userData.getProfiles()
.getProfile(command.getOptionValue(PROFILE));
}
else {
profile = userData.getProfiles().getDefaultProfile();
if (profile != null) {
verbose("Using default profile '" +
profile.getProfileName() + "'");
}
else {
die("No default profile set; must use --profile");
}
}
String url = null;
if (command.hasOption(URL)) {
url = command.getOptionValue(URL);
}
else if (profile != null){
url = profile.getUrl();
}
if (url == null) {
die("No URL specified. Specify with --url=<url>");
}
WebService ws = new WebService(url, XMLInputFactory.newInstance());
// XXX Ugly
// TODO: also, lazily calculate this -- right now we always do it
// even if the command dies immediately
String token = getAuthToken(userData, profile);
try {
execWithAuth(ws, userData, command, token, profile);
}
catch (RemoteException e) {
ErrorParser parser = new ErrorParser();
Error error = parser.parse(e.getMessage());
if (error instanceof InvalidTokenError) {
try {
execWithAuth(ws, userData, command, null, profile);
}
catch (RemoteException e2) {
dieWithError(parser.parse(e2.getMessage()));
}
}
else {
dieWithError(error);
}
}
}
| public void handle(CommandLine command, UserData userData)
throws Exception {
if (command.hasOption(PROFILE)) {
profile = userData.getProfiles()
.getProfile(command.getOptionValue(PROFILE));
if (profile == null) {
die("Not such profile: '" + command.getOptionValue(PROFILE) + "'");
}
}
else {
profile = userData.getProfiles().getDefaultProfile();
if (profile != null) {
verbose("Using default profile '" +
profile.getProfileName() + "'");
}
else {
die("No default profile set; must use --profile");
}
}
String url = null;
if (command.hasOption(URL)) {
url = command.getOptionValue(URL);
}
else if (profile != null){
url = profile.getUrl();
}
if (url == null) {
die("No URL specified. Specify with --url=<url>");
}
WebService ws = new WebService(url, XMLInputFactory.newInstance());
// XXX Ugly
// TODO: also, lazily calculate this -- right now we always do it
// even if the command dies immediately
String token = getAuthToken(userData, profile);
try {
execWithAuth(ws, userData, command, token, profile);
}
catch (RemoteException e) {
ErrorParser parser = new ErrorParser();
Error error = parser.parse(e.getMessage());
if (error instanceof InvalidTokenError) {
try {
execWithAuth(ws, userData, command, null, profile);
}
catch (RemoteException e2) {
dieWithError(parser.parse(e2.getMessage()));
}
}
else {
dieWithError(error);
}
}
}
|
diff --git a/src/com/undeadscythes/udsplugin/Config.java b/src/com/undeadscythes/udsplugin/Config.java
index 1b3af89..a7ce33c 100644
--- a/src/com/undeadscythes/udsplugin/Config.java
+++ b/src/com/undeadscythes/udsplugin/Config.java
@@ -1,158 +1,159 @@
package com.undeadscythes.udsplugin;
import java.util.*;
import org.apache.commons.lang.*;
import org.bukkit.*;
import org.bukkit.configuration.file.*;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
/**
* Storage of config values to help aid maintenance.
* @author UndeadScythes
*/
public final class Config {
public static boolean blockEndermen;
public static boolean blockSilverfish;
public static boolean blockCreepers;
public static boolean blockTNT;
public static boolean blockWither;
public static byte mapData;
public static int undoCount;
public static int compassRange;
public static int drainRange;
public static int expandCost;
public static int mapCost;
public static int homeCost;
public static int shopCost;
public static int vipCost;
public static int clanCost;
public static int baseCost;
public static int cityCost;
public static int buildCost;
public static int spawnerEXP;
public static int moveRange;
public static int editRange;
public static int butcherRange;
public static int worldBorder;
public static int worldBorderSq;
public static int vipSpawns;
public static long minecartTTL;
public static long dragonRespawn;
public static long pvpTime;
public static long requestTTL;
public static long vipTime;
public static long slowTime;
public static String currency;
public static String currencies;
public static String serverOwner;
public static String welcome;
public static String welcomeAdmin;
public static World mainWorld;
public static Material welcomeGift;
public static List<String> serverRules;
public static List<Material> whitelistVIP;
public static List<Kit> kits;
public static Map<RegionFlag, Boolean> globalFlags;
public static Map<String, Integer> mobRewards;
public final static List<Material> WATER = new ArrayList<Material>(Arrays.asList(Material.WATER, Material.STATIONARY_WATER));
public final static List<Material> RAILS = new ArrayList<Material>(Arrays.asList(Material.RAILS, Material.POWERED_RAIL, Material.DETECTOR_RAIL));
public final static org.bukkit.util.Vector HALF_BLOCK = new org.bukkit.util.Vector(.5, .5, .5);
public static final List<EntityType> HOSTILE_MOBS = new ArrayList<EntityType>(Arrays.asList(EntityType.BLAZE, EntityType.CAVE_SPIDER, EntityType.CREEPER, EntityType.ENDERMAN, EntityType.ENDER_DRAGON, EntityType.GHAST, EntityType.MAGMA_CUBE, EntityType.SILVERFISH, EntityType.SKELETON, EntityType.SLIME, EntityType.SPIDER, EntityType.WITCH, EntityType.WITHER, EntityType.ZOMBIE));
public static final List<EntityType> PASSIVE_MOBS = new ArrayList<EntityType>(Arrays.asList(EntityType.BAT, EntityType.CHICKEN, EntityType.COW, EntityType.MUSHROOM_COW, EntityType.OCELOT, EntityType.PIG, EntityType.SHEEP, EntityType.SQUID, EntityType.VILLAGER));
public static final List<EntityType> NEUTRAL_MOBS = new ArrayList<EntityType>(Arrays.asList(EntityType.IRON_GOLEM, EntityType.PIG_ZOMBIE, EntityType.SNOWMAN, EntityType.WOLF));
public final static String INT_REGEX = "[0-9][0-9]*";
private static UDSPlugin plugin;
/**
* Load the online 'easy-access' config class with values from the file on disk.
* @param config
*/
public static void loadConfig(final UDSPlugin plugin) {
Config.plugin = plugin;
plugin.saveDefaultConfig();
plugin.getConfig();
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
undoCount = config.getInt("range.undo");
buildCost = config.getInt("cost.build");
currencies = config.getString("currency.plural");
requestTTL = config.getLong("request-timeout") * Timer.SECOND;
slowTime = config.getLong("auto-save") * Timer.MINUTE;
vipSpawns = config.getInt("vip.spawns");
vipTime = config.getLong("vip.time") * Timer.DAY;
welcome = config.getString("welcome.message");
welcomeGift = Material.getMaterial(config.getString("welcome.gift").toUpperCase());
worldBorder = config.getInt("range.world");
worldBorderSq = (int)Math.pow(worldBorder, 2);
welcomeAdmin = config.getString("welcome.admin");
butcherRange = (int)Math.pow(config.getInt("range.butcher"), 2);
pvpTime = config.getLong("pvp-time") * Timer.SECOND;
spawnerEXP = config.getInt("exp.spawner");
serverOwner = config.getString("server-owner");
dragonRespawn = config.getLong("respawn-dragon") * Timer.MINUTE;
cityCost = config.getInt("cost.city");
currency = config.getString("currency.singular");
mapCost = config.getInt("cost.map");
homeCost = config.getInt("cost.home");
shopCost = config.getInt("cost.shop");
vipCost = config.getInt("cost.vip");
clanCost = config.getInt("cost.clan");
baseCost = config.getInt("cost.base");
drainRange = config.getInt("range.drain");
moveRange = config.getInt("range.move");
editRange = config.getInt("range.edit");
whitelistVIP = new ArrayList<Material>();
for(int id : config.getIntegerList("item-whitelist")) {
whitelistVIP.add(Material.getMaterial(id));
}
kits = new ArrayList<Kit>();
for(String kit : config.getStringList("kits")) {
final String[] kitSplit = kit.split(",");
final List<ItemStack> items = new ArrayList<ItemStack>();
for(Object item : ArrayUtils.subarray(kitSplit, 3, kitSplit.length -1)) {
items.add(new ItemStack(Material.getMaterial(Integer.parseInt((String)item))));
}
kits.add(new Kit(kitSplit[0], Integer.parseInt(kitSplit[1]), items, PlayerRank.getByName(kitSplit[2])));
}
expandCost = config.getInt("cost.expand");
mapData = (byte)config.getInt("map-data");
serverRules = new ArrayList<String>(config.getStringList("server-rules"));
blockCreepers = config.getBoolean("block.creeper");
blockTNT = config.getBoolean("block.tnt");
blockWither = config.getBoolean("block.wither");
blockEndermen = config.getBoolean("block.enderman");
blockSilverfish = config.getBoolean("block.silverfish");
mobRewards = new HashMap<String, Integer>();
for(String reward : config.getStringList("mob-rewards")) {
mobRewards.put(reward.split(":")[0], Integer.parseInt(reward.split(":")[1]));
}
compassRange = config.getInt("range.compass");
globalFlags = new HashMap<RegionFlag, Boolean>();
for(RegionFlag flag : RegionFlag.values()) {
- globalFlags.put(flag, config.getBoolean("global-flags." + flag.toString()));
+ String flagname = "global-flags." + flag.toString().toLowerCase();
+ globalFlags.put(flag, config.getBoolean(flagname));
}
mainWorld = Bukkit.getWorld(config.getString("world-name"));
minecartTTL = config.getLong("minecart.life") * Timer.SECOND;
}
/**
*
*/
public static void updateConfig() {
plugin.getConfig().options().copyDefaults(true);
plugin.saveConfig();
loadConfig(plugin);
}
/**
*
*/
public static void reload() {
loadConfig(plugin);
}
private Config() {}
}
| true | true | public static void loadConfig(final UDSPlugin plugin) {
Config.plugin = plugin;
plugin.saveDefaultConfig();
plugin.getConfig();
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
undoCount = config.getInt("range.undo");
buildCost = config.getInt("cost.build");
currencies = config.getString("currency.plural");
requestTTL = config.getLong("request-timeout") * Timer.SECOND;
slowTime = config.getLong("auto-save") * Timer.MINUTE;
vipSpawns = config.getInt("vip.spawns");
vipTime = config.getLong("vip.time") * Timer.DAY;
welcome = config.getString("welcome.message");
welcomeGift = Material.getMaterial(config.getString("welcome.gift").toUpperCase());
worldBorder = config.getInt("range.world");
worldBorderSq = (int)Math.pow(worldBorder, 2);
welcomeAdmin = config.getString("welcome.admin");
butcherRange = (int)Math.pow(config.getInt("range.butcher"), 2);
pvpTime = config.getLong("pvp-time") * Timer.SECOND;
spawnerEXP = config.getInt("exp.spawner");
serverOwner = config.getString("server-owner");
dragonRespawn = config.getLong("respawn-dragon") * Timer.MINUTE;
cityCost = config.getInt("cost.city");
currency = config.getString("currency.singular");
mapCost = config.getInt("cost.map");
homeCost = config.getInt("cost.home");
shopCost = config.getInt("cost.shop");
vipCost = config.getInt("cost.vip");
clanCost = config.getInt("cost.clan");
baseCost = config.getInt("cost.base");
drainRange = config.getInt("range.drain");
moveRange = config.getInt("range.move");
editRange = config.getInt("range.edit");
whitelistVIP = new ArrayList<Material>();
for(int id : config.getIntegerList("item-whitelist")) {
whitelistVIP.add(Material.getMaterial(id));
}
kits = new ArrayList<Kit>();
for(String kit : config.getStringList("kits")) {
final String[] kitSplit = kit.split(",");
final List<ItemStack> items = new ArrayList<ItemStack>();
for(Object item : ArrayUtils.subarray(kitSplit, 3, kitSplit.length -1)) {
items.add(new ItemStack(Material.getMaterial(Integer.parseInt((String)item))));
}
kits.add(new Kit(kitSplit[0], Integer.parseInt(kitSplit[1]), items, PlayerRank.getByName(kitSplit[2])));
}
expandCost = config.getInt("cost.expand");
mapData = (byte)config.getInt("map-data");
serverRules = new ArrayList<String>(config.getStringList("server-rules"));
blockCreepers = config.getBoolean("block.creeper");
blockTNT = config.getBoolean("block.tnt");
blockWither = config.getBoolean("block.wither");
blockEndermen = config.getBoolean("block.enderman");
blockSilverfish = config.getBoolean("block.silverfish");
mobRewards = new HashMap<String, Integer>();
for(String reward : config.getStringList("mob-rewards")) {
mobRewards.put(reward.split(":")[0], Integer.parseInt(reward.split(":")[1]));
}
compassRange = config.getInt("range.compass");
globalFlags = new HashMap<RegionFlag, Boolean>();
for(RegionFlag flag : RegionFlag.values()) {
globalFlags.put(flag, config.getBoolean("global-flags." + flag.toString()));
}
mainWorld = Bukkit.getWorld(config.getString("world-name"));
minecartTTL = config.getLong("minecart.life") * Timer.SECOND;
}
| public static void loadConfig(final UDSPlugin plugin) {
Config.plugin = plugin;
plugin.saveDefaultConfig();
plugin.getConfig();
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
undoCount = config.getInt("range.undo");
buildCost = config.getInt("cost.build");
currencies = config.getString("currency.plural");
requestTTL = config.getLong("request-timeout") * Timer.SECOND;
slowTime = config.getLong("auto-save") * Timer.MINUTE;
vipSpawns = config.getInt("vip.spawns");
vipTime = config.getLong("vip.time") * Timer.DAY;
welcome = config.getString("welcome.message");
welcomeGift = Material.getMaterial(config.getString("welcome.gift").toUpperCase());
worldBorder = config.getInt("range.world");
worldBorderSq = (int)Math.pow(worldBorder, 2);
welcomeAdmin = config.getString("welcome.admin");
butcherRange = (int)Math.pow(config.getInt("range.butcher"), 2);
pvpTime = config.getLong("pvp-time") * Timer.SECOND;
spawnerEXP = config.getInt("exp.spawner");
serverOwner = config.getString("server-owner");
dragonRespawn = config.getLong("respawn-dragon") * Timer.MINUTE;
cityCost = config.getInt("cost.city");
currency = config.getString("currency.singular");
mapCost = config.getInt("cost.map");
homeCost = config.getInt("cost.home");
shopCost = config.getInt("cost.shop");
vipCost = config.getInt("cost.vip");
clanCost = config.getInt("cost.clan");
baseCost = config.getInt("cost.base");
drainRange = config.getInt("range.drain");
moveRange = config.getInt("range.move");
editRange = config.getInt("range.edit");
whitelistVIP = new ArrayList<Material>();
for(int id : config.getIntegerList("item-whitelist")) {
whitelistVIP.add(Material.getMaterial(id));
}
kits = new ArrayList<Kit>();
for(String kit : config.getStringList("kits")) {
final String[] kitSplit = kit.split(",");
final List<ItemStack> items = new ArrayList<ItemStack>();
for(Object item : ArrayUtils.subarray(kitSplit, 3, kitSplit.length -1)) {
items.add(new ItemStack(Material.getMaterial(Integer.parseInt((String)item))));
}
kits.add(new Kit(kitSplit[0], Integer.parseInt(kitSplit[1]), items, PlayerRank.getByName(kitSplit[2])));
}
expandCost = config.getInt("cost.expand");
mapData = (byte)config.getInt("map-data");
serverRules = new ArrayList<String>(config.getStringList("server-rules"));
blockCreepers = config.getBoolean("block.creeper");
blockTNT = config.getBoolean("block.tnt");
blockWither = config.getBoolean("block.wither");
blockEndermen = config.getBoolean("block.enderman");
blockSilverfish = config.getBoolean("block.silverfish");
mobRewards = new HashMap<String, Integer>();
for(String reward : config.getStringList("mob-rewards")) {
mobRewards.put(reward.split(":")[0], Integer.parseInt(reward.split(":")[1]));
}
compassRange = config.getInt("range.compass");
globalFlags = new HashMap<RegionFlag, Boolean>();
for(RegionFlag flag : RegionFlag.values()) {
String flagname = "global-flags." + flag.toString().toLowerCase();
globalFlags.put(flag, config.getBoolean(flagname));
}
mainWorld = Bukkit.getWorld(config.getString("world-name"));
minecartTTL = config.getLong("minecart.life") * Timer.SECOND;
}
|
diff --git a/src/joshua/sarray/ExtractRules.java b/src/joshua/sarray/ExtractRules.java
index 8bc173b4..82ee0d98 100644
--- a/src/joshua/sarray/ExtractRules.java
+++ b/src/joshua/sarray/ExtractRules.java
@@ -1,318 +1,318 @@
/* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package joshua.sarray;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import joshua.decoder.ff.tm.Rule;
import joshua.util.Cache;
import joshua.util.CommandLineParser;
import joshua.util.CommandLineParser.Option;
import joshua.util.sentence.Vocabulary;
import joshua.util.sentence.alignment.AlignmentGrids;
import joshua.util.sentence.alignment.Alignments;
/**
*
* @author Lane Schwartz
* @version $LastChangedDate:2008-11-13 13:13:31 -0600 (Thu, 13 Nov 2008) $
*/
public class ExtractRules {
/** Logger for this class. */
private static final Logger logger = Logger.getLogger(ExtractRules.class.getName());
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
boolean finalConfirmation = false;
try {
CommandLineParser commandLine = new CommandLineParser();
Option<String> source = commandLine.addStringOption('f',"source","SOURCE_FILE","Source language training file");
Option<String> target = commandLine.addStringOption('e',"target","TARGET_FILE","Target language training file");
Option<String> alignment = commandLine.addStringOption('a',"alignments","ALIGNMENTS_FILE","Source-target alignments training file");
Option<String> test = commandLine.addStringOption('t',"test","TEST_FILE","Source language test file");
Option<String> output = commandLine.addStringOption('o',"output","OUTPUT_FILE","-","Output file");
Option<String> encoding = commandLine.addStringOption("encoding","ENCODING","UTF-8","File encoding format");
Option<Integer> lexSampleSize = commandLine.addIntegerOption("lexSampleSize","LEX_SAMPLE_SIZE",1000, "Size to use when sampling for lexical probability calculations");
Option<Integer> ruleSampleSize = commandLine.addIntegerOption("ruleSampleSize","RULE_SAMPLE_SIZE",300, "Maximum number of rules to store at each node in the prefix tree");
Option<Integer> maxPhraseSpan = commandLine.addIntegerOption("maxPhraseSpan","MAX_PHRASE_SPAN",10, "Max phrase span");
Option<Integer> maxPhraseLength = commandLine.addIntegerOption("maxPhraseLength","MAX_PHRASE_LENGTH",10, "Max phrase length");
Option<Integer> maxNonterminals = commandLine.addIntegerOption("maxNonterminals","MAX_NONTERMINALS",2, "Max nonterminals");
Option<Integer> minNonterminalSpan = commandLine.addIntegerOption("minNonterminalSpan","MIN_NONTERMINAL_SPAN", 2, "Minimum nonterminal span");
Option<Integer> cacheSize = commandLine.addIntegerOption("cache","CACHE",1000, "Max number of patterns for which to cache hierarchical phrases");
//Option<Integer> trainingSize = commandLine.addIntegerOption("trainingSize","NUMBER_OF_TRAINING_SENTENCES", "Number of training sentences");
// Option<String> target_given_source_counts = commandLine.addStringOption("target-given-source-counts","FILENAME","file containing co-occurence counts of source and target word pairs, sorted by source words");
// Option<String> source_given_target_counts = commandLine.addStringOption("source-given-target-counts","FILENAME","file containing co-occurence counts of target and source word pairs, sorted by target words");
Option<Boolean> output_gz = commandLine.addBooleanOption("output-gzipped",false,"should the output file be gzipped");
// Option<Boolean> target_given_source_gz = commandLine.addBooleanOption("target-given-source-gzipped",false,"is the target given source word pair counts file gzipped");
// Option<Boolean> source_given_target_gz = commandLine.addBooleanOption("source-given-target-gzipped",false,"is the source given target word pair counts file gzipped");
Option<Boolean> sentence_initial_X = commandLine.addBooleanOption("sentence-initial-X",false,"should rules with initial X be extracted from sentence-initial phrases");
Option<Boolean> sentence_final_X = commandLine.addBooleanOption("sentence-final-X",false,"should rules with final X be extracted from sentence-final phrases");
Option<Boolean> print_prefixTree = commandLine.addBooleanOption("print-prefix-tree",false,"should prefix tree be printed to standard out (for debugging)");
Option<Boolean> print_rules = commandLine.addBooleanOption("print-rules",true,"should extracted rules be printed to standard out");
Option<String> alignmentType = commandLine.addStringOption("alignmentsType","ALIGNMENT_TYPE","AlignmentGrids","Type of alignment data structure");
Option<Boolean> confirm = commandLine.addBooleanOption("confirm",false,"should program pause for user input before constructing prefix trees?");
commandLine.parse(args);
if (commandLine.getValue(confirm)==true) {
finalConfirmation = true;
}
// Set System.out and System.err to use the provided character encoding
try {
System.setOut(new PrintStream(System.out, true, commandLine.getValue(encoding)));
System.setErr(new PrintStream(System.err, true, commandLine.getValue(encoding)));
} catch (UnsupportedEncodingException e1) {
System.err.println(commandLine.getValue(encoding) + " is not a valid encoding; using system default encoding for System.out and System.err.");
} catch (SecurityException e2) {
System.err.println("Security manager is configured to disallow changes to System.out or System.err; using system default encoding.");
}
// Lane - TODO -
//SuffixArray.INVERTED_INDEX_PRECOMPUTATION_MIN_FREQ = commandLine.getValue("CACHE_PRECOMPUTATION_FREQUENCY_THRESHOLD");
SuffixArray.CACHE_CAPACITY = commandLine.getValue(cacheSize);
if (logger.isLoggable(Level.INFO)) logger.info("Suffix array will cache hierarchical phrases for at most " + SuffixArray.CACHE_CAPACITY + " patterns.");
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language vocabulary.");
String sourceFileName = commandLine.getValue(source);
Vocabulary sourceVocab = new Vocabulary();
int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language corpus array.");
CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language suffix array.");
SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language vocabulary.");
String targetFileName = commandLine.getValue(target);
Vocabulary targetVocab = new Vocabulary();
int[] targetWordsSentences = SuffixArrayFactory.createVocabulary(commandLine.getValue(target), targetVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language corpus array.");
CorpusArray targetCorpusArray = SuffixArrayFactory.createCorpusArray(targetFileName, targetVocab, targetWordsSentences[0], targetWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language suffix array.");
SuffixArray targetSuffixArray = SuffixArrayFactory.createSuffixArray(targetCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
int trainingSize = sourceCorpusArray.getNumSentences();
if (trainingSize != targetCorpusArray.getNumSentences()) {
throw new RuntimeException("Source and target corpora have different number of sentences. This is bad.");
}
if (logger.isLoggable(Level.INFO)) logger.info("Reading alignment data.");
String alignmentFileName = commandLine.getValue(alignment);
Alignments alignments;
if ("AlignmentArray".equals(commandLine.getValue(alignmentType))) {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentArray");
alignments = SuffixArrayFactory.createAlignmentArray(alignmentFileName, sourceSuffixArray, targetSuffixArray);
} else {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentGrids");
alignments = new AlignmentGrids(new Scanner(new File(alignmentFileName)), sourceCorpusArray, targetCorpusArray, trainingSize);
}
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
// Set up the source text for reading
// Scanner target_given_source;
// if (commandLine.getValue(target_given_source_counts).endsWith(".gz") || commandLine.getValue(target_given_source_gz))
// target_given_source = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(target_given_source_counts))),commandLine.getValue(encoding))));
// else
// target_given_source = new Scanner( new File(commandLine.getValue(target_given_source_counts)), commandLine.getValue(encoding));
// // Set up the target text for reading
// Scanner source_given_target;
// if (commandLine.getValue(source_given_target_counts).endsWith(".gz") || commandLine.getValue(source_given_target_gz))
// source_given_target = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(source_given_target_counts))),commandLine.getValue(encoding))));
// else
// source_given_target = new Scanner( new File(commandLine.getValue(source_given_target_counts)), commandLine.getValue(encoding));
PrintStream out;
if ("-".equals(commandLine.getValue(output))) {
out = System.out;
} else if (commandLine.getValue(output).endsWith(".gz") || commandLine.getValue(output_gz)) {
//XXX This currently doesn't work
out = new PrintStream(new GZIPOutputStream(new FileOutputStream(commandLine.getValue(output))));
System.err.println("GZIP output not currently working properly");
System.exit(-1);
} else {
out = new PrintStream(commandLine.getValue(output));
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing lexical probabilities table");
SampledLexProbs lexProbs =
new SampledLexProbs(commandLine.getValue(lexSampleSize), sourceSuffixArray, targetSuffixArray, alignments, Cache.DEFAULT_CAPACITY, false);
//new LexProbs(source_given_target, target_given_source, sourceVocab, targetVocab);
if (logger.isLoggable(Level.INFO)) logger.info("Done constructing lexical probabilities table");
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Should store a max of " + commandLine.getValue(ruleSampleSize) + " rules at each node in a prefix tree.");
Map<Integer,String> ntVocab = new HashMap<Integer,String>();
ntVocab.put(PrefixTree.X, "X");
Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
PrefixTree.SENTENCE_INITIAL_X = commandLine.getValue(sentence_initial_X);
PrefixTree.SENTENCE_FINAL_X = commandLine.getValue(sentence_final_X);
int lineNumber = 0;
RuleExtractor ruleExtractor = new HierarchicalRuleExtractor(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, commandLine.getValue(ruleSampleSize), commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(minNonterminalSpan), commandLine.getValue(maxPhraseSpan));
while (testFileScanner.hasNextLine()) {
String line = testFileScanner.nextLine();
lineNumber++;
int[] words = sourceVocab.getIDs(line);
if (logger.isLoggable(Level.INFO)) logger.info("Constructing prefix tree for source line " + lineNumber + ": " + line);
PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, ruleExtractor, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(minNonterminalSpan));
if (commandLine.getValue(print_prefixTree)==true) {
System.out.println(prefixTree.toString());
}
if (commandLine.getValue(print_rules)) {
if (logger.isLoggable(Level.FINE)) logger.fine("Outputting rules for source line: " + line);
for (Rule rule : prefixTree.getAllRules()) {
String ruleString = rule.toString(ntVocab, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINEST)) logger.finest("Rule: " + ruleString);
out.println(ruleString);
}
}
if (logger.isLoggable(Level.FINER)) logger.finer(lexProbs.sizeInfo());
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
if (logger.isLoggable(Level.FINER)) {
logger.finer("Prefix tree had " + prefixTree.size() + " nodes.");
Pattern maxPattern = null;
int maxHPsize = 0;
int hpsize = 0;
int psize = 0;
for (Map.Entry<Pattern,HierarchicalPhrases> entry : sourceSuffixArray.hierarchicalPhraseCache.entrySet()) {
psize++;
hpsize += entry.getValue().size();
if (hpsize>maxHPsize) {
- maxHPsize = hpsize;
+ maxHPsize = entry.getValue().size();
maxPattern = entry.getKey();
}
}
logger.finer(
psize + " source side entries in the SA cache." + "\n" +
hpsize+ " target side HierarchicalPhrases represented in the cache." + "\n" +
maxHPsize + " is the most HierarchicalPhrases stored for one source side entry ( " +
maxPattern + ")\n"
);
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (finalConfirmation) {
if (logger.isLoggable(Level.INFO)) logger.info("Complete: Please press a key to end program.");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Done extracting rules");
}
}
}
| true | true | public static void main(String[] args) throws IOException {
boolean finalConfirmation = false;
try {
CommandLineParser commandLine = new CommandLineParser();
Option<String> source = commandLine.addStringOption('f',"source","SOURCE_FILE","Source language training file");
Option<String> target = commandLine.addStringOption('e',"target","TARGET_FILE","Target language training file");
Option<String> alignment = commandLine.addStringOption('a',"alignments","ALIGNMENTS_FILE","Source-target alignments training file");
Option<String> test = commandLine.addStringOption('t',"test","TEST_FILE","Source language test file");
Option<String> output = commandLine.addStringOption('o',"output","OUTPUT_FILE","-","Output file");
Option<String> encoding = commandLine.addStringOption("encoding","ENCODING","UTF-8","File encoding format");
Option<Integer> lexSampleSize = commandLine.addIntegerOption("lexSampleSize","LEX_SAMPLE_SIZE",1000, "Size to use when sampling for lexical probability calculations");
Option<Integer> ruleSampleSize = commandLine.addIntegerOption("ruleSampleSize","RULE_SAMPLE_SIZE",300, "Maximum number of rules to store at each node in the prefix tree");
Option<Integer> maxPhraseSpan = commandLine.addIntegerOption("maxPhraseSpan","MAX_PHRASE_SPAN",10, "Max phrase span");
Option<Integer> maxPhraseLength = commandLine.addIntegerOption("maxPhraseLength","MAX_PHRASE_LENGTH",10, "Max phrase length");
Option<Integer> maxNonterminals = commandLine.addIntegerOption("maxNonterminals","MAX_NONTERMINALS",2, "Max nonterminals");
Option<Integer> minNonterminalSpan = commandLine.addIntegerOption("minNonterminalSpan","MIN_NONTERMINAL_SPAN", 2, "Minimum nonterminal span");
Option<Integer> cacheSize = commandLine.addIntegerOption("cache","CACHE",1000, "Max number of patterns for which to cache hierarchical phrases");
//Option<Integer> trainingSize = commandLine.addIntegerOption("trainingSize","NUMBER_OF_TRAINING_SENTENCES", "Number of training sentences");
// Option<String> target_given_source_counts = commandLine.addStringOption("target-given-source-counts","FILENAME","file containing co-occurence counts of source and target word pairs, sorted by source words");
// Option<String> source_given_target_counts = commandLine.addStringOption("source-given-target-counts","FILENAME","file containing co-occurence counts of target and source word pairs, sorted by target words");
Option<Boolean> output_gz = commandLine.addBooleanOption("output-gzipped",false,"should the output file be gzipped");
// Option<Boolean> target_given_source_gz = commandLine.addBooleanOption("target-given-source-gzipped",false,"is the target given source word pair counts file gzipped");
// Option<Boolean> source_given_target_gz = commandLine.addBooleanOption("source-given-target-gzipped",false,"is the source given target word pair counts file gzipped");
Option<Boolean> sentence_initial_X = commandLine.addBooleanOption("sentence-initial-X",false,"should rules with initial X be extracted from sentence-initial phrases");
Option<Boolean> sentence_final_X = commandLine.addBooleanOption("sentence-final-X",false,"should rules with final X be extracted from sentence-final phrases");
Option<Boolean> print_prefixTree = commandLine.addBooleanOption("print-prefix-tree",false,"should prefix tree be printed to standard out (for debugging)");
Option<Boolean> print_rules = commandLine.addBooleanOption("print-rules",true,"should extracted rules be printed to standard out");
Option<String> alignmentType = commandLine.addStringOption("alignmentsType","ALIGNMENT_TYPE","AlignmentGrids","Type of alignment data structure");
Option<Boolean> confirm = commandLine.addBooleanOption("confirm",false,"should program pause for user input before constructing prefix trees?");
commandLine.parse(args);
if (commandLine.getValue(confirm)==true) {
finalConfirmation = true;
}
// Set System.out and System.err to use the provided character encoding
try {
System.setOut(new PrintStream(System.out, true, commandLine.getValue(encoding)));
System.setErr(new PrintStream(System.err, true, commandLine.getValue(encoding)));
} catch (UnsupportedEncodingException e1) {
System.err.println(commandLine.getValue(encoding) + " is not a valid encoding; using system default encoding for System.out and System.err.");
} catch (SecurityException e2) {
System.err.println("Security manager is configured to disallow changes to System.out or System.err; using system default encoding.");
}
// Lane - TODO -
//SuffixArray.INVERTED_INDEX_PRECOMPUTATION_MIN_FREQ = commandLine.getValue("CACHE_PRECOMPUTATION_FREQUENCY_THRESHOLD");
SuffixArray.CACHE_CAPACITY = commandLine.getValue(cacheSize);
if (logger.isLoggable(Level.INFO)) logger.info("Suffix array will cache hierarchical phrases for at most " + SuffixArray.CACHE_CAPACITY + " patterns.");
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language vocabulary.");
String sourceFileName = commandLine.getValue(source);
Vocabulary sourceVocab = new Vocabulary();
int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language corpus array.");
CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language suffix array.");
SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language vocabulary.");
String targetFileName = commandLine.getValue(target);
Vocabulary targetVocab = new Vocabulary();
int[] targetWordsSentences = SuffixArrayFactory.createVocabulary(commandLine.getValue(target), targetVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language corpus array.");
CorpusArray targetCorpusArray = SuffixArrayFactory.createCorpusArray(targetFileName, targetVocab, targetWordsSentences[0], targetWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language suffix array.");
SuffixArray targetSuffixArray = SuffixArrayFactory.createSuffixArray(targetCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
int trainingSize = sourceCorpusArray.getNumSentences();
if (trainingSize != targetCorpusArray.getNumSentences()) {
throw new RuntimeException("Source and target corpora have different number of sentences. This is bad.");
}
if (logger.isLoggable(Level.INFO)) logger.info("Reading alignment data.");
String alignmentFileName = commandLine.getValue(alignment);
Alignments alignments;
if ("AlignmentArray".equals(commandLine.getValue(alignmentType))) {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentArray");
alignments = SuffixArrayFactory.createAlignmentArray(alignmentFileName, sourceSuffixArray, targetSuffixArray);
} else {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentGrids");
alignments = new AlignmentGrids(new Scanner(new File(alignmentFileName)), sourceCorpusArray, targetCorpusArray, trainingSize);
}
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
// Set up the source text for reading
// Scanner target_given_source;
// if (commandLine.getValue(target_given_source_counts).endsWith(".gz") || commandLine.getValue(target_given_source_gz))
// target_given_source = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(target_given_source_counts))),commandLine.getValue(encoding))));
// else
// target_given_source = new Scanner( new File(commandLine.getValue(target_given_source_counts)), commandLine.getValue(encoding));
// // Set up the target text for reading
// Scanner source_given_target;
// if (commandLine.getValue(source_given_target_counts).endsWith(".gz") || commandLine.getValue(source_given_target_gz))
// source_given_target = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(source_given_target_counts))),commandLine.getValue(encoding))));
// else
// source_given_target = new Scanner( new File(commandLine.getValue(source_given_target_counts)), commandLine.getValue(encoding));
PrintStream out;
if ("-".equals(commandLine.getValue(output))) {
out = System.out;
} else if (commandLine.getValue(output).endsWith(".gz") || commandLine.getValue(output_gz)) {
//XXX This currently doesn't work
out = new PrintStream(new GZIPOutputStream(new FileOutputStream(commandLine.getValue(output))));
System.err.println("GZIP output not currently working properly");
System.exit(-1);
} else {
out = new PrintStream(commandLine.getValue(output));
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing lexical probabilities table");
SampledLexProbs lexProbs =
new SampledLexProbs(commandLine.getValue(lexSampleSize), sourceSuffixArray, targetSuffixArray, alignments, Cache.DEFAULT_CAPACITY, false);
//new LexProbs(source_given_target, target_given_source, sourceVocab, targetVocab);
if (logger.isLoggable(Level.INFO)) logger.info("Done constructing lexical probabilities table");
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Should store a max of " + commandLine.getValue(ruleSampleSize) + " rules at each node in a prefix tree.");
Map<Integer,String> ntVocab = new HashMap<Integer,String>();
ntVocab.put(PrefixTree.X, "X");
Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
PrefixTree.SENTENCE_INITIAL_X = commandLine.getValue(sentence_initial_X);
PrefixTree.SENTENCE_FINAL_X = commandLine.getValue(sentence_final_X);
int lineNumber = 0;
RuleExtractor ruleExtractor = new HierarchicalRuleExtractor(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, commandLine.getValue(ruleSampleSize), commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(minNonterminalSpan), commandLine.getValue(maxPhraseSpan));
while (testFileScanner.hasNextLine()) {
String line = testFileScanner.nextLine();
lineNumber++;
int[] words = sourceVocab.getIDs(line);
if (logger.isLoggable(Level.INFO)) logger.info("Constructing prefix tree for source line " + lineNumber + ": " + line);
PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, ruleExtractor, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(minNonterminalSpan));
if (commandLine.getValue(print_prefixTree)==true) {
System.out.println(prefixTree.toString());
}
if (commandLine.getValue(print_rules)) {
if (logger.isLoggable(Level.FINE)) logger.fine("Outputting rules for source line: " + line);
for (Rule rule : prefixTree.getAllRules()) {
String ruleString = rule.toString(ntVocab, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINEST)) logger.finest("Rule: " + ruleString);
out.println(ruleString);
}
}
if (logger.isLoggable(Level.FINER)) logger.finer(lexProbs.sizeInfo());
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
if (logger.isLoggable(Level.FINER)) {
logger.finer("Prefix tree had " + prefixTree.size() + " nodes.");
Pattern maxPattern = null;
int maxHPsize = 0;
int hpsize = 0;
int psize = 0;
for (Map.Entry<Pattern,HierarchicalPhrases> entry : sourceSuffixArray.hierarchicalPhraseCache.entrySet()) {
psize++;
hpsize += entry.getValue().size();
if (hpsize>maxHPsize) {
maxHPsize = hpsize;
maxPattern = entry.getKey();
}
}
logger.finer(
psize + " source side entries in the SA cache." + "\n" +
hpsize+ " target side HierarchicalPhrases represented in the cache." + "\n" +
maxHPsize + " is the most HierarchicalPhrases stored for one source side entry ( " +
maxPattern + ")\n"
);
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (finalConfirmation) {
if (logger.isLoggable(Level.INFO)) logger.info("Complete: Please press a key to end program.");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Done extracting rules");
}
}
| public static void main(String[] args) throws IOException {
boolean finalConfirmation = false;
try {
CommandLineParser commandLine = new CommandLineParser();
Option<String> source = commandLine.addStringOption('f',"source","SOURCE_FILE","Source language training file");
Option<String> target = commandLine.addStringOption('e',"target","TARGET_FILE","Target language training file");
Option<String> alignment = commandLine.addStringOption('a',"alignments","ALIGNMENTS_FILE","Source-target alignments training file");
Option<String> test = commandLine.addStringOption('t',"test","TEST_FILE","Source language test file");
Option<String> output = commandLine.addStringOption('o',"output","OUTPUT_FILE","-","Output file");
Option<String> encoding = commandLine.addStringOption("encoding","ENCODING","UTF-8","File encoding format");
Option<Integer> lexSampleSize = commandLine.addIntegerOption("lexSampleSize","LEX_SAMPLE_SIZE",1000, "Size to use when sampling for lexical probability calculations");
Option<Integer> ruleSampleSize = commandLine.addIntegerOption("ruleSampleSize","RULE_SAMPLE_SIZE",300, "Maximum number of rules to store at each node in the prefix tree");
Option<Integer> maxPhraseSpan = commandLine.addIntegerOption("maxPhraseSpan","MAX_PHRASE_SPAN",10, "Max phrase span");
Option<Integer> maxPhraseLength = commandLine.addIntegerOption("maxPhraseLength","MAX_PHRASE_LENGTH",10, "Max phrase length");
Option<Integer> maxNonterminals = commandLine.addIntegerOption("maxNonterminals","MAX_NONTERMINALS",2, "Max nonterminals");
Option<Integer> minNonterminalSpan = commandLine.addIntegerOption("minNonterminalSpan","MIN_NONTERMINAL_SPAN", 2, "Minimum nonterminal span");
Option<Integer> cacheSize = commandLine.addIntegerOption("cache","CACHE",1000, "Max number of patterns for which to cache hierarchical phrases");
//Option<Integer> trainingSize = commandLine.addIntegerOption("trainingSize","NUMBER_OF_TRAINING_SENTENCES", "Number of training sentences");
// Option<String> target_given_source_counts = commandLine.addStringOption("target-given-source-counts","FILENAME","file containing co-occurence counts of source and target word pairs, sorted by source words");
// Option<String> source_given_target_counts = commandLine.addStringOption("source-given-target-counts","FILENAME","file containing co-occurence counts of target and source word pairs, sorted by target words");
Option<Boolean> output_gz = commandLine.addBooleanOption("output-gzipped",false,"should the output file be gzipped");
// Option<Boolean> target_given_source_gz = commandLine.addBooleanOption("target-given-source-gzipped",false,"is the target given source word pair counts file gzipped");
// Option<Boolean> source_given_target_gz = commandLine.addBooleanOption("source-given-target-gzipped",false,"is the source given target word pair counts file gzipped");
Option<Boolean> sentence_initial_X = commandLine.addBooleanOption("sentence-initial-X",false,"should rules with initial X be extracted from sentence-initial phrases");
Option<Boolean> sentence_final_X = commandLine.addBooleanOption("sentence-final-X",false,"should rules with final X be extracted from sentence-final phrases");
Option<Boolean> print_prefixTree = commandLine.addBooleanOption("print-prefix-tree",false,"should prefix tree be printed to standard out (for debugging)");
Option<Boolean> print_rules = commandLine.addBooleanOption("print-rules",true,"should extracted rules be printed to standard out");
Option<String> alignmentType = commandLine.addStringOption("alignmentsType","ALIGNMENT_TYPE","AlignmentGrids","Type of alignment data structure");
Option<Boolean> confirm = commandLine.addBooleanOption("confirm",false,"should program pause for user input before constructing prefix trees?");
commandLine.parse(args);
if (commandLine.getValue(confirm)==true) {
finalConfirmation = true;
}
// Set System.out and System.err to use the provided character encoding
try {
System.setOut(new PrintStream(System.out, true, commandLine.getValue(encoding)));
System.setErr(new PrintStream(System.err, true, commandLine.getValue(encoding)));
} catch (UnsupportedEncodingException e1) {
System.err.println(commandLine.getValue(encoding) + " is not a valid encoding; using system default encoding for System.out and System.err.");
} catch (SecurityException e2) {
System.err.println("Security manager is configured to disallow changes to System.out or System.err; using system default encoding.");
}
// Lane - TODO -
//SuffixArray.INVERTED_INDEX_PRECOMPUTATION_MIN_FREQ = commandLine.getValue("CACHE_PRECOMPUTATION_FREQUENCY_THRESHOLD");
SuffixArray.CACHE_CAPACITY = commandLine.getValue(cacheSize);
if (logger.isLoggable(Level.INFO)) logger.info("Suffix array will cache hierarchical phrases for at most " + SuffixArray.CACHE_CAPACITY + " patterns.");
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language vocabulary.");
String sourceFileName = commandLine.getValue(source);
Vocabulary sourceVocab = new Vocabulary();
int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language corpus array.");
CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing source language suffix array.");
SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language vocabulary.");
String targetFileName = commandLine.getValue(target);
Vocabulary targetVocab = new Vocabulary();
int[] targetWordsSentences = SuffixArrayFactory.createVocabulary(commandLine.getValue(target), targetVocab);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language corpus array.");
CorpusArray targetCorpusArray = SuffixArrayFactory.createCorpusArray(targetFileName, targetVocab, targetWordsSentences[0], targetWordsSentences[1]);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing target language suffix array.");
SuffixArray targetSuffixArray = SuffixArrayFactory.createSuffixArray(targetCorpusArray);
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
int trainingSize = sourceCorpusArray.getNumSentences();
if (trainingSize != targetCorpusArray.getNumSentences()) {
throw new RuntimeException("Source and target corpora have different number of sentences. This is bad.");
}
if (logger.isLoggable(Level.INFO)) logger.info("Reading alignment data.");
String alignmentFileName = commandLine.getValue(alignment);
Alignments alignments;
if ("AlignmentArray".equals(commandLine.getValue(alignmentType))) {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentArray");
alignments = SuffixArrayFactory.createAlignmentArray(alignmentFileName, sourceSuffixArray, targetSuffixArray);
} else {
if (logger.isLoggable(Level.INFO)) logger.info("Using AlignmentGrids");
alignments = new AlignmentGrids(new Scanner(new File(alignmentFileName)), sourceCorpusArray, targetCorpusArray, trainingSize);
}
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
// Set up the source text for reading
// Scanner target_given_source;
// if (commandLine.getValue(target_given_source_counts).endsWith(".gz") || commandLine.getValue(target_given_source_gz))
// target_given_source = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(target_given_source_counts))),commandLine.getValue(encoding))));
// else
// target_given_source = new Scanner( new File(commandLine.getValue(target_given_source_counts)), commandLine.getValue(encoding));
// // Set up the target text for reading
// Scanner source_given_target;
// if (commandLine.getValue(source_given_target_counts).endsWith(".gz") || commandLine.getValue(source_given_target_gz))
// source_given_target = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(source_given_target_counts))),commandLine.getValue(encoding))));
// else
// source_given_target = new Scanner( new File(commandLine.getValue(source_given_target_counts)), commandLine.getValue(encoding));
PrintStream out;
if ("-".equals(commandLine.getValue(output))) {
out = System.out;
} else if (commandLine.getValue(output).endsWith(".gz") || commandLine.getValue(output_gz)) {
//XXX This currently doesn't work
out = new PrintStream(new GZIPOutputStream(new FileOutputStream(commandLine.getValue(output))));
System.err.println("GZIP output not currently working properly");
System.exit(-1);
} else {
out = new PrintStream(commandLine.getValue(output));
}
if (logger.isLoggable(Level.INFO)) logger.info("Constructing lexical probabilities table");
SampledLexProbs lexProbs =
new SampledLexProbs(commandLine.getValue(lexSampleSize), sourceSuffixArray, targetSuffixArray, alignments, Cache.DEFAULT_CAPACITY, false);
//new LexProbs(source_given_target, target_given_source, sourceVocab, targetVocab);
if (logger.isLoggable(Level.INFO)) logger.info("Done constructing lexical probabilities table");
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Should store a max of " + commandLine.getValue(ruleSampleSize) + " rules at each node in a prefix tree.");
Map<Integer,String> ntVocab = new HashMap<Integer,String>();
ntVocab.put(PrefixTree.X, "X");
Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
}
PrefixTree.SENTENCE_INITIAL_X = commandLine.getValue(sentence_initial_X);
PrefixTree.SENTENCE_FINAL_X = commandLine.getValue(sentence_final_X);
int lineNumber = 0;
RuleExtractor ruleExtractor = new HierarchicalRuleExtractor(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, commandLine.getValue(ruleSampleSize), commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(minNonterminalSpan), commandLine.getValue(maxPhraseSpan));
while (testFileScanner.hasNextLine()) {
String line = testFileScanner.nextLine();
lineNumber++;
int[] words = sourceVocab.getIDs(line);
if (logger.isLoggable(Level.INFO)) logger.info("Constructing prefix tree for source line " + lineNumber + ": " + line);
PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignments, lexProbs, ruleExtractor, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(minNonterminalSpan));
if (commandLine.getValue(print_prefixTree)==true) {
System.out.println(prefixTree.toString());
}
if (commandLine.getValue(print_rules)) {
if (logger.isLoggable(Level.FINE)) logger.fine("Outputting rules for source line: " + line);
for (Rule rule : prefixTree.getAllRules()) {
String ruleString = rule.toString(ntVocab, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINEST)) logger.finest("Rule: " + ruleString);
out.println(ruleString);
}
}
if (logger.isLoggable(Level.FINER)) logger.finer(lexProbs.sizeInfo());
if (commandLine.getValue(confirm)) {
if (logger.isLoggable(Level.INFO)) logger.info("Please press a key to continue");
System.in.read();
if (logger.isLoggable(Level.FINER)) {
logger.finer("Prefix tree had " + prefixTree.size() + " nodes.");
Pattern maxPattern = null;
int maxHPsize = 0;
int hpsize = 0;
int psize = 0;
for (Map.Entry<Pattern,HierarchicalPhrases> entry : sourceSuffixArray.hierarchicalPhraseCache.entrySet()) {
psize++;
hpsize += entry.getValue().size();
if (hpsize>maxHPsize) {
maxHPsize = entry.getValue().size();
maxPattern = entry.getKey();
}
}
logger.finer(
psize + " source side entries in the SA cache." + "\n" +
hpsize+ " target side HierarchicalPhrases represented in the cache." + "\n" +
maxHPsize + " is the most HierarchicalPhrases stored for one source side entry ( " +
maxPattern + ")\n"
);
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (finalConfirmation) {
if (logger.isLoggable(Level.INFO)) logger.info("Complete: Please press a key to end program.");
System.in.read();
}
if (logger.isLoggable(Level.INFO)) logger.info("Done extracting rules");
}
}
|
diff --git a/MainProject/src/se/chalmers/dat255/risk/model/BattleHandler.java b/MainProject/src/se/chalmers/dat255/risk/model/BattleHandler.java
index 890cfe4..b5dfb8b 100644
--- a/MainProject/src/se/chalmers/dat255/risk/model/BattleHandler.java
+++ b/MainProject/src/se/chalmers/dat255/risk/model/BattleHandler.java
@@ -1,67 +1,67 @@
package se.chalmers.dat255.risk.model;
import java.util.Random;
/**
* Battle simulator. rolls dice and determine how many units are lost.
*
*/
public class BattleHandler {
private Random generator = new Random();
//private int[] diceOffensive;
//private int[] diceDefensive;
/**
* Handles the attack between two provinces.
*
* @param offensive
* number of offensive attackers.
* @param defensive
* number of defensive attackers.
* @return lost Armies, offensive and defensive.
*/
public int[] doBattle(int offensive, int defensive) {
int[] lostArmies = new int[2];
int[] diceDefensive = rollDice(defensive);
int[] diceOffensive = rollDice(offensive);
for (int i = 0; (i < defensive) && (i < offensive); i++) {
- if (diceOffensive[i] < diceDefensive[i]) {
+ if (diceOffensive[i] <= diceDefensive[i]) {
lostArmies[0]++;
} else {
lostArmies[1]++;
}
}
//flushVariables();
return lostArmies;
}
/**
* Creates dice.
*
* @param armies
* number of attacking armies
* @return the two largest dice.
*/
private int[] rollDice(int armies) {
// Random generator = new Random();
int[] dice = new int[2];
for (int i = 0; i < armies; i++) {
int newDice = generator.nextInt(6) + 1;
if (newDice > dice[0]) {
dice[1] = dice[0];
dice[0] = newDice;
} else if (newDice > dice[1]) {
dice[1] = newDice;
}
}
return dice;
}
/*private void flushVariables(){
diceDefensive=null;
diceOffensive=null;
}*/
}
| true | true | public int[] doBattle(int offensive, int defensive) {
int[] lostArmies = new int[2];
int[] diceDefensive = rollDice(defensive);
int[] diceOffensive = rollDice(offensive);
for (int i = 0; (i < defensive) && (i < offensive); i++) {
if (diceOffensive[i] < diceDefensive[i]) {
lostArmies[0]++;
} else {
lostArmies[1]++;
}
}
//flushVariables();
return lostArmies;
}
| public int[] doBattle(int offensive, int defensive) {
int[] lostArmies = new int[2];
int[] diceDefensive = rollDice(defensive);
int[] diceOffensive = rollDice(offensive);
for (int i = 0; (i < defensive) && (i < offensive); i++) {
if (diceOffensive[i] <= diceDefensive[i]) {
lostArmies[0]++;
} else {
lostArmies[1]++;
}
}
//flushVariables();
return lostArmies;
}
|
diff --git a/src/elfville/server/model/Clan.java b/src/elfville/server/model/Clan.java
index 1f66371..6338cde 100644
--- a/src/elfville/server/model/Clan.java
+++ b/src/elfville/server/model/Clan.java
@@ -1,201 +1,201 @@
package elfville.server.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import elfville.protocol.models.SerializableClan;
import elfville.protocol.models.SerializableElf;
import elfville.server.Database;
import elfville.server.SecurityUtils;
/**
* Clan Model.
*/
public class Clan extends Model implements Comparable<Clan> {
private static final long serialVersionUID = -696380887203611286L;
private final String name;
private final String description;
private final List<Integer> postIDs = Collections
.synchronizedList(new ArrayList<Integer>());
private final int leaderID;
private final Set<Integer> applicants = Collections
.synchronizedSet(new HashSet<Integer>());
private final Set<Integer> members = Collections
.synchronizedSet(new HashSet<Integer>());
public Clan(String name, String description, Elf leader) {
super();
this.name = name;
this.description = description;
leaderID = leader.modelID;
members.add(leader.modelID);
}
// make a serializable clan object out of this clan
public SerializableClan toSerializableClan() {
SerializableClan sClan = new SerializableClan();
sClan.clanName = getName();
sClan.clanDescription = getDescription();
sClan.numSocks = getNumSock();
sClan.modelID = getEncryptedModelID();
sClan.applicants = getApplicants();
sClan.members = getMembers();
sClan.leader = getLeader().toSerializableElf();
return sClan;
}
public List<Post> getPosts() {
Collections.sort(postIDs);
ArrayList<Post> posts = new ArrayList<Post>(postIDs.size());
for (Integer id : postIDs) {
posts.add(Database.getInstance().postDB.findByModelID(id));
}
return posts;
}
public List<SerializableElf> getApplicants() {
Integer[] appList = applicants.toArray(new Integer[0]);
Arrays.sort(appList);
List<SerializableElf> applicantList = new ArrayList<SerializableElf>(
applicants.size());
for (Integer elfID : appList) {
applicantList.add(Elf.get(elfID).toSerializableElf());
}
return applicantList;
}
public Set<SerializableElf> getMembers() {
Set<SerializableElf> memberList = new HashSet<SerializableElf>();
for (Integer elfID : members) {
memberList.add(Elf.get(elfID).toSerializableElf());
}
return memberList;
}
/* The number of socks owned by all clan members combined */
public int getNumSock() {
int numSock = 0;
for (Integer elfID : members) {
numSock += Elf.get(elfID).getNumSocks();
}
return numSock;
}
public Elf getLeader() {
return Elf.get(leaderID);
}
// A stranger becomes an applicant
public void apply(Elf elf) {
if (!members.contains(elf.modelID)) {
applicants.add(elf.modelID);
save();
}
}
// An applicant becomes a member
public void join(Elf elf) {
if (applicants.contains(elf.modelID)) {
members.add(elf.modelID);
applicants.remove(elf.modelID);
save();
System.out.println("elf " + elf.getName() + " is accepted at "
+ this.name);
}
}
// the database takes care of cascading delete
public void delete() {
Database.getInstance().clanDB.remove(this);
Database.getInstance().persist(new Deletion(this));
}
// The clan leader cannot do this operation
public void leaveClan(Elf elf) {
if (isLeader(elf)) {
return;
}
- for (Integer pid : postIDs) {
+ for (Integer pid : postIDs.subList(0, postIDs.size())) {
Post p = Database.getInstance().postDB.findByModelID(pid);
if (p.getElf().equals(elf)) {
postIDs.remove(pid);
}
}
members.remove(elf.modelID);
save();
}
public boolean isLeader(Elf elf) {
return elf.modelID == leaderID;
}
// also true if the elf is the leader
public boolean isMember(Elf elf) {
return members.contains(elf.modelID);
}
public boolean isApplicant(Elf elf) {
return applicants.contains(elf.modelID);
}
public Post getPostFromEncryptedModelID(String encryptedModelID) {
int id = SecurityUtils.decryptStringToInt(encryptedModelID);
if (postIDs.contains(id)) {
return Database.getInstance().postDB.findByModelID(id);
}
return null;
}
public void createPost(Post post) {
post.clanID = modelID;
postIDs.add(post.modelID);
Database.getInstance().postDB.add(post);
save();
post.save();
}
public void deletePost(Post post) {
postIDs.remove(postIDs.indexOf(post.modelID));
Database.getInstance().postDB.remove(post.modelID);
save();
}
public void deletePost(String encryptedModelID) {
deletePost(getPostFromEncryptedModelID(encryptedModelID));
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public void save() {
super.save();
Database.getInstance().clanDB.add(this);
}
public void deny(Elf elf) {
applicants.remove(elf.modelID);
save();
}
public static Clan get(String name) {
return Database.getInstance().clanDB.findByName(name);
}
@Override
public int compareTo(Clan c) {
return name.compareTo(c.name);
}
}
| true | true | public void leaveClan(Elf elf) {
if (isLeader(elf)) {
return;
}
for (Integer pid : postIDs) {
Post p = Database.getInstance().postDB.findByModelID(pid);
if (p.getElf().equals(elf)) {
postIDs.remove(pid);
}
}
members.remove(elf.modelID);
save();
}
| public void leaveClan(Elf elf) {
if (isLeader(elf)) {
return;
}
for (Integer pid : postIDs.subList(0, postIDs.size())) {
Post p = Database.getInstance().postDB.findByModelID(pid);
if (p.getElf().equals(elf)) {
postIDs.remove(pid);
}
}
members.remove(elf.modelID);
save();
}
|
diff --git a/src/org/kered/dko/ant/SchemaExtractor.java b/src/org/kered/dko/ant/SchemaExtractor.java
index 0d1f301..0cca3fb 100644
--- a/src/org/kered/dko/ant/SchemaExtractor.java
+++ b/src/org/kered/dko/ant/SchemaExtractor.java
@@ -1,898 +1,898 @@
package org.kered.dko.ant;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.tools.ant.Task;
import org.kered.dko.Constants;
import org.kered.dko.Constants.DB_TYPE;
import org.kered.dko.json.JSONArray;
import org.kered.dko.json.JSONException;
import org.kered.dko.json.JSONObject;
/**
* Extracts schema information from a provided database into a JSON file.
* Designed to be run occasionally, with the output file checked into version control.
* (to avoid regular builds hitting your DB server, and for code generation history)
*
* @author Derek Anderson
*/
public class SchemaExtractor extends Task {
private static int[] version = {0,2,0};
private DB_TYPE dbType = null;
private String url = null;
private String username = null;
private String password = null;
private HashSet<String> includeSchemas = null;
private String[] enums = {};
private File enumsOut = null;
private File out = null;
private final List<Pattern> onlyTables = new ArrayList<Pattern>();
private final List<Pattern> excludeTables = new ArrayList<Pattern>();
public void setOut(final String s) {
this.out = new File(s);
}
public void setEnums(final String s) {
if (s != null && s.length() > 0) this.enums = s.split(",");
}
public void setEnumsOut(final String s) {
this.enumsOut = s==null ? null : new File(s);
}
public void setDBType(final String s) {
if ("sqlserver".equalsIgnoreCase(s))
this.dbType = Constants.DB_TYPE.SQLSERVER;
if ("mysql".equalsIgnoreCase(s))
this.dbType = Constants.DB_TYPE.MYSQL;
if ("hsql".equalsIgnoreCase(s) || "hsqldb".equalsIgnoreCase(s))
this.dbType = Constants.DB_TYPE.HSQL;
}
public void setURL(final String s) throws Exception {
this.url = s;
if (url.startsWith("jdbc:sqlserver")) {
try {
final Driver d = (Driver) Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
} catch (final ClassNotFoundException e) {
System.err.println("not found: com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.err.print("trying: com.microsoft.sqlserver.jdbc.SQLServerDriver");
final Driver d = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
System.err.println(" ...success!");
}
dbType = DB_TYPE.SQLSERVER;
}
if (url.startsWith("jdbc:mysql")) {
final Driver d = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
dbType = DB_TYPE.MYSQL;
}
if (url.startsWith("jdbc:hsqldb")) {
final Driver d = (Driver) Class.forName("org.hsqldb.jdbc.JDBCDriver").newInstance();
dbType = DB_TYPE.HSQL;
}
if (url.startsWith("jdbc:sqlite")) {
final Driver d = (Driver) Class.forName("org.sqlite.JDBC").newInstance();
dbType = DB_TYPE.SQLITE3;
}
}
public void setUsername(final String s) {
this.username = s;
}
public void setPassword(final String s) {
this.password = s;
}
public void setPasswordFile(final String s) {
try {
final BufferedReader br = new BufferedReader(new FileReader(s));
this.password = br.readLine().trim();
} catch (final FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setSchemas(final String s) {
this.includeSchemas = new HashSet<String>();
for (final String schema : s.split(",")) {
this.includeSchemas.add(schema.trim());
}
}
/**
* A comma separated list of regex patterns. If "schema_name.table_name" contains the
* java pattern, the table will be included. Otherwise, it will be excluded.
* If this is not set, all tables will be included.
* @param s
*/
public void setOnlyTables(final String s) {
for (String v : s.split(",")) {
v = v.trim();
final Pattern p = Pattern.compile(v);
onlyTables.add(p);
}
}
/**
* A comma separated list of regex patterns. If "schema_name.table_name" contains the
* java pattern, the table will be excluded. Otherwise, it will be included.
* If this is not set, all tables will be included.
* @param s
*/
public void setExcludeTables(final String s) {
for (String v : s.split(",")) {
v = v.trim();
final Pattern p = Pattern.compile(v);
excludeTables.add(p);
}
}
public void execute() {
Connection conn;
try {
System.err.println("connecting to "+ url);
conn = DriverManager.getConnection (url, username, password);
final Map<String,Map<String,Map<String,String>>> schemas = getSchemas(conn);
final Map<String,Map<String,Set<String>>> primaryKeys =getPrimaryKeys(conn);
final Map<String, Map<String,Object>> foreignKeys = getForeignKeys(conn);
final JSONObject json = new JSONObject();
json.put("version", new JSONArray(version));
json.put("schemas", new JSONObject(schemas));
json.put("primary_keys", new JSONObject(primaryKeys));
json.put("foreign_keys", new JSONObject(foreignKeys));
System.err.println("writing: "+ out.getAbsolutePath());
final FileWriter w = new FileWriter(out);
w.write(json.toString(4));
w.close();
if (enums!=null && enums.length > 0 && enumsOut != null) {
final JSONObject allEnums = new JSONObject();
for (String x : enums) {
x = x.trim();
final String[] xa = x.split("[.]");
if (xa.length != 3) {
throw new RuntimeException("'"+ x +"' " +
"must be of the format 'schema.table.name_column'");
}
final String schema = xa[0];
final String table = xa[1];
final String column = xa[2];
allEnums.put(x, getEnums(conn, schema, table, column,
primaryKeys.get(schema).get(table)));
}
System.err.println("writing: "+ enumsOut.getAbsolutePath());
final FileWriter w2 = new FileWriter(enumsOut);
w2.write(allEnums.toString(4));
w2.close();
}
} catch (final SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (final JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JSONObject getEnums(final Connection conn, final String schema, final String table, final String column,
final Set<String> pks) throws SQLException {
if (pks == null) throw new RuntimeException("primary keys not set for enum table: "
+ schema +"."+ table +"."+ column);
String sep =".";
if (conn.getClass().getName().startsWith("com.microsoft")) {
sep ="..";
}
final JSONObject ret = new JSONObject();
final String sql = "select "+ column +", "+ Util.join(", ", pks) +" "
+ "from "+ schema + sep + table +" order by "+ column +";";
System.err.println(sql);
final Statement s = conn.createStatement();
s.execute(sql);
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String name = rs.getString(1);
final JSONArray values = new JSONArray();
for (final String key : pks) {
values.put(rs.getObject(key));
}
try {
ret.put(name, values);
} catch (final JSONException e) {
e.printStackTrace();
}
}
return ret;
}
private static Set<String> ignoredSchemas = new HashSet<String>() {{
add("information_schema");
add("mysql");
}};
private Map<String, Map<String, Map<String, String>>> getSchemas(
final Connection conn) throws SQLException {
if (dbType == DB_TYPE.SQLSERVER) return getSchemasMSSQL(conn);
if (dbType == DB_TYPE.SQLITE3) return getSchemasSQLITE3(conn);
else return getSchemasSQL92(conn);
}
private Map<String, Map<String, Map<String, String>>> getSchemasSQLITE3(
final Connection conn) throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final DatabaseMetaData metadata = conn.getMetaData();
final ResultSet tableRS = metadata.getTables(null, null, null, null);
while (tableRS.next()) {
final String catalog = tableRS.getString("TABLE_CAT");
String schema = tableRS.getString("TABLE_SCHEM");
if (schema == null) schema = "";
final String tableName = tableRS.getString("TABLE_NAME");
final String tableType = tableRS.getString("TABLE_TYPE");
if (!"TABLE".equals(tableType)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
System.out.println("found schema: "+ schema);
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
Map<String, String> columns = tables.get(tableName);
if (columns == null) {
System.out.println("found table: "+ tableName);
columns = new LinkedHashMap<String, String>();
tables.put(tableName, columns);
}
}
final Statement stmt = conn.createStatement();
for (final Entry<String, Map<String, Map<String, String>>> e1 : schemas.entrySet()) {
final Map<String, Map<String, String>> tables = e1.getValue();
for (final Entry<String, Map<String, String>> e2 : tables.entrySet()) {
final String tableName = e2.getKey();
final Map<String, String> columns = e2.getValue();
final ResultSet rs = stmt.executeQuery("pragma table_info("+ tableName +");");
while (rs.next()) {
final String columnName = rs.getString(2);
final String columnType = rs.getString(3);
columns.put(columnName, columnType);
}
}
}
return schemas;
}
private Map<String, Map<String, Map<String, String>>> getSchemasJDBC(
final Connection conn) throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final DatabaseMetaData metadata = conn.getMetaData();
final ResultSet columnRS = metadata.getColumns(null, null, null, null);
while (columnRS.next()) {
System.out.println("woot");
final String catalog = columnRS.getString("TABLE_CAT");
String schema = columnRS.getString("TABLE_SCHEM");
if (schema == null) schema = "";
final String tableName = columnRS.getString("TABLE_NAME");
final String tableType = columnRS.getString("TABLE_TYPE");
final String columnName = columnRS.getString("COLUMN_NAME");
final String columnType = columnRS.getString("TYPE_NAME");
System.out.println("found column: "+ columnName +" "+ columnType);
if (!"TABLE".equals(tableType)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
System.out.println("found schema: "+ schema);
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
Map<String, String> columns = tables.get(tableName);
if (columns == null) {
System.out.println("found table: "+ tableName);
columns = new LinkedHashMap<String, String>();
tables.put(tableName, columns);
}
System.out.println("found column: "+ columnName +" "+ columnType);
columns.put(columnName, columnType);
}
return schemas;
}
private Map<String, Map<String, Map<String, String>>> getSchemasSQL92(
final Connection conn)
throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final Statement s = conn.createStatement();
s.execute("select table_schema, table_name, column_name, data_type "
+ "from information_schema.columns order by table_schema, table_name, column_name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("table_schema");
final String table = rs.getString("table_name");
final String column = rs.getString("column_name");
final String type = rs.getString("data_type");
if (ignoredSchemas.contains(schema))
continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
Map<String, String> columns = tables.get(table);
if (columns == null) {
columns = new LinkedHashMap<String, String>();
tables.put(table, columns);
}
columns.put(column, type);
}
rs.close();
s.close();
return schemas;
}
private final Set<String> excluded = new HashSet<String>();
private boolean includeTable(final String schema, final String table) {
final String s = schema +"."+ table;
if (this.onlyTables.size() > 0) {
boolean include = false;
for (final Pattern p : onlyTables) {
if (p.matcher(s).find()) {
include = true;
break;
}
}
if (!include) return false;
}
for (final Pattern p : this.excludeTables) {
if (p.matcher(s).find()) {
if (!excluded.contains(s)) System.err.println("excluding: "+ s);
excluded.add(s);
return false;
}
}
return true;
}
private Map<String, Map<String, Map<String, String>>> getSchemasMSSQL(final Connection conn)
throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final List<String> dbs = new ArrayList<String>();
final Statement s = conn.createStatement();
- s.execute("SELECT NAME FROM SYS.DATABASES ORDER BY NAME;");
+ s.execute("SELECT name FROM sys.databases ORDER BY name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("NAME");
if (ignoredSchemas.contains(schema))
continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
dbs.add(schema);
}
rs.close();
// s.close();
for (final String db : dbs) {
if (ignoredSchemas.contains(db))
continue;
if (includeSchemas != null && !includeSchemas.contains(db))
continue;
System.err.println("extracting schema for: "+ db);
try {
s.execute("use \"" + db + "\";");
s.execute("SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, " +
"CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS ORDER BY " +
"TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME;");
final ResultSet rs2 = s.getResultSet();
while (rs2.next()) {
final String schema = db; // +"."+ rs2.getString("TABLE_SCHEMA");
final String table = rs2.getString("TABLE_NAME");
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
if (table.toLowerCase().startsWith("syncobj_")) continue;
if (table.startsWith("MS") && table.length() > 2
&& Character.isLowerCase(table.charAt(2))) continue;
final String column = rs2.getString("COLUMN_NAME");
String type = rs2.getString("DATA_TYPE");
final int maxLength = rs2.getInt("CHARACTER_MAXIMUM_LENGTH");
if ("char".equalsIgnoreCase(type) && maxLength > 1)
type = "varchar";
Map<String, String> columns = tables.get(table);
if (columns == null) {
columns = new LinkedHashMap<String, String>();
tables.put(table, columns);
}
columns.put(column, type);
}
rs2.close();
} catch (final SQLException e) {
if (e.getMessage().contains("security context")) {
System.err.println(e.getMessage());
} else {
throw e;
}
}
}
s.close();
return schemas;
}
private Map<String,Map<String,Set<String>>> getPrimaryKeys(final Connection conn) throws SQLException {
if (dbType == DB_TYPE.SQLSERVER) return getPrimaryKeysMSSQL(conn);
if (dbType == DB_TYPE.HSQL) return getPrimaryKeysHSQL(conn);
if (dbType == DB_TYPE.SQLITE3) return getPrimaryKeysSQLITE3(conn);
return getPrimaryKeysMySQL(conn);
}
private Map<String, Map<String, Set<String>>> getPrimaryKeysSQLITE3(
final Connection conn) throws SQLException {
final Map<String, Map<String, Set<String>>> pks = new LinkedHashMap<String, Map<String, Set<String>>>();
final DatabaseMetaData metadata = conn.getMetaData();
final ResultSet tableRS = metadata.getTables(null, null, null, null);
while (tableRS.next()) {
final String catalog = tableRS.getString("TABLE_CAT");
String schema = tableRS.getString("TABLE_SCHEM");
if (schema == null) schema = "";
final String tableName = tableRS.getString("TABLE_NAME");
final String tableType = tableRS.getString("TABLE_TYPE");
if (!"TABLE".equals(tableType)) continue;
Map<String, Set<String>> tables = pks.get(schema);
if (tables == null) {
System.out.println("found schema: "+ schema);
tables = new LinkedHashMap<String, Set<String>>();
pks.put(schema, tables);
}
Set<String> pk = tables.get(tableName);
if (pk == null) {
System.out.println("found table: "+ tableName);
pk = new LinkedHashSet<String>();
tables.put(tableName, pk);
}
}
final Statement stmt = conn.createStatement();
for (final Entry<String, Map<String, Set<String>>> e1 : pks.entrySet()) {
final Map<String, Set<String>> tables = e1.getValue();
for (final Entry<String, Set<String>> e2 : tables.entrySet()) {
final String tableName = e2.getKey();
final Set<String> pk = e2.getValue();
final ResultSet rs = stmt.executeQuery("pragma table_info("+ tableName +");");
while (rs.next()) {
if (rs.getInt(6) == 1) {
pk.add(rs.getString(2));
}
}
}
}
return pks;
}
private Map<String, Map<String, Set<String>>> getPrimaryKeysJDBC(
final Connection conn) throws SQLException {
final Map<String, Map<String, Set<String>>> pks = new LinkedHashMap<String, Map<String, Set<String>>>();
final DatabaseMetaData metadata = conn.getMetaData();
final ResultSet rs = metadata.getPrimaryKeys(null, null, null);
while (rs.next()) {
final String catalog = rs.getString("TABLE_CAT");
final String schema = rs.getString("TABLE_SCHEM");
final String tableName = rs.getString("TABLE_NAME");
final String columnName = rs.getString("COLUMN_NAME");
final String pkName = rs.getString("PK_NAME");
Map<String, Set<String>> tables = pks.get(schema);
if (tables == null) {
tables = new LinkedHashMap<String, Set<String>>();
pks.put(schema, tables);
}
Set<String> pk = tables.get(tableName);
if (pk == null) {
pk = new LinkedHashSet<String>();
tables.put(tableName, pk);
}
pk.add(columnName);
}
return pks;
}
private Map<String, Map<String, Set<String>>> getPrimaryKeysMSSQL(final Connection conn) throws SQLException {
final Map<String,Map<String,Map<String,String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final Map<String,Map<String,Set<String>>> primaryKeys =
new LinkedHashMap<String, Map<String, Set<String>>>();
final Statement s = conn.createStatement();
s.execute("SELECT name FROM sys.databases order by name;");
final ResultSet rs2 = s.getResultSet();
while (rs2.next()) {
final String schema = rs2.getString("name");
final Map<String, Map<String, String>> tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema,tables);
}
rs2.close();
for(final String schema2 : schemas.keySet()) {
if (ignoredSchemas.contains(schema2)) continue;
if (includeSchemas != null && !includeSchemas.contains(schema2))
continue;
s.execute("use \""+ schema2 +"\";");
s.execute("SELECT A.TABLE_CATALOG, A.TABLE_NAME, B.COLUMN_NAME, A.CONSTRAINT_NAME " +
"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS A, " +
"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B " +
"WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' " +
"AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME " +
"ORDER BY A.TABLE_CATALOG, A.TABLE_NAME, B.COLUMN_NAME, A.CONSTRAINT_NAME;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("TABLE_CATALOG");
final String table = rs.getString("TABLE_NAME");
final String column = rs.getString("COLUMN_NAME");
if (ignoredSchemas.contains(schema)) continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables==null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema,tables);
}
Map<String, Set<String>> pkTables = primaryKeys.get(schema);
if (pkTables==null) {
pkTables = new LinkedHashMap<String, Set<String>>();
primaryKeys.put(schema,pkTables);
}
Map<String, String> columns = tables.get(table);
if (columns==null) {
columns = new LinkedHashMap<String, String>();
tables.put(table,columns);
}
Set<String> pkColumns = pkTables.get(table);
if (pkColumns==null) {
pkColumns = new LinkedHashSet<String>();
pkTables.put(table,pkColumns);
}
pkColumns.add(column);
}
rs.close();
}
s.close();
return primaryKeys;
}
private Map<String, Map<String, Set<String>>> getPrimaryKeysHSQL(final Connection conn) throws SQLException {
final Map<String,Map<String,Map<String,String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final Map<String,Map<String,Set<String>>> primaryKeys =
new LinkedHashMap<String, Map<String, Set<String>>>();
final Statement s = conn.createStatement();
s.execute("select a.table_catalog, a.table_name, b.column_name, a.constraint_name " +
"from information_schema.table_constraints a, " +
"information_schema.constraint_column_usage b " +
"where constraint_type = 'PRIMARY KEY' " +
"and a.constraint_name = b.constraint_name " +
"order by a.table_catalog, a.table_name, b.column_name, a.constraint_name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("table_catalog");
final String table = rs.getString("table_name");
final String column = rs.getString("column_name");
if (ignoredSchemas.contains(schema)) continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables==null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema,tables);
}
Map<String, Set<String>> pkTables = primaryKeys.get(schema);
if (pkTables==null) {
pkTables = new LinkedHashMap<String, Set<String>>();
primaryKeys.put(schema,pkTables);
}
Map<String, String> columns = tables.get(table);
if (columns==null) {
columns = new LinkedHashMap<String, String>();
tables.put(table,columns);
}
Set<String> pkColumns = pkTables.get(table);
if (pkColumns==null) {
pkColumns = new LinkedHashSet<String>();
pkTables.put(table,pkColumns);
}
pkColumns.add(column);
}
rs.close();
s.close();
return primaryKeys;
}
private Map<String,Map<String,Set<String>>> getPrimaryKeysMySQL(final Connection conn) throws SQLException {
final Map<String,Map<String,Map<String,String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final Map<String,Map<String,Set<String>>> primaryKeys =
new LinkedHashMap<String, Map<String, Set<String>>>();
final Statement s = conn.createStatement();
s.execute("select table_schema, table_name, column_name, column_key " +
"from information_schema.columns " +
"order by table_schema, table_name, column_name, column_key;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("table_schema");
final String table = rs.getString("table_name");
final String column = rs.getString("column_name");
final String columnKey = rs.getString("column_key");
if (ignoredSchemas.contains(schema)) continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables==null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema,tables);
}
Map<String, Set<String>> pkTables = primaryKeys.get(schema);
if (pkTables==null) {
pkTables = new LinkedHashMap<String, Set<String>>();
primaryKeys.put(schema,pkTables);
}
Map<String, String> columns = tables.get(table);
if (columns==null) {
columns = new LinkedHashMap<String, String>();
tables.put(table,columns);
}
Set<String> pkColumns = pkTables.get(table);
if (pkColumns==null) {
pkColumns = new HashSet<String>();
pkTables.put(table,pkColumns);
}
if ("PRI".equals(columnKey)) {
pkColumns.add(column);
}
}
rs.close();
s.close();
return primaryKeys;
}
private Map<String, Map<String,Object>> getForeignKeys(
final Connection conn) throws SQLException {
if (dbType == DB_TYPE.SQLSERVER) return getForeignKeysMSSQL(conn);
if (dbType == DB_TYPE.HSQL) return getForeignKeysHSQL(conn);
if (dbType == DB_TYPE.SQLITE3) return getNoForeignKeys(conn);
return getForeignKeysMySQL(conn);
}
private Map<String, Map<String, Object>> getNoForeignKeys(final Connection conn) {
return new LinkedHashMap<String, Map<String, Object>>();
}
private Map<String, Map<String,Object>> getForeignKeysMSSQL(
final Connection conn) throws SQLException {
final Map<String, Map<String,Object>> foreignKeys =
new LinkedHashMap<String, Map<String,Object>>();
final Statement s = conn.createStatement();
s.execute("SELECT KCU1.TABLE_CATALOG AS 'TABLE_SCHEMA', KCU1.CONSTRAINT_NAME, KCU1.TABLE_NAME, KCU1.COLUMN_NAME, KCU2.TABLE_CATALOG AS 'REFERENCED_TABLE_SCHEMA', KCU2.TABLE_NAME AS 'REFERENCED_TABLE_NAME', KCU2.COLUMN_NAME AS 'REFERENCED_COLUMN_NAME' " +
"FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC " +
"JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME " +
"JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION " +
"ORDER BY CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, KCU1.ORDINAL_POSITION;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String constraint_name = rs.getString("CONSTRAINT_NAME");
final String schema = rs.getString("TABLE_SCHEMA");
final String table = rs.getString("TABLE_NAME");
final String column = rs.getString("COLUMN_NAME");
final String referenced_schema = rs.getString("REFERENCED_TABLE_SCHEMA");
final String referenced_table = rs.getString("REFERENCED_TABLE_NAME");
final String referenced_column = rs.getString("REFERENCED_COLUMN_NAME");
if (!includeTable(schema, table) || !includeTable(referenced_schema, referenced_table)) continue;
Map<String, Object> fk = foreignKeys.get(constraint_name);
if (fk==null) {
fk = new LinkedHashMap<String,Object>();
final String[] reffing = {schema, table};
fk.put("reffing", reffing);
final String[] reffed = {referenced_schema, referenced_table};
fk.put("reffed", reffed);
foreignKeys.put(constraint_name,fk);
fk.put("columns", new LinkedHashMap<String,String>());
}
@SuppressWarnings("unchecked")
final
Map<String,String> columns = (Map<String,String>) fk.get("columns");
columns.put(column, referenced_column);
}
return foreignKeys;
}
private Map<String, Map<String,Object>> getForeignKeysMySQL(
final Connection conn) throws SQLException {
final Map<String, Map<String,Object>> foreignKeys =
new LinkedHashMap<String, Map<String,Object>>();
final Statement s = conn.createStatement();
s.execute("select constraint_name, table_schema, table_name, column_name, " +
" referenced_table_schema, referenced_table_name, " +
" referenced_column_name " +
"from information_schema.key_column_usage " +
"where table_schema is not null " +
" and table_name is not null " +
" and column_name is not null " +
" and referenced_table_schema is not null " +
" and referenced_table_name is not null " +
" and referenced_column_name is not null " +
"order by constraint_name, table_schema, table_name, column_name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String constraint_name = rs.getString("constraint_name");
final String schema = rs.getString("table_schema");
final String table = rs.getString("table_name");
final String column = rs.getString("column_name");
final String referenced_schema = rs.getString("referenced_table_schema");
final String referenced_table = rs.getString("referenced_table_name");
final String referenced_column = rs.getString("referenced_column_name");
if (!includeTable(schema, table) || !includeTable(referenced_schema, referenced_table)) continue;
Map<String, Object> fk = foreignKeys.get(constraint_name);
if (fk==null) {
fk = new LinkedHashMap<String,Object>();
final String[] reffing = {schema, table};
fk.put("reffing", reffing);
final String[] reffed = {referenced_schema, referenced_table};
fk.put("reffed", reffed);
foreignKeys.put(constraint_name,fk);
fk.put("columns", new LinkedHashMap<String,String>());
}
@SuppressWarnings("unchecked")
final
Map<String,String> columns = (Map<String,String>) fk.get("columns");
columns.put(column, referenced_column);
}
return foreignKeys;
}
private Map<String, Map<String,Object>> getForeignKeysHSQL(
final Connection conn) throws SQLException {
final Map<String, Map<String,Object>> foreignKeys =
new LinkedHashMap<String, Map<String,Object>>();
final Statement s = conn.createStatement();
s.execute("select fk_name, pktable_schem, pktable_name, pkcolumn_name, " +
" fktable_schem, fktable_name, " +
" fkcolumn_name " +
"from information_schema.SYSTEM_CROSSREFERENCE " +
"where pktable_schem is not null " +
" and pktable_name is not null " +
" and pkcolumn_name is not null " +
" and fktable_schem is not null " +
" and fktable_name is not null " +
" and fkcolumn_name is not null " +
"order by fk_name, pktable_schem, pktable_name, pkcolumn_name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String constraint_name = rs.getString("fk_name");
final String schema = rs.getString("fktable_schem");
final String table = rs.getString("fktable_name");
final String column = rs.getString("fkcolumn_name");
final String referenced_schema = rs.getString("pktable_schem");
final String referenced_table = rs.getString("pktable_name");
final String referenced_column = rs.getString("pkcolumn_name");
if (!includeTable(schema, table) || !includeTable(referenced_schema, referenced_table)) continue;
Map<String, Object> fk = foreignKeys.get(constraint_name);
if (fk==null) {
fk = new LinkedHashMap<String,Object>();
final String[] reffing = {schema, table};
fk.put("reffing", reffing);
final String[] reffed = {referenced_schema, referenced_table};
fk.put("reffed", reffed);
foreignKeys.put(constraint_name,fk);
fk.put("columns", new LinkedHashMap<String,String>());
}
@SuppressWarnings("unchecked")
final
Map<String,String> columns = (Map<String,String>) fk.get("columns");
columns.put(column, referenced_column);
}
return foreignKeys;
}
}
| true | true | private Map<String, Map<String, Map<String, String>>> getSchemasMSSQL(final Connection conn)
throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final List<String> dbs = new ArrayList<String>();
final Statement s = conn.createStatement();
s.execute("SELECT NAME FROM SYS.DATABASES ORDER BY NAME;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("NAME");
if (ignoredSchemas.contains(schema))
continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
dbs.add(schema);
}
rs.close();
// s.close();
for (final String db : dbs) {
if (ignoredSchemas.contains(db))
continue;
if (includeSchemas != null && !includeSchemas.contains(db))
continue;
System.err.println("extracting schema for: "+ db);
try {
s.execute("use \"" + db + "\";");
s.execute("SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, " +
"CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS ORDER BY " +
"TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME;");
final ResultSet rs2 = s.getResultSet();
while (rs2.next()) {
final String schema = db; // +"."+ rs2.getString("TABLE_SCHEMA");
final String table = rs2.getString("TABLE_NAME");
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
if (table.toLowerCase().startsWith("syncobj_")) continue;
if (table.startsWith("MS") && table.length() > 2
&& Character.isLowerCase(table.charAt(2))) continue;
final String column = rs2.getString("COLUMN_NAME");
String type = rs2.getString("DATA_TYPE");
final int maxLength = rs2.getInt("CHARACTER_MAXIMUM_LENGTH");
if ("char".equalsIgnoreCase(type) && maxLength > 1)
type = "varchar";
Map<String, String> columns = tables.get(table);
if (columns == null) {
columns = new LinkedHashMap<String, String>();
tables.put(table, columns);
}
columns.put(column, type);
}
rs2.close();
} catch (final SQLException e) {
if (e.getMessage().contains("security context")) {
System.err.println(e.getMessage());
} else {
throw e;
}
}
}
s.close();
return schemas;
}
| private Map<String, Map<String, Map<String, String>>> getSchemasMSSQL(final Connection conn)
throws SQLException {
final Map<String, Map<String, Map<String, String>>> schemas = new LinkedHashMap<String, Map<String, Map<String, String>>>();
final List<String> dbs = new ArrayList<String>();
final Statement s = conn.createStatement();
s.execute("SELECT name FROM sys.databases ORDER BY name;");
final ResultSet rs = s.getResultSet();
while (rs.next()) {
final String schema = rs.getString("NAME");
if (ignoredSchemas.contains(schema))
continue;
if (includeSchemas != null && !includeSchemas.contains(schema))
continue;
dbs.add(schema);
}
rs.close();
// s.close();
for (final String db : dbs) {
if (ignoredSchemas.contains(db))
continue;
if (includeSchemas != null && !includeSchemas.contains(db))
continue;
System.err.println("extracting schema for: "+ db);
try {
s.execute("use \"" + db + "\";");
s.execute("SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, " +
"CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS ORDER BY " +
"TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME;");
final ResultSet rs2 = s.getResultSet();
while (rs2.next()) {
final String schema = db; // +"."+ rs2.getString("TABLE_SCHEMA");
final String table = rs2.getString("TABLE_NAME");
if (!includeTable(schema, table)) continue;
Map<String, Map<String, String>> tables = schemas.get(schema);
if (tables == null) {
tables = new LinkedHashMap<String, Map<String, String>>();
schemas.put(schema, tables);
}
if (table.toLowerCase().startsWith("syncobj_")) continue;
if (table.startsWith("MS") && table.length() > 2
&& Character.isLowerCase(table.charAt(2))) continue;
final String column = rs2.getString("COLUMN_NAME");
String type = rs2.getString("DATA_TYPE");
final int maxLength = rs2.getInt("CHARACTER_MAXIMUM_LENGTH");
if ("char".equalsIgnoreCase(type) && maxLength > 1)
type = "varchar";
Map<String, String> columns = tables.get(table);
if (columns == null) {
columns = new LinkedHashMap<String, String>();
tables.put(table, columns);
}
columns.put(column, type);
}
rs2.close();
} catch (final SQLException e) {
if (e.getMessage().contains("security context")) {
System.err.println(e.getMessage());
} else {
throw e;
}
}
}
s.close();
return schemas;
}
|
diff --git a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/HomeController.java b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/HomeController.java
index be2665f9..22d1df52 100644
--- a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/HomeController.java
+++ b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/HomeController.java
@@ -1,159 +1,162 @@
/*
* Copyright 2012 SURFnet bv, The Netherlands
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.surfnet.coin.selfservice.control;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import nl.surfnet.coin.csa.Csa;
import nl.surfnet.coin.csa.model.Category;
import nl.surfnet.coin.csa.model.CategoryValue;
import nl.surfnet.coin.csa.model.Service;
import nl.surfnet.coin.csa.model.Taxonomy;
import nl.surfnet.coin.selfservice.domain.CoinUser;
import nl.surfnet.coin.selfservice.domain.IdentityProvider;
import nl.surfnet.coin.selfservice.domain.PersonAttributeLabel;
import nl.surfnet.coin.selfservice.service.impl.PersonAttributeLabelServiceJsonImpl;
import nl.surfnet.coin.selfservice.util.PersonMainAttributes;
import nl.surfnet.coin.selfservice.util.SpringSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* Controller of the homepage showing 'my apps' (or my services, meaning the
* services that belong to you as a user with a specific role)
*
*/
@Controller
public class HomeController extends BaseController {
@Resource(name = "personAttributeLabelService")
private PersonAttributeLabelServiceJsonImpl personAttributeLabelService;
@Resource
private Csa csa;
@ModelAttribute(value = "personAttributeLabels")
public Map<String, PersonAttributeLabel> getPersonAttributeLabels() {
return personAttributeLabelService.getAttributeLabelMap();
}
@RequestMapping("/app-overview.shtml")
public ModelAndView home(@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp,
@RequestParam(value = "view", defaultValue = "card") String view) {
Map<String, Object> model = new HashMap<String, Object>();
List<Service> services = csa.getServicesForIdp(selectedidp.getId());
model.put(SERVICES, services);
final Map<String, PersonAttributeLabel> attributeLabelMap = personAttributeLabelService.getAttributeLabelMap();
model.put("personAttributeLabels", attributeLabelMap);
model.put("view", view);
addLicensedConnectedCounts(model, services);
model.put("showFacetSearch", true);
List<Category> facets = this.filterFacetValues(services, csa.getTaxonomy());
model.put("facets", facets);
model.put("facetsUsed", this.isCategoryValuesUsed(facets));
return new ModelAndView("app-overview", model);
}
private void addLicensedConnectedCounts(Map<String, Object> model, List<Service> services) {
int connectedCount = getConnectedCount(services);
model.put("connectedCount", connectedCount);
model.put("notConnectedCount", services.size() - connectedCount);
int licensedCount = getLicensedCount(services);
model.put("licensedCount", licensedCount);
model.put("notLicensedCount", services.size() - licensedCount);
}
private boolean isCategoryValuesUsed(List<Category> categories) {
for (Category cat : categories) {
if (cat.isUsedFacetValues()) {
return true;
}
}
return false;
}
private int getLicensedCount(List<Service> services) {
int result = 0;
for (Service service : services) {
if (service.getLicense() != null) {
++result;
}
}
return result;
}
private int getConnectedCount(List<Service> services) {
int result = 0;
for (Service service : services) {
if (service.isConnected()) {
++result;
}
}
return result;
}
@RequestMapping("/user.shtml")
public ModelAndView user() {
Map<String, Object> model = new HashMap<String, Object>();
CoinUser user = SpringSecurity.getCurrentUser();
model.put("mainAttributes", new PersonMainAttributes(user.getAttributeMap()));
return new ModelAndView("user", model);
}
@RequestMapping(value = "/closeNotificationPopup.shtml")
public void closeNotificationPopup(HttpServletRequest request) {
notificationPopupClosed(request);
}
private List<Category> filterFacetValues(List<Service> services, Taxonomy taxonomy) {
if (taxonomy == null || taxonomy.getCategories() == null) {
return Collections.emptyList();
}
for (Category category : taxonomy.getCategories()) {
if (category.getValues() == null) {
continue;
}
for (CategoryValue value : category.getValues()) {
int count = 0;
for (Service service : services) {
+ if (service.getCategories() == null || service.getCategories().isEmpty()) {
+ continue;
+ }
List<CategoryValue> categoryValues = service.getCategories().get(category);
if (categoryValues != null && categoryValues.contains(value)) {
++count;
}
}
value.setCount(count);
}
}
return taxonomy.getCategories();
}
}
| true | true | private List<Category> filterFacetValues(List<Service> services, Taxonomy taxonomy) {
if (taxonomy == null || taxonomy.getCategories() == null) {
return Collections.emptyList();
}
for (Category category : taxonomy.getCategories()) {
if (category.getValues() == null) {
continue;
}
for (CategoryValue value : category.getValues()) {
int count = 0;
for (Service service : services) {
List<CategoryValue> categoryValues = service.getCategories().get(category);
if (categoryValues != null && categoryValues.contains(value)) {
++count;
}
}
value.setCount(count);
}
}
return taxonomy.getCategories();
}
| private List<Category> filterFacetValues(List<Service> services, Taxonomy taxonomy) {
if (taxonomy == null || taxonomy.getCategories() == null) {
return Collections.emptyList();
}
for (Category category : taxonomy.getCategories()) {
if (category.getValues() == null) {
continue;
}
for (CategoryValue value : category.getValues()) {
int count = 0;
for (Service service : services) {
if (service.getCategories() == null || service.getCategories().isEmpty()) {
continue;
}
List<CategoryValue> categoryValues = service.getCategories().get(category);
if (categoryValues != null && categoryValues.contains(value)) {
++count;
}
}
value.setCount(count);
}
}
return taxonomy.getCategories();
}
|
diff --git a/src/main/java/org/jahia/modules/location/LocationService.java b/src/main/java/org/jahia/modules/location/LocationService.java
index 4519c7f..13d52bc 100644
--- a/src/main/java/org/jahia/modules/location/LocationService.java
+++ b/src/main/java/org/jahia/modules/location/LocationService.java
@@ -1,43 +1,43 @@
package org.jahia.modules.location;
import com.google.code.geocoder.Geocoder;
import com.google.code.geocoder.GeocoderRequestBuilder;
import com.google.code.geocoder.model.GeocodeResponse;
import com.google.code.geocoder.model.GeocoderRequest;
import com.google.code.geocoder.model.GeocoderResult;
import org.drools.spi.KnowledgeHelper;
import org.jahia.services.content.JCRNodeWrapper;
import org.jahia.services.content.rules.AddedNodeFact;
import javax.jcr.RepositoryException;
import java.util.List;
public class LocationService {
public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
- if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:locationAware")) {
- nodeWrapper.addMixin("jmix:locationAware");
+ if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:geotagged")) {
+ nodeWrapper.addMixin("jmix:geotagged");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
}
| true | true | public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:locationAware")) {
nodeWrapper.addMixin("jmix:locationAware");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
| public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:geotagged")) {
nodeWrapper.addMixin("jmix:geotagged");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
|
diff --git a/src/gov/nih/nci/caintegrator/analysis/server/CorrelationTaskR.java b/src/gov/nih/nci/caintegrator/analysis/server/CorrelationTaskR.java
index ef133b4..5434cc7 100644
--- a/src/gov/nih/nci/caintegrator/analysis/server/CorrelationTaskR.java
+++ b/src/gov/nih/nci/caintegrator/analysis/server/CorrelationTaskR.java
@@ -1,123 +1,121 @@
package gov.nih.nci.caintegrator.analysis.server;
import gov.nih.nci.caintegrator.analysis.messaging.AnalysisRequest;
import gov.nih.nci.caintegrator.analysis.messaging.AnalysisResult;
import gov.nih.nci.caintegrator.analysis.messaging.CorrelationRequest;
import gov.nih.nci.caintegrator.analysis.messaging.CorrelationResult;
import gov.nih.nci.caintegrator.enumeration.CorrelationType;
import gov.nih.nci.caintegrator.exceptions.AnalysisServerException;
import org.apache.log4j.Logger;
import org.rosuda.JRclient.REXP;
public class CorrelationTaskR extends AnalysisTaskR {
private CorrelationResult result;
private static Logger logger = Logger.getLogger(CorrelationTaskR.class);
public CorrelationTaskR(AnalysisRequest request) {
super(request);
}
public CorrelationTaskR(AnalysisRequest request, boolean debugRcommands) {
super(request, debugRcommands);
}
@Override
public void run() {
CorrelationRequest corrRequest = (CorrelationRequest) getRequest();
result = new CorrelationResult(getRequest().getSessionId(), getRequest().getTaskId());
logger.info(getExecutingThreadName() + " processing correlation request="
+ corrRequest);
try {
String dataFileName = corrRequest.getDataFileName();
if (dataFileName == null) {
//check to make sure that the vectors have data
if ((corrRequest.getVector1()==null)||(corrRequest.getVector2()==null)) {
throw new AnalysisServerException("Problem with correlation request. No data file specified and vectors are null.");
}
}
else {
setDataFile(corrRequest.getDataFileName());
}
} catch (AnalysisServerException e) {
e.setFailedRequest(corrRequest);
logger.error("Internal Error. " + e.getMessage());
setException(e);
return;
}
try {
//Need to handle case where gene expression reporters are passed in..
- String cmd = CorrelationTaskR.getRgroupCmd("GRP1", corrRequest.getVector1());
+ String cmd = CorrelationTaskR.getRgroupCmd("GRP1", corrRequest.getVector1().getValues());
doRvoidEval(cmd);
- cmd = CorrelationTaskR.getRgroupCmd("GRP2", corrRequest.getVector2());
+ cmd = CorrelationTaskR.getRgroupCmd("GRP2", corrRequest.getVector2().getValues());
doRvoidEval(cmd);
REXP rVal = null;
if (corrRequest.getCorrelationType() == CorrelationType.PEARSON) {
cmd = "r <- correlation(GRP1,GRP2,\"pearson\")";
rVal = doREval(cmd);
}
else if (corrRequest.getCorrelationType() == CorrelationType.SPEARMAN) {
cmd = "r <- correlation(GRP1,GRP2, \"spearman\")";
rVal = doREval(cmd);
}
else {
throw new AnalysisServerException("Unrecognized correlationType or correlation type is null.");
}
double r = rVal.asDouble();
result.setCorrelationValue(r);
- result.setVector1Name(corrRequest.getVector1Name());
- result.setVector1(corrRequest.getVector1());
- result.setVector2Name(corrRequest.getVector2Name());
+ result.setVector1(corrRequest.getVector1());
result.setVector2(corrRequest.getVector2());
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage());
aex.setFailedRequest(corrRequest);
setException(aex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage());
asex.setFailedRequest(corrRequest);
setException(asex);
return;
}
}
@Override
public void cleanUp() {
try {
setRComputeConnection(null);
} catch (AnalysisServerException e) {
logger.error("Error in cleanUp method.");
logger.error(e);
setException(e);
}
}
@Override
public AnalysisResult getResult() {
return result;
}
}
| false | true | public void run() {
CorrelationRequest corrRequest = (CorrelationRequest) getRequest();
result = new CorrelationResult(getRequest().getSessionId(), getRequest().getTaskId());
logger.info(getExecutingThreadName() + " processing correlation request="
+ corrRequest);
try {
String dataFileName = corrRequest.getDataFileName();
if (dataFileName == null) {
//check to make sure that the vectors have data
if ((corrRequest.getVector1()==null)||(corrRequest.getVector2()==null)) {
throw new AnalysisServerException("Problem with correlation request. No data file specified and vectors are null.");
}
}
else {
setDataFile(corrRequest.getDataFileName());
}
} catch (AnalysisServerException e) {
e.setFailedRequest(corrRequest);
logger.error("Internal Error. " + e.getMessage());
setException(e);
return;
}
try {
//Need to handle case where gene expression reporters are passed in..
String cmd = CorrelationTaskR.getRgroupCmd("GRP1", corrRequest.getVector1());
doRvoidEval(cmd);
cmd = CorrelationTaskR.getRgroupCmd("GRP2", corrRequest.getVector2());
doRvoidEval(cmd);
REXP rVal = null;
if (corrRequest.getCorrelationType() == CorrelationType.PEARSON) {
cmd = "r <- correlation(GRP1,GRP2,\"pearson\")";
rVal = doREval(cmd);
}
else if (corrRequest.getCorrelationType() == CorrelationType.SPEARMAN) {
cmd = "r <- correlation(GRP1,GRP2, \"spearman\")";
rVal = doREval(cmd);
}
else {
throw new AnalysisServerException("Unrecognized correlationType or correlation type is null.");
}
double r = rVal.asDouble();
result.setCorrelationValue(r);
result.setVector1Name(corrRequest.getVector1Name());
result.setVector1(corrRequest.getVector1());
result.setVector2Name(corrRequest.getVector2Name());
result.setVector2(corrRequest.getVector2());
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage());
aex.setFailedRequest(corrRequest);
setException(aex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage());
asex.setFailedRequest(corrRequest);
setException(asex);
return;
}
}
| public void run() {
CorrelationRequest corrRequest = (CorrelationRequest) getRequest();
result = new CorrelationResult(getRequest().getSessionId(), getRequest().getTaskId());
logger.info(getExecutingThreadName() + " processing correlation request="
+ corrRequest);
try {
String dataFileName = corrRequest.getDataFileName();
if (dataFileName == null) {
//check to make sure that the vectors have data
if ((corrRequest.getVector1()==null)||(corrRequest.getVector2()==null)) {
throw new AnalysisServerException("Problem with correlation request. No data file specified and vectors are null.");
}
}
else {
setDataFile(corrRequest.getDataFileName());
}
} catch (AnalysisServerException e) {
e.setFailedRequest(corrRequest);
logger.error("Internal Error. " + e.getMessage());
setException(e);
return;
}
try {
//Need to handle case where gene expression reporters are passed in..
String cmd = CorrelationTaskR.getRgroupCmd("GRP1", corrRequest.getVector1().getValues());
doRvoidEval(cmd);
cmd = CorrelationTaskR.getRgroupCmd("GRP2", corrRequest.getVector2().getValues());
doRvoidEval(cmd);
REXP rVal = null;
if (corrRequest.getCorrelationType() == CorrelationType.PEARSON) {
cmd = "r <- correlation(GRP1,GRP2,\"pearson\")";
rVal = doREval(cmd);
}
else if (corrRequest.getCorrelationType() == CorrelationType.SPEARMAN) {
cmd = "r <- correlation(GRP1,GRP2, \"spearman\")";
rVal = doREval(cmd);
}
else {
throw new AnalysisServerException("Unrecognized correlationType or correlation type is null.");
}
double r = rVal.asDouble();
result.setCorrelationValue(r);
result.setVector1(corrRequest.getVector1());
result.setVector2(corrRequest.getVector2());
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Problem computing correlation. Caught AnalysisServerException in CorrelationTaskR." + asex.getMessage());
aex.setFailedRequest(corrRequest);
setException(aex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught Exception in CorrelationTaskR exClass=" + ex.getClass() + " msg=" + ex.getMessage());
asex.setFailedRequest(corrRequest);
setException(asex);
return;
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java
index a5790eb51..d79972968 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java
@@ -1,109 +1,109 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui;
import java.util.Map;
import org.eclipse.osgi.util.TextProcessor;
public class CVSDecoratorConfiguration {
// bindings for
public static final String RESOURCE_NAME = "name"; //$NON-NLS-1$
public static final String RESOURCE_TAG = "tag"; //$NON-NLS-1$
public static final String FILE_REVISION = "revision"; //$NON-NLS-1$
public static final String FILE_KEYWORD = "keyword"; //$NON-NLS-1$
// bindings for repository location
public static final String REMOTELOCATION_METHOD = "method"; //$NON-NLS-1$
public static final String REMOTELOCATION_USER = "user"; //$NON-NLS-1$
public static final String REMOTELOCATION_HOST = "host"; //$NON-NLS-1$
public static final String REMOTELOCATION_ROOT = "root"; //$NON-NLS-1$
public static final String REMOTELOCATION_REPOSITORY = "repository"; //$NON-NLS-1$
public static final String REMOTELOCATION_LABEL = "label"; //$NON-NLS-1$
// bindings for resource states
public static final String DIRTY_FLAG = "dirty_flag"; //$NON-NLS-1$
public static final String ADDED_FLAG = "added_flag"; //$NON-NLS-1$
public static final String DEFAULT_DIRTY_FLAG = CVSUIMessages.CVSDecoratorConfiguration_0;
public static final String DEFAULT_ADDED_FLAG = CVSUIMessages.CVSDecoratorConfiguration_1;
// default text decoration formats
public static final String DEFAULT_FILETEXTFORMAT = CVSUIMessages.CVSDecoratorConfiguration_2;
public static final String DEFAULT_FOLDERTEXTFORMAT = CVSUIMessages.CVSDecoratorConfiguration_3;
public static final String DEFAULT_PROJECTTEXTFORMAT = CVSUIMessages.CVSDecoratorConfiguration_4;
// prefix characters that can be removed if the following binding is not found
private static final char KEYWORD_SEPCOLON = ':';
private static final char KEYWORD_SEPAT = '@';
// font and color definition ids
public static final String OUTGOING_CHANGE_FOREGROUND_COLOR = "org.eclipse.team.cvs.ui.fontsandcolors.outgoing_change_foreground_color"; //$NON-NLS-1$
public static final String OUTGOING_CHANGE_BACKGROUND_COLOR = "org.eclipse.team.cvs.ui.fontsandcolors.outgoing_change_background_color"; //$NON-NLS-1$
public static final String OUTGOING_CHANGE_FONT = "org.eclipse.team.cvs.ui.fontsandcolors.outgoing_change_font"; //$NON-NLS-1$
public static final String IGNORED_FOREGROUND_COLOR = "org.eclipse.team.cvs.ui.fontsandcolors.ignored_resource_foreground_color"; //$NON-NLS-1$
public static final String IGNORED_BACKGROUND_COLOR = "org.eclipse.team.cvs.ui.fontsandcolors.ignored_resource_background_color"; //$NON-NLS-1$
public static final String IGNORED_FONT = "org.eclipse.team.cvs.ui.fontsandcolors.ignored_resource_font"; //$NON-NLS-1$
public static void decorate(CVSDecoration decoration, String format, Map bindings) {
- StringBuffer prefix = new StringBuffer(80);
- StringBuffer suffix = new StringBuffer(80);
+ StringBuffer prefix = new StringBuffer();
+ StringBuffer suffix = new StringBuffer();
StringBuffer output = prefix;
int length = format.length();
int start = -1;
int end = length;
while (true) {
if ((end = format.indexOf('{', start)) > -1) {
output.append(format.substring(start + 1, end));
if ((start = format.indexOf('}', end)) > -1) {
String key = format.substring(end + 1, start);
String s;
//We use the RESOURCE_NAME key to determine if we are doing the prefix or suffix. The name isn't actually part of either.
if(key.equals(RESOURCE_NAME)) {
output = suffix;
s = null;
} else {
s = (String) bindings.get(key);
}
if(s!=null) {
output.append(s);
} else {
// support for removing prefix character if binding is null
int curLength = output.length();
if(curLength>0) {
char c = output.charAt(curLength - 1);
if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPAT) {
output.deleteCharAt(curLength - 1);
}
}
}
} else {
output.append(format.substring(end, length));
break;
}
} else {
output.append(format.substring(start + 1, length));
break;
}
}
if (prefix.length() != 0) {
decoration.addPrefix(TextProcessor.process(prefix.toString(),"()[].")); //$NON-NLS-1$
}
if (suffix.length() != 0) {
decoration.addSuffix(TextProcessor.process(suffix.toString(),"()[].")); //$NON-NLS-1$
}
}
}
| true | true | public static void decorate(CVSDecoration decoration, String format, Map bindings) {
StringBuffer prefix = new StringBuffer(80);
StringBuffer suffix = new StringBuffer(80);
StringBuffer output = prefix;
int length = format.length();
int start = -1;
int end = length;
while (true) {
if ((end = format.indexOf('{', start)) > -1) {
output.append(format.substring(start + 1, end));
if ((start = format.indexOf('}', end)) > -1) {
String key = format.substring(end + 1, start);
String s;
//We use the RESOURCE_NAME key to determine if we are doing the prefix or suffix. The name isn't actually part of either.
if(key.equals(RESOURCE_NAME)) {
output = suffix;
s = null;
} else {
s = (String) bindings.get(key);
}
if(s!=null) {
output.append(s);
} else {
// support for removing prefix character if binding is null
int curLength = output.length();
if(curLength>0) {
char c = output.charAt(curLength - 1);
if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPAT) {
output.deleteCharAt(curLength - 1);
}
}
}
} else {
output.append(format.substring(end, length));
break;
}
} else {
output.append(format.substring(start + 1, length));
break;
}
}
if (prefix.length() != 0) {
decoration.addPrefix(TextProcessor.process(prefix.toString(),"()[].")); //$NON-NLS-1$
}
if (suffix.length() != 0) {
decoration.addSuffix(TextProcessor.process(suffix.toString(),"()[].")); //$NON-NLS-1$
}
}
| public static void decorate(CVSDecoration decoration, String format, Map bindings) {
StringBuffer prefix = new StringBuffer();
StringBuffer suffix = new StringBuffer();
StringBuffer output = prefix;
int length = format.length();
int start = -1;
int end = length;
while (true) {
if ((end = format.indexOf('{', start)) > -1) {
output.append(format.substring(start + 1, end));
if ((start = format.indexOf('}', end)) > -1) {
String key = format.substring(end + 1, start);
String s;
//We use the RESOURCE_NAME key to determine if we are doing the prefix or suffix. The name isn't actually part of either.
if(key.equals(RESOURCE_NAME)) {
output = suffix;
s = null;
} else {
s = (String) bindings.get(key);
}
if(s!=null) {
output.append(s);
} else {
// support for removing prefix character if binding is null
int curLength = output.length();
if(curLength>0) {
char c = output.charAt(curLength - 1);
if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPAT) {
output.deleteCharAt(curLength - 1);
}
}
}
} else {
output.append(format.substring(end, length));
break;
}
} else {
output.append(format.substring(start + 1, length));
break;
}
}
if (prefix.length() != 0) {
decoration.addPrefix(TextProcessor.process(prefix.toString(),"()[].")); //$NON-NLS-1$
}
if (suffix.length() != 0) {
decoration.addSuffix(TextProcessor.process(suffix.toString(),"()[].")); //$NON-NLS-1$
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.