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/core/src/main/java/hudson/model/LoadBalancer.java b/core/src/main/java/hudson/model/LoadBalancer.java
index b873102f7..8f82c8b20 100644
--- a/core/src/main/java/hudson/model/LoadBalancer.java
+++ b/core/src/main/java/hudson/model/LoadBalancer.java
@@ -1,157 +1,157 @@
package hudson.model;
import hudson.model.Node.Mode;
import hudson.model.Queue.ApplicableJobOfferList;
import hudson.model.Queue.JobOffer;
import hudson.model.Queue.Task;
import hudson.util.ConsistentHash;
import hudson.util.ConsistentHash.Hash;
import java.util.logging.Logger;
/**
* Strategy that decides which {@link Task} gets run on which {@link Executor}.
*
* @author Kohsuke Kawaguchi
* @since 1.301
*/
public abstract class LoadBalancer /*implements ExtensionPoint*/ {
/**
* Chooses the executor to carry out the build for the given project.
*
* <p>
* This method is invoked from different threads, but the execution is serialized by the caller.
* The thread that invokes this method always holds a lock to {@link Queue}, so queue contents
* can be safely introspected from this method, if that information is necessary to make
* decisions.
*
* @param applicable
* The list of {@link JobOffer}s that represent {@linkplain JobOffer#isAvailable() available} {@link Executor}s, from which
* the callee can choose. Never null.
* @param task
* The task whose execution is being considered. Never null.
*
* @return
* Pick one of the items from {@code available}, and return it. How you choose it
* is the crucial part of the implementation. Return null if you don't want
* the task to be executed right now, in which case this method will be called
* some time later with the same task.
*/
protected abstract JobOffer choose(Task task, ApplicableJobOfferList applicable);
/**
* Traditional implementation of this.
*/
public static final LoadBalancer DEFAULT = new LoadBalancer() {
protected JobOffer choose(Task task, ApplicableJobOfferList applicable) {
Label l = task.getAssignedLabel();
if (l != null) {
// if a project has assigned label, it can be only built on it
for (JobOffer offer : applicable) {
if (l.contains(offer.getNode()))
return offer;
}
return null;
}
// if we are a large deployment, then we will favor slaves
boolean isLargeHudson = Hudson.getInstance().getNodes().size() > 10;
// otherwise let's see if the last node where this project was built is available
// it has up-to-date workspace, so that's usually preferable.
// (but we can't use an exclusive node)
Node n = task.getLastBuiltOn();
if (n != null && n.getMode() == Mode.NORMAL) {
for (JobOffer offer : applicable) {
if (offer.getNode() == n) {
- if (isLargeHudson && offer.getNode() instanceof Slave)
+ if (isLargeHudson && offer.getNode() instanceof Hudson)
// but if we are a large Hudson, then we really do want to keep the master free from builds
continue;
return offer;
}
}
}
// duration of a build on a slave tends not to have an impact on
// the master/slave communication, so that means we should favor
// running long jobs on slaves.
// Similarly if we have many slaves, master should be made available
// for HTTP requests and coordination as much as possible
if (isLargeHudson || task.getEstimatedDuration() > 15 * 60 * 1000) {
// consider a long job to be > 15 mins
for (JobOffer offer : applicable) {
if (offer.getNode() instanceof Slave && offer.isNotExclusive())
return offer;
}
}
// lastly, just look for any idle executor
for (JobOffer offer : applicable) {
if (offer.isNotExclusive())
return offer;
}
// nothing available
return null;
}
};
/**
* Uses a consistent hash for scheduling.
*/
public static final LoadBalancer CONSISTENT_HASH = new LoadBalancer() {
protected JobOffer choose(Task task, ApplicableJobOfferList applicable) {
// populate a consistent hash linear to the # of executors
// TODO: there's a lot of room for innovations here
// TODO: do this upfront and reuse the consistent hash
ConsistentHash<Node> hash = new ConsistentHash<Node>(new Hash<Node>() {
public String hash(Node node) {
return node.getNodeName();
}
});
for (Node n : applicable.nodes())
hash.add(n,n.getNumExecutors()*100);
// TODO: add some salt as a query point so that the user can tell Hudson to hop the project to a new node
for(Node n : hash.list(task.getFullDisplayName())) {
JobOffer o = applicable._for(n);
if(o!=null)
return o;
}
// nothing available
return null;
}
};
/**
* Wraps this {@link LoadBalancer} into a decorator that tests the basic sanity of the implementation.
* Only override this if you find some of the checks excessive, but beware that it's like driving without a seat belt.
*/
protected LoadBalancer sanitize() {
final LoadBalancer base = this;
return new LoadBalancer() {
@Override
protected JobOffer choose(Task task, ApplicableJobOfferList applicable) {
if (Hudson.getInstance().isQuietingDown()) {
// if we are quieting down, don't start anything new so that
// all executors will be eventually free.
return null;
}
return base.choose(task, applicable);
}
/**
* Double-sanitization is pointless.
*/
@Override
protected LoadBalancer sanitize() {
return this;
}
private final Logger LOGGER = Logger.getLogger(LoadBalancer.class.getName());
};
}
}
| true | true | protected JobOffer choose(Task task, ApplicableJobOfferList applicable) {
Label l = task.getAssignedLabel();
if (l != null) {
// if a project has assigned label, it can be only built on it
for (JobOffer offer : applicable) {
if (l.contains(offer.getNode()))
return offer;
}
return null;
}
// if we are a large deployment, then we will favor slaves
boolean isLargeHudson = Hudson.getInstance().getNodes().size() > 10;
// otherwise let's see if the last node where this project was built is available
// it has up-to-date workspace, so that's usually preferable.
// (but we can't use an exclusive node)
Node n = task.getLastBuiltOn();
if (n != null && n.getMode() == Mode.NORMAL) {
for (JobOffer offer : applicable) {
if (offer.getNode() == n) {
if (isLargeHudson && offer.getNode() instanceof Slave)
// but if we are a large Hudson, then we really do want to keep the master free from builds
continue;
return offer;
}
}
}
// duration of a build on a slave tends not to have an impact on
// the master/slave communication, so that means we should favor
// running long jobs on slaves.
// Similarly if we have many slaves, master should be made available
// for HTTP requests and coordination as much as possible
if (isLargeHudson || task.getEstimatedDuration() > 15 * 60 * 1000) {
// consider a long job to be > 15 mins
for (JobOffer offer : applicable) {
if (offer.getNode() instanceof Slave && offer.isNotExclusive())
return offer;
}
}
// lastly, just look for any idle executor
for (JobOffer offer : applicable) {
if (offer.isNotExclusive())
return offer;
}
// nothing available
return null;
}
| protected JobOffer choose(Task task, ApplicableJobOfferList applicable) {
Label l = task.getAssignedLabel();
if (l != null) {
// if a project has assigned label, it can be only built on it
for (JobOffer offer : applicable) {
if (l.contains(offer.getNode()))
return offer;
}
return null;
}
// if we are a large deployment, then we will favor slaves
boolean isLargeHudson = Hudson.getInstance().getNodes().size() > 10;
// otherwise let's see if the last node where this project was built is available
// it has up-to-date workspace, so that's usually preferable.
// (but we can't use an exclusive node)
Node n = task.getLastBuiltOn();
if (n != null && n.getMode() == Mode.NORMAL) {
for (JobOffer offer : applicable) {
if (offer.getNode() == n) {
if (isLargeHudson && offer.getNode() instanceof Hudson)
// but if we are a large Hudson, then we really do want to keep the master free from builds
continue;
return offer;
}
}
}
// duration of a build on a slave tends not to have an impact on
// the master/slave communication, so that means we should favor
// running long jobs on slaves.
// Similarly if we have many slaves, master should be made available
// for HTTP requests and coordination as much as possible
if (isLargeHudson || task.getEstimatedDuration() > 15 * 60 * 1000) {
// consider a long job to be > 15 mins
for (JobOffer offer : applicable) {
if (offer.getNode() instanceof Slave && offer.isNotExclusive())
return offer;
}
}
// lastly, just look for any idle executor
for (JobOffer offer : applicable) {
if (offer.isNotExclusive())
return offer;
}
// nothing available
return null;
}
|
diff --git a/robot/Multiplexor.java b/robot/Multiplexor.java
index 9a32b79..ad86ae8 100644
--- a/robot/Multiplexor.java
+++ b/robot/Multiplexor.java
@@ -1,47 +1,49 @@
import lejos.nxt.I2CPort;
import lejos.nxt.I2CSensor;
public class Multiplexor extends I2CSensor{
private static byte direction;
private static byte speed;
public Multiplexor(I2CPort port){
super(port);
setAddress(0x5A);
}
public static void main(String[] args){
}
public void setMotors(int directionIndex, int speedIndex, int wheelIndex){
// sets up possible values
if(directionIndex == -1){
direction = (byte)2;
}else if(directionIndex == 0){
direction = (byte)0;
} else if(speedIndex == 1){
direction = (byte)1;
}
if(speedIndex == 0){
speed = (byte)0;
}else if(speedIndex == 1){
- speed = (byte)130;
- } else if(speedIndex == 2){
+ speed = (byte)90;
+ }else if(speedIndex == 2){
+ speed = (byte)180;
+ } else if(speedIndex == 3){
speed = (byte)255;
}
switch (wheelIndex){
// left wheel
case 0:
sendData((byte)0x03,direction);
sendData((byte)0x04,speed);
break;
// right wheel
case 1:
sendData((byte)0x01,direction);
sendData((byte)0x02,speed);
break;
}
}
}
| true | true | public void setMotors(int directionIndex, int speedIndex, int wheelIndex){
// sets up possible values
if(directionIndex == -1){
direction = (byte)2;
}else if(directionIndex == 0){
direction = (byte)0;
} else if(speedIndex == 1){
direction = (byte)1;
}
if(speedIndex == 0){
speed = (byte)0;
}else if(speedIndex == 1){
speed = (byte)130;
} else if(speedIndex == 2){
speed = (byte)255;
}
switch (wheelIndex){
// left wheel
case 0:
sendData((byte)0x03,direction);
sendData((byte)0x04,speed);
break;
// right wheel
case 1:
sendData((byte)0x01,direction);
sendData((byte)0x02,speed);
break;
}
}
| public void setMotors(int directionIndex, int speedIndex, int wheelIndex){
// sets up possible values
if(directionIndex == -1){
direction = (byte)2;
}else if(directionIndex == 0){
direction = (byte)0;
} else if(speedIndex == 1){
direction = (byte)1;
}
if(speedIndex == 0){
speed = (byte)0;
}else if(speedIndex == 1){
speed = (byte)90;
}else if(speedIndex == 2){
speed = (byte)180;
} else if(speedIndex == 3){
speed = (byte)255;
}
switch (wheelIndex){
// left wheel
case 0:
sendData((byte)0x03,direction);
sendData((byte)0x04,speed);
break;
// right wheel
case 1:
sendData((byte)0x01,direction);
sendData((byte)0x02,speed);
break;
}
}
|
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
index 83b68cf6..6de8e728 100644
--- a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
+++ b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
@@ -1,220 +1,220 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.recorder.ui;
import java.util.HashMap;
import java.util.Map;
import org.cubictest.common.utils.ErrorHandler;
import org.cubictest.common.utils.UserInfo;
import org.cubictest.export.exceptions.ExporterException;
import org.cubictest.export.utils.exported.ExportUtils;
import org.cubictest.export.utils.exported.TestWalkerUtils;
import org.cubictest.exporters.selenium.ui.RunSeleniumRunnerAction;
import org.cubictest.model.ExtensionStartPoint;
import org.cubictest.model.Page;
import org.cubictest.model.Test;
import org.cubictest.model.Transition;
import org.cubictest.model.TransitionNode;
import org.cubictest.model.UrlStartPoint;
import org.cubictest.recorder.CubicRecorder;
import org.cubictest.recorder.GUIAwareRecorder;
import org.cubictest.recorder.IRecorder;
import org.cubictest.recorder.selenium.SeleniumRecorder;
import org.cubictest.ui.gef.interfaces.exported.IDisposeListener;
import org.cubictest.ui.gef.interfaces.exported.ITestEditor;
import org.cubictest.ui.gef.layout.AutoLayout;
import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
/**
* Action for starting / stopping the CubicRecorder.
*
*/
public class RecordEditorAction implements IObjectActionDelegate {
private static Map<Test, Boolean> testsRecording;
private SeleniumRecorder seleniumRecorder;
private ITestEditor testEditor;
private Test test;
private Page selectedPage;
private IAction currentState;
public RecordEditorAction() {
super();
}
/**
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
//action is toggle action:
if(isRecording()) {
//recorder running. stop it
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
setRunning(false);
} else {
setRunning(true);
TransitionNode firstPage = test.getStartPoint().getFirstNodeFromOutTransitions();
if (firstPage != null) {
if (firstPage.getFirstNodeFromOutTransitions() != null && selectedPage == null) {
- UserInfo.showWarnDialog("Test is not empty, please select a Page/State to record from.");
+ UserInfo.showWarnDialog("Please select a Page/State to record from (test is not empty).");
setRunning(false);
return;
}
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt(), new Shell());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
//check if the browser should be forwarded:
if (selectedPage != null || test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActiveEditor(action, (IEditorPart) testEditor);
- runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
+ runner.setCustomCompletedMessage("Recording can begin (test browser is forwarded). Result: $result.");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
if (selectedPage != null) {
if (!TestWalkerUtils.isOnPathToNode(test.getStartPoint(), selectedPage)) {
ErrorHandler.logAndShowErrorDialogAndThrow("Cannot find path from start point to selected page");
}
runner.setTargetPage(selectedPage);
}
runner.setPreSelectedTest(test);
runner.run(action);
}
cubicRecorder.setEnabled(true);
if (selectedPage != null) {
cubicRecorder.setCursor(selectedPage);
}
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
setRunning(false);
return;
}
}
}
private void stopSelenium(AutoLayout autoLayout) {
try {
if (seleniumRecorder != null) {
seleniumRecorder.stop();
}
if (autoLayout != null) {
autoLayout.setPageSelected(null);
}
}
catch(Exception e) {
ErrorHandler.logAndRethrow(e);
}
finally {
setRunning(false);
}
}
private void setRunning(boolean running) {
testsRecording.put(test, running);
currentState.setChecked(running);
}
/**
* Get the initial URL start point of the test (expands subtests).
*/
private UrlStartPoint getInitialUrlStartPoint(Test test) {
if (test.getStartPoint() instanceof UrlStartPoint) {
return (UrlStartPoint) test.getStartPoint();
}
else {
//ExtensionStartPoint, get url start point recursively:
return getInitialUrlStartPoint(((ExtensionStartPoint) test.getStartPoint()).getTest(true));
}
}
public boolean firstPageIsEmpty(Test test) {
for(Transition t : test.getStartPoint().getOutTransitions()) {
if(t.getEnd() instanceof Page && ((Page)t.getEnd()).getRootElements().size() == 0) {
return true;
}
}
return false;
}
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
this.testEditor = (ITestEditor) targetPart;
this.test = testEditor.getTest();
}
public void selectionChanged(IAction action, ISelection selection) {
this.currentState = action;
currentState.setChecked(isRecording());
this.selectedPage = null;
Object selected = ((StructuredSelection) selection).getFirstElement();
if (selected instanceof AbstractEditPart) {
Object model = ((AbstractEditPart) selected).getModel();
if (model instanceof Page) {
this.selectedPage = (Page) model;
}
}
}
private Boolean isRecording() {
if (testsRecording == null) {
testsRecording = new HashMap<Test, Boolean>();
}
Boolean recording = testsRecording.get(test);
return recording == null ? false : recording;
}
}
| false | true | public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
//action is toggle action:
if(isRecording()) {
//recorder running. stop it
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
setRunning(false);
} else {
setRunning(true);
TransitionNode firstPage = test.getStartPoint().getFirstNodeFromOutTransitions();
if (firstPage != null) {
if (firstPage.getFirstNodeFromOutTransitions() != null && selectedPage == null) {
UserInfo.showWarnDialog("Test is not empty, please select a Page/State to record from.");
setRunning(false);
return;
}
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt(), new Shell());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
//check if the browser should be forwarded:
if (selectedPage != null || test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActiveEditor(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
if (selectedPage != null) {
if (!TestWalkerUtils.isOnPathToNode(test.getStartPoint(), selectedPage)) {
ErrorHandler.logAndShowErrorDialogAndThrow("Cannot find path from start point to selected page");
}
runner.setTargetPage(selectedPage);
}
runner.setPreSelectedTest(test);
runner.run(action);
}
cubicRecorder.setEnabled(true);
if (selectedPage != null) {
cubicRecorder.setCursor(selectedPage);
}
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
setRunning(false);
return;
}
}
}
| public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
//action is toggle action:
if(isRecording()) {
//recorder running. stop it
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
setRunning(false);
} else {
setRunning(true);
TransitionNode firstPage = test.getStartPoint().getFirstNodeFromOutTransitions();
if (firstPage != null) {
if (firstPage.getFirstNodeFromOutTransitions() != null && selectedPage == null) {
UserInfo.showWarnDialog("Please select a Page/State to record from (test is not empty).");
setRunning(false);
return;
}
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt(), new Shell());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
//check if the browser should be forwarded:
if (selectedPage != null || test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActiveEditor(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Recording can begin (test browser is forwarded). Result: $result.");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
if (selectedPage != null) {
if (!TestWalkerUtils.isOnPathToNode(test.getStartPoint(), selectedPage)) {
ErrorHandler.logAndShowErrorDialogAndThrow("Cannot find path from start point to selected page");
}
runner.setTargetPage(selectedPage);
}
runner.setPreSelectedTest(test);
runner.run(action);
}
cubicRecorder.setEnabled(true);
if (selectedPage != null) {
cubicRecorder.setCursor(selectedPage);
}
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
setRunning(false);
return;
}
}
}
|
diff --git a/modules/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/AwsSdbHelper.java b/modules/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/AwsSdbHelper.java
index 45424c913..5d519c064 100644
--- a/modules/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/AwsSdbHelper.java
+++ b/modules/org.restlet.ext.crypto/src/org/restlet/ext/crypto/internal/AwsSdbHelper.java
@@ -1,84 +1,84 @@
/**
* Copyright 2005-2011 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.ext.crypto.internal;
import java.util.Date;
import org.restlet.Request;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.engine.security.AuthenticatorHelper;
import org.restlet.engine.util.DateUtils;
import org.restlet.representation.Representation;
/**
* Implements the HTTP authentication for the Amazon SimpleDB service.
*
* @author Jerome Louvel
*/
public class AwsSdbHelper extends AuthenticatorHelper {
/**
* Constructor.
*/
public AwsSdbHelper() {
super(ChallengeScheme.HTTP_AWS_SDB, true, false);
}
@Override
public Representation updateEntity(Representation entity,
ChallengeResponse challengeResponse, Request request) {
Representation result = entity;
if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
Form form = new Form(entity);
form.add("AWSAccessKeyId", new String(request
- .getChallengeResponse().getSecret()));
+ .getChallengeResponse().getIdentifier()));
form.add("SignatureMethod", "HmacSHA256");
form.add("SignatureVersion", "2");
form.add("Version", "2009-04-15");
String df = DateUtils.format(new Date(),
DateUtils.FORMAT_ISO_8601.get(0));
form.add("Timestamp", df);
// Compute then add the signature parameter
String signature = AwsUtils.getSdbSignature(request.getMethod(),
request.getResourceRef(), form, request
.getChallengeResponse().getSecret());
form.add("Signature", signature);
result = form.getWebRepresentation();
}
return result;
}
}
| true | true | public Representation updateEntity(Representation entity,
ChallengeResponse challengeResponse, Request request) {
Representation result = entity;
if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
Form form = new Form(entity);
form.add("AWSAccessKeyId", new String(request
.getChallengeResponse().getSecret()));
form.add("SignatureMethod", "HmacSHA256");
form.add("SignatureVersion", "2");
form.add("Version", "2009-04-15");
String df = DateUtils.format(new Date(),
DateUtils.FORMAT_ISO_8601.get(0));
form.add("Timestamp", df);
// Compute then add the signature parameter
String signature = AwsUtils.getSdbSignature(request.getMethod(),
request.getResourceRef(), form, request
.getChallengeResponse().getSecret());
form.add("Signature", signature);
result = form.getWebRepresentation();
}
return result;
}
| public Representation updateEntity(Representation entity,
ChallengeResponse challengeResponse, Request request) {
Representation result = entity;
if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
Form form = new Form(entity);
form.add("AWSAccessKeyId", new String(request
.getChallengeResponse().getIdentifier()));
form.add("SignatureMethod", "HmacSHA256");
form.add("SignatureVersion", "2");
form.add("Version", "2009-04-15");
String df = DateUtils.format(new Date(),
DateUtils.FORMAT_ISO_8601.get(0));
form.add("Timestamp", df);
// Compute then add the signature parameter
String signature = AwsUtils.getSdbSignature(request.getMethod(),
request.getResourceRef(), form, request
.getChallengeResponse().getSecret());
form.add("Signature", signature);
result = form.getWebRepresentation();
}
return result;
}
|
diff --git a/plugins/org.eclipse.m2m.atl.adt.editor/src/org/eclipse/m2m/atl/adt/ui/outline/AtlLabelProvider.java b/plugins/org.eclipse.m2m.atl.adt.editor/src/org/eclipse/m2m/atl/adt/ui/outline/AtlLabelProvider.java
index 55d9158c..35350ba2 100644
--- a/plugins/org.eclipse.m2m.atl.adt.editor/src/org/eclipse/m2m/atl/adt/ui/outline/AtlLabelProvider.java
+++ b/plugins/org.eclipse.m2m.atl.adt.editor/src/org/eclipse/m2m/atl/adt/ui/outline/AtlLabelProvider.java
@@ -1,290 +1,293 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA.
* 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:
* Tarik Idrissi (INRIA) - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.adt.ui.outline;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.m2m.atl.adt.ui.AtlUIPlugin;
import org.eclipse.m2m.atl.adt.ui.editor.AtlEditorMessages;
import org.eclipse.swt.graphics.Image;
public class AtlLabelProvider extends LabelProvider {
private boolean initialized = false;
private Map readers = new HashMap();
private Map imageCache = new HashMap();
private Map classToImages = new HashMap();
private Reader defaultReader = new Reader() {
public String getText(EObject object) {
return "<default> : " + object.eClass().getName(); //$NON-NLS-1$
}
};
private abstract class Reader {
public abstract String getText(EObject rule);
}
public AtlLabelProvider() {
initForImages();
}
public void initReaders() {
readers.put(AtlEMFConstants.clRule, new Reader() {
private EStructuralFeature name = AtlEMFConstants.clRule.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject rule) {
return (String)rule.eGet(name);
}
});
readers.put(AtlEMFConstants.clMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clLazyMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clCalledRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clHelper, new Reader() {
private EStructuralFeature sfFeature = AtlEMFConstants.clOclFeatureDefinition
.getEStructuralFeature("feature"); //$NON-NLS-1$
public String getText(EObject helper) {
EObject featureDef = (EObject)helper.eGet(AtlEMFConstants.sfHelperDefinition);
EObject feature = (EObject)featureDef.eGet(sfFeature);
+ if (feature == null) {
+ return null;
+ }
return (String)feature.eGet(feature.eClass().getEStructuralFeature("name")); //$NON-NLS-1$
}
});
readers.put(AtlEMFConstants.clLibraryRef, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clLibraryRef.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject libraryRef) {
return (String)libraryRef.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clOclModel, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clOclModel.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject oclModel) {
return (String)oclModel.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
private EStructuralFeature sfVarName = AtlEMFConstants.clVariableDeclaration
.getEStructuralFeature("varName"); //$NON-NLS-1$
public String getText(EObject variableDeclaration) {
return (String)variableDeclaration.eGet(sfVarName);
}
});
readers.put(AtlEMFConstants.clUnit, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clUnit.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject unit) {
return (String)unit.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clModule, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clLibrary, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clQuery, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
public String getText(EObject rule) {
return (String)rule.eGet(AtlEMFConstants.sfVarName);
}
});
readers.put(AtlEMFConstants.clPatternElement, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clRuleVariableDeclaration, readers
.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clParameter, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clInPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers
.put(AtlEMFConstants.clSimpleInPatternElement, readers
.get(AtlEMFConstants.clInPatternElement));
readers.put(AtlEMFConstants.clOutPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers.put(AtlEMFConstants.clSimpleOutPatternElement, readers
.get(AtlEMFConstants.clOutPatternElement));
}
private void initForText(EObject unit) {
if (!initialized) {
AtlEMFConstants.pkAtl = unit.eClass().getEPackage();
AtlEMFConstants.clModule = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Module"); //$NON-NLS-1$
AtlEMFConstants.clLibrary = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Library"); //$NON-NLS-1$
AtlEMFConstants.clQuery = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Query"); //$NON-NLS-1$
AtlEMFConstants.sfModuleElements = AtlEMFConstants.clModule.getEStructuralFeature("elements"); //$NON-NLS-1$
AtlEMFConstants.clRule = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Rule"); //$NON-NLS-1$
AtlEMFConstants.clMatchedRule = (EClass)AtlEMFConstants.pkAtl.getEClassifier("MatchedRule"); //$NON-NLS-1$
AtlEMFConstants.clLazyMatchedRule = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("LazyMatchedRule"); //$NON-NLS-1$
AtlEMFConstants.clCalledRule = (EClass)AtlEMFConstants.pkAtl.getEClassifier("CalledRule"); //$NON-NLS-1$
AtlEMFConstants.clHelper = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Helper"); //$NON-NLS-1$
AtlEMFConstants.sfHelperDefinition = AtlEMFConstants.clHelper
.getEStructuralFeature("definition"); //$NON-NLS-1$
AtlEMFConstants.clLibraryRef = (EClass)AtlEMFConstants.pkAtl.getEClassifier("LibraryRef"); //$NON-NLS-1$
AtlEMFConstants.clUnit = (EClass)AtlEMFConstants.pkAtl.getEClassifier("Unit"); //$NON-NLS-1$
AtlEMFConstants.clPatternElement = (EClass)AtlEMFConstants.pkAtl.getEClassifier("PatternElement"); //$NON-NLS-1$
AtlEMFConstants.clRuleVariableDeclaration = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("RuleVariableDeclaration"); //$NON-NLS-1$
AtlEMFConstants.clInPatternElement = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("InPatternElement"); //$NON-NLS-1$
AtlEMFConstants.clOutPatternElement = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("OutPatternElement"); //$NON-NLS-1$
AtlEMFConstants.clSimpleInPatternElement = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("SimpleInPatternElement"); //$NON-NLS-1$
AtlEMFConstants.clSimpleOutPatternElement = (EClass)AtlEMFConstants.pkAtl
.getEClassifier("SimpleOutPatternElement"); //$NON-NLS-1$
AtlEMFConstants.clInPattern = (EClass)AtlEMFConstants.pkAtl.getEClassifier("InPattern"); //$NON-NLS-1$
AtlEMFConstants.clOutPattern = (EClass)AtlEMFConstants.pkAtl.getEClassifier("OutPattern"); //$NON-NLS-1$
AtlEMFConstants.pkOcl = AtlEMFConstants.sfHelperDefinition.getEType().getEPackage();
AtlEMFConstants.clOclFeatureDefinition = (EClass)AtlEMFConstants.pkOcl
.getEClassifier("OclFeatureDefinition"); //$NON-NLS-1$
AtlEMFConstants.clOclFeature = (EClass)AtlEMFConstants.pkOcl.getEClassifier("OclFeature"); //$NON-NLS-1$
AtlEMFConstants.clOclModel = (EClass)AtlEMFConstants.pkOcl.getEClassifier("OclModel"); //$NON-NLS-1$
AtlEMFConstants.clParameter = (EClass)AtlEMFConstants.pkOcl.getEClassifier("Parameter"); //$NON-NLS-1$
AtlEMFConstants.clVariableDeclaration = (EClass)AtlEMFConstants.pkOcl
.getEClassifier("VariableDeclaration"); //$NON-NLS-1$
AtlEMFConstants.sfVarName = AtlEMFConstants.clVariableDeclaration
.getEStructuralFeature("varName"); //$NON-NLS-1$
AtlEMFConstants.clElement = (EClass)AtlEMFConstants.pkAtl.getEClassifier("LocatedElement"); //$NON-NLS-1$
AtlEMFConstants.sfLocation = AtlEMFConstants.clElement.getEStructuralFeature("location"); //$NON-NLS-1$
initReaders();
initialized = true;
}
}
private void initForImages() {
classToImages.put("Library", "libs.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Module", "module.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Query", "query.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("OclModel", "oclModel.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("LibraryRef", "libsreference.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Helper", "helper.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("MatchedRule", "matchedRule.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("LazyMatchedRule", "lazyRule.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Operation", "operation.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("InPattern", "inPattern.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("OutPattern", "outPattern.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Binding", "binding.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("Iterator", "iterator.gif"); //$NON-NLS-1$ //$NON-NLS-2$
// classToImages.put("OclFeatureDefinition", ".gif");
// classToImages.put("OclContextDefinition", "helper.gif");
classToImages.put("SimpleInPatternElement", "element.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("SimpleOutPatternElement", "element.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("OperationCallExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("OperatorCallExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("NavigationOrAttributeCallExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("EnumLiteralExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("IteratorExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("CollectionOperationCallExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("IfExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("StringExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("VariableExp", "expressionATL.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("BooleanType", "type.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("OclModelElement", "type.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("StringType", "type.gif"); //$NON-NLS-1$ //$NON-NLS-2$
classToImages.put("TupleType", "type.gif"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* returns the images descriptor for an element of the ATL AST
*
* @param className
* the class name for which to find the image descriptor
* @return the images descriptor for an element of the ATL AST
*/
private ImageDescriptor getImage(String className) {
String iconName = (String)classToImages.get(className);
if (iconName != null) {
return AtlUIPlugin.getImageDescriptor(iconName);
}
return AtlUIPlugin.getImageDescriptor("test.gif"); //$NON-NLS-1$
}
/**
* @see ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
Image ret = null;
if (!(element instanceof Root)) {
EObject eo = (EObject)element;
if (AtlEMFConstants.clUnit.isInstance(element)) {
initForText(eo);
}
String className = ((EObject)element).eClass().getName();
ImageDescriptor descriptor = getImage(className);
ret = (Image)imageCache.get(descriptor);
if (ret == null) {
ret = descriptor.createImage();
imageCache.put(descriptor, ret);
}
}
return ret;
}
private Reader getReader(EObject eo) {
Reader ret = null;
ret = (Reader)readers.get(eo.eClass());
if (ret == null) {
ret = defaultReader;
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
String ret = "default"; //$NON-NLS-1$
if (!(element instanceof Root)) {
EObject eo = (EObject)element;
initForText(eo);
ret = getReader(eo).getText(eo);
ret += " : " + eo.eClass().getName(); //$NON-NLS-1$
}
return ret;
}
/**
* @see org.eclipse.jface.viewers.LabelProvider#dispose()
*/
public void dispose() {
for (Iterator images = imageCache.values().iterator(); images.hasNext();)
((Image)images.next()).dispose();
imageCache.clear();
}
protected RuntimeException unknownElement(Object element) {
return new RuntimeException(
AtlEditorMessages.getString("AtlLabelProvider.0") + element.getClass().getName()); //$NON-NLS-1$
}
}
| true | true | public void initReaders() {
readers.put(AtlEMFConstants.clRule, new Reader() {
private EStructuralFeature name = AtlEMFConstants.clRule.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject rule) {
return (String)rule.eGet(name);
}
});
readers.put(AtlEMFConstants.clMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clLazyMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clCalledRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clHelper, new Reader() {
private EStructuralFeature sfFeature = AtlEMFConstants.clOclFeatureDefinition
.getEStructuralFeature("feature"); //$NON-NLS-1$
public String getText(EObject helper) {
EObject featureDef = (EObject)helper.eGet(AtlEMFConstants.sfHelperDefinition);
EObject feature = (EObject)featureDef.eGet(sfFeature);
return (String)feature.eGet(feature.eClass().getEStructuralFeature("name")); //$NON-NLS-1$
}
});
readers.put(AtlEMFConstants.clLibraryRef, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clLibraryRef.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject libraryRef) {
return (String)libraryRef.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clOclModel, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clOclModel.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject oclModel) {
return (String)oclModel.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
private EStructuralFeature sfVarName = AtlEMFConstants.clVariableDeclaration
.getEStructuralFeature("varName"); //$NON-NLS-1$
public String getText(EObject variableDeclaration) {
return (String)variableDeclaration.eGet(sfVarName);
}
});
readers.put(AtlEMFConstants.clUnit, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clUnit.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject unit) {
return (String)unit.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clModule, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clLibrary, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clQuery, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
public String getText(EObject rule) {
return (String)rule.eGet(AtlEMFConstants.sfVarName);
}
});
readers.put(AtlEMFConstants.clPatternElement, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clRuleVariableDeclaration, readers
.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clParameter, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clInPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers
.put(AtlEMFConstants.clSimpleInPatternElement, readers
.get(AtlEMFConstants.clInPatternElement));
readers.put(AtlEMFConstants.clOutPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers.put(AtlEMFConstants.clSimpleOutPatternElement, readers
.get(AtlEMFConstants.clOutPatternElement));
}
| public void initReaders() {
readers.put(AtlEMFConstants.clRule, new Reader() {
private EStructuralFeature name = AtlEMFConstants.clRule.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject rule) {
return (String)rule.eGet(name);
}
});
readers.put(AtlEMFConstants.clMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clLazyMatchedRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clCalledRule, readers.get(AtlEMFConstants.clRule));
readers.put(AtlEMFConstants.clHelper, new Reader() {
private EStructuralFeature sfFeature = AtlEMFConstants.clOclFeatureDefinition
.getEStructuralFeature("feature"); //$NON-NLS-1$
public String getText(EObject helper) {
EObject featureDef = (EObject)helper.eGet(AtlEMFConstants.sfHelperDefinition);
EObject feature = (EObject)featureDef.eGet(sfFeature);
if (feature == null) {
return null;
}
return (String)feature.eGet(feature.eClass().getEStructuralFeature("name")); //$NON-NLS-1$
}
});
readers.put(AtlEMFConstants.clLibraryRef, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clLibraryRef.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject libraryRef) {
return (String)libraryRef.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clOclModel, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clOclModel.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject oclModel) {
return (String)oclModel.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
private EStructuralFeature sfVarName = AtlEMFConstants.clVariableDeclaration
.getEStructuralFeature("varName"); //$NON-NLS-1$
public String getText(EObject variableDeclaration) {
return (String)variableDeclaration.eGet(sfVarName);
}
});
readers.put(AtlEMFConstants.clUnit, new Reader() {
private EStructuralFeature sfName = AtlEMFConstants.clUnit.getEStructuralFeature("name"); //$NON-NLS-1$
public String getText(EObject unit) {
return (String)unit.eGet(sfName);
}
});
readers.put(AtlEMFConstants.clModule, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clLibrary, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clQuery, readers.get(AtlEMFConstants.clUnit));
readers.put(AtlEMFConstants.clVariableDeclaration, new Reader() {
public String getText(EObject rule) {
return (String)rule.eGet(AtlEMFConstants.sfVarName);
}
});
readers.put(AtlEMFConstants.clPatternElement, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clRuleVariableDeclaration, readers
.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clParameter, readers.get(AtlEMFConstants.clVariableDeclaration));
readers.put(AtlEMFConstants.clInPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers
.put(AtlEMFConstants.clSimpleInPatternElement, readers
.get(AtlEMFConstants.clInPatternElement));
readers.put(AtlEMFConstants.clOutPatternElement, readers.get(AtlEMFConstants.clPatternElement));
readers.put(AtlEMFConstants.clSimpleOutPatternElement, readers
.get(AtlEMFConstants.clOutPatternElement));
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/ViewRender.java b/src/uk/org/ponder/rsf/renderer/ViewRender.java
index 4dbffb2..ba818df 100644
--- a/src/uk/org/ponder/rsf/renderer/ViewRender.java
+++ b/src/uk/org/ponder/rsf/renderer/ViewRender.java
@@ -1,472 +1,472 @@
/*
* Created on Aug 7, 2005
*/
package uk.org.ponder.rsf.renderer;
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 uk.org.ponder.messageutil.TargettedMessageList;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.content.ContentTypeInfo;
import uk.org.ponder.rsf.renderer.decorator.DecoratorManager;
import uk.org.ponder.rsf.renderer.message.MessageFlyweight;
import uk.org.ponder.rsf.renderer.message.MessageRenderer;
import uk.org.ponder.rsf.renderer.message.MessageTargetMap;
import uk.org.ponder.rsf.renderer.message.MessageTargetter;
import uk.org.ponder.rsf.template.XMLCompositeViewTemplate;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.rsf.template.XMLLumpMMap;
import uk.org.ponder.rsf.template.XMLViewTemplate;
import uk.org.ponder.rsf.util.RSFUtil;
import uk.org.ponder.rsf.util.SplitID;
import uk.org.ponder.rsf.view.View;
import uk.org.ponder.rsf.view.ViewTemplate;
import uk.org.ponder.streamutil.write.PrintOutputStream;
import uk.org.ponder.stringutil.CharWrap;
import uk.org.ponder.util.Logger;
import uk.org.ponder.xml.XMLUtil;
import uk.org.ponder.xml.XMLWriter;
/**
* Encapsulates the request-specific process of rendering a view - a
* request-scope bean containing the implementation of the IKAT rendering
* algorithm.
*
* @author Antranig Basman ([email protected])
*
*/
public class ViewRender {
private XMLViewTemplate roott;
private XMLLumpMMap globalmap;
private View view;
private RenderSystem renderer;
private PrintOutputStream pos;
private XMLWriter xmlw;
// a map of UIBranchContainer to XMLLump
private Map branchmap;
private XMLLumpMMap collected = new XMLLumpMMap();
private Map idrewritemap = new HashMap();
private MessageFlyweight messageFlyweight;
private XMLLump messagelump;
private TargettedMessageList messagelist;
// a map of HTMLLumps to StringList of messages due to be delivered to
// that component when it is reached (registered with a FORID prefix)
private MessageTargetMap messagetargets;
private MessageRenderer messagerenderer;
private String globalmessagetarget;
private boolean rendereddeadletters;
private ContentTypeInfo contenttypeinfo;
private IDAssigner IDassigner;
private DecoratorManager decoratormanager;
private boolean debugrender;
private RenderSystemContext rsc;
public void setViewTemplate(ViewTemplate viewtemplateo) {
if (viewtemplateo instanceof XMLCompositeViewTemplate) {
XMLCompositeViewTemplate viewtemplate = (XMLCompositeViewTemplate) viewtemplateo;
roott = viewtemplate.roottemplate;
globalmap = viewtemplate.globalmap;
collected.aggregate(viewtemplate.mustcollectmap);
}
else {
roott = (XMLViewTemplate) viewtemplateo;
globalmap = roott.globalmap;
}
}
public void setView(View view) {
this.view = view;
}
// a useful access point for the rendered view for testing and debugging purposes
public View getView() {
return view;
}
public void setRenderSystem(RenderSystem renderer) {
this.renderer = renderer;
}
public void setContentTypeInfo(ContentTypeInfo contenttypeinfo) {
this.contenttypeinfo = contenttypeinfo;
}
public void setMessages(TargettedMessageList messages) {
this.messagelist = messages;
}
public void setGlobalMessageTarget(String globalmessagetarget) {
this.globalmessagetarget = globalmessagetarget;
}
public void setMessageRenderer(MessageRenderer messagerenderer) {
this.messagerenderer = messagerenderer;
}
public void setDecoratorManager(DecoratorManager decoratormanager) {
this.decoratormanager = decoratormanager;
}
public void setDebugRender(boolean debugrender) {
this.debugrender = debugrender;
}
private void collectContributions() {
Set seenset = new HashSet();
for (Iterator lumpit = branchmap.values().iterator(); lumpit.hasNext();) {
XMLLump headlump = (XMLLump) lumpit.next();
if (!seenset.contains(headlump.parent)) {
collected.aggregate(headlump.parent.collectmap);
seenset.add(headlump.parent);
}
}
}
private void debugGlobalTargets() {
renderer.renderDebugMessage(rsc,
"All global branch targets in resolution set:");
for (Iterator globalit = globalmap.iterator(); globalit.hasNext();) {
String key = (String) globalit.next();
if (key.indexOf(':') != -1) {
renderer.renderDebugMessage(rsc, "Branch key " + key);
XMLLumpList res = globalmap.headsForID(key);
for (int i = 0; i < res.size(); ++i) {
renderer.renderDebugMessage(rsc, "\t" + res.lumpAt(i).toString());
}
}
}
renderer.renderDebugMessage(rsc, "");
}
public void render(PrintOutputStream pos) {
IDassigner = new IDAssigner(debugrender ? ContentTypeInfo.ID_FORCE
: contenttypeinfo.IDStrategy);
// Add and remove the flyweight immediately around "resolveBranches" - instances of it
// will be dynamically "invented" around the tree wherever there are messages
messageFlyweight = new MessageFlyweight(view.viewroot);
branchmap = BranchResolver.resolveBranches(globalmap, view.viewroot,
roott.rootlump, idrewritemap);
view.viewroot.remove(messageFlyweight.rsfMessages);
messagelump = (XMLLump) branchmap.get(messageFlyweight.rsfMessages);
collectContributions();
messagetargets = MessageTargetter.targetMessages(branchmap, view,
messagelist, globalmessagetarget);
String declaration = contenttypeinfo.get().declaration;
if (declaration != null)
pos.print(declaration);
this.pos = pos;
this.xmlw = new XMLWriter(pos);
rsc = new RenderSystemContext(debugrender, view, pos, xmlw, IDassigner,
collected, idrewritemap);
rendereddeadletters = false;
if (debugrender) {
debugGlobalTargets();
}
renderRecurse(view.viewroot, roott.rootlump,
roott.lumps[roott.roottagindex]);
}
private void renderContainer(UIContainer child, XMLLump targetlump) {
// may have jumped template file
XMLViewTemplate t2 = targetlump.parent;
XMLLump firstchild = t2.lumps[targetlump.open_end.lumpindex + 1];
if (child instanceof UIBranchContainer) {
dumpBranchHead((UIBranchContainer) child, targetlump);
}
else {
renderer.renderComponent(rsc, child.parent, child, targetlump);
}
renderRecurse(child, targetlump, firstchild);
}
private void renderRecurse(UIContainer basecontainer,
XMLLump parentlump, XMLLump baselump) {
int renderindex = baselump.lumpindex;
int basedepth = parentlump.nestingdepth;
XMLViewTemplate tl = parentlump.parent;
Set rendered = null;
if (debugrender) {
rendered = new HashSet();
}
while (true) {
// continue scanning along this template section until we either each
// the last lump, or the recursion level.
renderindex = RenderUtil.dumpScan(tl.lumps, renderindex, basedepth, pos,
true, false);
if (renderindex == tl.lumps.length)
break;
XMLLump lump = tl.lumps[renderindex];
if (lump.nestingdepth < basedepth)
break;
String id = lump.rsfID;
if (id == null) {
throw new IllegalArgumentException("Fatal internal error during rendering - no rsf:id found on stopping tag " + lump);
}
if (id.startsWith(XMLLump.ELISION_PREFIX)) {
id = id.substring(XMLLump.ELISION_PREFIX.length());
}
boolean ismessagefor = id.startsWith(XMLLump.FORID_PREFIX);
if (!ismessagefor && SplitID.isSplit(id)) {
// we have entered a repetitive domain, by diagnosis of the template.
// Seek in the component tree for the child list that must be here
// at this component, and process them in order, looking them up in
// the forward map, which must ALSO be here.
String prefix = SplitID.getPrefix(id);
List children = RenderUtil.fetchComponents(basecontainer, prefix);
// these are all children with the same prefix, which will be rendered
// synchronously.
if (children != null) {
for (int i = 0; i < children.size(); ++i) {
UIComponent child = (UIComponent) children.get(i);
if (child instanceof UIContainer) {
XMLLump targetlump = (XMLLump) branchmap.get(child);
if (targetlump != null) {
if (debugrender) {
renderComment("Branching for " + child.getFullID() + " from "
+ lump + " to " + targetlump);
}
renderContainer((UIContainer) child, targetlump);
if (debugrender) {
renderComment("Branch returned for " + child.getFullID()
+ " to " + lump + " from " + targetlump);
}
}
else {
if (debugrender) {
renderer.renderDebugMessage(rsc,
"No matching template branch found for branch container with full ID "
+ child.getFullID()
+ " rendering from parent template branch "
+ baselump.toString());
}
}
}
else { // repetitive leaf
XMLLump targetlump = findChild(parentlump, child);
// this case may trigger if there are suffix-specific renderers
// but no fallback.
if (targetlump == null) {
renderer.renderDebugMessage(rsc,
"Repetitive leaf with full ID " + child.getFullID()
+ " could not be rendered from parent template branch "
+ baselump.toString());
continue;
}
int renderend = renderer.renderComponent(rsc, basecontainer, child, targetlump);
- boolean wasopentag = tl.lumps[renderend].nestingdepth >= targetlump.nestingdepth;
+ boolean wasopentag = renderend < tl.lumps.length && tl.lumps[renderend].nestingdepth >= targetlump.nestingdepth;
UIContainer newbase = child instanceof UIContainer? (UIContainer) child : basecontainer;
if (wasopentag) {
renderRecurse(newbase, targetlump, tl.lumps[renderend]);
renderend = targetlump.close_tag.lumpindex + 1;
}
if (i != children.size() - 1) {
// at this point, magically locate any "glue" that matches the
// transition
// from this component to the next in the template, and scan
// along
// until we reach the next component with a matching id prefix.
// NB transition matching is not implemented and may never be.
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth - 1, pos, false, false);
// we discard any index reached by this dump, continuing the
// controlled sequence as long as there are any children.
// given we are in the middle of a sequence here, we expect to
// see nothing perverse like components or forms, at most static
// things (needing rewriting?)
// TODO: split of beginning logic from renderComponent that
// deals
// with static rewriting, and somehow fix this call to dumpScan
// so that it can invoke it. Not urgent, we currently only have
// the TINIEST text forming repetition glue.
}
else {
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth, pos, true, false);
}
}
} // end for each repetitive child
}
else {
if (debugrender) {
renderer
.renderDebugMessage(rsc, "No branch container with prefix "
+ prefix + ": found at "
+ RSFUtil.reportPath(basecontainer)
+ " at template position " + baselump.toString()
+ ", skipping");
}
}
// at this point, magically locate the "postamble" from lump, and
// reset the index.
XMLLump finallump = lump.uplump.getFinal(prefix);
//parentlump.downmap.getFinal(prefix);
XMLLump closefinal = finallump.close_tag;
renderindex = closefinal.lumpindex + 1;
if (debugrender) {
renderComment("Stack returned from branch for ID " + id + " to "
+ baselump.toString() + ": skipping from " + lump.toString()
+ " to " + closefinal.toString());
}
}
else if (ismessagefor) {
TargettedMessageList messages = messagetargets.getMessages(lump);
if (messages == null)
messages = new TargettedMessageList();
if (!rendereddeadletters) {
rendereddeadletters = true;
TargettedMessageList deadmessages = messagetargets
.getMessages(MessageTargetter.DEAD_LETTERS);
if (deadmessages != null) {
messages.addMessages(deadmessages);
}
}
if (messages.size() != 0) {
if (messagelump == null) {
Logger.log
.warn("No message template is configured (containing branch with rsf id rsf-messages:)");
}
else {
basecontainer.addComponent(messageFlyweight.rsfMessages);
messagerenderer.renderMessageList(basecontainer, messageFlyweight, messages);
renderContainer(messageFlyweight.rsfMessages, messagelump);
basecontainer.remove(messageFlyweight.rsfMessages);
}
}
XMLLump closelump = lump.close_tag;
renderindex = closelump.lumpindex + 1;
}
else {
// no colon - continue template-driven.
// it is a single, irrepitable component - just render it, and skip
// on, or skip completely if there is no peer in the component tree.
UIComponent component = null;
if (id != null) {
if (debugrender) {
rendered.add(id);
}
component = fetchComponent(basecontainer, id, lump);
}
// Form rendering is now subject to "fairly normal" branch rendering logic
// That is, a UIContainer may now also be a leaf
if (component instanceof UIContainer) {
renderContainer((UIContainer) component, lump);
renderindex = lump.close_tag.lumpindex + 1;
}
else {
// if we find a leaf component, render it.
renderindex = renderer.renderComponent(rsc, basecontainer, component, lump);
}
} // end if unrepeatable component.
if (renderindex == tl.lumps.length) {
// deal with the case where component was root element - Ryan of
// 11/10/06
break;
}
}
if (debugrender) {
UIComponent[] flatchildren = basecontainer.flatChildren();
for (int i = 0; i < flatchildren.length; ++i) {
UIComponent child = flatchildren[i];
if (!(child.ID.indexOf(':') != -1) && !rendered.contains(child.ID)) {
renderer.renderDebugMessage(rsc, "Leaf child component "
+ child.getClass().getName() + " with full ID "
+ child.getFullID() + " could not be found within template "
+ baselump.toString());
}
}
}
}
private void renderComment(String string) {
pos.print("<!-- " + string + "-->");
}
private UIComponent fetchComponent(UIContainer basecontainer,
String id, XMLLump lump) {
if (id.startsWith(XMLLump.MSG_PREFIX)) {
String key = id.substring(XMLLump.MSG_PREFIX.length());
return messagerenderer.renderMessage(basecontainer,
(String) lump.attributemap.get("id"), key);
}
return RenderUtil.fetchComponent(basecontainer, id);
}
private XMLLump findChild(XMLLump sourcescope, UIComponent child) {
// if child is not a container, there can be no lookahead in resolution,
// and it must resolve to a component in THIS container which either
// matches exactly or in prefix.
SplitID split = new SplitID(child.ID);
XMLLumpList headlumps = sourcescope.downmap.headsForID(child.ID);
if (headlumps == null) {
headlumps = sourcescope.downmap.headsForID(split.prefix
+ SplitID.SEPARATOR);
// if (headlumps.size() == 0) {
// throw UniversalRuntimeException.accumulate(new IOException(),
// "Error in template file: peer for component with ID " + child.ID
// + " not found in scope " + sourcescope.toDebugString());
// }
}
return headlumps == null ? null
: headlumps.lumpAt(0);
}
private void dumpBranchHead(UIBranchContainer branch, XMLLump targetlump) {
HashMap attrcopy = new HashMap();
attrcopy.putAll(targetlump.attributemap);
IDassigner.adjustForID(attrcopy, branch);
decoratormanager.decorate(branch.decorators, targetlump.getTag(), attrcopy);
// TODO: normalise this silly space business
pos
.write(targetlump.parent.buffer, targetlump.start,
targetlump.length - 1);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
}
public static String debugLump(XMLLump debug) {
XMLLump[] lumps = debug.parent.lumps;
CharWrap message = new CharWrap();
message.append("Lump index " + debug.lumpindex + " (line " + debug.line
+ " column " + debug.column + ") ");
int frontpoint = debug.lumpindex - 5;
if (frontpoint < 0)
frontpoint = 0;
int endpoint = debug.lumpindex + 5;
if (frontpoint > lumps.length)
frontpoint = lumps.length;
for (int i = frontpoint; i < endpoint; ++i) {
if (i == debug.lumpindex) {
message.append("(*)");
}
XMLLump lump = lumps[i];
message.append(lump.parent.buffer, lump.start, lump.length);
}
if (debug.downmap != null) {
message.append("\nDownmap here: ").append(debug.downmap.getHeadsDebug());
}
return message.toString();
}
}
| true | true | private void renderRecurse(UIContainer basecontainer,
XMLLump parentlump, XMLLump baselump) {
int renderindex = baselump.lumpindex;
int basedepth = parentlump.nestingdepth;
XMLViewTemplate tl = parentlump.parent;
Set rendered = null;
if (debugrender) {
rendered = new HashSet();
}
while (true) {
// continue scanning along this template section until we either each
// the last lump, or the recursion level.
renderindex = RenderUtil.dumpScan(tl.lumps, renderindex, basedepth, pos,
true, false);
if (renderindex == tl.lumps.length)
break;
XMLLump lump = tl.lumps[renderindex];
if (lump.nestingdepth < basedepth)
break;
String id = lump.rsfID;
if (id == null) {
throw new IllegalArgumentException("Fatal internal error during rendering - no rsf:id found on stopping tag " + lump);
}
if (id.startsWith(XMLLump.ELISION_PREFIX)) {
id = id.substring(XMLLump.ELISION_PREFIX.length());
}
boolean ismessagefor = id.startsWith(XMLLump.FORID_PREFIX);
if (!ismessagefor && SplitID.isSplit(id)) {
// we have entered a repetitive domain, by diagnosis of the template.
// Seek in the component tree for the child list that must be here
// at this component, and process them in order, looking them up in
// the forward map, which must ALSO be here.
String prefix = SplitID.getPrefix(id);
List children = RenderUtil.fetchComponents(basecontainer, prefix);
// these are all children with the same prefix, which will be rendered
// synchronously.
if (children != null) {
for (int i = 0; i < children.size(); ++i) {
UIComponent child = (UIComponent) children.get(i);
if (child instanceof UIContainer) {
XMLLump targetlump = (XMLLump) branchmap.get(child);
if (targetlump != null) {
if (debugrender) {
renderComment("Branching for " + child.getFullID() + " from "
+ lump + " to " + targetlump);
}
renderContainer((UIContainer) child, targetlump);
if (debugrender) {
renderComment("Branch returned for " + child.getFullID()
+ " to " + lump + " from " + targetlump);
}
}
else {
if (debugrender) {
renderer.renderDebugMessage(rsc,
"No matching template branch found for branch container with full ID "
+ child.getFullID()
+ " rendering from parent template branch "
+ baselump.toString());
}
}
}
else { // repetitive leaf
XMLLump targetlump = findChild(parentlump, child);
// this case may trigger if there are suffix-specific renderers
// but no fallback.
if (targetlump == null) {
renderer.renderDebugMessage(rsc,
"Repetitive leaf with full ID " + child.getFullID()
+ " could not be rendered from parent template branch "
+ baselump.toString());
continue;
}
int renderend = renderer.renderComponent(rsc, basecontainer, child, targetlump);
boolean wasopentag = tl.lumps[renderend].nestingdepth >= targetlump.nestingdepth;
UIContainer newbase = child instanceof UIContainer? (UIContainer) child : basecontainer;
if (wasopentag) {
renderRecurse(newbase, targetlump, tl.lumps[renderend]);
renderend = targetlump.close_tag.lumpindex + 1;
}
if (i != children.size() - 1) {
// at this point, magically locate any "glue" that matches the
// transition
// from this component to the next in the template, and scan
// along
// until we reach the next component with a matching id prefix.
// NB transition matching is not implemented and may never be.
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth - 1, pos, false, false);
// we discard any index reached by this dump, continuing the
// controlled sequence as long as there are any children.
// given we are in the middle of a sequence here, we expect to
// see nothing perverse like components or forms, at most static
// things (needing rewriting?)
// TODO: split of beginning logic from renderComponent that
// deals
// with static rewriting, and somehow fix this call to dumpScan
// so that it can invoke it. Not urgent, we currently only have
// the TINIEST text forming repetition glue.
}
else {
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth, pos, true, false);
}
}
} // end for each repetitive child
}
else {
if (debugrender) {
renderer
.renderDebugMessage(rsc, "No branch container with prefix "
+ prefix + ": found at "
+ RSFUtil.reportPath(basecontainer)
+ " at template position " + baselump.toString()
+ ", skipping");
}
}
// at this point, magically locate the "postamble" from lump, and
// reset the index.
XMLLump finallump = lump.uplump.getFinal(prefix);
//parentlump.downmap.getFinal(prefix);
XMLLump closefinal = finallump.close_tag;
renderindex = closefinal.lumpindex + 1;
if (debugrender) {
renderComment("Stack returned from branch for ID " + id + " to "
+ baselump.toString() + ": skipping from " + lump.toString()
+ " to " + closefinal.toString());
}
}
else if (ismessagefor) {
TargettedMessageList messages = messagetargets.getMessages(lump);
if (messages == null)
messages = new TargettedMessageList();
if (!rendereddeadletters) {
rendereddeadletters = true;
TargettedMessageList deadmessages = messagetargets
.getMessages(MessageTargetter.DEAD_LETTERS);
if (deadmessages != null) {
messages.addMessages(deadmessages);
}
}
if (messages.size() != 0) {
if (messagelump == null) {
Logger.log
.warn("No message template is configured (containing branch with rsf id rsf-messages:)");
}
else {
basecontainer.addComponent(messageFlyweight.rsfMessages);
messagerenderer.renderMessageList(basecontainer, messageFlyweight, messages);
renderContainer(messageFlyweight.rsfMessages, messagelump);
basecontainer.remove(messageFlyweight.rsfMessages);
}
}
XMLLump closelump = lump.close_tag;
renderindex = closelump.lumpindex + 1;
}
else {
// no colon - continue template-driven.
// it is a single, irrepitable component - just render it, and skip
// on, or skip completely if there is no peer in the component tree.
UIComponent component = null;
if (id != null) {
if (debugrender) {
rendered.add(id);
}
component = fetchComponent(basecontainer, id, lump);
}
// Form rendering is now subject to "fairly normal" branch rendering logic
// That is, a UIContainer may now also be a leaf
if (component instanceof UIContainer) {
renderContainer((UIContainer) component, lump);
renderindex = lump.close_tag.lumpindex + 1;
}
else {
// if we find a leaf component, render it.
renderindex = renderer.renderComponent(rsc, basecontainer, component, lump);
}
} // end if unrepeatable component.
if (renderindex == tl.lumps.length) {
// deal with the case where component was root element - Ryan of
// 11/10/06
break;
}
}
if (debugrender) {
UIComponent[] flatchildren = basecontainer.flatChildren();
for (int i = 0; i < flatchildren.length; ++i) {
UIComponent child = flatchildren[i];
if (!(child.ID.indexOf(':') != -1) && !rendered.contains(child.ID)) {
renderer.renderDebugMessage(rsc, "Leaf child component "
+ child.getClass().getName() + " with full ID "
+ child.getFullID() + " could not be found within template "
+ baselump.toString());
}
}
}
}
| private void renderRecurse(UIContainer basecontainer,
XMLLump parentlump, XMLLump baselump) {
int renderindex = baselump.lumpindex;
int basedepth = parentlump.nestingdepth;
XMLViewTemplate tl = parentlump.parent;
Set rendered = null;
if (debugrender) {
rendered = new HashSet();
}
while (true) {
// continue scanning along this template section until we either each
// the last lump, or the recursion level.
renderindex = RenderUtil.dumpScan(tl.lumps, renderindex, basedepth, pos,
true, false);
if (renderindex == tl.lumps.length)
break;
XMLLump lump = tl.lumps[renderindex];
if (lump.nestingdepth < basedepth)
break;
String id = lump.rsfID;
if (id == null) {
throw new IllegalArgumentException("Fatal internal error during rendering - no rsf:id found on stopping tag " + lump);
}
if (id.startsWith(XMLLump.ELISION_PREFIX)) {
id = id.substring(XMLLump.ELISION_PREFIX.length());
}
boolean ismessagefor = id.startsWith(XMLLump.FORID_PREFIX);
if (!ismessagefor && SplitID.isSplit(id)) {
// we have entered a repetitive domain, by diagnosis of the template.
// Seek in the component tree for the child list that must be here
// at this component, and process them in order, looking them up in
// the forward map, which must ALSO be here.
String prefix = SplitID.getPrefix(id);
List children = RenderUtil.fetchComponents(basecontainer, prefix);
// these are all children with the same prefix, which will be rendered
// synchronously.
if (children != null) {
for (int i = 0; i < children.size(); ++i) {
UIComponent child = (UIComponent) children.get(i);
if (child instanceof UIContainer) {
XMLLump targetlump = (XMLLump) branchmap.get(child);
if (targetlump != null) {
if (debugrender) {
renderComment("Branching for " + child.getFullID() + " from "
+ lump + " to " + targetlump);
}
renderContainer((UIContainer) child, targetlump);
if (debugrender) {
renderComment("Branch returned for " + child.getFullID()
+ " to " + lump + " from " + targetlump);
}
}
else {
if (debugrender) {
renderer.renderDebugMessage(rsc,
"No matching template branch found for branch container with full ID "
+ child.getFullID()
+ " rendering from parent template branch "
+ baselump.toString());
}
}
}
else { // repetitive leaf
XMLLump targetlump = findChild(parentlump, child);
// this case may trigger if there are suffix-specific renderers
// but no fallback.
if (targetlump == null) {
renderer.renderDebugMessage(rsc,
"Repetitive leaf with full ID " + child.getFullID()
+ " could not be rendered from parent template branch "
+ baselump.toString());
continue;
}
int renderend = renderer.renderComponent(rsc, basecontainer, child, targetlump);
boolean wasopentag = renderend < tl.lumps.length && tl.lumps[renderend].nestingdepth >= targetlump.nestingdepth;
UIContainer newbase = child instanceof UIContainer? (UIContainer) child : basecontainer;
if (wasopentag) {
renderRecurse(newbase, targetlump, tl.lumps[renderend]);
renderend = targetlump.close_tag.lumpindex + 1;
}
if (i != children.size() - 1) {
// at this point, magically locate any "glue" that matches the
// transition
// from this component to the next in the template, and scan
// along
// until we reach the next component with a matching id prefix.
// NB transition matching is not implemented and may never be.
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth - 1, pos, false, false);
// we discard any index reached by this dump, continuing the
// controlled sequence as long as there are any children.
// given we are in the middle of a sequence here, we expect to
// see nothing perverse like components or forms, at most static
// things (needing rewriting?)
// TODO: split of beginning logic from renderComponent that
// deals
// with static rewriting, and somehow fix this call to dumpScan
// so that it can invoke it. Not urgent, we currently only have
// the TINIEST text forming repetition glue.
}
else {
RenderUtil.dumpScan(tl.lumps, renderend,
targetlump.nestingdepth, pos, true, false);
}
}
} // end for each repetitive child
}
else {
if (debugrender) {
renderer
.renderDebugMessage(rsc, "No branch container with prefix "
+ prefix + ": found at "
+ RSFUtil.reportPath(basecontainer)
+ " at template position " + baselump.toString()
+ ", skipping");
}
}
// at this point, magically locate the "postamble" from lump, and
// reset the index.
XMLLump finallump = lump.uplump.getFinal(prefix);
//parentlump.downmap.getFinal(prefix);
XMLLump closefinal = finallump.close_tag;
renderindex = closefinal.lumpindex + 1;
if (debugrender) {
renderComment("Stack returned from branch for ID " + id + " to "
+ baselump.toString() + ": skipping from " + lump.toString()
+ " to " + closefinal.toString());
}
}
else if (ismessagefor) {
TargettedMessageList messages = messagetargets.getMessages(lump);
if (messages == null)
messages = new TargettedMessageList();
if (!rendereddeadletters) {
rendereddeadletters = true;
TargettedMessageList deadmessages = messagetargets
.getMessages(MessageTargetter.DEAD_LETTERS);
if (deadmessages != null) {
messages.addMessages(deadmessages);
}
}
if (messages.size() != 0) {
if (messagelump == null) {
Logger.log
.warn("No message template is configured (containing branch with rsf id rsf-messages:)");
}
else {
basecontainer.addComponent(messageFlyweight.rsfMessages);
messagerenderer.renderMessageList(basecontainer, messageFlyweight, messages);
renderContainer(messageFlyweight.rsfMessages, messagelump);
basecontainer.remove(messageFlyweight.rsfMessages);
}
}
XMLLump closelump = lump.close_tag;
renderindex = closelump.lumpindex + 1;
}
else {
// no colon - continue template-driven.
// it is a single, irrepitable component - just render it, and skip
// on, or skip completely if there is no peer in the component tree.
UIComponent component = null;
if (id != null) {
if (debugrender) {
rendered.add(id);
}
component = fetchComponent(basecontainer, id, lump);
}
// Form rendering is now subject to "fairly normal" branch rendering logic
// That is, a UIContainer may now also be a leaf
if (component instanceof UIContainer) {
renderContainer((UIContainer) component, lump);
renderindex = lump.close_tag.lumpindex + 1;
}
else {
// if we find a leaf component, render it.
renderindex = renderer.renderComponent(rsc, basecontainer, component, lump);
}
} // end if unrepeatable component.
if (renderindex == tl.lumps.length) {
// deal with the case where component was root element - Ryan of
// 11/10/06
break;
}
}
if (debugrender) {
UIComponent[] flatchildren = basecontainer.flatChildren();
for (int i = 0; i < flatchildren.length; ++i) {
UIComponent child = flatchildren[i];
if (!(child.ID.indexOf(':') != -1) && !rendered.contains(child.ID)) {
renderer.renderDebugMessage(rsc, "Leaf child component "
+ child.getClass().getName() + " with full ID "
+ child.getFullID() + " could not be found within template "
+ baselump.toString());
}
}
}
}
|
diff --git a/src/main/java/com/datascience/gal/dawidSkeneProcessors/DSalgorithmComputer.java b/src/main/java/com/datascience/gal/dawidSkeneProcessors/DSalgorithmComputer.java
index e1b1087b..f3f82546 100644
--- a/src/main/java/com/datascience/gal/dawidSkeneProcessors/DSalgorithmComputer.java
+++ b/src/main/java/com/datascience/gal/dawidSkeneProcessors/DSalgorithmComputer.java
@@ -1,69 +1,69 @@
/*******************************************************************************
* Copyright (c) 2012 Panagiotis G. Ipeirotis & Josh M. Attenberg
*
* 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 com.datascience.gal.dawidSkeneProcessors;
import org.apache.log4j.Logger;
import com.datascience.gal.DawidSkene;
import com.datascience.gal.service.DawidSkeneCache;
/**
* Objects of this class execute Dawid-Skene algorithm on DS model with given
* id.
*/
public class DSalgorithmComputer extends DawidSkeneProcessor {
public DSalgorithmComputer(String id, DawidSkeneCache cache, int iterations) {
super(id, cache);
this.setIterations(iterations);
}
@Override
public void run() {
logger.info("Started DS-computer for " + this.getDawidSkeneId()
+ " with " + this.iterations + " iterations.");
DawidSkene ds = this.getCache().getDawidSkeneForEditing(
this.getDawidSkeneId(), this);
if (!ds.isComputed()) {
ds.estimate(this.iterations);
- this.getCache().insertDawidSkene(ds, this);
}
+ this.getCache().insertDawidSkene(ds, this);
this.setState(DawidSkeneProcessorState.FINISHED);
logger.info("DS-computer for " + this.getDawidSkeneId() + " finished.");
}
/**
* How many iterations of Dawid-Skene algorithm will be run
*/
private int iterations;
/**
* @return How many iterations of Dawid-Skene algorithm will be run
*/
public int getIterations() {
return iterations;
}
/**
* @param iterations
* How many iterations of Dawid-Skene algorithm will be run
*/
public void setIterations(int iterations) {
this.iterations = iterations;
}
private static Logger logger = Logger.getLogger(LabelWriter.class);
}
| false | true | public void run() {
logger.info("Started DS-computer for " + this.getDawidSkeneId()
+ " with " + this.iterations + " iterations.");
DawidSkene ds = this.getCache().getDawidSkeneForEditing(
this.getDawidSkeneId(), this);
if (!ds.isComputed()) {
ds.estimate(this.iterations);
this.getCache().insertDawidSkene(ds, this);
}
this.setState(DawidSkeneProcessorState.FINISHED);
logger.info("DS-computer for " + this.getDawidSkeneId() + " finished.");
}
| public void run() {
logger.info("Started DS-computer for " + this.getDawidSkeneId()
+ " with " + this.iterations + " iterations.");
DawidSkene ds = this.getCache().getDawidSkeneForEditing(
this.getDawidSkeneId(), this);
if (!ds.isComputed()) {
ds.estimate(this.iterations);
}
this.getCache().insertDawidSkene(ds, this);
this.setState(DawidSkeneProcessorState.FINISHED);
logger.info("DS-computer for " + this.getDawidSkeneId() + " finished.");
}
|
diff --git a/app/controllers/Dummy.java b/app/controllers/Dummy.java
index 817f177..df3d90a 100644
--- a/app/controllers/Dummy.java
+++ b/app/controllers/Dummy.java
@@ -1,141 +1,141 @@
package controllers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import models.*;
import play.libs.Mail;
import play.mvc.Controller;
import play.data.validation.Required;
import repo.Repository;
/**
* Non-secured controller class.
*/
public class Dummy extends Controller {
/**
* Displays the main welcome page.
*/
public static void index(){
if(!Security.isConnected())
render();
else
PageController.welcome();
}
/**
* Displays the form to create a new account
*/
public static void createAccount(){
render();
}
/**
* Creates a new user
* @param email
* @param password
* @param firstName
* @param lastName
* @param address
* @param phoneNumber
* @param sex
* @param code code to create the account as a physician
*/
public static void newAccount(@Required(message = "Please enter a valid email address") String email,
@Required(message = "Please enter a password") String password,
@Required(message = "Please enter your first name") String firstName,
@Required(message = "Please enter your last name") String lastName,
@Required(message = "Please enter your address") String address,
@Required(message = "Please enter your phone number") String phoneNumber,
@Required String sex,
String code){
//Check that the email isnt registered already
if(User.find("byUsername", email).fetch().size() > 0){
//Email already registered.
validation.addError("email", "Email already registered", "email");
}
//Validate email address
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("email", "Enter a valid email address", email);
}
//Validate the phone number
expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
inputStr = phoneNumber;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber);
}
/*
* Doesnt work currently, skipping
//Validate the address
expression = "\\d+ \\s+ \\.*";
inputStr = address;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("address", "Enter a valid address", address);
}*/
if (validation.hasErrors()) {
- render("createAccount.html", email, firstName, lastName, address, phoneNumber, code);
+ render("Dummy/createAccount.html", email, firstName, lastName, address, phoneNumber, code);
}
//If the code is correct, create user as physician
if(code.equals("physician")){
new Physician(email, password, firstName, lastName).save();
} else {
//Else, create them as a patient
new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save();
}
//Authenticate them automatically
session.put("username", email);
PageController.welcome();
}
/**
* Reders the forgot password page
*/
public static void forgotPassword(){
render();
}
public static void sendPassword(@Required(message = "A valid email address is required") String email){
User user = User.find("byUsername", email).first();
if(validation.hasErrors() || user == null){
if(user == null)
validation.addError(email, "Email address is not registered", email);
render("Dummy/forgotPassword.html");
}
try {
//Will need to set up email prefs in the conf to be able to use
SimpleEmail toSend = new SimpleEmail();
toSend.setFrom("[email protected]");
toSend.addTo(email, user.getName());
toSend.setSubject("Ultra Password");
toSend.setMsg("Your password to Ultra is: "+ Repository.decodePassword( user.getPassword() ) );
Mail.send(toSend);
} catch (EmailException e) {
e.printStackTrace(System.out);
}
render(email);
}
}
| true | true | public static void newAccount(@Required(message = "Please enter a valid email address") String email,
@Required(message = "Please enter a password") String password,
@Required(message = "Please enter your first name") String firstName,
@Required(message = "Please enter your last name") String lastName,
@Required(message = "Please enter your address") String address,
@Required(message = "Please enter your phone number") String phoneNumber,
@Required String sex,
String code){
//Check that the email isnt registered already
if(User.find("byUsername", email).fetch().size() > 0){
//Email already registered.
validation.addError("email", "Email already registered", "email");
}
//Validate email address
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("email", "Enter a valid email address", email);
}
//Validate the phone number
expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
inputStr = phoneNumber;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber);
}
/*
* Doesnt work currently, skipping
//Validate the address
expression = "\\d+ \\s+ \\.*";
inputStr = address;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("address", "Enter a valid address", address);
}*/
if (validation.hasErrors()) {
render("createAccount.html", email, firstName, lastName, address, phoneNumber, code);
}
//If the code is correct, create user as physician
if(code.equals("physician")){
new Physician(email, password, firstName, lastName).save();
} else {
//Else, create them as a patient
new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save();
}
//Authenticate them automatically
session.put("username", email);
PageController.welcome();
}
| public static void newAccount(@Required(message = "Please enter a valid email address") String email,
@Required(message = "Please enter a password") String password,
@Required(message = "Please enter your first name") String firstName,
@Required(message = "Please enter your last name") String lastName,
@Required(message = "Please enter your address") String address,
@Required(message = "Please enter your phone number") String phoneNumber,
@Required String sex,
String code){
//Check that the email isnt registered already
if(User.find("byUsername", email).fetch().size() > 0){
//Email already registered.
validation.addError("email", "Email already registered", "email");
}
//Validate email address
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("email", "Enter a valid email address", email);
}
//Validate the phone number
expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
inputStr = phoneNumber;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber);
}
/*
* Doesnt work currently, skipping
//Validate the address
expression = "\\d+ \\s+ \\.*";
inputStr = address;
pattern = Pattern.compile(expression);
matcher = pattern.matcher(inputStr);
if( !matcher.matches() ){
validation.addError("address", "Enter a valid address", address);
}*/
if (validation.hasErrors()) {
render("Dummy/createAccount.html", email, firstName, lastName, address, phoneNumber, code);
}
//If the code is correct, create user as physician
if(code.equals("physician")){
new Physician(email, password, firstName, lastName).save();
} else {
//Else, create them as a patient
new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save();
}
//Authenticate them automatically
session.put("username", email);
PageController.welcome();
}
|
diff --git a/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java b/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
index dd7517a..9f30618 100644
--- a/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
+++ b/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
@@ -1,961 +1,961 @@
package com.rackspace.cloud.api.docs;
import java.net.*;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXSource;
import org.apache.maven.project.MavenProject;
import org.apache.maven.plugin.MojoExecutionException;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.agilejava.docbkx.maven.AbstractWebhelpMojo;
import com.agilejava.docbkx.maven.PreprocessingFilter;
import com.agilejava.docbkx.maven.TransformerBuilder;
import com.rackspace.cloud.api.docs.builders.PDFBuilder;
import com.rackspace.cloud.api.docs.CalabashHelper;
import com.rackspace.cloud.api.docs.DocBookResolver;
import com.agilejava.docbkx.maven.Parameter;
import com.agilejava.docbkx.maven.FileUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipOutputStream;
public abstract class WebHelpMojo extends AbstractWebhelpMojo {
/**
* Sets the URI for the glossary.
*
* @parameter expression="${glossary.uri}" default-value=""
*/
private String glossaryUri;
private File sourceDirectory;
private File sourceDocBook;
private File atomFeed;
private File atomFeedClean;
private static final String COPY_XSL = "cloud/webhelp/copy.xsl";
/**
* A reference to the project.
*
* @parameter expression="${project}"
* @required
*/
private MavenProject docProject;
/**
* @parameter expression="${project.build.directory}"
*/
private String projectBuildDirectory;
/**
* Controls whether to build webhelp war output or not.
*
* @parameter expression="${generate-webhelp.webhelp.war}"
*/
private String webhelpWar;
/**
* List of emails (comma delimited) to send a notification to when
* a war is deployed in autopublish.
*
* @parameter expression="${generate-webhelp.publicationNotificationEmails}"
*/
private String publicationNotificationEmails;
/**
* Controls whether the pubdate is included in the pdf file name.
*
* @parameter expression="${generate-webhelp.includeDateInPdfFilename}"
*/
private String includeDateInPdfFilename;
/**
* Base for the pdf file name. By default this is the
* base of the input xml file.
*
* @parameter expression="${generate-webhelp.pdfFilenameBase}"
*/
private String pdfFilenameBase;
/**
* Base for the webhelp dir name. By default this is the
* base of the input xml file.
*
* @parameter expression="${generate-webhelp.webhelpDirname}"
*/
private String webhelpDirname;
/**
* Controls whether output is colorized based on revisionflag attributes.
*
* @parameter expression="${generate-webhelp.show.changebars}"
*/
private String showChangebars;
/**
* Display built for OpenStack logo?
*
* @parameter expression="${generate-webhelp.builtForOpenStack}" default-value="0"
*/
private String builtForOpenStack;
/**
* Path to an alternative cover logo.
*
* @parameter expression="${generate-pdf.coverLogoPath}" default-value=""
*/
private String coverLogoPath;
/**
* Path to an alternative cover logo.
*
* @parameter expression="${generate-webhelp.secondaryCoverLogoPath}" default-value=""
*/
private String secondaryCoverLogoPath;
/**
* Distance from the left edge of the page at which the
* cover logo is displayed.
*
* @parameter expression="${generate-webhelp.coverLogoLeft}" default-value=""
*/
private String coverLogoLeft;
/**
* Distance from the top of the page at which teh
* cover logo is displayed.
*
* @parameter expression="${generate-webhelp.coverLogoTop}" default-value=""
*/
private String coverLogoTop;
/**
* url to display under the cover logo.
*
* @parameter expression="${generate-webhelp.coverUrl}" default-value=""
*/
private String coverUrl;
/**
* The color to use for the polygon on the cover
*
* @parameter expression="${generate-webhelp.coverColor}" default-value=""
*/
private String coverColor;
/**
*
*
* @parameter expression="${generate-pdf.pageWidth}" default-value=""
*/
private String pageWidth;
/**
*
*
* @parameter expression="${generate-pdf.pageHeight}" default-value=""
*/
private String pageHeight;
/**
* Should cover be omitted?
*
* @parameter expression="${generate-pdf.omitCover}" default-value=""
*/
private String omitCover;
/**
* Double sided pdfs?
*
* @parameter expression="${generate-pdf.doubleSided}" default-value=""
*/
private String doubleSided;
/**
* Controls whether output is colorized based on revisionflag attributes.
*
* @parameter expression="${generate-webhelp.meta.robots}"
*/
private String metaRobots;
/**
* Controls whether the version string is used as part of the Disqus identifier.
*
* @parameter expression="${generate-webhelp.use.version.for.disqus}" default-value="0"
*/
private String useVersionForDisqus;
/**
* Controls whether the disqus identifier is used.
*
* @parameter expression="${generate-webhelp.use.disqus.id}" default-value="1"
*/
private String useDisqusId;
/**
* Controls whether the disqus identifier is used.
*
* @parameter expression="${generate-webhelp.disqus_identifier}"
*/
private String disqusIdentifier;
/**
* Controls the branding of the output.
*
* @parameter expression="${generate-webhelp.branding}" default-value="rackspace"
*/
private String branding;
/**
* Controls whether Disqus comments appear at the bottom of each page.
*
* @parameter expression="${generate-webhelp.enable.disqus}" default-value="0"
*/
private String enableDisqus;
/**
* A parameter used by the Disqus comments.
*
* @parameter expression="${generate-webhelp.disqus.shortname}" default-value=""
*/
private String disqusShortname;
/**
* A parameter used to control whether to include Google Analytics goo.
*
* @parameter expression="${generate-webhelp.enable.google.analytics}" default-value=""
*/
private String enableGoogleAnalytics;
/**
* A parameter used to control whether to include Google Analytics goo.
*
* @parameter expression="${generate-webhelp.google.analytics.id}" default-value=""
*/
private String googleAnalyticsId;
/**
* A parameter used to control whether to include Google Analytics goo.
*
* @parameter expression="${generate-webhelp.google.analytics.domain}" default-value=""
*/
private String googleAnalyticsDomain;
/**
* A parameter used to specify the path to the pdf for download in webhelp.
*
* @parameter expression="${generate-webhelp.pdf.url}" default-value=""
*/
private String pdfUrl;
/**
* If makePdf is set to true then just before creating the Webhelp output this variable will be set
* with the location of the automatically created pdf file.
*/
private String autoPdfUrl;
/**
* A parameter used to control whether the autoPdfUrl is changed
* to end with -latest.pdf instead of being the actual file name.
*
* @parameter expression="${generate-webhelp.useLatestSuffixInPdfUrl}"
*/
private String useLatestSuffixInPdfUrl;
/**
* @parameter
* expression="${generate-webhelp.canonicalUrlBase}"
* default-value=""
*/
private String canonicalUrlBase;
/**
* @parameter
* expression="${generate-webhelp.replacementsFile}"
* default-value="replacements.config"
*/
private String replacementsFile;
/**
* @parameter
* expression="${generate-webhelp.makePdf}"
* default-value=true
*/
private boolean makePdf;
/**
* @parameter
* expression="${generate-webhelp.strictImageValidation}"
* default-value=true
*/
private boolean strictImageValidation;
/**
*
* @parameter
* expression="${generate-webhelp.failOnValidationError}"
* default-value="yes"
*/
private String failOnValidationError;
/**
*
* @parameter
* expression="${generate-webhelp.commentsPhp}"
*/
private String commentsPhp;
/**
* A parameter used to specify the security level (external, internal, reviewer, writeronly) of the document.
*
* @parameter
* expression="${generate-webhelp.security}"
* default-value="external"
*/
private String security;
/**
*
*
* @parameter expression="${basedir}"
*/
private File baseDir;
/**
* A parameter used to specify the presence of extensions metadata.
*
* @parameter
* expression="${generate-webhelp.includes}"
* default-value=""
*/
private String transformDir;
/**
* A parameter used to configure how many elements to trim from the URI in the documentation for a wadl method.
*
* @parameter expression="${generate-webhelp.trim.wadl.uri.count}" default-value=""
*/
private String trimWadlUriCount;
/**
* Controls how the path to the wadl is calculated. If 0 or not set, then
* The xslts look for the normalized wadl in /generated-resources/xml/xslt/.
* Otherwise, in /generated-resources/xml/xslt/path/to/docbook-src, e.g.
* /generated-resources/xml/xslt/src/docbkx/foo.wadl
*
* @parameter expression="${generate-webhelp.compute.wadl.path.from.docbook.path}" default-value="0"
*/
private String computeWadlPathFromDocbookPath;
/**
* Sets the email for TildeHash (internal) comments. Note that this
* doesn't affect Disqus comments.
*
* @parameter expression="${generate-webhelp.feedback.email}" default-value=""
*/
private String feedbackEmail;
/**
* Controls whether or not the social icons are displayed.
*
* @parameter expression="${generate-webhelp.social.icons}" default-value="0"
*/
private String socialIcons;
/**
* A parameter used to specify the path to the lega notice in webhelp.
*
* @parameter expression="${generate-webhelp.legal.notice.url}" default-value="index.html"
*/
private String legalNoticeUrl;
/**
*
*
* @parameter expression="${generate-webhelp.draft.status}" default-value=""
*/
private String draftStatus;
/**
*
*
* @parameter expression="${generate-webhelp.draft.status}" default-value=""
*/
private String statusBarText;
/**
* DOCUMENT ME!
*
* @param transformer DOCUMENT ME!
* @param sourceFilename DOCUMENT ME!
* @param targetFile DOCUMENT ME!
*/
public void adjustTransformer(Transformer transformer, String sourceFilename, File targetFile) {
String warBasename;
String webhelpOutdir = targetFile.getName().substring(0, targetFile.getName().lastIndexOf('.'));
if(null != webhelpDirname && webhelpDirname != ""){
warBasename = webhelpDirname;
} else {
warBasename = webhelpOutdir;
}
targetFile = new File( getTargetDirectory() + "/" + warBasename + "/" + warBasename + ".xml" );
super.adjustTransformer(transformer, sourceFilename, targetFile);
transformer.setParameter("groupId", docProject.getGroupId());
transformer.setParameter("artifactId", docProject.getArtifactId());
transformer.setParameter("docProjectVersion", docProject.getVersion());
transformer.setParameter("pomProjectName", docProject.getName());
if(commentsPhp != null){
transformer.setParameter("comments.php", commentsPhp);
}
if(glossaryUri != null){
transformer.setParameter("glossary.uri", glossaryUri);
}
if(feedbackEmail != null){
transformer.setParameter("feedback.email", feedbackEmail);
}
if(useDisqusId != null){
transformer.setParameter("use.disqus.id", useDisqusId);
}
if (useVersionForDisqus != null) {
transformer.setParameter("use.version.for.disqus", useVersionForDisqus);
}
transformer.setParameter("project.build.directory", projectBuildDirectory);
transformer.setParameter("branding", branding);
//if the pdf is generated automatically with webhelp then this will be set.
transformer.setParameter("autoPdfUrl", autoPdfUrl);
transformer.setParameter("builtForOpenStack", builtForOpenStack);
transformer.setParameter("coverLogoPath", coverLogoPath);
transformer.setParameter("secondaryCoverLogoPath", secondaryCoverLogoPath);
transformer.setParameter("coverLogoLeft", coverLogoLeft);
transformer.setParameter("coverLogoTop", coverLogoTop);
transformer.setParameter("coverUrl", coverUrl);
transformer.setParameter("coverColor", coverColor);
if(null != pageWidth){
transformer.setParameter("page.width", pageWidth);
}
if(null != pageHeight){
transformer.setParameter("page.height", pageHeight);
}
if(null != omitCover){
transformer.setParameter("omitCover", omitCover);
}
if(null != doubleSided){
transformer.setParameter("double.sided", doubleSided);
}
transformer.setParameter("enable.disqus", enableDisqus);
if (disqusShortname != null) {
transformer.setParameter("disqus.shortname", disqusShortname);
}
if (disqusIdentifier != null) {
transformer.setParameter("disqus_identifier", disqusIdentifier);
}
if (enableGoogleAnalytics != null) {
transformer.setParameter("enable.google.analytics", enableGoogleAnalytics);
}
if (googleAnalyticsId != null) {
transformer.setParameter("google.analytics.id", googleAnalyticsId);
}
if(googleAnalyticsDomain != null){
transformer.setParameter("google.analytics.domain", googleAnalyticsDomain);
}
if (pdfUrl != null) {
transformer.setParameter("pdf.url", pdfUrl);
}
if (useLatestSuffixInPdfUrl != null) {
transformer.setParameter("useLatestSuffixInPdfUrl", useLatestSuffixInPdfUrl);
}
if (legalNoticeUrl != null) {
transformer.setParameter("legal.notice.url", legalNoticeUrl);
}
String sysWebhelpWar=System.getProperty("webhelp.war");
if(null!=sysWebhelpWar && !sysWebhelpWar.isEmpty()){
webhelpWar=sysWebhelpWar;
}
transformer.setParameter("webhelp.war", webhelpWar);
if(null != includeDateInPdfFilename){
transformer.setParameter("includeDateInPdfFilename", includeDateInPdfFilename);
}
transformer.setParameter("pdfFilenameBase", pdfFilenameBase);
transformer.setParameter("webhelpDirname", webhelpDirname);
transformer.setParameter("publicationNotificationEmails", publicationNotificationEmails);
String sysDraftStatus=System.getProperty("draft.status");
if(null!=sysDraftStatus && !sysDraftStatus.isEmpty()){
draftStatus=sysDraftStatus;
}
transformer.setParameter("draft.status", draftStatus);
String sysStatusBarText=System.getProperty("statusBarText");
if(null!=sysStatusBarText && !sysStatusBarText.isEmpty()){
statusBarText=sysStatusBarText;
}
if(null != statusBarText){
transformer.setParameter("status.bar.text", statusBarText);
}
if(canonicalUrlBase != null){
transformer.setParameter("canonical.url.base",canonicalUrlBase);
}
String sysSecurity=System.getProperty("security");
if(null!=sysSecurity && !sysSecurity.isEmpty()){
security=sysSecurity;
}
if(security != null){
transformer.setParameter("security",security);
}
if(showChangebars != null){
transformer.setParameter("show.changebars",showChangebars);
}
if(metaRobots != null){
transformer.setParameter("meta.robots",metaRobots);
}
if(trimWadlUriCount != null){
transformer.setParameter("trim.wadl.uri.count",trimWadlUriCount);
}
transformer.setParameter("social.icons",socialIcons);
sourceDocBook = new File(sourceFilename);
sourceDirectory = sourceDocBook.getParentFile();
transformer.setParameter("docbook.infile",sourceDocBook.getAbsolutePath());
transformer.setParameter("source.directory",sourceDirectory);
transformer.setParameter("compute.wadl.path.from.docbook.path",computeWadlPathFromDocbookPath);
}
protected TransformerBuilder createTransformerBuilder(URIResolver resolver) {
return super.createTransformerBuilder(new DocBookResolver(resolver, getType()));
}
//Note for this to work, you need to have the customization layer in place.
protected String getNonDefaultStylesheetLocation() {
return "cloud/webhelp/profile-webhelp.xsl";
}
public void postProcessResult(File result) throws MojoExecutionException {
String warBasename;
String webhelpOutdir = result.getName().substring(0, result.getName().lastIndexOf('.'));
if(null != webhelpDirname && webhelpDirname != ""){
warBasename = webhelpDirname;
} else {
warBasename = webhelpOutdir;
}
result = new File( getTargetDirectory() + "/" + warBasename + "/" + warBasename + ".xml" );
super.postProcessResult(result);
copyTemplate(result);
transformFeed(result);
//final File targetDirectory = result.getParentFile();
//com.rackspace.cloud.api.docs.FileUtils.extractJaredDirectory("apiref",ApiRefMojo.class,targetDirectory);
Properties properties = new Properties();
InputStream is = null;
try {
File f = new File(result.getParentFile() + "/webapp/WEB-INF/bookinfo.properties");
is = new FileInputStream( f );
properties.load(is);
}
catch ( Exception e ) {
System.out.println("Got an Exception: " + e.getMessage());
}
String warSuffix = properties.getProperty("warsuffix","");
String warSuffixForWar = warSuffix.equals("-external") ? "" : warSuffix;
if(null != webhelpWar && webhelpWar != "0"){
//Zip up the war from here.
String sourceDir = result.getParentFile().getParentFile() + "/" + webhelpOutdir ;
String zipFile = result.getParentFile().getParentFile() + "/" + properties.getProperty("warprefix","") + warBasename + warSuffixForWar + ".war";
//result.deleteOnExit();
try{
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
//create File object from source directory
File fileSource = new File(sourceDir);
com.rackspace.cloud.api.docs.FileUtils.addDirectory(zout, fileSource);
//close the ZipOutputStream
zout.close();
System.out.println("Zip file has been created!");
}catch(IOException ioe){
System.out.println("IOException :" + ioe);
}
}
// if(null == webhelpWar || webhelpWar.equals("0")){
//TODO: Move dir to add warsuffix/security value
//String sourceDir = result.getParentFile().getParentFile() + "/" + warBasename ;
File webhelpDirWithSecurity = new File(result.getParentFile().getParentFile() + "/" + warBasename + warSuffix);
File webhelpOrigDir = new File(result.getParentFile().getParentFile() + "/" + webhelpOutdir );
boolean success = webhelpOrigDir.renameTo(webhelpDirWithSecurity);
//}
}
protected void copyTemplate(File result) throws MojoExecutionException {
final File targetDirectory = result.getParentFile();
com.rackspace.cloud.api.docs.FileUtils.extractJaredDirectory("content", WebHelpMojo.class, targetDirectory);
com.rackspace.cloud.api.docs.FileUtils.extractJaredDirectory("common", WebHelpMojo.class, targetDirectory);
com.agilejava.docbkx.maven.FileUtils.copyFile(new File(targetDirectory, "common/images/favicon-" + branding + ".ico"), new File(targetDirectory, "favicon.ico"));
com.agilejava.docbkx.maven.FileUtils.copyFile(new File(targetDirectory, "common/css/positioning-" + branding + ".css"), new File(targetDirectory, "common/css/positioning.css"));
com.agilejava.docbkx.maven.FileUtils.copyFile(new File(targetDirectory, "common/main-" + branding + ".js"), new File(targetDirectory, "common/main.js"));
}
protected void transformFeed(File result) throws MojoExecutionException {
try {
atomFeed = new File (result.getParentFile(),"atom-doctype.xml");
atomFeedClean = new File (result.getParentFile(),"atom.xml");
if(!atomFeed.isFile()){
return;
}
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(classLoader.getResourceAsStream(COPY_XSL)));
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
dbfactory.setValidating(false);
DocumentBuilder builder = dbfactory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
Document xmlDocument = builder.parse(atomFeed);
DOMSource source = new DOMSource(xmlDocument);
transformer.transform(source, new StreamResult(atomFeedClean));
atomFeed.deleteOnExit();
}
catch (TransformerConfigurationException e)
{
throw new MojoExecutionException("Failed to load JAXP configuration", e);
}
catch (javax.xml.parsers.ParserConfigurationException e)
{
throw new MojoExecutionException("Failed to configure parser", e);
}
catch (org.xml.sax.SAXException e)
{
throw new MojoExecutionException("Sax exception", e);
}
catch(java.io.IOException e)
{
throw new MojoExecutionException("IO Exception", e);
}
catch (TransformerException e)
{
throw new MojoExecutionException("Failed to transform to atom feed", e);
}
}
public void preProcess() throws MojoExecutionException {
super.preProcess();
final File targetDirectory = getTargetDirectory();
File xslParentDirectory = targetDirectory.getParentFile();
if (!targetDirectory.exists()) {
com.rackspace.cloud.api.docs.FileUtils.mkdir(targetDirectory);
}
//
// Extract all images into the image directory.
//
com.rackspace.cloud.api.docs.FileUtils.extractJaredDirectory("cloud/war",PDFMojo.class,xslParentDirectory);
com.rackspace.cloud.api.docs.FileUtils.extractJaredDirectory("cloud/webhelp",PDFMojo.class,xslParentDirectory);
}
@Override
protected Source createSource(String inputFilename, File sourceFile, PreprocessingFilter filter)
throws MojoExecutionException {
String pathToPipelineFile = "classpath:/webhelp.xpl"; //use "classpath:/path" for this to work
String sourceFileNameNormalized = "file:///" + sourceFile.getAbsolutePath().replaceAll("\\\\","/");
//from super
final InputSource inputSource = new InputSource(sourceFileNameNormalized);
Source source = new SAXSource(filter, inputSource);
//Source source = super.createSource(inputFilename, sourceFile, filter);
Map<String, String> map=new HashMap<String, String>();
String sysWebhelpWar=System.getProperty("webhelp.war");
if(null!=sysWebhelpWar && !sysWebhelpWar.isEmpty()){
webhelpWar=sysWebhelpWar;
}
String targetDirString = "";
try{
targetDirString = this.getTargetDirectory().getParentFile().getCanonicalPath().replaceAll("\\\\","/");
}catch(Exception e){
getLog().info("Exceptional!" + e);
}
map.put("targetDirectory", this.getTargetDirectory().getParentFile().getAbsolutePath());
map.put("webhelp.war", webhelpWar);
map.put("publicationNotificationEmails", publicationNotificationEmails);
map.put("includeDateInPdfFilename", includeDateInPdfFilename);
map.put("pdfFilenameBase", pdfFilenameBase);
map.put("webhelpDirname", webhelpDirname);
map.put("groupId", docProject.getGroupId());
map.put("artifactId", docProject.getArtifactId());
map.put("docProjectVersion", docProject.getVersion());
map.put("pomProjectName", docProject.getName());
map.put("security", this.security);
map.put("branding", this.branding);
map.put("canonicalUrlBase", this.canonicalUrlBase);
map.put("replacementsFile", this.replacementsFile);
map.put("failOnValidationError", this.failOnValidationError);
map.put("comments.php", this.commentsPhp);
map.put("project.build.directory", this.projectBuildDirectory);
map.put("inputSrcFile", inputFilename);
map.put("strictImageValidation", String.valueOf(this.strictImageValidation));
map.put("trim.wadl.uri.count", this.trimWadlUriCount);
map.put("status.bar.text", getProperty("statusBarText"));
map.put("draft.status", getProperty("draftStatus"));
// Profiling attrs:
map.put("profile.os", getProperty("profileOs"));
map.put("profile.arch", getProperty("profileArch"));
map.put("profile.condition", getProperty("profileCondition"));
map.put("profile.audience", getProperty("profileAudience"));
map.put("profile.conformance", getProperty("profileConformance"));
map.put("profile.revision", getProperty("profileRevision"));
map.put("profile.userlevel", getProperty("profileUserlevel"));
map.put("profile.vendor", getProperty("profileVendor"));
int lastSlash=inputFilename.lastIndexOf("/");
//This is the case if the path includes a relative path
if (-1!=lastSlash){
String theFileName=inputFilename.substring(lastSlash);
String theDirName=inputFilename.substring(0,lastSlash);
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index) + "/content/");
map.put("base.dir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index));
map.put("input.filename",theDirName+theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~theFileName file has incompatible format: "+theFileName);
}
}
//This is the case when it's just a file name with no path information
else {
String theFileName=inputFilename;
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theFileName.substring(0,index) + "/content/");
String targetDir= getTargetDirectory() + "/" + theFileName.substring(0,index) + "/";
map.put("base.dir", targetDir);
map.put("input.filename", theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~inputFilename file has incompatible format: "+inputFilename);
}
}
if (null != webhelpDirname && webhelpDirname != "" ) {
map.put("targetExtQueryFile", getTargetDirectory() + "/" + webhelpDirname + "/content/"+"ext_query.xml");
map.put("base.dir", getTargetDirectory() + "/" + webhelpDirname);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + webhelpDirname + "/content/");
}
//targetExtQueryFile can tell us where the html will be built. We pass this absolute path to the
//pipeline so that the copy-and-transform-image step can use it to calculate where to place the images.
map.put("targetDir", baseDir.getAbsolutePath()+File.separator+"figures");
// String targetDirFiguresString = baseDir.getAbsolutePath()+File.separator+"figures";
// map.put("targetDir", targetDirFiguresString.replaceAll("\\\\","/").replace("file:/", "file:///"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
// getLog().info("~~~~~~~~baseDir:" + baseDir);
// getLog().info("~~~~~~~~projectBuildDirectory:" + projectBuildDirectory);
// getLog().info("~~~~~~~~targetDirectory:"+ getTargetDirectory());
// getLog().info("~~~~~~~~targetDirectory (map.put):" + this.getTargetDirectory().getParentFile().getAbsolutePath());
// getLog().info("~~~~~~~~inputFilename:" + inputFilename);
// getLog().info("~~~~~~~~targetExtQueryFile:" + map.get("targetExtQueryFile"));
// getLog().info("~~~~~~~~targetHtmlContentDir:" + map.get("targetHtmlContentDir"));
// getLog().info("~~~~~~~~targetDir:" + map.get("targetDir"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
//makePdf is a POM configuration for generate-webhelp goal to control the execution of
//automatic building of pdf output
if(this.makePdf) {
getLog().info("\n************************************* START: Automatically generating PDF for WEBHELP *************************************");
//Target directory for Webhelp points to ${basepath}/target/docbkx/webhelp. So get parent.
File baseDir = getTargetDirectory().getParentFile();
//The point FO/PDF file output to be generated at ${basepath}/target/docbkx/autopdf.
File targetDir = new File(baseDir.getAbsolutePath()+"/autopdf");
//Create a new instance of PDFBuilder class and set config variables.
PDFBuilder pdfBuilder = new PDFBuilder();
pdfBuilder.setProject(getMavenProject());
pdfBuilder.setSourceDirectory(getSourceDirectory());
pdfBuilder.setAutopdfTargetDirectory(targetDir);
pdfBuilder.setCoverColor(coverColor);
pdfBuilder.setPageWidth(pageWidth);
pdfBuilder.setPageHeight(pageHeight);
pdfBuilder.setOmitCover(omitCover);
- pdfBuilder.setOmitCover(doubleSided);
+ pdfBuilder.setDoubleSided(doubleSided);
pdfBuilder.setCoverLogoPath(coverLogoPath);
pdfBuilder.setSecondaryCoverLogoPath(secondaryCoverLogoPath);
pdfBuilder.setCoverLogoLeft(coverLogoLeft);
pdfBuilder.setCoverLogoTop(coverLogoTop);
pdfBuilder.setCoverUrl(coverUrl);
pdfBuilder.setPdfFilenameBase(pdfFilenameBase);
pdfBuilder.setBranding(branding);
pdfBuilder.setSecurity(security);
pdfBuilder.setDraftStatus(draftStatus);
pdfBuilder.setStatusBarText(statusBarText);
pdfBuilder.setTrimWadlUriCount(trimWadlUriCount);
pdfBuilder.setComputeWadlPathFromDocbookPath(computeWadlPathFromDocbookPath);
pdfBuilder.setInputFilename(inputFilename);
pdfBuilder.setEntities(getEntities());
pdfBuilder.setChapterAutolabel(getProperty("chapterAutolabel"));
pdfBuilder.setAppendixAutolabel(getProperty("appendixAutolabel"));
pdfBuilder.setSectionAutolabel(getProperty("sectionAutolabel"));
pdfBuilder.setSectionLabelIncludesComponentLabel(getProperty("sectionLabelIncludesComponentLabel"));
pdfBuilder.setFormalProcedures(getProperty("formalProcedures"));
pdfBuilder.setGenerateToc(getProperty("generateToc"));
pdfBuilder.setTocMaxDepth(getProperty("tocMaxDepth"));
pdfBuilder.setTocSectionDepth(getProperty("tocSectionDepth"));
String srcFilename = this.projectBuildDirectory+"/docbkx/"+sourceFile.getName();
File tempHandle = new File(srcFilename);
if(tempHandle.exists()) {
getLog().debug("***********************"+ srcFilename);
pdfBuilder.setSourceFilePath(srcFilename);
} else {
getLog().debug("***********************"+ getSourceDirectory()+File.separator+inputFilename);
pdfBuilder.setSourceFilePath(getSourceDirectory()+File.separator+inputFilename);
}
pdfBuilder.setProjectBuildDirectory(baseDir.getAbsolutePath());
//setup fonts and images
pdfBuilder.preProcess();
//process input docbook to create FO file
File foFile = pdfBuilder.processSources(map);
//transform FO file to PDF
File pdfFile = pdfBuilder.postProcessResult(foFile);
//move PDF to where the webhelp stuff is for this docbook.
if(pdfFile!=null) {
File targetDirForPdf = new File(map.get("targetHtmlContentDir")).getParentFile();
if(!targetDirForPdf.exists()) {
com.rackspace.cloud.api.docs.FileUtils.mkdir(targetDirForPdf);
}
boolean moved = pdfBuilder.movePdfToWebhelpDir(pdfFile, targetDirForPdf);
if(moved) {
getLog().info("Successfully moved auto-generated PDF file to Webhelp target directory!");
} else {
getLog().error("Unable to move auto-generated PDF file to Webhelp target directory!");
}
}
autoPdfUrl = "../"+foFile.getName();
getLog().info("************************************* END: Automatically generating PDF for WEBHELP *************************************\n");
}
map.put("webhelp", "true");
map.put("autoPdfUrl",autoPdfUrl);
//this parameter will be used the copy and transform image step to decide whether to just check the existence of an image (for pdf)
//or to check existence, transform and copy image as well (for html)
map.put("outputType", "html");
return CalabashHelper.createSource(source, pathToPipelineFile, map);
}
}
| true | true | protected Source createSource(String inputFilename, File sourceFile, PreprocessingFilter filter)
throws MojoExecutionException {
String pathToPipelineFile = "classpath:/webhelp.xpl"; //use "classpath:/path" for this to work
String sourceFileNameNormalized = "file:///" + sourceFile.getAbsolutePath().replaceAll("\\\\","/");
//from super
final InputSource inputSource = new InputSource(sourceFileNameNormalized);
Source source = new SAXSource(filter, inputSource);
//Source source = super.createSource(inputFilename, sourceFile, filter);
Map<String, String> map=new HashMap<String, String>();
String sysWebhelpWar=System.getProperty("webhelp.war");
if(null!=sysWebhelpWar && !sysWebhelpWar.isEmpty()){
webhelpWar=sysWebhelpWar;
}
String targetDirString = "";
try{
targetDirString = this.getTargetDirectory().getParentFile().getCanonicalPath().replaceAll("\\\\","/");
}catch(Exception e){
getLog().info("Exceptional!" + e);
}
map.put("targetDirectory", this.getTargetDirectory().getParentFile().getAbsolutePath());
map.put("webhelp.war", webhelpWar);
map.put("publicationNotificationEmails", publicationNotificationEmails);
map.put("includeDateInPdfFilename", includeDateInPdfFilename);
map.put("pdfFilenameBase", pdfFilenameBase);
map.put("webhelpDirname", webhelpDirname);
map.put("groupId", docProject.getGroupId());
map.put("artifactId", docProject.getArtifactId());
map.put("docProjectVersion", docProject.getVersion());
map.put("pomProjectName", docProject.getName());
map.put("security", this.security);
map.put("branding", this.branding);
map.put("canonicalUrlBase", this.canonicalUrlBase);
map.put("replacementsFile", this.replacementsFile);
map.put("failOnValidationError", this.failOnValidationError);
map.put("comments.php", this.commentsPhp);
map.put("project.build.directory", this.projectBuildDirectory);
map.put("inputSrcFile", inputFilename);
map.put("strictImageValidation", String.valueOf(this.strictImageValidation));
map.put("trim.wadl.uri.count", this.trimWadlUriCount);
map.put("status.bar.text", getProperty("statusBarText"));
map.put("draft.status", getProperty("draftStatus"));
// Profiling attrs:
map.put("profile.os", getProperty("profileOs"));
map.put("profile.arch", getProperty("profileArch"));
map.put("profile.condition", getProperty("profileCondition"));
map.put("profile.audience", getProperty("profileAudience"));
map.put("profile.conformance", getProperty("profileConformance"));
map.put("profile.revision", getProperty("profileRevision"));
map.put("profile.userlevel", getProperty("profileUserlevel"));
map.put("profile.vendor", getProperty("profileVendor"));
int lastSlash=inputFilename.lastIndexOf("/");
//This is the case if the path includes a relative path
if (-1!=lastSlash){
String theFileName=inputFilename.substring(lastSlash);
String theDirName=inputFilename.substring(0,lastSlash);
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index) + "/content/");
map.put("base.dir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index));
map.put("input.filename",theDirName+theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~theFileName file has incompatible format: "+theFileName);
}
}
//This is the case when it's just a file name with no path information
else {
String theFileName=inputFilename;
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theFileName.substring(0,index) + "/content/");
String targetDir= getTargetDirectory() + "/" + theFileName.substring(0,index) + "/";
map.put("base.dir", targetDir);
map.put("input.filename", theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~inputFilename file has incompatible format: "+inputFilename);
}
}
if (null != webhelpDirname && webhelpDirname != "" ) {
map.put("targetExtQueryFile", getTargetDirectory() + "/" + webhelpDirname + "/content/"+"ext_query.xml");
map.put("base.dir", getTargetDirectory() + "/" + webhelpDirname);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + webhelpDirname + "/content/");
}
//targetExtQueryFile can tell us where the html will be built. We pass this absolute path to the
//pipeline so that the copy-and-transform-image step can use it to calculate where to place the images.
map.put("targetDir", baseDir.getAbsolutePath()+File.separator+"figures");
// String targetDirFiguresString = baseDir.getAbsolutePath()+File.separator+"figures";
// map.put("targetDir", targetDirFiguresString.replaceAll("\\\\","/").replace("file:/", "file:///"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
// getLog().info("~~~~~~~~baseDir:" + baseDir);
// getLog().info("~~~~~~~~projectBuildDirectory:" + projectBuildDirectory);
// getLog().info("~~~~~~~~targetDirectory:"+ getTargetDirectory());
// getLog().info("~~~~~~~~targetDirectory (map.put):" + this.getTargetDirectory().getParentFile().getAbsolutePath());
// getLog().info("~~~~~~~~inputFilename:" + inputFilename);
// getLog().info("~~~~~~~~targetExtQueryFile:" + map.get("targetExtQueryFile"));
// getLog().info("~~~~~~~~targetHtmlContentDir:" + map.get("targetHtmlContentDir"));
// getLog().info("~~~~~~~~targetDir:" + map.get("targetDir"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
//makePdf is a POM configuration for generate-webhelp goal to control the execution of
//automatic building of pdf output
if(this.makePdf) {
getLog().info("\n************************************* START: Automatically generating PDF for WEBHELP *************************************");
//Target directory for Webhelp points to ${basepath}/target/docbkx/webhelp. So get parent.
File baseDir = getTargetDirectory().getParentFile();
//The point FO/PDF file output to be generated at ${basepath}/target/docbkx/autopdf.
File targetDir = new File(baseDir.getAbsolutePath()+"/autopdf");
//Create a new instance of PDFBuilder class and set config variables.
PDFBuilder pdfBuilder = new PDFBuilder();
pdfBuilder.setProject(getMavenProject());
pdfBuilder.setSourceDirectory(getSourceDirectory());
pdfBuilder.setAutopdfTargetDirectory(targetDir);
pdfBuilder.setCoverColor(coverColor);
pdfBuilder.setPageWidth(pageWidth);
pdfBuilder.setPageHeight(pageHeight);
pdfBuilder.setOmitCover(omitCover);
pdfBuilder.setOmitCover(doubleSided);
pdfBuilder.setCoverLogoPath(coverLogoPath);
pdfBuilder.setSecondaryCoverLogoPath(secondaryCoverLogoPath);
pdfBuilder.setCoverLogoLeft(coverLogoLeft);
pdfBuilder.setCoverLogoTop(coverLogoTop);
pdfBuilder.setCoverUrl(coverUrl);
pdfBuilder.setPdfFilenameBase(pdfFilenameBase);
pdfBuilder.setBranding(branding);
pdfBuilder.setSecurity(security);
pdfBuilder.setDraftStatus(draftStatus);
pdfBuilder.setStatusBarText(statusBarText);
pdfBuilder.setTrimWadlUriCount(trimWadlUriCount);
pdfBuilder.setComputeWadlPathFromDocbookPath(computeWadlPathFromDocbookPath);
pdfBuilder.setInputFilename(inputFilename);
pdfBuilder.setEntities(getEntities());
pdfBuilder.setChapterAutolabel(getProperty("chapterAutolabel"));
pdfBuilder.setAppendixAutolabel(getProperty("appendixAutolabel"));
pdfBuilder.setSectionAutolabel(getProperty("sectionAutolabel"));
pdfBuilder.setSectionLabelIncludesComponentLabel(getProperty("sectionLabelIncludesComponentLabel"));
pdfBuilder.setFormalProcedures(getProperty("formalProcedures"));
pdfBuilder.setGenerateToc(getProperty("generateToc"));
pdfBuilder.setTocMaxDepth(getProperty("tocMaxDepth"));
pdfBuilder.setTocSectionDepth(getProperty("tocSectionDepth"));
String srcFilename = this.projectBuildDirectory+"/docbkx/"+sourceFile.getName();
File tempHandle = new File(srcFilename);
if(tempHandle.exists()) {
getLog().debug("***********************"+ srcFilename);
pdfBuilder.setSourceFilePath(srcFilename);
} else {
getLog().debug("***********************"+ getSourceDirectory()+File.separator+inputFilename);
pdfBuilder.setSourceFilePath(getSourceDirectory()+File.separator+inputFilename);
}
pdfBuilder.setProjectBuildDirectory(baseDir.getAbsolutePath());
//setup fonts and images
pdfBuilder.preProcess();
//process input docbook to create FO file
File foFile = pdfBuilder.processSources(map);
//transform FO file to PDF
File pdfFile = pdfBuilder.postProcessResult(foFile);
//move PDF to where the webhelp stuff is for this docbook.
if(pdfFile!=null) {
File targetDirForPdf = new File(map.get("targetHtmlContentDir")).getParentFile();
if(!targetDirForPdf.exists()) {
com.rackspace.cloud.api.docs.FileUtils.mkdir(targetDirForPdf);
}
boolean moved = pdfBuilder.movePdfToWebhelpDir(pdfFile, targetDirForPdf);
if(moved) {
getLog().info("Successfully moved auto-generated PDF file to Webhelp target directory!");
} else {
getLog().error("Unable to move auto-generated PDF file to Webhelp target directory!");
}
}
autoPdfUrl = "../"+foFile.getName();
getLog().info("************************************* END: Automatically generating PDF for WEBHELP *************************************\n");
}
map.put("webhelp", "true");
map.put("autoPdfUrl",autoPdfUrl);
//this parameter will be used the copy and transform image step to decide whether to just check the existence of an image (for pdf)
//or to check existence, transform and copy image as well (for html)
map.put("outputType", "html");
return CalabashHelper.createSource(source, pathToPipelineFile, map);
}
| protected Source createSource(String inputFilename, File sourceFile, PreprocessingFilter filter)
throws MojoExecutionException {
String pathToPipelineFile = "classpath:/webhelp.xpl"; //use "classpath:/path" for this to work
String sourceFileNameNormalized = "file:///" + sourceFile.getAbsolutePath().replaceAll("\\\\","/");
//from super
final InputSource inputSource = new InputSource(sourceFileNameNormalized);
Source source = new SAXSource(filter, inputSource);
//Source source = super.createSource(inputFilename, sourceFile, filter);
Map<String, String> map=new HashMap<String, String>();
String sysWebhelpWar=System.getProperty("webhelp.war");
if(null!=sysWebhelpWar && !sysWebhelpWar.isEmpty()){
webhelpWar=sysWebhelpWar;
}
String targetDirString = "";
try{
targetDirString = this.getTargetDirectory().getParentFile().getCanonicalPath().replaceAll("\\\\","/");
}catch(Exception e){
getLog().info("Exceptional!" + e);
}
map.put("targetDirectory", this.getTargetDirectory().getParentFile().getAbsolutePath());
map.put("webhelp.war", webhelpWar);
map.put("publicationNotificationEmails", publicationNotificationEmails);
map.put("includeDateInPdfFilename", includeDateInPdfFilename);
map.put("pdfFilenameBase", pdfFilenameBase);
map.put("webhelpDirname", webhelpDirname);
map.put("groupId", docProject.getGroupId());
map.put("artifactId", docProject.getArtifactId());
map.put("docProjectVersion", docProject.getVersion());
map.put("pomProjectName", docProject.getName());
map.put("security", this.security);
map.put("branding", this.branding);
map.put("canonicalUrlBase", this.canonicalUrlBase);
map.put("replacementsFile", this.replacementsFile);
map.put("failOnValidationError", this.failOnValidationError);
map.put("comments.php", this.commentsPhp);
map.put("project.build.directory", this.projectBuildDirectory);
map.put("inputSrcFile", inputFilename);
map.put("strictImageValidation", String.valueOf(this.strictImageValidation));
map.put("trim.wadl.uri.count", this.trimWadlUriCount);
map.put("status.bar.text", getProperty("statusBarText"));
map.put("draft.status", getProperty("draftStatus"));
// Profiling attrs:
map.put("profile.os", getProperty("profileOs"));
map.put("profile.arch", getProperty("profileArch"));
map.put("profile.condition", getProperty("profileCondition"));
map.put("profile.audience", getProperty("profileAudience"));
map.put("profile.conformance", getProperty("profileConformance"));
map.put("profile.revision", getProperty("profileRevision"));
map.put("profile.userlevel", getProperty("profileUserlevel"));
map.put("profile.vendor", getProperty("profileVendor"));
int lastSlash=inputFilename.lastIndexOf("/");
//This is the case if the path includes a relative path
if (-1!=lastSlash){
String theFileName=inputFilename.substring(lastSlash);
String theDirName=inputFilename.substring(0,lastSlash);
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index) + "/content/");
map.put("base.dir", getTargetDirectory() + "/" + theDirName+theFileName.substring(0,index));
map.put("input.filename",theDirName+theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~theFileName file has incompatible format: "+theFileName);
}
}
//This is the case when it's just a file name with no path information
else {
String theFileName=inputFilename;
int index = theFileName.indexOf('.');
if(-1!=index){
String targetFile= getTargetDirectory() + "/" + theFileName.substring(0,index)+"/content/"+"ext_query.xml";
map.put("targetExtQueryFile", targetFile);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + theFileName.substring(0,index) + "/content/");
String targetDir= getTargetDirectory() + "/" + theFileName.substring(0,index) + "/";
map.put("base.dir", targetDir);
map.put("input.filename", theFileName.substring(0,index));
}
else{
//getLog().info("~~~~~~~~inputFilename file has incompatible format: "+inputFilename);
}
}
if (null != webhelpDirname && webhelpDirname != "" ) {
map.put("targetExtQueryFile", getTargetDirectory() + "/" + webhelpDirname + "/content/"+"ext_query.xml");
map.put("base.dir", getTargetDirectory() + "/" + webhelpDirname);
map.put("targetHtmlContentDir", getTargetDirectory() + "/" + webhelpDirname + "/content/");
}
//targetExtQueryFile can tell us where the html will be built. We pass this absolute path to the
//pipeline so that the copy-and-transform-image step can use it to calculate where to place the images.
map.put("targetDir", baseDir.getAbsolutePath()+File.separator+"figures");
// String targetDirFiguresString = baseDir.getAbsolutePath()+File.separator+"figures";
// map.put("targetDir", targetDirFiguresString.replaceAll("\\\\","/").replace("file:/", "file:///"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
// getLog().info("~~~~~~~~baseDir:" + baseDir);
// getLog().info("~~~~~~~~projectBuildDirectory:" + projectBuildDirectory);
// getLog().info("~~~~~~~~targetDirectory:"+ getTargetDirectory());
// getLog().info("~~~~~~~~targetDirectory (map.put):" + this.getTargetDirectory().getParentFile().getAbsolutePath());
// getLog().info("~~~~~~~~inputFilename:" + inputFilename);
// getLog().info("~~~~~~~~targetExtQueryFile:" + map.get("targetExtQueryFile"));
// getLog().info("~~~~~~~~targetHtmlContentDir:" + map.get("targetHtmlContentDir"));
// getLog().info("~~~~~~~~targetDir:" + map.get("targetDir"));
// getLog().info("~~~~~~~~FOOBAR~~~~~~~~~~~~~~~~:");
//makePdf is a POM configuration for generate-webhelp goal to control the execution of
//automatic building of pdf output
if(this.makePdf) {
getLog().info("\n************************************* START: Automatically generating PDF for WEBHELP *************************************");
//Target directory for Webhelp points to ${basepath}/target/docbkx/webhelp. So get parent.
File baseDir = getTargetDirectory().getParentFile();
//The point FO/PDF file output to be generated at ${basepath}/target/docbkx/autopdf.
File targetDir = new File(baseDir.getAbsolutePath()+"/autopdf");
//Create a new instance of PDFBuilder class and set config variables.
PDFBuilder pdfBuilder = new PDFBuilder();
pdfBuilder.setProject(getMavenProject());
pdfBuilder.setSourceDirectory(getSourceDirectory());
pdfBuilder.setAutopdfTargetDirectory(targetDir);
pdfBuilder.setCoverColor(coverColor);
pdfBuilder.setPageWidth(pageWidth);
pdfBuilder.setPageHeight(pageHeight);
pdfBuilder.setOmitCover(omitCover);
pdfBuilder.setDoubleSided(doubleSided);
pdfBuilder.setCoverLogoPath(coverLogoPath);
pdfBuilder.setSecondaryCoverLogoPath(secondaryCoverLogoPath);
pdfBuilder.setCoverLogoLeft(coverLogoLeft);
pdfBuilder.setCoverLogoTop(coverLogoTop);
pdfBuilder.setCoverUrl(coverUrl);
pdfBuilder.setPdfFilenameBase(pdfFilenameBase);
pdfBuilder.setBranding(branding);
pdfBuilder.setSecurity(security);
pdfBuilder.setDraftStatus(draftStatus);
pdfBuilder.setStatusBarText(statusBarText);
pdfBuilder.setTrimWadlUriCount(trimWadlUriCount);
pdfBuilder.setComputeWadlPathFromDocbookPath(computeWadlPathFromDocbookPath);
pdfBuilder.setInputFilename(inputFilename);
pdfBuilder.setEntities(getEntities());
pdfBuilder.setChapterAutolabel(getProperty("chapterAutolabel"));
pdfBuilder.setAppendixAutolabel(getProperty("appendixAutolabel"));
pdfBuilder.setSectionAutolabel(getProperty("sectionAutolabel"));
pdfBuilder.setSectionLabelIncludesComponentLabel(getProperty("sectionLabelIncludesComponentLabel"));
pdfBuilder.setFormalProcedures(getProperty("formalProcedures"));
pdfBuilder.setGenerateToc(getProperty("generateToc"));
pdfBuilder.setTocMaxDepth(getProperty("tocMaxDepth"));
pdfBuilder.setTocSectionDepth(getProperty("tocSectionDepth"));
String srcFilename = this.projectBuildDirectory+"/docbkx/"+sourceFile.getName();
File tempHandle = new File(srcFilename);
if(tempHandle.exists()) {
getLog().debug("***********************"+ srcFilename);
pdfBuilder.setSourceFilePath(srcFilename);
} else {
getLog().debug("***********************"+ getSourceDirectory()+File.separator+inputFilename);
pdfBuilder.setSourceFilePath(getSourceDirectory()+File.separator+inputFilename);
}
pdfBuilder.setProjectBuildDirectory(baseDir.getAbsolutePath());
//setup fonts and images
pdfBuilder.preProcess();
//process input docbook to create FO file
File foFile = pdfBuilder.processSources(map);
//transform FO file to PDF
File pdfFile = pdfBuilder.postProcessResult(foFile);
//move PDF to where the webhelp stuff is for this docbook.
if(pdfFile!=null) {
File targetDirForPdf = new File(map.get("targetHtmlContentDir")).getParentFile();
if(!targetDirForPdf.exists()) {
com.rackspace.cloud.api.docs.FileUtils.mkdir(targetDirForPdf);
}
boolean moved = pdfBuilder.movePdfToWebhelpDir(pdfFile, targetDirForPdf);
if(moved) {
getLog().info("Successfully moved auto-generated PDF file to Webhelp target directory!");
} else {
getLog().error("Unable to move auto-generated PDF file to Webhelp target directory!");
}
}
autoPdfUrl = "../"+foFile.getName();
getLog().info("************************************* END: Automatically generating PDF for WEBHELP *************************************\n");
}
map.put("webhelp", "true");
map.put("autoPdfUrl",autoPdfUrl);
//this parameter will be used the copy and transform image step to decide whether to just check the existence of an image (for pdf)
//or to check existence, transform and copy image as well (for html)
map.put("outputType", "html");
return CalabashHelper.createSource(source, pathToPipelineFile, map);
}
|
diff --git a/code/Hyushik.Registration.Test/src/test/java/com/hyushik/registration/test/HyushikRegistrationTest.java b/code/Hyushik.Registration.Test/src/test/java/com/hyushik/registration/test/HyushikRegistrationTest.java
index 4ee726f..5ad1cd2 100644
--- a/code/Hyushik.Registration.Test/src/test/java/com/hyushik/registration/test/HyushikRegistrationTest.java
+++ b/code/Hyushik.Registration.Test/src/test/java/com/hyushik/registration/test/HyushikRegistrationTest.java
@@ -1,67 +1,67 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.hyushik.registration.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.Before;
import org.junit.After;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
/**
*
* @author McAfee
*/
@RunWith(JUnit4.class)
public class HyushikRegistrationTest{
private Properties props = new Properties();
private String baseUrl;
private WebDriver driver;
@Before
public void openBrowser() {
FileInputStream fizban;
try{
- fizban = new FileInputStream("targetserver.properties");
+ fizban = new FileInputStream("webserver.properties");
}catch(Exception e){
return;
}
try{
props.load(fizban);
}catch(Exception io){
return;
}
baseUrl = props.getProperty("weburl");
driver = new FirefoxDriver();
driver.get(baseUrl);
}
@Test
public void assTrue(){
String actualTitle = driver.getTitle();
assertEquals("Hyushik Registration", actualTitle);
}
@After
public void closeBrowser(){
driver.close();
}
}
| true | true | public void openBrowser() {
FileInputStream fizban;
try{
fizban = new FileInputStream("targetserver.properties");
}catch(Exception e){
return;
}
try{
props.load(fizban);
}catch(Exception io){
return;
}
baseUrl = props.getProperty("weburl");
driver = new FirefoxDriver();
driver.get(baseUrl);
}
| public void openBrowser() {
FileInputStream fizban;
try{
fizban = new FileInputStream("webserver.properties");
}catch(Exception e){
return;
}
try{
props.load(fizban);
}catch(Exception io){
return;
}
baseUrl = props.getProperty("weburl");
driver = new FirefoxDriver();
driver.get(baseUrl);
}
|
diff --git a/com/raphfrk/bukkit/serverport/MyPlayer.java b/com/raphfrk/bukkit/serverport/MyPlayer.java
index 0c34a3c..f6acdc2 100755
--- a/com/raphfrk/bukkit/serverport/MyPlayer.java
+++ b/com/raphfrk/bukkit/serverport/MyPlayer.java
@@ -1,275 +1,276 @@
package com.raphfrk.bukkit.serverport;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
public class MyPlayer {
private org.bukkit.entity.Player bukkitPlayer;
private org.bukkit.Location teleportTo = null;
MyPlayer() {
bukkitPlayer = null;
}
public MyPlayer( org.bukkit.entity.Player player ) {
bukkitPlayer = player;
}
void setBukkitPlayer( org.bukkit.entity.Player player ) {
this.bukkitPlayer = player;
}
String getColor() {
String displayName = bukkitPlayer.getDisplayName();
if( displayName.indexOf("\u00A7") == 0 ) {
return displayName.substring(0,2);
}
return "";
}
org.bukkit.Location getTeleportTo() {
return teleportTo;
}
String getName() {
return bukkitPlayer.getName();
}
Vehicle getVehicle() {
if(bukkitPlayer == null || !bukkitPlayer.isInsideVehicle()) {
return null;
} else {
return bukkitPlayer.getVehicle();
}
}
org.bukkit.entity.Player getBukkitPlayer() {
return bukkitPlayer;
}
boolean leaveVehicle() {
return bukkitPlayer.leaveVehicle();
}
String getIP() {
byte[] ip = bukkitPlayer.getAddress().getAddress().getAddress();
return (ip[0]&0xFF) + "." + (ip[1]&0xFF) + "." + (ip[2]&0xFF) + "." + (ip[3]&0xFF);
}
MyInventory getInventory() {
MyInventory inv = new MyInventory();
inv.setBukkitInventory( bukkitPlayer.getInventory() );
return inv;
}
MyLocation getLocation() {
MyLocation loc = new MyLocation();
loc.setBukkitLocation(bukkitPlayer.getLocation());
return loc;
}
void sendMessage(String message) {
if( bukkitPlayer != null ) {
bukkitPlayer.sendMessage(message);
}
}
void setHealth(int health) {
bukkitPlayer.setHealth(health);
}
int getHealth() {
return bukkitPlayer.getHealth();
}
void teleportTo(MyLocation loc) {
bukkitPlayer.teleportTo(loc.getBukkitLocation());
teleportTo = loc.getBukkitLocation();
}
static String[][] comments = new String[][] {
new String[] {"Allows sign activated gates of type <gate type> to be created from <from> to <to>" , "create_gate_type" , "<gate type>, <from-world>, <to-world/server>"},
new String[] {"Allows flint activated gates of type <gate type> to be created from <from> to <to>" , "create_fire_gate_type" , "<gate type>, <from-world>, <to-world/server>"},
new String[] {"Allows gates of type <gate type> connecting <from> to <to> to be used" , "use_gate_type" ,"<gate type>, <from-world>, <to-world/server>"},
new String[] {"Allows gates of type <gate type> connecting <from> to <to> to be destroyed" , "destroy_gate" , "<gate type>, <from-world>, <to-world/server>"},
new String[] {"Allows use of /cancelredirect command", "cancel_redirect" , "allow"},
new String[] {"Allows use of /release command", "release" , "allow"},
new String[] {"Allows use of /regengates command", "regen_gates" , "allow"},
new String[] {"Allows use of /serverport command", "serverport" , "allow"},
new String[] {"Allows use of /drawgate command", "draw_gate" , "<gate type>"},
new String[] {"Allows use of /stele command", "opteleport", "allow"}
};
static HashMap<String,HashMap> hashMaps = new HashMap<String,HashMap>();
boolean permissionCheck(String permissionName, String[] params) {
if(isOp()) {
return true;
}
MyPermissions handler = ((ServerPortBukkit)MyServer.plugin).permissions;
if(handler.isActive()) {
StringBuilder sb = new StringBuilder("serverport." + permissionName);
for(String current : params) {
if(current != null && !current.equals("*")) {
sb.append("." + current);
}
}
String checkString = sb.toString();
- return handler.has(bukkitPlayer, checkString);
+ boolean adminCheck = !permissionName.equals("admins") && isAdmin();
+ return adminCheck || handler.has(bukkitPlayer, checkString);
}
String[] paramsAndName = new String[params.length + 1];
for(int cnt=0;cnt<params.length;cnt++) {
if( params[cnt] == null ) {
return false;
} else {
paramsAndName[cnt+1] = params[cnt].trim();
}
}
paramsAndName[0] = getName();
if(!hashMaps.containsKey(permissionName)) {
File folder = new File(MyServer.getBaseFolder() + MiscUtils.slash + "permissions");
if(!folder.exists()) {
folder.mkdirs();
}
File file = new File(folder + MiscUtils.slash + permissionName + "_list.txt" );
if(!file.exists()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String[] arr = null;
for(String[] current: comments) {
if(current[1].equalsIgnoreCase(permissionName)) {
arr = current;
break;
}
}
if(arr!=null) {
out.write("# " + arr[0]);
out.newLine();
out.write("# <playername>, " + arr[2]);
out.newLine();
}
} catch (IOException e) {
} finally {
try {
if(out!=null) {
out.close();
}
} catch (IOException e) {
}
}
}
HashMap<String,HashMap> map = MiscUtils.fileToMap(file.toString(), true);
hashMaps.put(permissionName.trim(), map);
}
if(MiscUtils.allowed(paramsAndName, 0, hashMaps.get(permissionName), true)) {
return true;
}
if(!permissionName.equals("admins") && isAdmin()) {
return true;
}
return false;
}
boolean isOp() {
return bukkitPlayer != null && bukkitPlayer.isOp();
}
boolean isAdmin(String player) {
if(bukkitPlayer != null && bukkitPlayer.isOp()) {
return true;
}
boolean admin = permissionCheck("admins", new String[] {});
return admin;
}
static HashSet<String> admins = null;
int holding() {
return bukkitPlayer.getItemInHand().getAmount();
}
boolean isAdmin() {
return isAdmin(getName());
}
float getRotation() {
return bukkitPlayer.getLocation().getYaw();
}
float getPitch() {
return bukkitPlayer.getLocation().getPitch();
}
org.bukkit.World getWorld() {
return bukkitPlayer.getLocation().getWorld();
}
void kick( String message ) {
final String finalMessage = message;
final org.bukkit.entity.Player finalPlayer = bukkitPlayer;
MyServer.getServer().addToServerQueue(new Runnable() {
public void run() {
if( finalPlayer != null && finalMessage != null ) {
if( finalPlayer.isOnline() ) {
finalPlayer.kickPlayer(finalMessage);
}
}
}
});
}
boolean isNull() {
return bukkitPlayer == null || !bukkitPlayer.isOnline();
}
}
| true | true | boolean permissionCheck(String permissionName, String[] params) {
if(isOp()) {
return true;
}
MyPermissions handler = ((ServerPortBukkit)MyServer.plugin).permissions;
if(handler.isActive()) {
StringBuilder sb = new StringBuilder("serverport." + permissionName);
for(String current : params) {
if(current != null && !current.equals("*")) {
sb.append("." + current);
}
}
String checkString = sb.toString();
return handler.has(bukkitPlayer, checkString);
}
String[] paramsAndName = new String[params.length + 1];
for(int cnt=0;cnt<params.length;cnt++) {
if( params[cnt] == null ) {
return false;
} else {
paramsAndName[cnt+1] = params[cnt].trim();
}
}
paramsAndName[0] = getName();
if(!hashMaps.containsKey(permissionName)) {
File folder = new File(MyServer.getBaseFolder() + MiscUtils.slash + "permissions");
if(!folder.exists()) {
folder.mkdirs();
}
File file = new File(folder + MiscUtils.slash + permissionName + "_list.txt" );
if(!file.exists()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String[] arr = null;
for(String[] current: comments) {
if(current[1].equalsIgnoreCase(permissionName)) {
arr = current;
break;
}
}
if(arr!=null) {
out.write("# " + arr[0]);
out.newLine();
out.write("# <playername>, " + arr[2]);
out.newLine();
}
} catch (IOException e) {
} finally {
try {
if(out!=null) {
out.close();
}
} catch (IOException e) {
}
}
}
HashMap<String,HashMap> map = MiscUtils.fileToMap(file.toString(), true);
hashMaps.put(permissionName.trim(), map);
}
if(MiscUtils.allowed(paramsAndName, 0, hashMaps.get(permissionName), true)) {
return true;
}
if(!permissionName.equals("admins") && isAdmin()) {
return true;
}
return false;
}
| boolean permissionCheck(String permissionName, String[] params) {
if(isOp()) {
return true;
}
MyPermissions handler = ((ServerPortBukkit)MyServer.plugin).permissions;
if(handler.isActive()) {
StringBuilder sb = new StringBuilder("serverport." + permissionName);
for(String current : params) {
if(current != null && !current.equals("*")) {
sb.append("." + current);
}
}
String checkString = sb.toString();
boolean adminCheck = !permissionName.equals("admins") && isAdmin();
return adminCheck || handler.has(bukkitPlayer, checkString);
}
String[] paramsAndName = new String[params.length + 1];
for(int cnt=0;cnt<params.length;cnt++) {
if( params[cnt] == null ) {
return false;
} else {
paramsAndName[cnt+1] = params[cnt].trim();
}
}
paramsAndName[0] = getName();
if(!hashMaps.containsKey(permissionName)) {
File folder = new File(MyServer.getBaseFolder() + MiscUtils.slash + "permissions");
if(!folder.exists()) {
folder.mkdirs();
}
File file = new File(folder + MiscUtils.slash + permissionName + "_list.txt" );
if(!file.exists()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String[] arr = null;
for(String[] current: comments) {
if(current[1].equalsIgnoreCase(permissionName)) {
arr = current;
break;
}
}
if(arr!=null) {
out.write("# " + arr[0]);
out.newLine();
out.write("# <playername>, " + arr[2]);
out.newLine();
}
} catch (IOException e) {
} finally {
try {
if(out!=null) {
out.close();
}
} catch (IOException e) {
}
}
}
HashMap<String,HashMap> map = MiscUtils.fileToMap(file.toString(), true);
hashMaps.put(permissionName.trim(), map);
}
if(MiscUtils.allowed(paramsAndName, 0, hashMaps.get(permissionName), true)) {
return true;
}
if(!permissionName.equals("admins") && isAdmin()) {
return true;
}
return false;
}
|
diff --git a/src/demos/BoidWorld.java b/src/demos/BoidWorld.java
index 343d677..b3b1c07 100644
--- a/src/demos/BoidWorld.java
+++ b/src/demos/BoidWorld.java
@@ -1,117 +1,117 @@
package demos;
import vitro.*;
import vitro.plane.*;
import java.util.*;
public class BoidWorld extends Plane {
public Boid createBoid() { return new Boid(this); }
public BoidWorld(double width, double height) {
super(width, height);
}
public boolean done() {
return false;
}
public class Boid extends PlaneActor {
private double angle = 0.0;
public Boid(Plane model) {
super(model);
}
public Set<Boid> flock() {
Set<Boid> ret = new HashSet<Boid>();
for(Actor actor : model.positions.keySet()) {
if(actor instanceof Boid && positions.get(actor) != null) {
ret.add((Boid)actor);
}
}
return ret;
}
// here we just set it to what it should be... no agent needed!
public Set<Action> actions() {
Set<Action> ret = new HashSet<Action>(); // Forget anything else... I'm a boid!
// only continue if I am in the world
Position myPos = positions.get(this);
if(myPos == null) {
return ret;
}
// calculate!
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Position theirPos = positions.get(boid);
centerMass = centerMass.add(Position.ZERO.displace(theirPos).mul(1.0 / flock().size()));
centerHead = centerHead.add(new Vector2(Math.cos(boid.angle), Math.sin(boid.angle)).mul(1.0 / flock().size()));
- Vector2 repulse = myPos.displace(theirPos);
- if(repulse.normSq() > 0) {
+ Vector2 repulse = theirPos.displace(myPos);
+ if(0.25 > repulse.normSq() && repulse.normSq() > 0) {
repulsion = repulsion.add(repulse.normalize().mul(1.0 / repulse.normSq()));
}
}
- repulsion = repulsion.mul(1.0 / flock().size());
+ //repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(myPos.displace(new Position(centerMass)).normalize());
- heading = heading.add(centerHead.normalize());
- heading = heading.add(repulsion.mul(10.0));
+ heading = heading.add(centerHead.normalize().mul(5.0));
+ heading = heading.add(repulsion);
angle = Math.atan2(heading.y, heading.x);
Position newPos = myPos.translate(heading.normalize().mul(0.1));
newPos = new Position(Math.min(Math.max(newPos.x, 0.0), width), Math.min(Math.max(newPos.y, 0.0), height));
ret.add(new MoveAction(model, newPos, this));
// here we compute the new location (position + heading)
/*
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Frame frame = frames.get(boid);
Vector2 position = new Vector2(frame.x, frame.y);
double angle = frame.angle;
centerMass = centerMass.add(position);
centerHead = centerHead.add(new Vector2(Math.cos(angle), Math.sin(angle)));
Vector2 displace = (new Vector2(frames.get(this).x, frames.get(this).y)).sub(position);
if(displace.normSq() != 0.0) {
repulsion = repulsion.add(displace.normalize().mul(1.0 / displace.normSq()));
}
}
centerMass = centerMass.mul(1.0 / flock().size()).sub(new Vector2(frames.get(this).x, frames.get(this).y));
centerHead = centerHead.mul(1.0 / flock().size());
repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(centerMass.normalize());
heading = heading.add(centerHead.normalize());
heading = heading.add(repulsion.mul(2.0));
heading = heading.normalize().mul(0.1);
Frame newFrame = reference();
newFrame = newFrame.translate(heading.x, heading.y);
newFrame = newFrame.rotate(Math.atan2(-reference().y + newFrame.y, -reference().x + newFrame.x) - newFrame.angle);
newFrame = new Frame(Math.min(Math.max(newFrame.x, 0.0), width), Math.min(Math.max(newFrame.y, 0.0), height), newFrame.angle);
ret.add(new MoveAction(model, newFrame, this));
*/
return ret;
}
}
}
| false | true | public Set<Action> actions() {
Set<Action> ret = new HashSet<Action>(); // Forget anything else... I'm a boid!
// only continue if I am in the world
Position myPos = positions.get(this);
if(myPos == null) {
return ret;
}
// calculate!
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Position theirPos = positions.get(boid);
centerMass = centerMass.add(Position.ZERO.displace(theirPos).mul(1.0 / flock().size()));
centerHead = centerHead.add(new Vector2(Math.cos(boid.angle), Math.sin(boid.angle)).mul(1.0 / flock().size()));
Vector2 repulse = myPos.displace(theirPos);
if(repulse.normSq() > 0) {
repulsion = repulsion.add(repulse.normalize().mul(1.0 / repulse.normSq()));
}
}
repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(myPos.displace(new Position(centerMass)).normalize());
heading = heading.add(centerHead.normalize());
heading = heading.add(repulsion.mul(10.0));
angle = Math.atan2(heading.y, heading.x);
Position newPos = myPos.translate(heading.normalize().mul(0.1));
newPos = new Position(Math.min(Math.max(newPos.x, 0.0), width), Math.min(Math.max(newPos.y, 0.0), height));
ret.add(new MoveAction(model, newPos, this));
// here we compute the new location (position + heading)
/*
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Frame frame = frames.get(boid);
Vector2 position = new Vector2(frame.x, frame.y);
double angle = frame.angle;
centerMass = centerMass.add(position);
centerHead = centerHead.add(new Vector2(Math.cos(angle), Math.sin(angle)));
Vector2 displace = (new Vector2(frames.get(this).x, frames.get(this).y)).sub(position);
if(displace.normSq() != 0.0) {
repulsion = repulsion.add(displace.normalize().mul(1.0 / displace.normSq()));
}
}
centerMass = centerMass.mul(1.0 / flock().size()).sub(new Vector2(frames.get(this).x, frames.get(this).y));
centerHead = centerHead.mul(1.0 / flock().size());
repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(centerMass.normalize());
heading = heading.add(centerHead.normalize());
heading = heading.add(repulsion.mul(2.0));
heading = heading.normalize().mul(0.1);
Frame newFrame = reference();
newFrame = newFrame.translate(heading.x, heading.y);
newFrame = newFrame.rotate(Math.atan2(-reference().y + newFrame.y, -reference().x + newFrame.x) - newFrame.angle);
newFrame = new Frame(Math.min(Math.max(newFrame.x, 0.0), width), Math.min(Math.max(newFrame.y, 0.0), height), newFrame.angle);
ret.add(new MoveAction(model, newFrame, this));
*/
return ret;
}
| public Set<Action> actions() {
Set<Action> ret = new HashSet<Action>(); // Forget anything else... I'm a boid!
// only continue if I am in the world
Position myPos = positions.get(this);
if(myPos == null) {
return ret;
}
// calculate!
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Position theirPos = positions.get(boid);
centerMass = centerMass.add(Position.ZERO.displace(theirPos).mul(1.0 / flock().size()));
centerHead = centerHead.add(new Vector2(Math.cos(boid.angle), Math.sin(boid.angle)).mul(1.0 / flock().size()));
Vector2 repulse = theirPos.displace(myPos);
if(0.25 > repulse.normSq() && repulse.normSq() > 0) {
repulsion = repulsion.add(repulse.normalize().mul(1.0 / repulse.normSq()));
}
}
//repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(myPos.displace(new Position(centerMass)).normalize());
heading = heading.add(centerHead.normalize().mul(5.0));
heading = heading.add(repulsion);
angle = Math.atan2(heading.y, heading.x);
Position newPos = myPos.translate(heading.normalize().mul(0.1));
newPos = new Position(Math.min(Math.max(newPos.x, 0.0), width), Math.min(Math.max(newPos.y, 0.0), height));
ret.add(new MoveAction(model, newPos, this));
// here we compute the new location (position + heading)
/*
Vector2 centerMass = Vector2.ZERO;
Vector2 centerHead = Vector2.ZERO;
Vector2 repulsion = Vector2.ZERO;
for(Boid boid : flock()) {
Frame frame = frames.get(boid);
Vector2 position = new Vector2(frame.x, frame.y);
double angle = frame.angle;
centerMass = centerMass.add(position);
centerHead = centerHead.add(new Vector2(Math.cos(angle), Math.sin(angle)));
Vector2 displace = (new Vector2(frames.get(this).x, frames.get(this).y)).sub(position);
if(displace.normSq() != 0.0) {
repulsion = repulsion.add(displace.normalize().mul(1.0 / displace.normSq()));
}
}
centerMass = centerMass.mul(1.0 / flock().size()).sub(new Vector2(frames.get(this).x, frames.get(this).y));
centerHead = centerHead.mul(1.0 / flock().size());
repulsion = repulsion.mul(1.0 / flock().size());
Vector2 heading = Vector2.ZERO;
heading = heading.add(centerMass.normalize());
heading = heading.add(centerHead.normalize());
heading = heading.add(repulsion.mul(2.0));
heading = heading.normalize().mul(0.1);
Frame newFrame = reference();
newFrame = newFrame.translate(heading.x, heading.y);
newFrame = newFrame.rotate(Math.atan2(-reference().y + newFrame.y, -reference().x + newFrame.x) - newFrame.angle);
newFrame = new Frame(Math.min(Math.max(newFrame.x, 0.0), width), Math.min(Math.max(newFrame.y, 0.0), height), newFrame.angle);
ret.add(new MoveAction(model, newFrame, this));
*/
return ret;
}
|
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyStyles.java b/java/src/com/android/inputmethod/keyboard/internal/KeyStyles.java
index 30d9692a..3f9f3599 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyStyles.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyStyles.java
@@ -1,241 +1,241 @@
/*
* Copyright (C) 2010 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.inputmethod.keyboard.internal;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.android.inputmethod.keyboard.internal.KeyboardParser.ParseException;
import com.android.inputmethod.latin.R;
import java.util.ArrayList;
import java.util.HashMap;
public class KeyStyles {
private static final String TAG = "KeyStyles";
private static final boolean DEBUG = false;
private final HashMap<String, DeclaredKeyStyle> mStyles =
new HashMap<String, DeclaredKeyStyle>();
private static final KeyStyle EMPTY_KEY_STYLE = new EmptyKeyStyle();
public interface KeyStyle {
public CharSequence[] getTextArray(TypedArray a, int index);
public CharSequence getText(TypedArray a, int index);
public int getInt(TypedArray a, int index, int defaultValue);
public int getFlag(TypedArray a, int index, int defaultValue);
public boolean getBoolean(TypedArray a, int index, boolean defaultValue);
}
/* package */ static class EmptyKeyStyle implements KeyStyle {
private EmptyKeyStyle() {
// Nothing to do.
}
@Override
public CharSequence[] getTextArray(TypedArray a, int index) {
return parseTextArray(a, index);
}
@Override
public CharSequence getText(TypedArray a, int index) {
return a.getText(index);
}
@Override
public int getInt(TypedArray a, int index, int defaultValue) {
return a.getInt(index, defaultValue);
}
@Override
public int getFlag(TypedArray a, int index, int defaultValue) {
return a.getInt(index, defaultValue);
}
@Override
public boolean getBoolean(TypedArray a, int index, boolean defaultValue) {
return a.getBoolean(index, defaultValue);
}
protected static CharSequence[] parseTextArray(TypedArray a, int index) {
if (!a.hasValue(index))
return null;
final CharSequence text = a.getText(index);
return parseCsvText(text);
}
/* package */ static CharSequence[] parseCsvText(CharSequence text) {
final int size = text.length();
if (size == 0) return null;
if (size == 1) return new CharSequence[] { text };
final StringBuilder sb = new StringBuilder();
ArrayList<CharSequence> list = null;
int start = 0;
for (int pos = 0; pos < size; pos++) {
final char c = text.charAt(pos);
if (c == ',') {
if (list == null) list = new ArrayList<CharSequence>();
if (sb.length() == 0) {
list.add(text.subSequence(start, pos));
} else {
list.add(sb.toString());
sb.setLength(0);
}
start = pos + 1;
continue;
} else if (c == '\\') {
if (start == pos) {
// Skip escape character at the beginning of the value.
start++;
pos++;
} else {
if (start < pos && sb.length() == 0)
sb.append(text.subSequence(start, pos));
pos++;
if (pos < size)
sb.append(text.charAt(pos));
}
} else if (sb.length() > 0) {
sb.append(c);
}
}
if (list == null) {
return new CharSequence[] { sb.length() > 0 ? sb : text.subSequence(start, size) };
} else {
list.add(sb.length() > 0 ? sb : text.subSequence(start, size));
return list.toArray(new CharSequence[list.size()]);
}
}
}
private static class DeclaredKeyStyle extends EmptyKeyStyle {
private final HashMap<Integer, Object> mAttributes = new HashMap<Integer, Object>();
@Override
public CharSequence[] getTextArray(TypedArray a, int index) {
return a.hasValue(index)
? super.getTextArray(a, index) : (CharSequence[])mAttributes.get(index);
}
@Override
public CharSequence getText(TypedArray a, int index) {
return a.hasValue(index)
? super.getText(a, index) : (CharSequence)mAttributes.get(index);
}
@Override
public int getInt(TypedArray a, int index, int defaultValue) {
final Integer value = (Integer)mAttributes.get(index);
return super.getInt(a, index, (value != null) ? value : defaultValue);
}
@Override
public int getFlag(TypedArray a, int index, int defaultValue) {
final Integer value = (Integer)mAttributes.get(index);
return super.getFlag(a, index, defaultValue) | (value != null ? value : 0);
}
@Override
public boolean getBoolean(TypedArray a, int index, boolean defaultValue) {
final Boolean value = (Boolean)mAttributes.get(index);
return super.getBoolean(a, index, (value != null) ? value : defaultValue);
}
private DeclaredKeyStyle() {
super();
}
private void parseKeyStyleAttributes(TypedArray keyAttr) {
// TODO: Currently not all Key attributes can be declared as style.
readInt(keyAttr, R.styleable.Keyboard_Key_code);
readText(keyAttr, R.styleable.Keyboard_Key_keyLabel);
readText(keyAttr, R.styleable.Keyboard_Key_keyOutputText);
readText(keyAttr, R.styleable.Keyboard_Key_keyHintLabel);
readTextArray(keyAttr, R.styleable.Keyboard_Key_popupCharacters);
readFlag(keyAttr, R.styleable.Keyboard_Key_keyLabelOption);
readInt(keyAttr, R.styleable.Keyboard_Key_keyIcon);
readInt(keyAttr, R.styleable.Keyboard_Key_keyIconPreview);
readInt(keyAttr, R.styleable.Keyboard_Key_keyIconShifted);
readInt(keyAttr, R.styleable.Keyboard_Key_maxPopupKeyboardColumn);
readBoolean(keyAttr, R.styleable.Keyboard_Key_isFunctional);
readBoolean(keyAttr, R.styleable.Keyboard_Key_isSticky);
readBoolean(keyAttr, R.styleable.Keyboard_Key_isRepeatable);
readBoolean(keyAttr, R.styleable.Keyboard_Key_enabled);
}
private void readText(TypedArray a, int index) {
if (a.hasValue(index))
mAttributes.put(index, a.getText(index));
}
private void readInt(TypedArray a, int index) {
if (a.hasValue(index))
mAttributes.put(index, a.getInt(index, 0));
}
private void readFlag(TypedArray a, int index) {
final Integer value = (Integer)mAttributes.get(index);
if (a.hasValue(index))
mAttributes.put(index, a.getInt(index, 0) | (value != null ? value : 0));
}
private void readBoolean(TypedArray a, int index) {
if (a.hasValue(index))
mAttributes.put(index, a.getBoolean(index, false));
}
private void readTextArray(TypedArray a, int index) {
final CharSequence[] value = parseTextArray(a, index);
if (value != null)
mAttributes.put(index, value);
}
private void addParent(DeclaredKeyStyle parentStyle) {
mAttributes.putAll(parentStyle.mAttributes);
}
}
public void parseKeyStyleAttributes(TypedArray keyStyleAttr, TypedArray keyAttrs,
XmlResourceParser parser) {
- String styleName = keyStyleAttr.getString(R.styleable.Keyboard_KeyStyle_styleName);
+ final String styleName = keyStyleAttr.getString(R.styleable.Keyboard_KeyStyle_styleName);
if (DEBUG) Log.d(TAG, String.format("<%s styleName=%s />",
KeyboardParser.TAG_KEY_STYLE, styleName));
if (mStyles.containsKey(styleName))
throw new ParseException("duplicate key style declared: " + styleName, parser);
final DeclaredKeyStyle style = new DeclaredKeyStyle();
if (keyStyleAttr.hasValue(R.styleable.Keyboard_KeyStyle_parentStyle)) {
- String parentStyle = keyStyleAttr.getString(
+ final String parentStyle = keyStyleAttr.getString(
R.styleable.Keyboard_KeyStyle_parentStyle);
final DeclaredKeyStyle parent = mStyles.get(parentStyle);
if (parent == null)
- throw new ParseException("Unknown parentStyle " + parent, parser);
+ throw new ParseException("Unknown parentStyle " + parentStyle, parser);
style.addParent(parent);
}
style.parseKeyStyleAttributes(keyAttrs);
mStyles.put(styleName, style);
}
public KeyStyle getKeyStyle(String styleName) {
return mStyles.get(styleName);
}
public KeyStyle getEmptyKeyStyle() {
return EMPTY_KEY_STYLE;
}
}
| false | true | public void parseKeyStyleAttributes(TypedArray keyStyleAttr, TypedArray keyAttrs,
XmlResourceParser parser) {
String styleName = keyStyleAttr.getString(R.styleable.Keyboard_KeyStyle_styleName);
if (DEBUG) Log.d(TAG, String.format("<%s styleName=%s />",
KeyboardParser.TAG_KEY_STYLE, styleName));
if (mStyles.containsKey(styleName))
throw new ParseException("duplicate key style declared: " + styleName, parser);
final DeclaredKeyStyle style = new DeclaredKeyStyle();
if (keyStyleAttr.hasValue(R.styleable.Keyboard_KeyStyle_parentStyle)) {
String parentStyle = keyStyleAttr.getString(
R.styleable.Keyboard_KeyStyle_parentStyle);
final DeclaredKeyStyle parent = mStyles.get(parentStyle);
if (parent == null)
throw new ParseException("Unknown parentStyle " + parent, parser);
style.addParent(parent);
}
style.parseKeyStyleAttributes(keyAttrs);
mStyles.put(styleName, style);
}
| public void parseKeyStyleAttributes(TypedArray keyStyleAttr, TypedArray keyAttrs,
XmlResourceParser parser) {
final String styleName = keyStyleAttr.getString(R.styleable.Keyboard_KeyStyle_styleName);
if (DEBUG) Log.d(TAG, String.format("<%s styleName=%s />",
KeyboardParser.TAG_KEY_STYLE, styleName));
if (mStyles.containsKey(styleName))
throw new ParseException("duplicate key style declared: " + styleName, parser);
final DeclaredKeyStyle style = new DeclaredKeyStyle();
if (keyStyleAttr.hasValue(R.styleable.Keyboard_KeyStyle_parentStyle)) {
final String parentStyle = keyStyleAttr.getString(
R.styleable.Keyboard_KeyStyle_parentStyle);
final DeclaredKeyStyle parent = mStyles.get(parentStyle);
if (parent == null)
throw new ParseException("Unknown parentStyle " + parentStyle, parser);
style.addParent(parent);
}
style.parseKeyStyleAttributes(keyAttrs);
mStyles.put(styleName, style);
}
|
diff --git a/Core/Tests/org.emftext.test/src/org/emftext/test/locationmap/LocationMapOptionsTest.java b/Core/Tests/org.emftext.test/src/org/emftext/test/locationmap/LocationMapOptionsTest.java
index ac979c51b..8bfa4d121 100644
--- a/Core/Tests/org.emftext.test/src/org/emftext/test/locationmap/LocationMapOptionsTest.java
+++ b/Core/Tests/org.emftext.test/src/org/emftext/test/locationmap/LocationMapOptionsTest.java
@@ -1,115 +1,115 @@
/*******************************************************************************
* Copyright (c) 2006-2012
* Software Technology Group, Dresden University of Technology
* DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026
*
* 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:
* Software Technology Group - TU Dresden, Germany;
* DevBoost GmbH - Berlin, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.test.locationmap;
import static org.emftext.test.ConcreteSyntaxTestHelper.getConcreteSyntax;
import static org.emftext.test.ConcreteSyntaxTestHelper.registerResourceFactories;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import junit.framework.TestCase;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.resource.cs.ICsOptions;
import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsResource;
import org.emftext.test.PluginTestHelper;
/**
* This is a test case for bug 856 (Syntaxes that import theirself cause a
* StackOverflowError when opened in the editor). It loads a .cs file containing
* a self import and checks the result.
*/
public class LocationMapOptionsTest extends TestCase {
public void setUp() {
registerResourceFactories();
}
public void testDisableLocationMapOption() {
String pluginRootPath = new PluginTestHelper().getPluginRootPath(getClass());
String path = pluginRootPath + "/src/org/emftext/test/locationmap/main.cs";
File file = new File(path);
CsResource resource = (CsResource) new ResourceSetImpl().createResource(URI
.createFileURI(file.getAbsolutePath()));
try {
resource.load(null);
ConcreteSyntax cs = getConcreteSyntax(resource);
int l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
resource.unload();
resource.load(Collections.singletonMap(
- ICsOptions.DISABLE_LOCATION_MAP, null));
+ ICsOptions.DISABLE_LOCATION_MAP, true));
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map disabled -> no location information available
assertEquals(-1, l);
resource.unload();
resource.load(null);
resource.load(Collections.singletonMap(
- ICsOptions.DISABLE_LOCATION_MAP, null)); //no effect since already loaded
+ ICsOptions.DISABLE_LOCATION_MAP, true)); //no effect since already loaded
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
} catch (IOException e) {
fail(e.getMessage());
}
}
public void testDisableLayoutInformationRecording() {
String pluginRootPath = new PluginTestHelper().getPluginRootPath(getClass());
String path = pluginRootPath + "/src/org/emftext/test/locationmap/main.cs";
File file = new File(path);
CsResource resource = (CsResource) new ResourceSetImpl().createResource(URI
.createFileURI(file.getAbsolutePath()));
try {
resource.load(null);
ConcreteSyntax cs = getConcreteSyntax(resource);
Rule r = cs.getRules().get(0);
// layout information adapter available
assertEquals(1, r.eAdapters().size());
resource.unload();
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LAYOUT_INFORMATION_RECORDING, true));
cs = getConcreteSyntax(resource);
r = cs.getRules().get(0);
// no layout information adapter available
assertEquals("There must be no layout information adapters.", 0, r.eAdapters().size());
resource.unload();
resource.load(null);
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LAYOUT_INFORMATION_RECORDING, true)); //no effect since already loaded
cs = getConcreteSyntax(resource);
r = cs.getRules().get(0);
// layout information adapter available
assertEquals(1, r.eAdapters().size());
} catch (IOException e) {
fail(e.getMessage());
}
}
}
| false | true | public void testDisableLocationMapOption() {
String pluginRootPath = new PluginTestHelper().getPluginRootPath(getClass());
String path = pluginRootPath + "/src/org/emftext/test/locationmap/main.cs";
File file = new File(path);
CsResource resource = (CsResource) new ResourceSetImpl().createResource(URI
.createFileURI(file.getAbsolutePath()));
try {
resource.load(null);
ConcreteSyntax cs = getConcreteSyntax(resource);
int l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
resource.unload();
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LOCATION_MAP, null));
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map disabled -> no location information available
assertEquals(-1, l);
resource.unload();
resource.load(null);
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LOCATION_MAP, null)); //no effect since already loaded
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
} catch (IOException e) {
fail(e.getMessage());
}
}
| public void testDisableLocationMapOption() {
String pluginRootPath = new PluginTestHelper().getPluginRootPath(getClass());
String path = pluginRootPath + "/src/org/emftext/test/locationmap/main.cs";
File file = new File(path);
CsResource resource = (CsResource) new ResourceSetImpl().createResource(URI
.createFileURI(file.getAbsolutePath()));
try {
resource.load(null);
ConcreteSyntax cs = getConcreteSyntax(resource);
int l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
resource.unload();
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LOCATION_MAP, true));
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map disabled -> no location information available
assertEquals(-1, l);
resource.unload();
resource.load(null);
resource.load(Collections.singletonMap(
ICsOptions.DISABLE_LOCATION_MAP, true)); //no effect since already loaded
cs = getConcreteSyntax(resource);
l = resource.getLocationMap().getLine(cs.getRules().get(0));
//location map enabled -> location information available
assertEquals(10, l);
} catch (IOException e) {
fail(e.getMessage());
}
}
|
diff --git a/dev/cosbench-swauth/src/com/intel/cosbench/client/swauth/SwiftAuthClient.java b/dev/cosbench-swauth/src/com/intel/cosbench/client/swauth/SwiftAuthClient.java
index b771587..a3d66c5 100644
--- a/dev/cosbench-swauth/src/com/intel/cosbench/client/swauth/SwiftAuthClient.java
+++ b/dev/cosbench-swauth/src/com/intel/cosbench/client/swauth/SwiftAuthClient.java
@@ -1,85 +1,87 @@
/**
Copyright 2013 Intel Corporation, 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.intel.cosbench.client.swauth;
import static com.intel.cosbench.client.swauth.SwiftAuthConstants.*;
import java.io.IOException;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import com.intel.cosbench.client.http.HttpClientUtil;
public class SwiftAuthClient {
private String authURL;
private String username;
private String password;
private String authToken;
private String storageURL;
private HttpClient client;
public SwiftAuthClient(HttpClient client, String authUrl, String username,
String password) {
this.client = client;
this.authURL = authUrl;
this.username = username;
this.password = password;
}
public String getAuthToken() {
return authToken;
}
public String getStorageURL() {
return storageURL;
}
public void dispose() {
HttpClientUtil.disposeHttpClient(client);
}
public void login() throws IOException, SwiftAuthClientException {
HttpResponse response = null;
try {
HttpGet method = new HttpGet(authURL);
method.setHeader(X_STORAGE_USER, username);
method.setHeader(X_STORAGE_PASS, password);
response = client.execute(method);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
+ if ((response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) &&
+ (response.getStatusLine().getStatusCode() < (HttpStatus.SC_OK + 100))
+ ) {
authToken = response.getFirstHeader(X_AUTH_TOKEN) != null ? response
.getFirstHeader(X_AUTH_TOKEN).getValue() : null;
storageURL = response.getFirstHeader(X_STORAGE_URL) != null ? response
.getFirstHeader(X_STORAGE_URL).getValue() : null;
return;
}
throw new SwiftAuthClientException(response.getStatusLine()
.getStatusCode(), response.getStatusLine()
.getReasonPhrase());
} finally {
if (response != null)
EntityUtils.consume(response.getEntity());
}
}
}
| true | true | public void login() throws IOException, SwiftAuthClientException {
HttpResponse response = null;
try {
HttpGet method = new HttpGet(authURL);
method.setHeader(X_STORAGE_USER, username);
method.setHeader(X_STORAGE_PASS, password);
response = client.execute(method);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
authToken = response.getFirstHeader(X_AUTH_TOKEN) != null ? response
.getFirstHeader(X_AUTH_TOKEN).getValue() : null;
storageURL = response.getFirstHeader(X_STORAGE_URL) != null ? response
.getFirstHeader(X_STORAGE_URL).getValue() : null;
return;
}
throw new SwiftAuthClientException(response.getStatusLine()
.getStatusCode(), response.getStatusLine()
.getReasonPhrase());
} finally {
if (response != null)
EntityUtils.consume(response.getEntity());
}
}
| public void login() throws IOException, SwiftAuthClientException {
HttpResponse response = null;
try {
HttpGet method = new HttpGet(authURL);
method.setHeader(X_STORAGE_USER, username);
method.setHeader(X_STORAGE_PASS, password);
response = client.execute(method);
if ((response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) &&
(response.getStatusLine().getStatusCode() < (HttpStatus.SC_OK + 100))
) {
authToken = response.getFirstHeader(X_AUTH_TOKEN) != null ? response
.getFirstHeader(X_AUTH_TOKEN).getValue() : null;
storageURL = response.getFirstHeader(X_STORAGE_URL) != null ? response
.getFirstHeader(X_STORAGE_URL).getValue() : null;
return;
}
throw new SwiftAuthClientException(response.getStatusLine()
.getStatusCode(), response.getStatusLine()
.getReasonPhrase());
} finally {
if (response != null)
EntityUtils.consume(response.getEntity());
}
}
|
diff --git a/src/main/com/mongodb/DBTCPConnector.java b/src/main/com/mongodb/DBTCPConnector.java
index aa24ee7bf..a1a4d5395 100644
--- a/src/main/com/mongodb/DBTCPConnector.java
+++ b/src/main/com/mongodb/DBTCPConnector.java
@@ -1,551 +1,552 @@
// DBTCPConnector.java
/**
* Copyright (C) 2008 10gen 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 com.mongodb;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DBTCPConnector implements DBConnector {
static Logger _logger = Logger.getLogger( Bytes.LOGGER.getName() + ".tcp" );
static Logger _createLogger = Logger.getLogger( _logger.getName() + ".connect" );
public DBTCPConnector( Mongo m , ServerAddress addr )
throws MongoException {
_mongo = m;
_portHolder = new DBPortPool.Holder( m._options );
_checkAddress( addr );
_createLogger.info( addr.toString() );
if ( addr.isPaired() ){
_allHosts = new ArrayList<ServerAddress>( addr.explode() );
_rsStatus = new ReplicaSetStatus( m, _allHosts );
_createLogger.info( "switching to replica set mode : " + _allHosts + " -> " + getAddress() );
}
else {
_set( addr );
_allHosts = null;
_rsStatus = null;
}
}
public DBTCPConnector( Mongo m , ServerAddress ... all )
throws MongoException {
this( m , Arrays.asList( all ) );
}
public DBTCPConnector( Mongo m , List<ServerAddress> all )
throws MongoException {
_portHolder = new DBPortPool.Holder( m._options );
_checkAddress( all );
_allHosts = new ArrayList<ServerAddress>( all ); // make a copy so it can't be modified
_rsStatus = new ReplicaSetStatus( m, _allHosts );
_createLogger.info( all + " -> " + getAddress() );
}
public void start() {
if (_rsStatus != null)
_rsStatus.start();
}
private static ServerAddress _checkAddress( ServerAddress addr ){
if ( addr == null )
throw new NullPointerException( "address can't be null" );
return addr;
}
private static ServerAddress _checkAddress( List<ServerAddress> addrs ){
if ( addrs == null )
throw new NullPointerException( "addresses can't be null" );
if ( addrs.size() == 0 )
throw new IllegalArgumentException( "need to specify at least 1 address" );
return addrs.get(0);
}
/**
* Start a "request".
*
* A "request" is a group of operations in which order matters. Examples
* include inserting a document and then performing a query which expects
* that document to have been inserted, or performing an operation and
* then using com.mongodb.Mongo.getLastError to perform error-checking
* on that operation. When a thread performs operations in a "request", all
* operations will be performed on the same socket, so they will be
* correctly ordered.
*/
public void requestStart(){
_myPort.get().requestStart();
}
/**
* End the current "request", if this thread is in one.
*
* By ending a request when it is safe to do so the built-in connection-
* pool is allowed to reassign requests to different sockets in order to
* more effectively balance load. See requestStart for more information.
*/
public void requestDone(){
_myPort.get().requestDone();
}
public void requestEnsureConnection(){
_myPort.get().requestEnsureConnection();
}
void _checkClosed(){
if ( _closed )
throw new IllegalStateException( "this Mongo has been closed" );
}
WriteResult _checkWriteError( DB db , MyPort mp , DBPort port , WriteConcern concern )
throws MongoException, IOException {
CommandResult e = null;
e = port.runCommand( db , concern.getCommand() );
if ( ! e.hasErr() )
return new WriteResult( e , concern );
e.throwOnError();
return null;
}
public WriteResult say( DB db , OutMessage m , WriteConcern concern )
throws MongoException {
return say( db , m , concern , null );
}
public WriteResult say( DB db , OutMessage m , WriteConcern concern , ServerAddress hostNeeded )
throws MongoException {
_checkClosed();
checkMaster( false , true );
MyPort mp = _myPort.get();
DBPort port = mp.get( true , false , hostNeeded );
try {
port.checkAuth( db );
port.say( m );
if ( concern.callGetLastError() ){
return _checkWriteError( db , mp , port , concern );
}
else {
return new WriteResult( db , port , concern );
}
}
catch ( IOException ioe ){
mp.error( port , ioe );
_error( ioe, false );
if ( concern.raiseNetworkErrors() )
throw new MongoException.Network( "can't say something" , ioe );
CommandResult res = new CommandResult();
res.put( "ok" , false );
res.put( "$err" , "NETWORK ERROR" );
return new WriteResult( res , concern );
}
catch ( MongoException me ){
throw me;
}
catch ( RuntimeException re ){
mp.error( port , re );
throw re;
}
finally {
mp.done( port );
m.doneWithMessage();
}
}
public Response call( DB db , DBCollection coll , OutMessage m )
throws MongoException {
return call( db , coll , m , null , 2 );
}
public Response call( DB db , DBCollection coll , OutMessage m , ServerAddress hostNeeded )
throws MongoException {
return call( db , coll , m , hostNeeded , 2 );
}
public Response call( DB db , DBCollection coll , OutMessage m , ServerAddress hostNeeded , int retries )
throws MongoException {
boolean slaveOk = m.hasOption( Bytes.QUERYOPTION_SLAVEOK );
_checkClosed();
checkMaster( false , !slaveOk );
final MyPort mp = _myPort.get();
final DBPort port = mp.get( false , slaveOk, hostNeeded );
Response res = null;
boolean retry = false;
try {
port.checkAuth( db );
res = port.call( m , coll );
if ( res._responseTo != m.getId() )
throw new MongoException( "ids don't match" );
}
catch ( IOException ioe ){
mp.error( port , ioe );
retry = retries > 0 && !coll._name.equals( "$cmd" )
&& !(ioe instanceof SocketTimeoutException) && _error( ioe, slaveOk );
if ( !retry ){
- throw new MongoException.Network( "can't call something" , ioe );
+ throw new MongoException.Network( "can't call something : " + port.host() + "/" + db,
+ ioe );
}
}
catch ( RuntimeException re ){
mp.error( port , re );
throw re;
} finally {
mp.done( port );
}
if (retry)
return call( db , coll , m , hostNeeded , retries - 1 );
ServerError err = res.getError();
if ( err != null && err.isNotMasterError() ){
checkMaster( true , true );
if ( retries <= 0 ){
throw new MongoException( "not talking to master and retries used up" );
}
return call( db , coll , m , hostNeeded , retries -1 );
}
m.doneWithMessage();
return res;
}
public ServerAddress getAddress(){
DBPortPool pool = _masterPortPool;
return pool != null ? pool.getServerAddress() : null;
}
/**
* Gets the list of seed server addresses
* @return
*/
public List<ServerAddress> getAllAddress() {
return _allHosts;
}
/**
* Gets the list of server addresses currently seen by the connector.
* This includes addresses auto-discovered from a replica set.
* @return
*/
public List<ServerAddress> getServerAddressList() {
if (_rsStatus != null) {
return _rsStatus.getServerAddressList();
}
ServerAddress master = getAddress();
if (master != null) {
// single server
List<ServerAddress> list = new ArrayList<ServerAddress>();
list.add(master);
return list;
}
return null;
}
public ReplicaSetStatus getReplicaSetStatus() {
return _rsStatus;
}
public String getConnectPoint(){
ServerAddress master = getAddress();
return master != null ? master.toString() : null;
}
/**
* This method is called in case of an IOException.
* It will potentially trigger a checkMaster() to check the status of all servers.
* @param t the exception thrown
* @param slaveOk slaveOk flag
* @return true if the request should be retried, false otherwise
* @throws MongoException
*/
boolean _error( Throwable t, boolean slaveOk )
throws MongoException {
if (_rsStatus == null) {
// single server, no need to retry
return false;
}
// the replset has at least 1 server up, try to see if should switch master
// if no server is up, we wont retry until the updater thread finds one
// this is to cut down the volume of requests/errors when all servers are down
if ( _rsStatus.hasServerUp() ){
checkMaster( true , !slaveOk );
}
return _rsStatus.hasServerUp();
}
class MyPort {
DBPort get( boolean keep , boolean slaveOk , ServerAddress hostNeeded ){
if ( hostNeeded != null ){
// asked for a specific host
return _portHolder.get( hostNeeded ).get();
}
if ( _requestPort != null ){
// we are within a request, and have a port, should stick to it
if ( _requestPort.getPool() == _masterPortPool || !keep ) {
// if keep is false, it's a read, so we use port even if master changed
return _requestPort;
}
// it's write and master has changed
// we fall back on new master and try to go on with request
// this may not be best behavior if spec of request is to stick with same server
_requestPort.getPool().done(_requestPort);
_requestPort = null;
}
if ( slaveOk && _rsStatus != null ){
// if slaveOk, try to use a secondary
ServerAddress slave = _rsStatus.getASecondary();
if ( slave != null ){
return _portHolder.get( slave ).get();
}
}
if (_masterPortPool == null) {
// this should only happen in rare case that no master was ever found
// may get here at startup if it's a read, slaveOk=true, and ALL servers are down
throw new MongoException("Rare case where master=null, probably all servers are down");
}
// use master
DBPort p = _masterPortPool.get();
if ( keep && _inRequest ) {
// if within request, remember port to stick to same server
_requestPort = p;
}
return p;
}
void done( DBPort p ){
// keep request port
if ( p != _requestPort ){
p.getPool().done(p);
}
}
/**
* call this method when there is an IOException or other low level error on port.
* @param p
* @param e
*/
void error( DBPort p , Exception e ){
p.close();
_requestPort = null;
// _logger.log( Level.SEVERE , "MyPort.error called" , e );
// depending on type of error, may need to close other connections in pool
p.getPool().gotError(e);
}
void requestEnsureConnection(){
if ( ! _inRequest )
return;
if ( _requestPort != null )
return;
_requestPort = _masterPortPool.get();
}
void requestStart(){
_inRequest = true;
}
void requestDone(){
if ( _requestPort != null )
_requestPort.getPool().done( _requestPort );
_requestPort = null;
_inRequest = false;
}
DBPort _requestPort;
// DBPortPool _requestPool;
boolean _inRequest;
}
void checkMaster( boolean force , boolean failIfNoMaster )
throws MongoException {
if ( _rsStatus != null ){
if ( _masterPortPool == null || force ){
ReplicaSetStatus.Node n = _rsStatus.ensureMaster();
if ( n == null ){
if ( failIfNoMaster )
throw new MongoException( "can't find a master" );
}
else {
_set( n._addr );
maxBsonObjectSize = _rsStatus.getMaxBsonObjectSize();
}
}
} else {
// single server, may have to obtain max bson size
if (maxBsonObjectSize == 0)
maxBsonObjectSize = fetchMaxBsonObjectSize();
}
}
/**
* Fetches the maximum size for a BSON object from the current master server
* @return the size, or 0 if it could not be obtained
*/
int fetchMaxBsonObjectSize() {
if (_masterPortPool == null)
return 0;
DBPort port = _masterPortPool.get();
try {
CommandResult res = port.runCommand(_mongo.getDB("admin"), new BasicDBObject("isMaster", 1));
// max size was added in 1.8
if (res.containsField("maxBsonObjectSize")) {
maxBsonObjectSize = ((Integer) res.get("maxBsonObjectSize")).intValue();
} else {
maxBsonObjectSize = Bytes.MAX_OBJECT_SIZE;
}
} catch (Exception e) {
_logger.log(Level.WARNING, "Exception determining maxBSON size using"+maxBsonObjectSize, e);
} finally {
port.getPool().done(port);
}
return maxBsonObjectSize;
}
void testMaster()
throws MongoException {
DBPort p = null;
try {
p = _masterPortPool.get();
p.runCommand( _mongo.getDB("admin") , new BasicDBObject( "nonce" , 1 ) );
} catch ( IOException ioe ){
throw new MongoException.Network( ioe.getMessage() , ioe );
} finally {
_masterPortPool.done( p );
}
}
private boolean _set( ServerAddress addr ){
DBPortPool newPool = _portHolder.get( addr );
if (newPool == _masterPortPool)
return false;
if ( _logger.isLoggable( Level.WARNING ) && _masterPortPool != null )
_logger.log(Level.WARNING, "Master switching from " + _masterPortPool.getServerAddress() + " to " + addr);
_masterPortPool = newPool;
return true;
}
public String debugString(){
StringBuilder buf = new StringBuilder( "DBTCPConnector: " );
if ( _rsStatus != null ) {
buf.append( "replica set : " ).append( _allHosts );
} else {
ServerAddress master = getAddress();
buf.append( master ).append( " " ).append( master != null ? master._addr : null );
}
return buf.toString();
}
public void close(){
_closed = true;
if ( _portHolder != null ) {
_portHolder.close();
_portHolder = null;
}
if ( _rsStatus != null ) {
_rsStatus.close();
_rsStatus = null;
}
// below this will remove the myport for this thread only
// client using thread pool in web framework may need to call close() from all threads
_myPort.remove();
}
/**
* Assigns a new DBPortPool for a given ServerAddress.
* This is used to obtain a new pool when the resolved IP of a host changes, for example.
* User application should not have to call this method directly.
* @param addr
*/
public void updatePortPool(ServerAddress addr) {
// just remove from map, a new pool will be created lazily
_portHolder._pools.remove(addr);
}
/**
* Gets the DBPortPool associated with a ServerAddress.
* @param addr
* @return
*/
public DBPortPool getDBPortPool(ServerAddress addr) {
return _portHolder.get(addr);
}
public boolean isOpen(){
return ! _closed;
}
/**
* Gets the maximum size for a BSON object supported by the current master server.
* Note that this value may change over time depending on which server is master.
* @return the maximum size, or 0 if not obtained from servers yet.
*/
public int getMaxBsonObjectSize() {
return maxBsonObjectSize;
}
private Mongo _mongo;
// private ServerAddress _curMaster;
private DBPortPool _masterPortPool;
private DBPortPool.Holder _portHolder;
private final List<ServerAddress> _allHosts;
private ReplicaSetStatus _rsStatus;
private boolean _closed = false;
private int maxBsonObjectSize = 0;
private ThreadLocal<MyPort> _myPort = new ThreadLocal<MyPort>(){
protected MyPort initialValue(){
return new MyPort();
}
};
}
| true | true | public Response call( DB db , DBCollection coll , OutMessage m , ServerAddress hostNeeded , int retries )
throws MongoException {
boolean slaveOk = m.hasOption( Bytes.QUERYOPTION_SLAVEOK );
_checkClosed();
checkMaster( false , !slaveOk );
final MyPort mp = _myPort.get();
final DBPort port = mp.get( false , slaveOk, hostNeeded );
Response res = null;
boolean retry = false;
try {
port.checkAuth( db );
res = port.call( m , coll );
if ( res._responseTo != m.getId() )
throw new MongoException( "ids don't match" );
}
catch ( IOException ioe ){
mp.error( port , ioe );
retry = retries > 0 && !coll._name.equals( "$cmd" )
&& !(ioe instanceof SocketTimeoutException) && _error( ioe, slaveOk );
if ( !retry ){
throw new MongoException.Network( "can't call something" , ioe );
}
}
catch ( RuntimeException re ){
mp.error( port , re );
throw re;
} finally {
mp.done( port );
}
if (retry)
return call( db , coll , m , hostNeeded , retries - 1 );
ServerError err = res.getError();
if ( err != null && err.isNotMasterError() ){
checkMaster( true , true );
if ( retries <= 0 ){
throw new MongoException( "not talking to master and retries used up" );
}
return call( db , coll , m , hostNeeded , retries -1 );
}
m.doneWithMessage();
return res;
}
| public Response call( DB db , DBCollection coll , OutMessage m , ServerAddress hostNeeded , int retries )
throws MongoException {
boolean slaveOk = m.hasOption( Bytes.QUERYOPTION_SLAVEOK );
_checkClosed();
checkMaster( false , !slaveOk );
final MyPort mp = _myPort.get();
final DBPort port = mp.get( false , slaveOk, hostNeeded );
Response res = null;
boolean retry = false;
try {
port.checkAuth( db );
res = port.call( m , coll );
if ( res._responseTo != m.getId() )
throw new MongoException( "ids don't match" );
}
catch ( IOException ioe ){
mp.error( port , ioe );
retry = retries > 0 && !coll._name.equals( "$cmd" )
&& !(ioe instanceof SocketTimeoutException) && _error( ioe, slaveOk );
if ( !retry ){
throw new MongoException.Network( "can't call something : " + port.host() + "/" + db,
ioe );
}
}
catch ( RuntimeException re ){
mp.error( port , re );
throw re;
} finally {
mp.done( port );
}
if (retry)
return call( db , coll , m , hostNeeded , retries - 1 );
ServerError err = res.getError();
if ( err != null && err.isNotMasterError() ){
checkMaster( true , true );
if ( retries <= 0 ){
throw new MongoException( "not talking to master and retries used up" );
}
return call( db , coll , m , hostNeeded , retries -1 );
}
m.doneWithMessage();
return res;
}
|
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JClassLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JClassLiteral.java
index aab937b15..8a24a29c0 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JClassLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JClassLiteral.java
@@ -1,184 +1,186 @@
/*
* Copyright 2008 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 com.google.gwt.dev.jjs.ast;
import com.google.gwt.dev.jjs.InternalCompilerException;
import com.google.gwt.dev.jjs.SourceInfo;
import com.google.gwt.dev.jjs.ast.js.JsniMethodRef;
/**
* Java class literal expression.
*
* NOTE: This class is modeled as if it were a JFieldRef to a field declared in
* ClassLiteralHolder. That field contains the class object allocation
* initializer.
*/
public class JClassLiteral extends JLiteral {
/**
* Create an expression that will evaluate, at run time, to the class literal.
* Cannot be called after optimizations begin.
*/
static JMethodCall computeClassObjectAllocation(JProgram program,
SourceInfo info, JType type) {
String typeName = getTypeName(program, type);
JMethod method = program.getIndexedMethod(type.getClassLiteralFactoryMethod());
/*
* Use the classForEnum() constructor even for enum subtypes to aid in
* pruning supertype data.
*/
boolean isEnumOrSubclass = false;
if (type instanceof JClassType) {
JEnumType maybeEnum = ((JClassType) type).isEnumOrSubclass();
if (maybeEnum != null) {
isEnumOrSubclass = true;
method = program.getIndexedMethod(maybeEnum.getClassLiteralFactoryMethod());
}
}
assert method != null;
JMethodCall call = new JMethodCall(info, null, method);
call.addArgs(program.getLiteralString(info, getPackageName(typeName)),
program.getLiteralString(info, getClassName(typeName)));
if (type instanceof JArrayType) {
// There's only one seed function for all arrays
JDeclaredType arrayType = program.getIndexedType("Array");
call.addArg(new JNameOf(info, program, arrayType));
- } else if (type instanceof JDeclaredType) {
- // Add the name of the seed function for non-array reference types
+ } else if (type instanceof JClassType) {
+ // Add the name of the seed function for concrete types
call.addArg(new JNameOf(info, program, type));
} else if (type instanceof JPrimitiveType) {
// And give primitive types an illegal, though meaningful, value
call.addArg(program.getLiteralString(info, " "
+ type.getJavahSignatureName()));
}
if (type instanceof JClassType) {
/*
* For non-array classes and enums, determine the class literal of the
* supertype, if there is one. Arrays are excluded because they always
* have Object as their superclass.
*/
JClassType classType = (JClassType) type;
JLiteral superclassLiteral;
if (classType.getSuperClass() != null) {
superclassLiteral = program.getLiteralClass(classType.getSuperClass());
} else {
superclassLiteral = program.getLiteralNull();
}
call.addArg(superclassLiteral);
if (classType instanceof JEnumType) {
JEnumType enumType = (JEnumType) classType;
JMethod valuesMethod = null;
for (JMethod methodIt : enumType.getMethods()) {
if ("values".equals(methodIt.getName())) {
if (methodIt.getParams().size() != 0) {
continue;
}
valuesMethod = methodIt;
break;
}
}
if (valuesMethod == null) {
throw new InternalCompilerException(
"Could not find enum values() method");
}
JsniMethodRef jsniMethodRef = new JsniMethodRef(info, null,
valuesMethod, program.getJavaScriptObject());
call.addArg(jsniMethodRef);
} else if (isEnumOrSubclass) {
// A subclass of an enum class
call.addArg(program.getLiteralNull());
}
} else if (type instanceof JArrayType) {
JArrayType arrayType = (JArrayType) type;
JClassLiteral componentLiteral = program.getLiteralClass(arrayType.getElementType());
call.addArg(componentLiteral);
} else {
assert (type instanceof JInterfaceType || type instanceof JPrimitiveType);
}
+ assert call.getArgs().size() == method.getParams().size() : "Argument / param mismatch "
+ + call.toString() + " versus " + method.toString();
return call;
}
private static String getClassName(String fullName) {
int pos = fullName.lastIndexOf(".");
return fullName.substring(pos + 1);
}
private static String getPackageName(String fullName) {
int pos = fullName.lastIndexOf(".");
return fullName.substring(0, pos + 1);
}
private static String getTypeName(JProgram program, JType type) {
String typeName;
if (type instanceof JArrayType) {
typeName = type.getJsniSignatureName().replace('/', '.');
// Mangle the class name to match hosted mode.
if (program.isJavaScriptObject(((JArrayType) type).getLeafType())) {
typeName = typeName.replace(";", "$;");
}
} else {
typeName = type.getName();
// Mangle the class name to match hosted mode.
if (program.isJavaScriptObject(type)) {
typeName += '$';
}
}
return typeName;
}
private final JField field;
private final JType refType;
/**
* This constructor is only used by {@link JProgram}.
*/
JClassLiteral(SourceInfo sourceInfo, JType type, JField field) {
super(sourceInfo);
refType = type;
this.field = field;
}
/**
* Returns the field holding my allocated object.
*/
public JField getField() {
return field;
}
public JType getRefType() {
return refType;
}
public JType getType() {
return field.getType();
}
public void traverse(JVisitor visitor, Context ctx) {
if (visitor.visit(this, ctx)) {
}
visitor.endVisit(this, ctx);
}
}
| false | true | static JMethodCall computeClassObjectAllocation(JProgram program,
SourceInfo info, JType type) {
String typeName = getTypeName(program, type);
JMethod method = program.getIndexedMethod(type.getClassLiteralFactoryMethod());
/*
* Use the classForEnum() constructor even for enum subtypes to aid in
* pruning supertype data.
*/
boolean isEnumOrSubclass = false;
if (type instanceof JClassType) {
JEnumType maybeEnum = ((JClassType) type).isEnumOrSubclass();
if (maybeEnum != null) {
isEnumOrSubclass = true;
method = program.getIndexedMethod(maybeEnum.getClassLiteralFactoryMethod());
}
}
assert method != null;
JMethodCall call = new JMethodCall(info, null, method);
call.addArgs(program.getLiteralString(info, getPackageName(typeName)),
program.getLiteralString(info, getClassName(typeName)));
if (type instanceof JArrayType) {
// There's only one seed function for all arrays
JDeclaredType arrayType = program.getIndexedType("Array");
call.addArg(new JNameOf(info, program, arrayType));
} else if (type instanceof JDeclaredType) {
// Add the name of the seed function for non-array reference types
call.addArg(new JNameOf(info, program, type));
} else if (type instanceof JPrimitiveType) {
// And give primitive types an illegal, though meaningful, value
call.addArg(program.getLiteralString(info, " "
+ type.getJavahSignatureName()));
}
if (type instanceof JClassType) {
/*
* For non-array classes and enums, determine the class literal of the
* supertype, if there is one. Arrays are excluded because they always
* have Object as their superclass.
*/
JClassType classType = (JClassType) type;
JLiteral superclassLiteral;
if (classType.getSuperClass() != null) {
superclassLiteral = program.getLiteralClass(classType.getSuperClass());
} else {
superclassLiteral = program.getLiteralNull();
}
call.addArg(superclassLiteral);
if (classType instanceof JEnumType) {
JEnumType enumType = (JEnumType) classType;
JMethod valuesMethod = null;
for (JMethod methodIt : enumType.getMethods()) {
if ("values".equals(methodIt.getName())) {
if (methodIt.getParams().size() != 0) {
continue;
}
valuesMethod = methodIt;
break;
}
}
if (valuesMethod == null) {
throw new InternalCompilerException(
"Could not find enum values() method");
}
JsniMethodRef jsniMethodRef = new JsniMethodRef(info, null,
valuesMethod, program.getJavaScriptObject());
call.addArg(jsniMethodRef);
} else if (isEnumOrSubclass) {
// A subclass of an enum class
call.addArg(program.getLiteralNull());
}
} else if (type instanceof JArrayType) {
JArrayType arrayType = (JArrayType) type;
JClassLiteral componentLiteral = program.getLiteralClass(arrayType.getElementType());
call.addArg(componentLiteral);
} else {
assert (type instanceof JInterfaceType || type instanceof JPrimitiveType);
}
return call;
}
| static JMethodCall computeClassObjectAllocation(JProgram program,
SourceInfo info, JType type) {
String typeName = getTypeName(program, type);
JMethod method = program.getIndexedMethod(type.getClassLiteralFactoryMethod());
/*
* Use the classForEnum() constructor even for enum subtypes to aid in
* pruning supertype data.
*/
boolean isEnumOrSubclass = false;
if (type instanceof JClassType) {
JEnumType maybeEnum = ((JClassType) type).isEnumOrSubclass();
if (maybeEnum != null) {
isEnumOrSubclass = true;
method = program.getIndexedMethod(maybeEnum.getClassLiteralFactoryMethod());
}
}
assert method != null;
JMethodCall call = new JMethodCall(info, null, method);
call.addArgs(program.getLiteralString(info, getPackageName(typeName)),
program.getLiteralString(info, getClassName(typeName)));
if (type instanceof JArrayType) {
// There's only one seed function for all arrays
JDeclaredType arrayType = program.getIndexedType("Array");
call.addArg(new JNameOf(info, program, arrayType));
} else if (type instanceof JClassType) {
// Add the name of the seed function for concrete types
call.addArg(new JNameOf(info, program, type));
} else if (type instanceof JPrimitiveType) {
// And give primitive types an illegal, though meaningful, value
call.addArg(program.getLiteralString(info, " "
+ type.getJavahSignatureName()));
}
if (type instanceof JClassType) {
/*
* For non-array classes and enums, determine the class literal of the
* supertype, if there is one. Arrays are excluded because they always
* have Object as their superclass.
*/
JClassType classType = (JClassType) type;
JLiteral superclassLiteral;
if (classType.getSuperClass() != null) {
superclassLiteral = program.getLiteralClass(classType.getSuperClass());
} else {
superclassLiteral = program.getLiteralNull();
}
call.addArg(superclassLiteral);
if (classType instanceof JEnumType) {
JEnumType enumType = (JEnumType) classType;
JMethod valuesMethod = null;
for (JMethod methodIt : enumType.getMethods()) {
if ("values".equals(methodIt.getName())) {
if (methodIt.getParams().size() != 0) {
continue;
}
valuesMethod = methodIt;
break;
}
}
if (valuesMethod == null) {
throw new InternalCompilerException(
"Could not find enum values() method");
}
JsniMethodRef jsniMethodRef = new JsniMethodRef(info, null,
valuesMethod, program.getJavaScriptObject());
call.addArg(jsniMethodRef);
} else if (isEnumOrSubclass) {
// A subclass of an enum class
call.addArg(program.getLiteralNull());
}
} else if (type instanceof JArrayType) {
JArrayType arrayType = (JArrayType) type;
JClassLiteral componentLiteral = program.getLiteralClass(arrayType.getElementType());
call.addArg(componentLiteral);
} else {
assert (type instanceof JInterfaceType || type instanceof JPrimitiveType);
}
assert call.getArgs().size() == method.getParams().size() : "Argument / param mismatch "
+ call.toString() + " versus " + method.toString();
return call;
}
|
diff --git a/src/main/java/org/nuxeo/ecm/core/storage/sql/SQLBinaryManager.java b/src/main/java/org/nuxeo/ecm/core/storage/sql/SQLBinaryManager.java
index 56535e2..0c300c3 100644
--- a/src/main/java/org/nuxeo/ecm/core/storage/sql/SQLBinaryManager.java
+++ b/src/main/java/org/nuxeo/ecm/core/storage/sql/SQLBinaryManager.java
@@ -1,608 +1,608 @@
/*
* (C) Copyright 2010-2011 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* 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.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.storage.sql;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.file.FileCache;
import org.nuxeo.common.file.LRUFileCache;
import org.nuxeo.common.utils.SizeUtils;
import org.nuxeo.ecm.core.storage.StorageException;
import org.nuxeo.ecm.core.storage.sql.jdbc.db.Column;
import org.nuxeo.ecm.core.storage.sql.jdbc.db.Database;
import org.nuxeo.ecm.core.storage.sql.jdbc.db.Table;
import org.nuxeo.ecm.core.storage.sql.jdbc.dialect.Dialect;
import org.nuxeo.runtime.api.DataSourceHelper;
/**
* A Binary Manager that stores binaries as SQL BLOBs.
* <p>
* The BLOBs are cached locally on first access for efficiency.
* <p>
* Because the BLOB length can be accessed independently of the binary stream,
* it is also cached in a simple text file if accessed before the stream.
*/
public class SQLBinaryManager extends DefaultBinaryManager {
private static final Log log = LogFactory.getLog(SQLBinaryManager.class);
public static final String DS_PREFIX = "datasource=";
public static final String TABLE_PREFIX = "table=";
public static final String CACHE_SIZE_PREFIX = "cachesize=";
public static final String DEFAULT_CACHE_SIZE = "10M";
public static final String COL_ID = "id";
public static final String COL_BIN = "bin";
public static final String COL_MARK = "mark"; // for mark & sweep GC
protected static final String LEN_DIGEST_SUFFIX = "-len";
protected String dataSourceName;
protected DataSource dataSource;
protected FileCache fileCache;
protected String checkSql;
protected String putSql;
protected String getSql;
protected String getLengthSql;
protected String gcStartSql;
protected String gcMarkSql;
protected String gcStatsSql;
protected String gcSweepSql;
protected static boolean disableCheckExisting; // for unit tests
protected static boolean resetCache; // for unit tests
@Override
public void initialize(RepositoryDescriptor repositoryDescriptor)
throws IOException {
repositoryName = repositoryDescriptor.name;
descriptor = new BinaryManagerDescriptor();
descriptor.digest = getDigest();
log.info("Repository '" + repositoryDescriptor.name + "' using "
+ getClass().getSimpleName());
dataSourceName = null;
String tableName = null;
String cacheSizeStr = DEFAULT_CACHE_SIZE;
for (String part : repositoryDescriptor.binaryManagerKey.split(",")) {
if (part.startsWith(DS_PREFIX)) {
dataSourceName = part.substring(DS_PREFIX.length()).trim();
}
if (part.startsWith(TABLE_PREFIX)) {
tableName = part.substring(TABLE_PREFIX.length()).trim();
}
if (part.startsWith(CACHE_SIZE_PREFIX)) {
cacheSizeStr = part.substring(CACHE_SIZE_PREFIX.length()).trim();
}
}
if (dataSourceName == null) {
throw new RuntimeException("Missing " + DS_PREFIX
+ " in binaryManager key");
}
if (tableName == null) {
throw new RuntimeException("Missing " + TABLE_PREFIX
+ " in binaryManager key");
}
try {
dataSource = DataSourceHelper.getDataSource(dataSourceName);
} catch (NamingException e) {
throw new IOException("Cannot find datasource: " + dataSourceName,
e);
}
// create the SQL statements used
createSql(tableName);
// create file cache
File dir = File.createTempFile("nxbincache.", "", null);
dir.delete();
dir.mkdir();
dir.deleteOnExit();
long cacheSize = SizeUtils.parseSizeInBytes(cacheSizeStr);
fileCache = new LRUFileCache(dir, cacheSize);
log.info("Using binary cache directory: " + dir.getPath() + " size: "
+ cacheSizeStr);
createGarbageCollector();
}
@Override
protected void createGarbageCollector() {
garbageCollector = new SQLBinaryGarbageCollector(this);
}
protected void createSql(String tableName) throws IOException {
Dialect dialect = getDialect();
Database database = new Database(dialect);
Table table = database.addTable(tableName);
ColumnType dummytype = ColumnType.STRING;
Column idCol = table.addColumn(COL_ID, dummytype, COL_ID, null);
Column binCol = table.addColumn(COL_BIN, dummytype, COL_BIN, null);
Column markCol = table.addColumn(COL_MARK, dummytype, COL_MARK, null);
checkSql = String.format("SELECT 1 FROM %s WHERE %s = ?",
table.getQuotedName(), idCol.getQuotedName());
putSql = String.format("INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)",
table.getQuotedName(), idCol.getQuotedName(),
binCol.getQuotedName(), markCol.getQuotedName());
getSql = String.format("SELECT %s FROM %s WHERE %s = ?",
binCol.getQuotedName(), table.getQuotedName(),
idCol.getQuotedName());
getLengthSql = String.format("SELECT %s(%s) FROM %s WHERE %s = ?",
dialect.getBlobLengthFunction(), binCol.getQuotedName(),
table.getQuotedName(), idCol.getQuotedName());
gcStartSql = String.format("UPDATE %s SET %s = ?",
table.getQuotedName(), markCol.getQuotedName());
gcMarkSql = String.format("UPDATE %s SET %s = ? WHERE %s = ?",
table.getQuotedName(), markCol.getQuotedName(),
idCol.getQuotedName());
gcStatsSql = String.format(
"SELECT COUNT(*), SUM(%s(%s)) FROM %s WHERE %s = ?",
dialect.getBlobLengthFunction(), binCol.getQuotedName(),
table.getQuotedName(), markCol.getQuotedName());
gcSweepSql = String.format("DELETE FROM %s WHERE %s = ?",
table.getQuotedName(), markCol.getQuotedName());
}
protected Dialect getDialect() throws IOException {
Connection connection = null;
try {
connection = dataSource.getConnection();
return Dialect.createDialect(connection, null, null);
} catch (StorageException e) {
throw new IOException(e);
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
}
/**
* Gets the message digest to use to hash binaries.
*/
protected String getDigest() {
return DEFAULT_DIGEST;
}
protected static void logSQL(String sql, Serializable... values) {
if (!log.isTraceEnabled()) {
return;
}
StringBuilder buf = new StringBuilder();
int start = 0;
for (Serializable v : values) {
int index = sql.indexOf('?', start);
if (index == -1) {
// mismatch between number of ? and number of values
break;
}
buf.append(sql, start, index);
buf.append(loggedValue(v));
start = index + 1;
}
buf.append(sql, start, sql.length());
log.trace("(bin) SQL: " + buf.toString());
}
protected static String loggedValue(Serializable value) {
if (value == null) {
return "NULL";
}
if (value instanceof String) {
String v = (String) value;
return "'" + v.replace("'", "''") + "'";
}
return value.toString();
}
@Override
public Binary getBinary(InputStream in) throws IOException {
// write the input stream to a temporary file, while computing a digest
File tmp = fileCache.getTempFile();
OutputStream out = new FileOutputStream(tmp);
String digest;
try {
digest = storeAndDigest(in, out);
} finally {
in.close();
out.close();
}
// store the blob in the SQL database
Connection connection = null;
try {
connection = dataSource.getConnection();
boolean existing;
if (disableCheckExisting) {
// for unit tests
existing = false;
} else {
logSQL(checkSql, digest);
PreparedStatement ps = connection.prepareStatement(checkSql);
ps.setString(1, digest);
ResultSet rs = ps.executeQuery();
existing = rs.next();
ps.close();
}
if (!existing) {
// insert new blob
logSQL(putSql, digest, "somebinary", Boolean.TRUE);
PreparedStatement ps = connection.prepareStatement(putSql);
ps.setString(1, digest);
// needs dbcp 1.4:
// ps.setBlob(2, new FileInputStream(file), file.length());
FileInputStream tmpis = new FileInputStream(tmp);
try {
ps.setBinaryStream(2, tmpis, (int) tmp.length());
+ ps.setBoolean(3, true); // mark new additions for GC
+ try {
+ ps.execute();
+ } catch (SQLException e) {
+ if (!isDuplicateKeyException(e)) {
+ throw e;
+ }
+ }
} finally {
tmpis.close();
}
- ps.setBoolean(3, true); // mark new additions for GC
- try {
- ps.execute();
- } catch (SQLException e) {
- if (!isDuplicateKeyException(e)) {
- throw e;
- }
- }
ps.close();
}
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
// register the file in the file cache if all went well
File file = fileCache.putFile(digest, tmp);
return new Binary(file, digest, repositoryName);
}
protected boolean isDuplicateKeyException(SQLException e) {
String sqlState = e.getSQLState();
if ("23000".equals(sqlState)) {
// MySQL: Duplicate entry ... for key ...
// Oracle: unique constraint ... violated
// SQL Server: Violation of PRIMARY KEY constraint
return true;
}
if ("23001".equals(sqlState)) {
// H2: Unique index or primary key violation
return true;
}
if ("23505".equals(sqlState)) {
// PostgreSQL: duplicate key value violates unique constraint
return true;
}
return false;
}
@Override
public Binary getBinary(String digest) {
if (resetCache) {
// for unit tests
resetCache = false;
fileCache.clear();
}
// check in the cache
File file = fileCache.getFile(digest);
if (file == null) {
return new SQLLazyBinary(digest, fileCache, dataSource, getSql,
getLengthSql);
} else {
return new Binary(file, digest, repositoryName);
}
}
public static class SQLLazyBinary extends LazyBinary {
private static final long serialVersionUID = 1L;
protected final DataSource dataSource;
protected final String getSql;
protected final String getLengthSql;
public SQLLazyBinary(String digest, FileCache fileCache,
DataSource dataSource, String getSql, String getLengthSql) {
super(digest, fileCache);
this.dataSource = dataSource;
this.getSql = getSql;
this.getLengthSql = getLengthSql;
}
@Override
protected boolean fetchFile(File tmp) {
Connection connection = null;
try {
connection = dataSource.getConnection();
logSQL(getSql, digest);
PreparedStatement ps = connection.prepareStatement(getSql);
ps.setString(1, digest);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
log.error("Unknown binary: " + digest);
return false;
}
InputStream in = rs.getBinaryStream(1);
if (in == null) {
log.error("Missing binary: " + digest);
return false;
}
// store in file
OutputStream out = null;
try {
out = new FileOutputStream(tmp);
IOUtils.copy(in, out);
} finally {
in.close();
if (out != null) {
out.close();
}
}
return true;
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
}
@Override
protected Long fetchLength() {
Connection connection = null;
try {
connection = dataSource.getConnection();
logSQL(getLengthSql, digest);
PreparedStatement ps = connection.prepareStatement(getLengthSql);
ps.setString(1, digest);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
log.error("Unknown binary: " + digest);
return null;
}
return Long.valueOf(rs.getLong(1));
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
}
}
public static class SQLBinaryGarbageCollector implements
BinaryGarbageCollector {
protected final SQLBinaryManager binaryManager;
protected volatile long startTime;
protected BinaryManagerStatus status;
public SQLBinaryGarbageCollector(SQLBinaryManager binaryManager) {
this.binaryManager = binaryManager;
}
@Override
public String getId() {
return "datasource:" + binaryManager.dataSourceName;
}
@Override
public BinaryManagerStatus getStatus() {
return status;
}
@Override
public boolean isInProgress() {
// volatile as this is designed to be called from another thread
return startTime != 0;
}
@Override
public void start() {
if (startTime != 0) {
throw new RuntimeException("Alread started");
}
startTime = System.currentTimeMillis();
status = new BinaryManagerStatus();
Connection connection = null;
PreparedStatement ps = null;
try {
connection = binaryManager.dataSource.getConnection();
logSQL(binaryManager.gcStartSql, Boolean.FALSE);
ps = connection.prepareStatement(binaryManager.gcStartSql);
ps.setBoolean(1, false); // clear marks
int n = ps.executeUpdate();
logSQL(" -> ? rows", Long.valueOf(n));
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
log.error(e, e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
}
@Override
public void mark(String digest) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = binaryManager.dataSource.getConnection();
logSQL(binaryManager.gcMarkSql, Boolean.TRUE, digest);
ps = connection.prepareStatement(binaryManager.gcMarkSql);
ps.setBoolean(1, true); // mark
ps.setString(2, digest);
ps.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
log.error(e, e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
}
@Override
public void stop(boolean delete) {
if (startTime == 0) {
throw new RuntimeException("Not started");
}
Connection connection = null;
PreparedStatement ps = null;
try {
connection = binaryManager.dataSource.getConnection();
// stats
logSQL(binaryManager.gcStatsSql, Boolean.TRUE);
ps = connection.prepareStatement(binaryManager.gcStatsSql);
ps.setBoolean(1, true); // marked
ResultSet rs = ps.executeQuery();
rs.next();
status.numBinaries = rs.getLong(1);
status.sizeBinaries = rs.getLong(2);
logSQL(" -> ?, ?", Long.valueOf(status.numBinaries),
Long.valueOf(status.sizeBinaries));
logSQL(binaryManager.gcStatsSql, Boolean.FALSE);
ps.setBoolean(1, false); // unmarked
rs = ps.executeQuery();
rs.next();
status.numBinariesGC = rs.getLong(1);
status.sizeBinariesGC = rs.getLong(2);
logSQL(" -> ?, ?", Long.valueOf(status.numBinariesGC),
Long.valueOf(status.sizeBinariesGC));
if (delete) {
// sweep
ps.close();
logSQL(binaryManager.gcSweepSql, Boolean.FALSE);
ps = connection.prepareStatement(binaryManager.gcSweepSql);
ps.setBoolean(1, false); // sweep unmarked
int n = ps.executeUpdate();
logSQL(" -> ? rows", Long.valueOf(n));
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
log.error(e, e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
status.gcDuration = System.currentTimeMillis() - startTime;
startTime = 0;
}
}
}
| false | true | public Binary getBinary(InputStream in) throws IOException {
// write the input stream to a temporary file, while computing a digest
File tmp = fileCache.getTempFile();
OutputStream out = new FileOutputStream(tmp);
String digest;
try {
digest = storeAndDigest(in, out);
} finally {
in.close();
out.close();
}
// store the blob in the SQL database
Connection connection = null;
try {
connection = dataSource.getConnection();
boolean existing;
if (disableCheckExisting) {
// for unit tests
existing = false;
} else {
logSQL(checkSql, digest);
PreparedStatement ps = connection.prepareStatement(checkSql);
ps.setString(1, digest);
ResultSet rs = ps.executeQuery();
existing = rs.next();
ps.close();
}
if (!existing) {
// insert new blob
logSQL(putSql, digest, "somebinary", Boolean.TRUE);
PreparedStatement ps = connection.prepareStatement(putSql);
ps.setString(1, digest);
// needs dbcp 1.4:
// ps.setBlob(2, new FileInputStream(file), file.length());
FileInputStream tmpis = new FileInputStream(tmp);
try {
ps.setBinaryStream(2, tmpis, (int) tmp.length());
} finally {
tmpis.close();
}
ps.setBoolean(3, true); // mark new additions for GC
try {
ps.execute();
} catch (SQLException e) {
if (!isDuplicateKeyException(e)) {
throw e;
}
}
ps.close();
}
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
// register the file in the file cache if all went well
File file = fileCache.putFile(digest, tmp);
return new Binary(file, digest, repositoryName);
}
| public Binary getBinary(InputStream in) throws IOException {
// write the input stream to a temporary file, while computing a digest
File tmp = fileCache.getTempFile();
OutputStream out = new FileOutputStream(tmp);
String digest;
try {
digest = storeAndDigest(in, out);
} finally {
in.close();
out.close();
}
// store the blob in the SQL database
Connection connection = null;
try {
connection = dataSource.getConnection();
boolean existing;
if (disableCheckExisting) {
// for unit tests
existing = false;
} else {
logSQL(checkSql, digest);
PreparedStatement ps = connection.prepareStatement(checkSql);
ps.setString(1, digest);
ResultSet rs = ps.executeQuery();
existing = rs.next();
ps.close();
}
if (!existing) {
// insert new blob
logSQL(putSql, digest, "somebinary", Boolean.TRUE);
PreparedStatement ps = connection.prepareStatement(putSql);
ps.setString(1, digest);
// needs dbcp 1.4:
// ps.setBlob(2, new FileInputStream(file), file.length());
FileInputStream tmpis = new FileInputStream(tmp);
try {
ps.setBinaryStream(2, tmpis, (int) tmp.length());
ps.setBoolean(3, true); // mark new additions for GC
try {
ps.execute();
} catch (SQLException e) {
if (!isDuplicateKeyException(e)) {
throw e;
}
}
} finally {
tmpis.close();
}
ps.close();
}
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e, e);
}
}
}
// register the file in the file cache if all went well
File file = fileCache.putFile(digest, tmp);
return new Binary(file, digest, repositoryName);
}
|
diff --git a/sudoku/sudoku_v1.java b/sudoku/sudoku_v1.java
index cb3c777..e0cb2cd 100644
--- a/sudoku/sudoku_v1.java
+++ b/sudoku/sudoku_v1.java
@@ -1,110 +1,110 @@
import java.io.*;
class sudoku_v1 {
int[][] R, C;
public void genmat() {
R = new int[324][9];
C = new int[729][4];
int[] nr = new int[324];
int i, j, k, r, c, c2, r2;
for (i = r = 0; i < 9; ++i) // generate c[729][4]
for (j = 0; j < 9; ++j)
for (k = 0; k < 9; ++k) { // this "9" means each cell has 9 possible numbers
C[r][0] = 9 * i + j; // row-column constraint
C[r][1] = (i/3*3 + j/3) * 9 + k + 81; // box-number constraint
C[r][2] = 9 * i + k + 162; // row-number constraint
C[r][3] = 9 * j + k + 243; // col-number constraint
++r;
}
for (c = 0; c < 324; ++c) nr[c] = 0;
for (r = 0; r < 729; ++r) // generate r[][] from c[][]
for (c2 = 0; c2 < 4; ++c2) {
k = C[r][c2]; R[k][nr[k]++] = r;
}
}
private int sd_update(int[] sr, int[] sc, int r, int v) {
int c2, min = 10, min_c = 0;
for (c2 = 0; c2 < 4; ++c2) sc[C[r][c2]] += v<<7;
for (c2 = 0; c2 < 4; ++c2) { // update # available choices
int r2, rr, cc2, c = C[r][c2];
if (v > 0) { // move forward
for (r2 = 0; r2 < 9; ++r2) {
if (sr[rr = R[c][r2]]++ != 0) continue; // update the row status
for (cc2 = 0; cc2 < 4; ++cc2) {
int cc = C[rr][cc2];
if (--sc[cc] < min) { // update # allowed choices
min = sc[cc]; min_c = cc; // register the minimum number
}
}
}
} else { // revert
int[] p;
for (r2 = 0; r2 < 9; ++r2) {
if (--sr[rr = R[c][r2]] != 0) continue; // update the row status
p = C[rr]; ++sc[p[0]]; ++sc[p[1]]; ++sc[p[2]]; ++sc[p[3]]; // update the count array
}
}
}
return min<<16 | min_c; // return the col that has been modified and with the minimal available choices
}
// solve a Sudoku; _s is the standard dot/number representation
public int solve(String _s) {
int i, j, r, c, r2, dir, cand, n = 0, min, hints = 0; // dir=1: forward; dir=-1: backtrack
int[] sr = new int[729];
int[] cr = new int[81];
int[] sc = new int[324];
int[] cc = new int[81];
int[] out = new int[81];
for (r = 0; r < 729; ++r) sr[r] = 0; // no row is forbidden
for (c = 0; c < 324; ++c) sc[c] = 0<<7|9; // 9 allowed choices; no constraint has been used
for (i = 0; i < 81; ++i) {
int a = _s.charAt(i) >= '1' && _s.charAt(i) <= '9'? _s.codePointAt(i) - '1' : -1; // number from -1 to 8
if (a >= 0) sd_update(sr, sc, i * 9 + a, 1); // set the choice
if (a >= 0) ++hints; // count the number of hints
cr[i] = cc[i] = -1; out[i] = a;
}
i = 0; dir = 1; cand = 10<<16|0;
for (;;) {
while (i >= 0 && i < 81 - hints) { // maximum 81-hints steps
if (dir == 1) {
min = cand>>16; cc[i] = cand&0xffff;
if (min > 1) {
for (c = 0; c < 324; ++c) {
if (sc[c] < min) {
min = sc[c]; cc[i] = c; // choose the top constraint
if (min <= 1) break; // this is for acceleration; slower without this line
}
}
}
if (min == 0 || min == 10) cr[i--] = dir = -1; // backtrack
}
c = cc[i];
if (dir == -1 && cr[i] >= 0) sd_update(sr, sc, R[c][cr[i]], -1); // revert the choice
for (r2 = cr[i] + 1; r2 < 9; ++r2) // search for the choice to make
if (sr[R[c][r2]] == 0) break; // found if the state equals 0
if (r2 < 9) {
cand = sd_update(sr, sc, R[c][r2], 1); // set the choice
cr[i++] = r2; dir = 1; // moving forward
} else cr[i--] = dir = -1; // backtrack
}
if (i < 0) break;
char[] y = new char[81];
- for (j = 0; j < 81; ++j) y[i] = (char)(out[i] + '1');
+ for (j = 0; j < 81; ++j) y[j] = (char)(out[j] + '1');
for (j = 0; j < i; ++j) { r = R[cc[j]][cr[j]]; y[r/9] = (char)(r%9 + '1'); }
System.out.println(new String(y));
++n; --i; dir = -1; // backtrack
}
return n;
}
public static void main(String[] args) throws Exception {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
sudoku_v1 a = new sudoku_v1();
String l;
a.genmat();
while ((l = stdin.readLine()) != null)
if (l.length() >= 81) {
a.solve(l);
System.out.println();
}
}
}
| true | true | public int solve(String _s) {
int i, j, r, c, r2, dir, cand, n = 0, min, hints = 0; // dir=1: forward; dir=-1: backtrack
int[] sr = new int[729];
int[] cr = new int[81];
int[] sc = new int[324];
int[] cc = new int[81];
int[] out = new int[81];
for (r = 0; r < 729; ++r) sr[r] = 0; // no row is forbidden
for (c = 0; c < 324; ++c) sc[c] = 0<<7|9; // 9 allowed choices; no constraint has been used
for (i = 0; i < 81; ++i) {
int a = _s.charAt(i) >= '1' && _s.charAt(i) <= '9'? _s.codePointAt(i) - '1' : -1; // number from -1 to 8
if (a >= 0) sd_update(sr, sc, i * 9 + a, 1); // set the choice
if (a >= 0) ++hints; // count the number of hints
cr[i] = cc[i] = -1; out[i] = a;
}
i = 0; dir = 1; cand = 10<<16|0;
for (;;) {
while (i >= 0 && i < 81 - hints) { // maximum 81-hints steps
if (dir == 1) {
min = cand>>16; cc[i] = cand&0xffff;
if (min > 1) {
for (c = 0; c < 324; ++c) {
if (sc[c] < min) {
min = sc[c]; cc[i] = c; // choose the top constraint
if (min <= 1) break; // this is for acceleration; slower without this line
}
}
}
if (min == 0 || min == 10) cr[i--] = dir = -1; // backtrack
}
c = cc[i];
if (dir == -1 && cr[i] >= 0) sd_update(sr, sc, R[c][cr[i]], -1); // revert the choice
for (r2 = cr[i] + 1; r2 < 9; ++r2) // search for the choice to make
if (sr[R[c][r2]] == 0) break; // found if the state equals 0
if (r2 < 9) {
cand = sd_update(sr, sc, R[c][r2], 1); // set the choice
cr[i++] = r2; dir = 1; // moving forward
} else cr[i--] = dir = -1; // backtrack
}
if (i < 0) break;
char[] y = new char[81];
for (j = 0; j < 81; ++j) y[i] = (char)(out[i] + '1');
for (j = 0; j < i; ++j) { r = R[cc[j]][cr[j]]; y[r/9] = (char)(r%9 + '1'); }
System.out.println(new String(y));
++n; --i; dir = -1; // backtrack
}
return n;
}
| public int solve(String _s) {
int i, j, r, c, r2, dir, cand, n = 0, min, hints = 0; // dir=1: forward; dir=-1: backtrack
int[] sr = new int[729];
int[] cr = new int[81];
int[] sc = new int[324];
int[] cc = new int[81];
int[] out = new int[81];
for (r = 0; r < 729; ++r) sr[r] = 0; // no row is forbidden
for (c = 0; c < 324; ++c) sc[c] = 0<<7|9; // 9 allowed choices; no constraint has been used
for (i = 0; i < 81; ++i) {
int a = _s.charAt(i) >= '1' && _s.charAt(i) <= '9'? _s.codePointAt(i) - '1' : -1; // number from -1 to 8
if (a >= 0) sd_update(sr, sc, i * 9 + a, 1); // set the choice
if (a >= 0) ++hints; // count the number of hints
cr[i] = cc[i] = -1; out[i] = a;
}
i = 0; dir = 1; cand = 10<<16|0;
for (;;) {
while (i >= 0 && i < 81 - hints) { // maximum 81-hints steps
if (dir == 1) {
min = cand>>16; cc[i] = cand&0xffff;
if (min > 1) {
for (c = 0; c < 324; ++c) {
if (sc[c] < min) {
min = sc[c]; cc[i] = c; // choose the top constraint
if (min <= 1) break; // this is for acceleration; slower without this line
}
}
}
if (min == 0 || min == 10) cr[i--] = dir = -1; // backtrack
}
c = cc[i];
if (dir == -1 && cr[i] >= 0) sd_update(sr, sc, R[c][cr[i]], -1); // revert the choice
for (r2 = cr[i] + 1; r2 < 9; ++r2) // search for the choice to make
if (sr[R[c][r2]] == 0) break; // found if the state equals 0
if (r2 < 9) {
cand = sd_update(sr, sc, R[c][r2], 1); // set the choice
cr[i++] = r2; dir = 1; // moving forward
} else cr[i--] = dir = -1; // backtrack
}
if (i < 0) break;
char[] y = new char[81];
for (j = 0; j < 81; ++j) y[j] = (char)(out[j] + '1');
for (j = 0; j < i; ++j) { r = R[cc[j]][cr[j]]; y[r/9] = (char)(r%9 + '1'); }
System.out.println(new String(y));
++n; --i; dir = -1; // backtrack
}
return n;
}
|
diff --git a/modules/xdr/src/main/java/org/dcache/xdr/gss/RpcGssCall.java b/modules/xdr/src/main/java/org/dcache/xdr/gss/RpcGssCall.java
index 813ad9aa61..b41662b74a 100644
--- a/modules/xdr/src/main/java/org/dcache/xdr/gss/RpcGssCall.java
+++ b/modules/xdr/src/main/java/org/dcache/xdr/gss/RpcGssCall.java
@@ -1,125 +1,125 @@
package org.dcache.xdr.gss;
import java.io.IOException;
import org.dcache.xdr.*;
import org.glassfish.grizzly.Buffer;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.MessageProp;
import org.ietf.jgss.GSSContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An extention of {@link RpcCall} which Wrap/Unwrap the data according GSS QOS.
* The supported QOS are: NONE, INTEGRITY and PRIVACY as specified in rfs 2203.
*
* @since 0.0.4
*/
public class RpcGssCall extends RpcCall {
private final static Logger _log = LoggerFactory.getLogger(RpcGssCall.class);
private final GSSContext _gssContext;
private final MessageProp _mop;
public RpcGssCall(RpcCall call, GSSContext gssContext, MessageProp mop) {
super(call.getXid(), call.getProgram(), call.getProgramVersion(),
call.getProcedure(), call.getCredential(), call.getXdr(), call.getTransport());
_gssContext = gssContext;
_mop = mop;
}
@Override
public void retrieveCall(XdrAble args) throws OncRpcException, IOException {
try {
RpcAuthGss authGss = (RpcAuthGss) getCredential();
_log.debug("Call with GSS service: {}", authGss.getService());
XdrDecodingStream xdr;
switch (authGss.getService()) {
case RpcGssService.RPC_GSS_SVC_NONE:
super.retrieveCall(args);
break;
case RpcGssService.RPC_GSS_SVC_INTEGRITY:
DataBodyIntegrity integData = new DataBodyIntegrity();
super.retrieveCall(integData);
byte[] integBytes = integData.getData();
byte[] checksum = integData.getChecksum();
_gssContext.verifyMIC(checksum, 0, checksum.length,
integBytes, 0, integBytes.length, _mop);
xdr = new XdrBuffer(integBytes);
xdr.beginDecoding();
xdr.xdrDecodeInt(); // first 4 bytes of data is the sequence number. Skip it.
args.xdrDecode(xdr);
xdr.endDecoding();
break;
case RpcGssService.RPC_GSS_SVC_PRIVACY:
DataBodyPrivacy privacyData = new DataBodyPrivacy();
super.retrieveCall(privacyData);
byte[] privacyBytes = privacyData.getData();
byte[] rawData = _gssContext.unwrap(privacyBytes, 0, privacyBytes.length, _mop);
xdr = new XdrBuffer(rawData);
xdr.beginDecoding();
xdr.xdrDecodeInt(); // first 4 bytes of data is the sequence number. Skip it.
args.xdrDecode(xdr);
xdr.endDecoding();
}
} catch (GSSException e) {
_log.warn("GSS error: {}", e.getMessage());
throw new RpcAuthException( "GSS error: " + e.getMessage() ,
new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
}
}
@Override
public void acceptedReply(int state, XdrAble reply) {
try {
RpcAuthGss authGss = (RpcAuthGss) getCredential();
_log.debug("Reply with GSS service: {}", authGss.getService());
XdrEncodingStream xdr;
switch (authGss.getService()) {
case RpcGssService.RPC_GSS_SVC_NONE:
super.acceptedReply(state, reply);
break;
case RpcGssService.RPC_GSS_SVC_INTEGRITY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer b = ((Xdr)xdr).body();
- byte[] integBytes = new byte[b.limit()];
+ byte[] integBytes = new byte[b.remaining()];
b.get(integBytes);
byte[] checksum = _gssContext.getMIC(integBytes, 0, integBytes.length, _mop);
DataBodyIntegrity integData = new DataBodyIntegrity(integBytes, checksum);
super.acceptedReply(state, integData);
break;
case RpcGssService.RPC_GSS_SVC_PRIVACY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer bp = ((Xdr)xdr).body();
- byte[] rawData = new byte[bp.limit()];
+ byte[] rawData = new byte[bp.remaining()];
bp.get(rawData);
byte[] privacyBytes = _gssContext.wrap(rawData, 0, rawData.length, _mop);
DataBodyPrivacy privacyData = new DataBodyPrivacy(privacyBytes);
super.acceptedReply(state, privacyData);
break;
}
} catch (IOException e) {
_log.warn( "IO error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (OncRpcException e) {
_log.warn("RPC error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (GSSException e) {
_log.warn("GSS error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
}
}
}
| false | true | public void acceptedReply(int state, XdrAble reply) {
try {
RpcAuthGss authGss = (RpcAuthGss) getCredential();
_log.debug("Reply with GSS service: {}", authGss.getService());
XdrEncodingStream xdr;
switch (authGss.getService()) {
case RpcGssService.RPC_GSS_SVC_NONE:
super.acceptedReply(state, reply);
break;
case RpcGssService.RPC_GSS_SVC_INTEGRITY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer b = ((Xdr)xdr).body();
byte[] integBytes = new byte[b.limit()];
b.get(integBytes);
byte[] checksum = _gssContext.getMIC(integBytes, 0, integBytes.length, _mop);
DataBodyIntegrity integData = new DataBodyIntegrity(integBytes, checksum);
super.acceptedReply(state, integData);
break;
case RpcGssService.RPC_GSS_SVC_PRIVACY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer bp = ((Xdr)xdr).body();
byte[] rawData = new byte[bp.limit()];
bp.get(rawData);
byte[] privacyBytes = _gssContext.wrap(rawData, 0, rawData.length, _mop);
DataBodyPrivacy privacyData = new DataBodyPrivacy(privacyBytes);
super.acceptedReply(state, privacyData);
break;
}
} catch (IOException e) {
_log.warn( "IO error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (OncRpcException e) {
_log.warn("RPC error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (GSSException e) {
_log.warn("GSS error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
}
}
| public void acceptedReply(int state, XdrAble reply) {
try {
RpcAuthGss authGss = (RpcAuthGss) getCredential();
_log.debug("Reply with GSS service: {}", authGss.getService());
XdrEncodingStream xdr;
switch (authGss.getService()) {
case RpcGssService.RPC_GSS_SVC_NONE:
super.acceptedReply(state, reply);
break;
case RpcGssService.RPC_GSS_SVC_INTEGRITY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer b = ((Xdr)xdr).body();
byte[] integBytes = new byte[b.remaining()];
b.get(integBytes);
byte[] checksum = _gssContext.getMIC(integBytes, 0, integBytes.length, _mop);
DataBodyIntegrity integData = new DataBodyIntegrity(integBytes, checksum);
super.acceptedReply(state, integData);
break;
case RpcGssService.RPC_GSS_SVC_PRIVACY:
xdr = new XdrBuffer(256 * 1024);
xdr.beginEncoding();
xdr.xdrEncodeInt(authGss.getSequence());
reply.xdrEncode(xdr);
xdr.endEncoding();
Buffer bp = ((Xdr)xdr).body();
byte[] rawData = new byte[bp.remaining()];
bp.get(rawData);
byte[] privacyBytes = _gssContext.wrap(rawData, 0, rawData.length, _mop);
DataBodyPrivacy privacyData = new DataBodyPrivacy(privacyBytes);
super.acceptedReply(state, privacyData);
break;
}
} catch (IOException e) {
_log.warn( "IO error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (OncRpcException e) {
_log.warn("RPC error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
} catch (GSSException e) {
_log.warn("GSS error: {}", e.getMessage());
super.reject(RpcRejectStatus.AUTH_ERROR, new RpcAuthError(RpcAuthStat.RPCSEC_GSS_CTXPROBLEM));
}
}
|
diff --git a/java/core/src/test/java/li/rudin/arduino/core/test/mock/ArduinoEthernetDeviceServer.java b/java/core/src/test/java/li/rudin/arduino/core/test/mock/ArduinoEthernetDeviceServer.java
index 83b64d8..b825a14 100644
--- a/java/core/src/test/java/li/rudin/arduino/core/test/mock/ArduinoEthernetDeviceServer.java
+++ b/java/core/src/test/java/li/rudin/arduino/core/test/mock/ArduinoEthernetDeviceServer.java
@@ -1,143 +1,143 @@
package li.rudin.arduino.core.test.mock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import li.rudin.arduino.core.util.Message;
import li.rudin.arduino.core.util.MessageParser;
public class ArduinoEthernetDeviceServer implements Runnable
{
public ArduinoEthernetDeviceServer(int port)
{
this.port = port;
}
private final Map<String, String> valueMap = new HashMap<>();
private final int port;
private boolean run = false;
private ServerSocket serversocket;
private List<Client> clients = new CopyOnWriteArrayList<>();
public void start() throws IOException
{
run = true;
serversocket = new ServerSocket(port);
new Thread(this).start();
}
public void stop() throws IOException
{
run = false;
serversocket.close();
for (Client c: clients)
c.stop();
}
public void send(String key, String value) throws IOException
{
for (Client c: clients)
c.send(key, value);
}
@Override
public void run()
{
while(run)
{
try
{
Socket socket = serversocket.accept();
new Client(socket);
}
catch (Exception e)
{
return;
}
}
}
public Stack<Message> getRxMessages()
{
return rxMessages;
}
public Map<String, String> getValueMap()
{
return valueMap;
}
private final Stack<Message> rxMessages = new Stack<>();
class Client implements Runnable
{
public Client(Socket socket) throws IOException
{
input = socket.getInputStream();
output = socket.getOutputStream();
clients.add(this);
new Thread(this).start();
}
private final InputStream input;
private final OutputStream output;
public void send(String key, String value) throws IOException
{
output.write( new Message(key, value).toString().getBytes() );
}
public void stop() throws IOException
{
input.close();
}
@Override
public void run()
{
byte[] buffer = new byte[1024];
while(run)
{
try
{
int count = input.read(buffer);
List<Message> list = MessageParser.parse(buffer, count);
for (Message msg: list)
{
- if (msg.value.equals("get"))
+ if (msg.value.equals("get") && valueMap.containsKey(msg.key))
{
//Get message
send(msg.key, valueMap.get(msg.key));
}
else
rxMessages.push(msg);
}
}
catch (Exception e)
{
return;
}
}
}
}
}
| true | true | public void run()
{
byte[] buffer = new byte[1024];
while(run)
{
try
{
int count = input.read(buffer);
List<Message> list = MessageParser.parse(buffer, count);
for (Message msg: list)
{
if (msg.value.equals("get"))
{
//Get message
send(msg.key, valueMap.get(msg.key));
}
else
rxMessages.push(msg);
}
}
catch (Exception e)
{
return;
}
}
}
| public void run()
{
byte[] buffer = new byte[1024];
while(run)
{
try
{
int count = input.read(buffer);
List<Message> list = MessageParser.parse(buffer, count);
for (Message msg: list)
{
if (msg.value.equals("get") && valueMap.containsKey(msg.key))
{
//Get message
send(msg.key, valueMap.get(msg.key));
}
else
rxMessages.push(msg);
}
}
catch (Exception e)
{
return;
}
}
}
|
diff --git a/app/controllers/CronManager.java b/app/controllers/CronManager.java
index a221e63..da9f186 100644
--- a/app/controllers/CronManager.java
+++ b/app/controllers/CronManager.java
@@ -1,78 +1,78 @@
package controllers;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import common.reflection.ReflectionUtils;
import common.request.Headers;
import cron.Job;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import tasks.TaskContext;
/**
* This class is responsible for relaying a GET request to an appropriate {@link Job}.
* The GET request is made by cron service.
* <p>
* The job to run is determined from the request url. For example, the request url
* <code>/cron/foo/bar</code> will be interpreted as to run <code>cron.fool.bar</code>.
*
* @author syyang
*/
public class CronManager extends Controller {
public static final String pJOB_NAME = "jobName";
public static void process() {
if (Play.mode.isProd() && !isRequestFromCronService()) {
Logger.warn("CronManager: request is not from cron service: " + request.url);
- return;
+ forbidden();
}
Job job = null;
try {
String className = getJobClassName(request.url);
job = ReflectionUtils.newInstance(Job.class, className);
} catch (Exception e) {
Logger.error("CronManager failed to instantiate: "+request.url, e);
- return;
+ error(e);
}
process(job, request.params.allSimple());
}
private static void process(Job job, Map<String, String> jobData) {
assert job != null : "Job can't be null";
assert jobData != null : "Job data can't be null";
String jobName = job.getClass().getSimpleName();
try {
job.execute(jobData);
Logger.info("CronManager successfully executed: " + jobName);
} catch (Throwable t) {
// TODO (syyang): we should send out a gack here...
Logger.error("CronManager failed to execute: " + jobName, t);
// queued tasks rely on propagating the exception for retry
Throwables.propagate(t);
}
}
/**
* Gets the full job class name from the request url.
*/
public static String getJobClassName(String requestUrl) {
Preconditions.checkNotNull(requestUrl, "request url can't be null");
// skip the first "/" and replace the remaining "/" with "."
// e.g. /cron/foo/bar will be transformed to cron.foo.bar
return requestUrl.substring(1).replace('/', '.');
}
private static boolean isRequestFromCronService() {
String isCron = Headers.first(request, Headers.CRON);
return "true".equals(isCron);
}
}
| false | true | public static void process() {
if (Play.mode.isProd() && !isRequestFromCronService()) {
Logger.warn("CronManager: request is not from cron service: " + request.url);
return;
}
Job job = null;
try {
String className = getJobClassName(request.url);
job = ReflectionUtils.newInstance(Job.class, className);
} catch (Exception e) {
Logger.error("CronManager failed to instantiate: "+request.url, e);
return;
}
process(job, request.params.allSimple());
}
| public static void process() {
if (Play.mode.isProd() && !isRequestFromCronService()) {
Logger.warn("CronManager: request is not from cron service: " + request.url);
forbidden();
}
Job job = null;
try {
String className = getJobClassName(request.url);
job = ReflectionUtils.newInstance(Job.class, className);
} catch (Exception e) {
Logger.error("CronManager failed to instantiate: "+request.url, e);
error(e);
}
process(job, request.params.allSimple());
}
|
diff --git a/src/main/java/org/jenkinsci/constant_pool_scanner/ConstantPoolScanner.java b/src/main/java/org/jenkinsci/constant_pool_scanner/ConstantPoolScanner.java
index d2a0864..d194ad1 100644
--- a/src/main/java/org/jenkinsci/constant_pool_scanner/ConstantPoolScanner.java
+++ b/src/main/java/org/jenkinsci/constant_pool_scanner/ConstantPoolScanner.java
@@ -1,257 +1,259 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.jenkinsci.constant_pool_scanner;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Set;
import java.util.TreeSet;
import static org.jenkinsci.constant_pool_scanner.ConstantType.*;
/**
* Streaming parser of the constant pool in a Java class file.
*
* This might be used for dependency analysis, class loader optimizations, etc.
* @see <a href="http://hg.netbeans.org/main-silver/raw-file/4a24ea1d4a94/nbbuild/antsrc/org/netbeans/nbbuild/VerifyClassLinkage.java">original sources</a>
*/
public class ConstantPoolScanner {
/**
* Examines the constant pool of a class file and looks for references to other classes.
* @param data a Java class file
* @return a (sorted) set of binary class names (e.g. {@code some.pkg.Outer$Inner})
* @throws IOException in case of malformed bytecode
*/
public static Set<String> dependencies(byte[] data) throws IOException {
return dependencies(new ByteArrayInputStream(data));
}
/**
* Examines the constant pool of a class file and looks for references to other classes.
* @param in Stream that reads a Java class file
* @return a (sorted) set of binary class names (e.g. {@code some.pkg.Outer$Inner})
* @throws IOException in case of malformed bytecode
*/
public static Set<String> dependencies(InputStream in) throws IOException {
ConstantPool pool = parse(in,CLASS,NAME_AND_TYPE);
Set<String> result = new TreeSet<String>();
for (ClassConstant cc : pool.list(ClassConstant.class)) {
String s = cc.get();
while (s.charAt(0) == '[') {
// array type
s = s.substring(1);
}
if (s.length() == 1) {
// primitive
continue;
}
String c;
if (s.charAt(s.length() - 1) == ';' && s.charAt(0) == 'L') {
// Uncommon but seems sometimes this happens.
c = s.substring(1, s.length() - 1);
} else {
c = s;
}
result.add(c.replace('/', '.'));
}
for (NameAndTypeConstant cc : pool.list(NameAndTypeConstant.class)) {
String s = cc.getDescriptor();
int idx = 0;
while ((idx = s.indexOf('L', idx)) != -1) {
int semi = s.indexOf(';', idx);
if (semi == -1) {
throw new IOException("Invalid type or descriptor: " + s);
}
result.add(s.substring(idx + 1, semi).replace('/', '.'));
idx = semi;
}
}
return result;
}
private ConstantPoolScanner() {
}
/**
* Parses a class file and invokes the visitor with constants.
*/
public static ConstantPool parse(byte[] source, ConstantType... types) throws IOException {
return parse(new ByteArrayInputStream(source),types);
}
/**
* Parses a class file and invokes the visitor with constants.
*/
public static ConstantPool parse(InputStream source, ConstantType... types) throws IOException {
return parse(new DataInputStream(source),Arrays.asList(types));
}
/**
* Parses a class file and invokes the visitor with constants.
*/
public static ConstantPool parse(DataInput s, Collection<ConstantType> _collect) throws IOException {
skip(s,8); // magic, minor_version, major_version
int size = s.readUnsignedShort() - 1; // constantPoolCount
ConstantPool pool = new ConstantPool(size);
// figure out all the types of constants we need to collect
final EnumSet<ConstantType> collect = transitiveClosureOf(_collect);
for (int i = 0; i < size; i++) {
int tag = s.readByte();
switch (tag) {
case 1: // CONSTANT_Utf8
if (collect.contains(UTF8))
pool.utf8At(i).actual = s.readUTF();
else
skip(s,s.readUnsignedShort());
break;
case 7: // CONSTANT_Class
if (collect.contains(CLASS))
pool.classAt(i).set(pool.utf8At(readIndex(s)));
else
skip(s,2);
break;
case 3: // CONSTANT_Integer
if (collect.contains(INTEGER))
pool.set(i,s.readInt());
else
skip(s,4);
break;
case 4: // CONSTANT_Float
if (collect.contains(FLOAT))
pool.set(i,s.readFloat());
else
skip(s,4);
break;
case 9: // CONSTANT_Fieldref
if (collect.contains(FIELD_REF))
pool.fieldRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 10: // CONSTANT_Methodref
if (collect.contains(METHOD_REF))
pool.methodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 11: // CONSTANT_InterfaceMethodref
if (collect.contains(INTERFACE_METHOD_REF))
pool.interfaceMethodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 12: // CONSTANT_NameAndType
if (collect.contains(NAME_AND_TYPE))
pool.nameAndTypeAt(i).set(pool.utf8At(readIndex(s)),pool.utf8At(readIndex(s)));
else
skip(s,4);
break;
case 8: // CONSTANT_String
if (collect.contains(STRING))
pool.set(i, new StringConstant(pool.utf8At(readIndex(s))));
+ else
+ skip(s,2);
break;
case 5: // CONSTANT_Long
if (collect.contains(LONG))
pool.set(i,s.readLong());
else
skip(s,8);
i++; // weirdness in spec
break;
case 6: // CONSTANT_Double
if (collect.contains(DOUBLE))
pool.set(i,s.readDouble());
else
skip(s,8);
i++; // weirdness in spec
break;
case 15:// CONSTANT_MethodHandle
skip(s,3);
break;
case 16:// CONSTANT_MethodType
skip(s,2);
break;
case 18:// CONSTANT_INVOKE_DYNAMIC
skip(s,4);
break;
default:
throw new IOException("Unrecognized constant pool tag " + tag + " at index " + i +
"; running constants: " + pool);
}
}
return pool;
}
private static EnumSet<ConstantType> transitiveClosureOf(Collection<ConstantType> collect) {
EnumSet<ConstantType> subject = EnumSet.copyOf(collect);
for (ConstantType c : collect) {
subject.addAll(c.implies);
}
return subject;
}
private static void skip(DataInput source, int bytes) throws IOException {
// skipBytes cannot be used reliably because 0 is a valid return value
// and we can end up looping forever
source.readFully(new byte[bytes]);
}
private static int readIndex(DataInput source) throws IOException {
return source.readUnsignedShort() - 1;
}
}
| true | true | public static ConstantPool parse(DataInput s, Collection<ConstantType> _collect) throws IOException {
skip(s,8); // magic, minor_version, major_version
int size = s.readUnsignedShort() - 1; // constantPoolCount
ConstantPool pool = new ConstantPool(size);
// figure out all the types of constants we need to collect
final EnumSet<ConstantType> collect = transitiveClosureOf(_collect);
for (int i = 0; i < size; i++) {
int tag = s.readByte();
switch (tag) {
case 1: // CONSTANT_Utf8
if (collect.contains(UTF8))
pool.utf8At(i).actual = s.readUTF();
else
skip(s,s.readUnsignedShort());
break;
case 7: // CONSTANT_Class
if (collect.contains(CLASS))
pool.classAt(i).set(pool.utf8At(readIndex(s)));
else
skip(s,2);
break;
case 3: // CONSTANT_Integer
if (collect.contains(INTEGER))
pool.set(i,s.readInt());
else
skip(s,4);
break;
case 4: // CONSTANT_Float
if (collect.contains(FLOAT))
pool.set(i,s.readFloat());
else
skip(s,4);
break;
case 9: // CONSTANT_Fieldref
if (collect.contains(FIELD_REF))
pool.fieldRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 10: // CONSTANT_Methodref
if (collect.contains(METHOD_REF))
pool.methodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 11: // CONSTANT_InterfaceMethodref
if (collect.contains(INTERFACE_METHOD_REF))
pool.interfaceMethodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 12: // CONSTANT_NameAndType
if (collect.contains(NAME_AND_TYPE))
pool.nameAndTypeAt(i).set(pool.utf8At(readIndex(s)),pool.utf8At(readIndex(s)));
else
skip(s,4);
break;
case 8: // CONSTANT_String
if (collect.contains(STRING))
pool.set(i, new StringConstant(pool.utf8At(readIndex(s))));
break;
case 5: // CONSTANT_Long
if (collect.contains(LONG))
pool.set(i,s.readLong());
else
skip(s,8);
i++; // weirdness in spec
break;
case 6: // CONSTANT_Double
if (collect.contains(DOUBLE))
pool.set(i,s.readDouble());
else
skip(s,8);
i++; // weirdness in spec
break;
case 15:// CONSTANT_MethodHandle
skip(s,3);
break;
case 16:// CONSTANT_MethodType
skip(s,2);
break;
case 18:// CONSTANT_INVOKE_DYNAMIC
skip(s,4);
break;
default:
throw new IOException("Unrecognized constant pool tag " + tag + " at index " + i +
"; running constants: " + pool);
}
}
return pool;
}
| public static ConstantPool parse(DataInput s, Collection<ConstantType> _collect) throws IOException {
skip(s,8); // magic, minor_version, major_version
int size = s.readUnsignedShort() - 1; // constantPoolCount
ConstantPool pool = new ConstantPool(size);
// figure out all the types of constants we need to collect
final EnumSet<ConstantType> collect = transitiveClosureOf(_collect);
for (int i = 0; i < size; i++) {
int tag = s.readByte();
switch (tag) {
case 1: // CONSTANT_Utf8
if (collect.contains(UTF8))
pool.utf8At(i).actual = s.readUTF();
else
skip(s,s.readUnsignedShort());
break;
case 7: // CONSTANT_Class
if (collect.contains(CLASS))
pool.classAt(i).set(pool.utf8At(readIndex(s)));
else
skip(s,2);
break;
case 3: // CONSTANT_Integer
if (collect.contains(INTEGER))
pool.set(i,s.readInt());
else
skip(s,4);
break;
case 4: // CONSTANT_Float
if (collect.contains(FLOAT))
pool.set(i,s.readFloat());
else
skip(s,4);
break;
case 9: // CONSTANT_Fieldref
if (collect.contains(FIELD_REF))
pool.fieldRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 10: // CONSTANT_Methodref
if (collect.contains(METHOD_REF))
pool.methodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 11: // CONSTANT_InterfaceMethodref
if (collect.contains(INTERFACE_METHOD_REF))
pool.interfaceMethodRefAt(i).set(pool.classAt(readIndex(s)),pool.nameAndTypeAt(readIndex(s)));
else
skip(s,4);
break;
case 12: // CONSTANT_NameAndType
if (collect.contains(NAME_AND_TYPE))
pool.nameAndTypeAt(i).set(pool.utf8At(readIndex(s)),pool.utf8At(readIndex(s)));
else
skip(s,4);
break;
case 8: // CONSTANT_String
if (collect.contains(STRING))
pool.set(i, new StringConstant(pool.utf8At(readIndex(s))));
else
skip(s,2);
break;
case 5: // CONSTANT_Long
if (collect.contains(LONG))
pool.set(i,s.readLong());
else
skip(s,8);
i++; // weirdness in spec
break;
case 6: // CONSTANT_Double
if (collect.contains(DOUBLE))
pool.set(i,s.readDouble());
else
skip(s,8);
i++; // weirdness in spec
break;
case 15:// CONSTANT_MethodHandle
skip(s,3);
break;
case 16:// CONSTANT_MethodType
skip(s,2);
break;
case 18:// CONSTANT_INVOKE_DYNAMIC
skip(s,4);
break;
default:
throw new IOException("Unrecognized constant pool tag " + tag + " at index " + i +
"; running constants: " + pool);
}
}
return pool;
}
|
diff --git a/src/main/java/com/github/sgr/swingx/MultiLineRenderer.java b/src/main/java/com/github/sgr/swingx/MultiLineRenderer.java
index 55afb4f..3333df8 100644
--- a/src/main/java/com/github/sgr/swingx/MultiLineRenderer.java
+++ b/src/main/java/com/github/sgr/swingx/MultiLineRenderer.java
@@ -1,85 +1,87 @@
// -*- coding: utf-8-unix -*-
package com.github.sgr.swingx;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellRenderer;
public class MultiLineRenderer implements TableCellRenderer {
private static Color ODD_ROW_BACKGROUND = new Color(241, 246, 250);
private JTextArea _txtRenderer = null;
private JLabel _imgRenderer = null;
private SimpleDateFormat _df = null;
public MultiLineRenderer(String datePattern) {
_txtRenderer = new JTextArea();
_txtRenderer.setEditable(false);
_txtRenderer.setLineWrap(true);
_txtRenderer.setWrapStyleWord(false);
_imgRenderer = new JLabel();
_imgRenderer.setOpaque(true);
_imgRenderer.setHorizontalTextPosition(SwingConstants.CENTER);
_imgRenderer.setHorizontalAlignment(SwingConstants.CENTER);
if (datePattern != null) {
_df = new SimpleDateFormat(datePattern);
} else {
_df = new SimpleDateFormat("HH:mm:ss");
}
}
public MultiLineRenderer() {
this(null);
}
private JComponent getTxtTableCellRendererComponent(JTable table, String value, boolean isSelected, boolean hasFocus, int row, int column) {
int width = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
_txtRenderer.setSize(new Dimension(width, 1000));
_txtRenderer.setText(value);
return _txtRenderer;
}
private JComponent getImgTableCellRendererComponent(JTable table, Icon value, boolean isSelected, boolean hasFocus, int row, int column) {
_imgRenderer.setIcon(value);
return _imgRenderer;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent c = null;
if (value instanceof String) {
c = getTxtTableCellRendererComponent(table, (String)value, isSelected, hasFocus, row, column);
} else if (value instanceof Date) {
String dateString = _df.format((Date)value);
c = getTxtTableCellRendererComponent(table, dateString, isSelected, hasFocus, row, column);
} else if (value instanceof Icon) {
c = getImgTableCellRendererComponent(table, (Icon)value, isSelected, hasFocus, row, column);
} else {
- c = getTxtTableCellRendererComponent(table, value.toString(), isSelected, hasFocus, row, column);
+ if (value != null) {
+ c = getTxtTableCellRendererComponent(table, value.toString(), isSelected, hasFocus, row, column);
+ }
}
// render stripe
if (isSelected) {
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
} else {
c.setForeground(table.getForeground());
c.setBackground(row % 2 == 0 ? table.getBackground() : ODD_ROW_BACKGROUND);
}
// update rowHeight
int h = c.getPreferredSize().height;
if (table.getRowHeight(row) < h) {
table.setRowHeight(row, h);
}
return c;
}
}
| true | true | public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent c = null;
if (value instanceof String) {
c = getTxtTableCellRendererComponent(table, (String)value, isSelected, hasFocus, row, column);
} else if (value instanceof Date) {
String dateString = _df.format((Date)value);
c = getTxtTableCellRendererComponent(table, dateString, isSelected, hasFocus, row, column);
} else if (value instanceof Icon) {
c = getImgTableCellRendererComponent(table, (Icon)value, isSelected, hasFocus, row, column);
} else {
c = getTxtTableCellRendererComponent(table, value.toString(), isSelected, hasFocus, row, column);
}
// render stripe
if (isSelected) {
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
} else {
c.setForeground(table.getForeground());
c.setBackground(row % 2 == 0 ? table.getBackground() : ODD_ROW_BACKGROUND);
}
// update rowHeight
int h = c.getPreferredSize().height;
if (table.getRowHeight(row) < h) {
table.setRowHeight(row, h);
}
return c;
}
| public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent c = null;
if (value instanceof String) {
c = getTxtTableCellRendererComponent(table, (String)value, isSelected, hasFocus, row, column);
} else if (value instanceof Date) {
String dateString = _df.format((Date)value);
c = getTxtTableCellRendererComponent(table, dateString, isSelected, hasFocus, row, column);
} else if (value instanceof Icon) {
c = getImgTableCellRendererComponent(table, (Icon)value, isSelected, hasFocus, row, column);
} else {
if (value != null) {
c = getTxtTableCellRendererComponent(table, value.toString(), isSelected, hasFocus, row, column);
}
}
// render stripe
if (isSelected) {
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
} else {
c.setForeground(table.getForeground());
c.setBackground(row % 2 == 0 ? table.getBackground() : ODD_ROW_BACKGROUND);
}
// update rowHeight
int h = c.getPreferredSize().height;
if (table.getRowHeight(row) < h) {
table.setRowHeight(row, h);
}
return c;
}
|
diff --git a/metadata/src/main/java/org/apache/oodt/cas/metadata/util/PathUtils.java b/metadata/src/main/java/org/apache/oodt/cas/metadata/util/PathUtils.java
index 8998b87ac..7b6586af8 100644
--- a/metadata/src/main/java/org/apache/oodt/cas/metadata/util/PathUtils.java
+++ b/metadata/src/main/java/org/apache/oodt/cas/metadata/util/PathUtils.java
@@ -1,399 +1,399 @@
/*
* 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.
*/
//$Id$
package org.apache.oodt.cas.metadata.util;
//JDK imports
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//APACHE imports
import org.apache.commons.lang.StringUtils;
//OODT imports
import org.apache.oodt.commons.date.DateUtils;
import org.apache.oodt.commons.exec.EnvUtilities;
import org.apache.oodt.cas.metadata.Metadata;
/**
* @author mattmann
* @author bfoster
* @version $Revision$
*
* <p>
* A Utility class for replacing environment variables and maniuplating file
* path strings.
* </p>.
*/
public final class PathUtils {
public static String DELIMITER = ",";
public static String replaceEnvVariables(String origPath) {
return replaceEnvVariables(origPath, null);
}
public static String replaceEnvVariables(String origPath, Metadata metadata) {
return replaceEnvVariables(origPath, metadata, false);
}
public static String replaceEnvVariables(String origPath,
Metadata metadata, boolean expand) {
StringBuffer finalPath = new StringBuffer();
for (int i = 0; i < origPath.length(); i++) {
if (origPath.charAt(i) == '[') {
VarData data = readEnvVarName(origPath, i);
String var = null;
if (metadata != null
&& metadata.getMetadata(data.getFieldName()) != null) {
List valList = metadata.getAllMetadata(data.getFieldName());
var = (String) valList.get(0);
if (expand)
for (int j = 1; j < valList.size(); j++)
var += DELIMITER + (String) valList.get(j);
} else {
var = EnvUtilities.getEnv(data.getFieldName());
}
finalPath.append(var);
i = data.getEndIdx();
} else {
finalPath.append(origPath.charAt(i));
}
}
return finalPath.toString();
}
public static String doDynamicReplacement(String string) throws Exception {
return doDynamicReplacement(string, null);
}
public static String doDynamicReplacement(String string, Metadata metadata)
throws Exception {
return PathUtils.replaceEnvVariables(doDynamicDateReplacement(
doDynamicDateRollReplacement(
doDynamicDateFormatReplacement(
doDynamicUtcToTaiDateReplacement(
doDynamicDateToSecsReplacement(
doDynamicDateToMillisReplacement(
string, metadata),
metadata),
metadata),
metadata),
metadata),
metadata),
metadata, true);
}
public static String doDynamicDateReplacement(String string,
Metadata metadata) throws Exception {
Pattern datePattern = Pattern
.compile("\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
Matcher dateMatcher = datePattern.matcher(string);
while (dateMatcher.find()) {
String dateString = string.substring(dateMatcher.start(),
dateMatcher.end());
GregorianCalendar gc = new GregorianCalendar();
// roll the date if roll days was specfied
int plusMinusIndex;
if ((plusMinusIndex = dateString.indexOf('-')) != -1
|| (plusMinusIndex = dateString.indexOf('+')) != -1) {
int dotIndex;
if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
int rollDays = Integer.parseInt(PathUtils
.replaceEnvVariables(
dateString.substring(plusMinusIndex,
dotIndex), metadata).replaceAll(
"[\\+\\s]", ""));
gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
} else
throw new Exception(
"Malformed dynamic date replacement specified (no dot separator) - '"
+ dateString + "'");
}
// determine type and make the appropriate replacement
String[] splitDate = dateString.split("\\.");
if (splitDate.length < 2)
throw new Exception("No date type specified - '" + dateString
+ "'");
String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
String replacement = "";
if (dateType.equals("DAY")) {
replacement = StringUtils.leftPad(gc
.get(GregorianCalendar.DAY_OF_MONTH)
- + "", 2);
+ + "", 2, "0");
} else if (dateType.equals("MONTH")) {
replacement = StringUtils.leftPad((gc
.get(GregorianCalendar.MONTH) + 1)
- + "", 2);
+ + "", 2, "0");
} else if (dateType.equals("YEAR")) {
replacement = gc.get(GregorianCalendar.YEAR) + "";
} else if (dateType.equals("UTC")) {
replacement = DateUtils.toString(DateUtils.toUtc(gc));
} else if (dateType.equals("TAI")) {
replacement = DateUtils.toString(DateUtils.toTai(gc));
} else {
throw new Exception("Invalid date type specified '"
+ dateString + "'");
}
string = StringUtils.replace(string, dateString, replacement);
dateMatcher = datePattern.matcher(string);
}
return string;
}
/**
* usage format: [DATE_ADD(<date>,<date-format>,<add-amount>,<hr | min | sec | day | mo | yr>)]
* example: [DATE_ADD(2009-12-31, yyyy-MM-dd, 1, day)] . . . output will be: 2010-01-01
* - dynamic replacement is allowed for the <date> as well, for example:
* [DATE_ADD([DATE.UTC], yyyy-MM-dd'T'HH:mm:ss.SSS'Z', 1, day)] will add one day to the
* current UTC time
*/
public static String doDynamicDateRollReplacement(String string,
Metadata metadata) throws Exception {
Pattern dateFormatPattern = Pattern
.compile("\\[\\s*DATE_ADD\\s*\\(.{1,}?,.{1,}?,.{1,}?,.{1,}?\\)\\s*\\]");
Matcher dateFormatMatcher = dateFormatPattern.matcher(string);
while (dateFormatMatcher.find()) {
String dateFormatString = string.substring(dateFormatMatcher
.start(), dateFormatMatcher.end());
// get arguments
Matcher argMatcher = Pattern.compile("\\(.*\\)").matcher(
dateFormatString);
argMatcher.find();
String argsString = dateFormatString.substring(argMatcher.start() + 1,
argMatcher.end() - 1);
argsString = doDynamicReplacement(argsString, metadata);
String[] args = argsString.split(",");
String dateString = args[0].trim();
dateString = doDynamicReplacement(dateString, metadata);
String dateFormat = args[1].trim();
int addAmount = Integer.parseInt(args[2].trim());
String addUnits = args[3].trim().toLowerCase();
// reformat date
Date date = new SimpleDateFormat(dateFormat).parse(dateString);
Calendar calendar = (Calendar) Calendar.getInstance().clone();
calendar.setTime(date);
if (addUnits.equals("hr") || addUnits.equals("hour"))
calendar.add(Calendar.HOUR_OF_DAY, addAmount);
else if (addUnits.equals("min") || addUnits.equals("minute"))
calendar.add(Calendar.MINUTE, addAmount);
else if (addUnits.equals("sec") || addUnits.equals("second"))
calendar.add(Calendar.SECOND, addAmount);
else if (addUnits.equals("day"))
calendar.add(Calendar.DAY_OF_YEAR, addAmount);
else if (addUnits.equals("mo") || addUnits.equals("month"))
calendar.add(Calendar.MONTH, addAmount);
else if (addUnits.equals("yr") || addUnits.equals("year"))
calendar.add(Calendar.YEAR, addAmount);
String newDateString = new SimpleDateFormat(dateFormat).format(calendar.getTime());
// swap in date string
string = StringUtils.replace(string, dateFormatString,
newDateString);
dateFormatMatcher = dateFormatPattern.matcher(string);
}
return string;
}
public static String doDynamicDateFormatReplacement(String string,
Metadata metadata) throws Exception {
Pattern dateFormatPattern = Pattern
.compile("\\[\\s*FORMAT\\s*\\(.{1,}?,.{1,}?,.{1,}?\\)\\s*\\]");
Matcher dateFormatMatcher = dateFormatPattern.matcher(string);
while (dateFormatMatcher.find()) {
String dateFormatString = string.substring(dateFormatMatcher
.start(), dateFormatMatcher.end());
// get arguments
Matcher argMatcher = Pattern.compile("\\(.*\\)").matcher(
dateFormatString);
argMatcher.find();
String argsString = dateFormatString.substring(argMatcher.start() + 1,
argMatcher.end() - 1);
argsString = doDynamicReplacement(argsString, metadata);
String[] args = argsString.split(",");
String curFormat = args[0].trim();
String dateString = args[1].trim();
String newFormat = args[2].trim();
// reformat date
Date date = new SimpleDateFormat(curFormat).parse(dateString);
String newDateString = new SimpleDateFormat(newFormat).format(date);
// swap in date string
string = StringUtils.replace(string, dateFormatString,
newDateString);
dateFormatMatcher = dateFormatPattern.matcher(string);
}
return string;
}
/**
* Replaces String method of format [UTC_TO_TAI(<utc-string format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'">)]
* with TAI time with format: "yyyy-MM-dd'T'HH:mm:ss.SSS-0000<leapSecs>"
*/
public static String doDynamicUtcToTaiDateReplacement(String string,
Metadata metadata) throws Exception {
Pattern utcToTaiPattern = Pattern.compile("\\[\\s*UTC_TO_TAI\\s*\\(.{1,}?\\)\\s*\\]");
Matcher matcher = utcToTaiPattern.matcher(string);
while (matcher.find()) {
String utcToTaiString = string.substring(matcher.start(), matcher.end());
Matcher argMatcher = Pattern.compile("\\(.*\\)").matcher(utcToTaiString);
argMatcher.find();
String utcDateString =
utcToTaiString.substring(argMatcher.start() + 1, argMatcher.end() - 1).trim();
utcDateString = doDynamicReplacement(utcDateString, metadata);
string = StringUtils.replace(string, utcToTaiString,
DateUtils.toString(DateUtils.toTai(DateUtils.toCalendar(utcDateString,
DateUtils.FormatType.UTC_FORMAT))));
matcher = utcToTaiPattern.matcher(string);
}
return string;
}
/**
* Replaces String method of format [DATE_TO_SECS(<date-string>,<DateUtils.FormatType>,<epoch-date format: "yyyy-MM-dd">)]
* with seconds between <epoch-date> and <date-string>
*/
public static String doDynamicDateToSecsReplacement(String string,
Metadata metadata) throws Exception {
Pattern utcToTaiPattern = Pattern.compile("\\[\\s*DATE_TO_SECS\\s*\\(.{1,}?\\,.{1,}?,.{1,}?\\)\\s*\\]");
Matcher matcher = utcToTaiPattern.matcher(string);
while (matcher.find()) {
String dateToSecsString = string.substring(matcher.start(), matcher.end());
Matcher argMatcher = Pattern.compile("\\(.*\\)").matcher(dateToSecsString);
argMatcher.find();
String argsString = dateToSecsString.substring(argMatcher.start() + 1,
argMatcher.end() - 1);
argsString = doDynamicReplacement(argsString, metadata);
String[] args = argsString.split(",");
String dateString = args[0].trim();
String dateType = args[1].trim();
String epochString = args[2].trim();
Calendar date = DateUtils.toCalendar(dateString, DateUtils.FormatType.valueOf(dateType));
Calendar epoch = DateUtils.toLocalCustomFormatCalendar(epochString, "yyyy-MM-dd");
String seconds = DateUtils.toString(DateUtils.getTimeInSecs(date, epoch));
string = StringUtils.replace(string, dateToSecsString, seconds);
matcher = utcToTaiPattern.matcher(string);
}
return string;
}
/**
* Replaces String method of format [DATE_TO_MILLIS(<date-string>,<DateUtils.FormatType>,<epoch-date format: "yyyy-MM-dd">)]
* with milliseconds between <epoch-date> and <date-string>
*/
public static String doDynamicDateToMillisReplacement(String string,
Metadata metadata) throws Exception {
Pattern utcToTaiPattern = Pattern.compile("\\[\\s*DATE_TO_MILLIS\\s*\\(.{1,}?\\,.{1,}?,.{1,}?\\)\\s*\\]");
Matcher matcher = utcToTaiPattern.matcher(string);
while (matcher.find()) {
String dateToMillisString = string.substring(matcher.start(), matcher.end());
Matcher argMatcher = Pattern.compile("\\(.*\\)").matcher(dateToMillisString);
argMatcher.find();
String argsString = dateToMillisString.substring(argMatcher.start() + 1,
argMatcher.end() - 1);
argsString = doDynamicReplacement(argsString, metadata);
String[] args = argsString.split(",");
String dateString = args[0].trim();
String dateType = args[1].trim();
String epochString = args[2].trim();
Calendar date = DateUtils.toCalendar(dateString, DateUtils.FormatType.valueOf(dateType));
Calendar epoch = DateUtils.toLocalCustomFormatCalendar(epochString, "yyyy-MM-dd");
String milliseconds = DateUtils.getTimeInMillis(date, epoch) + "";
string = StringUtils.replace(string, dateToMillisString, milliseconds);
matcher = utcToTaiPattern.matcher(string);
}
return string;
}
private static VarData readEnvVarName(String origPathStr, int startIdx) {
StringBuffer varName = new StringBuffer();
int idx = startIdx + 1;
do {
varName.append(origPathStr.charAt(idx));
idx++;
} while (origPathStr.charAt(idx) != ']');
VarData data = new PathUtils().new VarData();
data.setFieldName(varName.toString());
data.setEndIdx(idx);
return data;
}
class VarData {
private String fieldName = null;
private int endIdx = -1;
public VarData() {
}
/**
* @return the endIdx
*/
public int getEndIdx() {
return endIdx;
}
/**
* @param endIdx
* the endIdx to set
*/
public void setEndIdx(int endIdx) {
this.endIdx = endIdx;
}
/**
* @return the fieldName
*/
public String getFieldName() {
return fieldName;
}
/**
* @param fieldName
* the fieldName to set
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
}
}
| false | true | public static String doDynamicDateReplacement(String string,
Metadata metadata) throws Exception {
Pattern datePattern = Pattern
.compile("\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
Matcher dateMatcher = datePattern.matcher(string);
while (dateMatcher.find()) {
String dateString = string.substring(dateMatcher.start(),
dateMatcher.end());
GregorianCalendar gc = new GregorianCalendar();
// roll the date if roll days was specfied
int plusMinusIndex;
if ((plusMinusIndex = dateString.indexOf('-')) != -1
|| (plusMinusIndex = dateString.indexOf('+')) != -1) {
int dotIndex;
if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
int rollDays = Integer.parseInt(PathUtils
.replaceEnvVariables(
dateString.substring(plusMinusIndex,
dotIndex), metadata).replaceAll(
"[\\+\\s]", ""));
gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
} else
throw new Exception(
"Malformed dynamic date replacement specified (no dot separator) - '"
+ dateString + "'");
}
// determine type and make the appropriate replacement
String[] splitDate = dateString.split("\\.");
if (splitDate.length < 2)
throw new Exception("No date type specified - '" + dateString
+ "'");
String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
String replacement = "";
if (dateType.equals("DAY")) {
replacement = StringUtils.leftPad(gc
.get(GregorianCalendar.DAY_OF_MONTH)
+ "", 2);
} else if (dateType.equals("MONTH")) {
replacement = StringUtils.leftPad((gc
.get(GregorianCalendar.MONTH) + 1)
+ "", 2);
} else if (dateType.equals("YEAR")) {
replacement = gc.get(GregorianCalendar.YEAR) + "";
} else if (dateType.equals("UTC")) {
replacement = DateUtils.toString(DateUtils.toUtc(gc));
} else if (dateType.equals("TAI")) {
replacement = DateUtils.toString(DateUtils.toTai(gc));
} else {
throw new Exception("Invalid date type specified '"
+ dateString + "'");
}
string = StringUtils.replace(string, dateString, replacement);
dateMatcher = datePattern.matcher(string);
}
return string;
}
| public static String doDynamicDateReplacement(String string,
Metadata metadata) throws Exception {
Pattern datePattern = Pattern
.compile("\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
Matcher dateMatcher = datePattern.matcher(string);
while (dateMatcher.find()) {
String dateString = string.substring(dateMatcher.start(),
dateMatcher.end());
GregorianCalendar gc = new GregorianCalendar();
// roll the date if roll days was specfied
int plusMinusIndex;
if ((plusMinusIndex = dateString.indexOf('-')) != -1
|| (plusMinusIndex = dateString.indexOf('+')) != -1) {
int dotIndex;
if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
int rollDays = Integer.parseInt(PathUtils
.replaceEnvVariables(
dateString.substring(plusMinusIndex,
dotIndex), metadata).replaceAll(
"[\\+\\s]", ""));
gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
} else
throw new Exception(
"Malformed dynamic date replacement specified (no dot separator) - '"
+ dateString + "'");
}
// determine type and make the appropriate replacement
String[] splitDate = dateString.split("\\.");
if (splitDate.length < 2)
throw new Exception("No date type specified - '" + dateString
+ "'");
String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
String replacement = "";
if (dateType.equals("DAY")) {
replacement = StringUtils.leftPad(gc
.get(GregorianCalendar.DAY_OF_MONTH)
+ "", 2, "0");
} else if (dateType.equals("MONTH")) {
replacement = StringUtils.leftPad((gc
.get(GregorianCalendar.MONTH) + 1)
+ "", 2, "0");
} else if (dateType.equals("YEAR")) {
replacement = gc.get(GregorianCalendar.YEAR) + "";
} else if (dateType.equals("UTC")) {
replacement = DateUtils.toString(DateUtils.toUtc(gc));
} else if (dateType.equals("TAI")) {
replacement = DateUtils.toString(DateUtils.toTai(gc));
} else {
throw new Exception("Invalid date type specified '"
+ dateString + "'");
}
string = StringUtils.replace(string, dateString, replacement);
dateMatcher = datePattern.matcher(string);
}
return string;
}
|
diff --git a/src/fniki/freenet/plugin/WikiWebInterface.java b/src/fniki/freenet/plugin/WikiWebInterface.java
index e357594..5beae21 100644
--- a/src/fniki/freenet/plugin/WikiWebInterface.java
+++ b/src/fniki/freenet/plugin/WikiWebInterface.java
@@ -1,177 +1,178 @@
package fniki.freenet.plugin;
//import fniki.freenet.plugin.Fniki.PluginRequest;
//import fniki.freenet.plugin.Fniki.ServerPluginHTTPException;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import fniki.freenet.plugin.Fniki.*;
//import fniki.wiki.AccessDeniedException;
//import fniki.wiki.ChildContainerException;
//import fniki.wiki.DownloadException;
//import fniki.wiki.NotFoundException;
//import fniki.wiki.RedirectException;
//import fniki.wiki.Request;
//import fniki.wiki.WikiApp;
import fniki.wiki.*;
import freenet.client.HighLevelSimpleClient;
import freenet.clients.http.PageNode;
import freenet.clients.http.Toadlet;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.pluginmanager.AccessDeniedPluginHTTPException;
import freenet.pluginmanager.DownloadPluginHTTPException;
import freenet.pluginmanager.NotFoundPluginHTTPException;
import freenet.pluginmanager.PluginHTTPException;
import freenet.pluginmanager.RedirectPluginHTTPException;
import freenet.support.api.HTTPRequest;
public class WikiWebInterface extends Toadlet {
private String mNameSpace;
private WikiApp mWikiApp;
protected WikiWebInterface(HighLevelSimpleClient client, String path, WikiApp wikiapp) {
super(client);
mNameSpace = path;
mWikiApp = wikiapp;
}
@Override
public String path() {
return mNameSpace;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException, PluginHTTPException {
if(uri.toASCIIString().equals(mNameSpace + "jfniki.css")) {
final String customCssString =
//"div#content { background-color: #FFFFFF; color: #000000;}\n"+
"div#content {margin-left: 8px;}\n"+
"div#content a { color: #1f6b9e;}\n"+
"div#content h1 {font-size:32px;}\n"+
"div#content h2 {font-size:24px;}\n"+
"div#content h3 {font-size:18.7167px;}\n"+
"div#content h4 {font-size:16px;}\n"+
"div#content h5 {font-size:140px;}\n"+
"div#content pre, textarea {font-family: monospace; font-size: 12px;}"+
"div#content blockquote {margin-left:20px;background-color:#e0e0e0;}\n"+
"div#content div.indent {margin-left:20px;}\n"+
"div#content div.center {text-align:center;}\n"+
"div#content span.underline {text-decoration:underline;}\n"+
"div#content .pagetitle {text-align:left;}\n"+
"div#content .talktitle {text-align:left;}\n"+
"div#content .notalktitle {color:#c0c0c0;text-align:left;}\n"+
"div#content .archiveuri {font-family: monospace; font-size: 70%;}\n"+
"div#content .archivever {font-family: monospace;}";
writeReply(ctx, 200, "text/css", "OK", customCssString);
} else {
PageNode mPageNode = ctx.getPageMaker().getPageNode("jFniki", true, ctx);
mPageNode.addCustomStyleSheet(mNameSpace + "jfniki.css");
mPageNode.content.setContent(handleWebRequest(req, ctx, false));
writeHTMLReply(ctx, 200, "OK", mPageNode.outer.generate());
}
}
public void handleMethodPOST(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException, PluginHTTPException {
// This method is called whenever a user requests a page from our mNameSpace
// POST form authentication
//FIXME link the core
//FIXME validate referrer
//FIXME validate session
//String passwordPlain = req.getPartAsString("formPassword", 32);
//if((passwordPlain.length() == 0) || !passwordPlain.equals(core.formPassword)) {
// writeHTMLReply(ctx, 403, "Forbidden", "Invalid form password.");
// return;
//}
PageNode mPageNode = ctx.getPageMaker().getPageNode("jFniki", true, ctx);
mPageNode.addCustomStyleSheet(mNameSpace + "jfniki.css");
mPageNode.content.setContent(handleWebRequest(req,ctx, false));
writeHTMLReply(ctx, 200, "OK", mPageNode.outer.generate());
}
private String handleWebRequest(HTTPRequest request, ToadletContext ctx, boolean createHtmlHeader) throws PluginHTTPException {
String tmpResult = "";
mWikiApp.setContainerPrefix(mNameSpace.substring(0, mNameSpace.length()-1));
try {
try {
mWikiApp.setRequest(new PluginRequest(request, mNameSpace), createHtmlHeader);
tmpResult = mWikiApp.handle(mWikiApp);
// IMPORTANT: Look at these catch blocks carefully. They bypass the freenet ContentFilter.
// SeekingForAttention: This could be insecure code because I have no clue and no documentation. Do not use it if you don't know what you are doing.
} catch(AccessDeniedException accessDenied) {
writeReply(ctx, 403, "text/plain", "Forbidden", accessDenied.getMessage());
} catch(NotFoundException notFound) {
writeHTMLReply(ctx, 200, "OK", createRequestInfo(request,ctx).outer.generate());
} catch(RedirectException redirected) {
writeTemporaryRedirect(ctx, redirected.getLocalizedMessage(), redirected.getLocation());
} catch(DownloadException forceDownload) {
// This is to allow exporting the configuration.
if("Download of: jfniki.cfg".equals(forceDownload.getMessage())) {
- throw new DownloadPluginHTTPException(forceDownload.mData,
- forceDownload.mFilename,
- forceDownload.mMimeType);
+ writeReply(ctx, 200, forceDownload.mMimeType, "OK", forceDownload.mData, 0, forceDownload.mData.length);
+ //throw new DownloadPluginHTTPException(forceDownload.mData,
+ // forceDownload.mFilename,
+ // forceDownload.mMimeType);
} else {
System.err.println("WikiWebInterface::handleWebRequest failed with a DownloadException: " + forceDownload.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + forceDownload.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
//} catch(ChildContainerException serverError) {
// throw new ServerPluginHTTPException(serverError.getMessage(), mNameSpace);
//} catch(IOException ioError) {
// throw new ServerPluginHTTPException(ioError.getMessage(), mNameSpace);
} catch(Exception ex) {
System.err.println("WikiWebInterface::handleWebRequest failed: " + ex.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + ex.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
} catch(ToadletContextClosedException e) {
// no clue what this means..
} catch(IOException e) {
// socket disconnected? otherwise no idea..
}
return tmpResult;
}
private PageNode createRequestInfo(HTTPRequest req, ToadletContext ctx) {
// FIXME: return a content node only instead of PageNode
URI uri = ctx.getUri();
PageNode mPageNode = ctx.getPageMaker().getPageNode("HelloWorld InfoPage", true, ctx);
mPageNode.content.addChild("br");
mPageNode.content.addChild("span","Sorry, something went wrong with your request to");
mPageNode.content.addChild("br");
mPageNode.content.addChild("br");
// requested URI
mPageNode.content.addChild("b", "URI:");
mPageNode.content.addChild("br");
mPageNode.content.addChild("i", uri.toString());
mPageNode.content.addChild("br");
mPageNode.content.addChild("br");
// used Method
mPageNode.content.addChild("b", "Method:");
mPageNode.content.addChild("br");
mPageNode.content.addChild("i", req.getMethod());
mPageNode.content.addChild("br");
mPageNode.content.addChild("br");
// POST data?
mPageNode.content.addChild("b", "HTTPRequest.getParts():");
mPageNode.content.addChild("br");
String tmpGetRequestParts[] = req.getParts();
for (int i = 0; i < tmpGetRequestParts.length; i++) {
mPageNode.content.addChild("i", tmpGetRequestParts[i]);
mPageNode.content.addChild("br");
}
mPageNode.content.addChild("br");
mPageNode.content.addChild("br");
// Parameters Key-->Value
mPageNode.content.addChild("b", "HTTPRequest.getParameterNames()-->HTTPRequest.getParam(parameter):");
mPageNode.content.addChild("br");
String partString = "";
Collection<String> tmpGetRequestParameterNames = req.getParameterNames();
for (Iterator<String> tmpIterator = tmpGetRequestParameterNames.iterator(); tmpIterator.hasNext();) {
partString = tmpIterator.next();
mPageNode.content.addChild("i", partString + "-->" + req.getParam(partString));
mPageNode.content.addChild("br");
}
return mPageNode;
}
}
| true | true | private String handleWebRequest(HTTPRequest request, ToadletContext ctx, boolean createHtmlHeader) throws PluginHTTPException {
String tmpResult = "";
mWikiApp.setContainerPrefix(mNameSpace.substring(0, mNameSpace.length()-1));
try {
try {
mWikiApp.setRequest(new PluginRequest(request, mNameSpace), createHtmlHeader);
tmpResult = mWikiApp.handle(mWikiApp);
// IMPORTANT: Look at these catch blocks carefully. They bypass the freenet ContentFilter.
// SeekingForAttention: This could be insecure code because I have no clue and no documentation. Do not use it if you don't know what you are doing.
} catch(AccessDeniedException accessDenied) {
writeReply(ctx, 403, "text/plain", "Forbidden", accessDenied.getMessage());
} catch(NotFoundException notFound) {
writeHTMLReply(ctx, 200, "OK", createRequestInfo(request,ctx).outer.generate());
} catch(RedirectException redirected) {
writeTemporaryRedirect(ctx, redirected.getLocalizedMessage(), redirected.getLocation());
} catch(DownloadException forceDownload) {
// This is to allow exporting the configuration.
if("Download of: jfniki.cfg".equals(forceDownload.getMessage())) {
throw new DownloadPluginHTTPException(forceDownload.mData,
forceDownload.mFilename,
forceDownload.mMimeType);
} else {
System.err.println("WikiWebInterface::handleWebRequest failed with a DownloadException: " + forceDownload.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + forceDownload.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
//} catch(ChildContainerException serverError) {
// throw new ServerPluginHTTPException(serverError.getMessage(), mNameSpace);
//} catch(IOException ioError) {
// throw new ServerPluginHTTPException(ioError.getMessage(), mNameSpace);
} catch(Exception ex) {
System.err.println("WikiWebInterface::handleWebRequest failed: " + ex.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + ex.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
} catch(ToadletContextClosedException e) {
// no clue what this means..
} catch(IOException e) {
// socket disconnected? otherwise no idea..
}
return tmpResult;
}
| private String handleWebRequest(HTTPRequest request, ToadletContext ctx, boolean createHtmlHeader) throws PluginHTTPException {
String tmpResult = "";
mWikiApp.setContainerPrefix(mNameSpace.substring(0, mNameSpace.length()-1));
try {
try {
mWikiApp.setRequest(new PluginRequest(request, mNameSpace), createHtmlHeader);
tmpResult = mWikiApp.handle(mWikiApp);
// IMPORTANT: Look at these catch blocks carefully. They bypass the freenet ContentFilter.
// SeekingForAttention: This could be insecure code because I have no clue and no documentation. Do not use it if you don't know what you are doing.
} catch(AccessDeniedException accessDenied) {
writeReply(ctx, 403, "text/plain", "Forbidden", accessDenied.getMessage());
} catch(NotFoundException notFound) {
writeHTMLReply(ctx, 200, "OK", createRequestInfo(request,ctx).outer.generate());
} catch(RedirectException redirected) {
writeTemporaryRedirect(ctx, redirected.getLocalizedMessage(), redirected.getLocation());
} catch(DownloadException forceDownload) {
// This is to allow exporting the configuration.
if("Download of: jfniki.cfg".equals(forceDownload.getMessage())) {
writeReply(ctx, 200, forceDownload.mMimeType, "OK", forceDownload.mData, 0, forceDownload.mData.length);
//throw new DownloadPluginHTTPException(forceDownload.mData,
// forceDownload.mFilename,
// forceDownload.mMimeType);
} else {
System.err.println("WikiWebInterface::handleWebRequest failed with a DownloadException: " + forceDownload.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + forceDownload.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
//} catch(ChildContainerException serverError) {
// throw new ServerPluginHTTPException(serverError.getMessage(), mNameSpace);
//} catch(IOException ioError) {
// throw new ServerPluginHTTPException(ioError.getMessage(), mNameSpace);
} catch(Exception ex) {
System.err.println("WikiWebInterface::handleWebRequest failed: " + ex.getMessage());
tmpResult = "Requested path " + request.getPath() + " can not be delivered: " + ex.getMessage() + "<br />Please report this message.<br />";
tmpResult += createRequestInfo(request, ctx).content.generate();
}
} catch(ToadletContextClosedException e) {
// no clue what this means..
} catch(IOException e) {
// socket disconnected? otherwise no idea..
}
return tmpResult;
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/CargoPanel.java b/src/net/sf/freecol/client/gui/panel/CargoPanel.java
index 4423a306a..dae5af7ce 100644
--- a/src/net/sf/freecol/client/gui/panel/CargoPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/CargoPanel.java
@@ -1,297 +1,299 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseListener;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import javax.swing.JPanel;
import net.sf.freecol.client.control.InGameController;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Unit;
/**
* A panel that holds units and goods that represent Units and cargo
* that are on board the currently selected ship.
*/
public class CargoPanel extends FreeColPanel {
/**
* The carrier that contains cargo.
*/
private Unit carrier;
private final DefaultTransferHandler defaultTransferHandler;
private final MouseListener pressListener;
private final TitledBorder border;
/**
* Describe editable here.
*/
private boolean editable = true;
/**
* Describe parentPanel here.
*/
private JPanel parentPanel;
/**
* Creates this CargoPanel.
*
* @param parent The parent Canvas that holds this CargoPanel.
*/
public CargoPanel(Canvas parent, boolean withTitle) {
super(parent);
defaultTransferHandler = new DefaultTransferHandler(parent, this);
pressListener = new DragListener(this);
if (withTitle) {
border = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
Messages.message("cargoOnCarrier"));
} else {
border = null;
}
setBorder(border);
initialize();
}
@Override
public String getUIClassID() {
return "CargoPanelUI";
}
/**
* Get the <code>ParentPanel</code> value.
*
* @return a <code>JPanel</code> value
*/
public final JPanel getParentPanel() {
return parentPanel;
}
/**
* Set the <code>ParentPanel</code> value.
*
* @param newParentPanel The new ParentPanel value.
*/
public final void setParentPanel(final JPanel newParentPanel) {
this.parentPanel = newParentPanel;
}
/**
* Get the <code>Carrier</code> value.
*
* @return an <code>Unit</code> value
*/
public Unit getCarrier() {
return carrier;
}
/**
* Set the <code>Carrier</code> value.
*
* @param newCarrier The new Carrier value.
*/
public void setCarrier(final Unit newCarrier) {
this.carrier = newCarrier;
initialize();
}
/**
* Get the <code>Editable</code> value.
*
* @return a <code>boolean</code> value
*/
public boolean isEditable() {
return editable;
}
/**
* Set the <code>Editable</code> value.
*
* @param newEditable The new Editable value.
*/
public void setEditable(final boolean newEditable) {
this.editable = newEditable;
}
public void initialize() {
removeAll();
if (carrier != null) {
Iterator<Unit> unitIterator = carrier.getUnitIterator();
while (unitIterator.hasNext()) {
Unit unit = unitIterator.next();
UnitLabel label = new UnitLabel(unit, getCanvas());
if (isEditable()) {
label.setTransferHandler(defaultTransferHandler);
label.addMouseListener(pressListener);
}
add(label);
}
Iterator<Goods> goodsIterator = carrier.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods g = goodsIterator.next();
GoodsLabel label = new GoodsLabel(g, getCanvas());
if (isEditable()) {
label.setTransferHandler(defaultTransferHandler);
label.addMouseListener(pressListener);
}
add(label);
}
}
updateTitle();
}
private void updateTitle() {
// sanitation
if (border == null) {
return;
}
if (carrier == null) {
border.setTitle(Messages.message("cargoOnCarrier"));
} else {
int spaceLeft = carrier.getSpaceLeft();
border.setTitle(Messages.message("cargoOnCarrierLong",
"%name%", carrier.getName(),
"%space%", String.valueOf(spaceLeft)));
}
}
public boolean isActive() {
return (carrier != null);
}
/**
* Adds a component to this CargoPanel and makes sure that the unit or
* good that the component represents gets modified so that it is on
* board the currently selected ship.
*
* @param comp The component to add to this CargoPanel.
* @param editState Must be set to 'true' if the state of the component
* that is added (which should be a dropped component
* representing a Unit or good) should be changed so that the
* underlying unit or goods are on board the currently
* selected ship.
* @return The component argument.
*/
public Component add(Component comp, boolean editState) {
if (carrier == null) {
return null;
}
if (editState) {
InGameController inGameController = getCanvas().getClient().getInGameController();
if (comp instanceof UnitLabel) {
Container oldParent = comp.getParent();
Unit unit = ((UnitLabel) comp).getUnit();
if (carrier.canAdd(unit)) {
((UnitLabel) comp).setSmall(false);
if (inGameController.boardShip(unit, carrier)) {
if (oldParent != null) {
oldParent.remove(comp);
oldParent.repaint();
}
add(comp);
updateTitle();
return comp;
}
}
} else if (comp instanceof GoodsLabel) {
Goods goods = ((GoodsLabel) comp).getGoods();
int loadableAmount = carrier.getLoadableAmount(goods.getType());
if (loadableAmount == 0) {
return null;
} else if (loadableAmount > goods.getAmount()) {
loadableAmount = goods.getAmount();
}
Goods goodsToAdd = new Goods(goods.getGame(), goods.getLocation(), goods.getType(), loadableAmount);
goods.setAmount(goods.getAmount() - loadableAmount);
inGameController.loadCargo(goodsToAdd, carrier);
initialize();
Container oldParent = comp.getParent();
if (oldParent instanceof ColonyPanel.WarehousePanel) {
((ColonyPanel.WarehousePanel) oldParent).initialize();
} else {
- oldParent.remove(comp);
+ if(oldParent != null){
+ oldParent.remove(comp);
+ }
}
return comp;
} else if (comp instanceof MarketLabel) {
MarketLabel label = (MarketLabel) comp;
Player player = carrier.getOwner();
if (player.canTrade(label.getType())) {
inGameController.buyGoods(label.getType(), label.getAmount(), carrier);
inGameController.nextModelMessage();
initialize();
updateTitle();
return comp;
} else {
inGameController.payArrears(label.getType());
return null;
}
} else {
return null;
}
} else {
super.add(comp);
}
return null;
}
@Override
public void remove(Component comp) {
InGameController inGameController = getCanvas().getClient().getInGameController();
if (comp instanceof UnitLabel) {
Unit unit = ((UnitLabel) comp).getUnit();
inGameController.leaveShip(unit);
updateTitle();
super.remove(comp);
} else if (comp instanceof GoodsLabel) {
Goods g = ((GoodsLabel) comp).getGoods();
inGameController.unloadCargo(g);
updateTitle();
super.remove(comp);
}
}
}
| true | true | public Component add(Component comp, boolean editState) {
if (carrier == null) {
return null;
}
if (editState) {
InGameController inGameController = getCanvas().getClient().getInGameController();
if (comp instanceof UnitLabel) {
Container oldParent = comp.getParent();
Unit unit = ((UnitLabel) comp).getUnit();
if (carrier.canAdd(unit)) {
((UnitLabel) comp).setSmall(false);
if (inGameController.boardShip(unit, carrier)) {
if (oldParent != null) {
oldParent.remove(comp);
oldParent.repaint();
}
add(comp);
updateTitle();
return comp;
}
}
} else if (comp instanceof GoodsLabel) {
Goods goods = ((GoodsLabel) comp).getGoods();
int loadableAmount = carrier.getLoadableAmount(goods.getType());
if (loadableAmount == 0) {
return null;
} else if (loadableAmount > goods.getAmount()) {
loadableAmount = goods.getAmount();
}
Goods goodsToAdd = new Goods(goods.getGame(), goods.getLocation(), goods.getType(), loadableAmount);
goods.setAmount(goods.getAmount() - loadableAmount);
inGameController.loadCargo(goodsToAdd, carrier);
initialize();
Container oldParent = comp.getParent();
if (oldParent instanceof ColonyPanel.WarehousePanel) {
((ColonyPanel.WarehousePanel) oldParent).initialize();
} else {
oldParent.remove(comp);
}
return comp;
} else if (comp instanceof MarketLabel) {
MarketLabel label = (MarketLabel) comp;
Player player = carrier.getOwner();
if (player.canTrade(label.getType())) {
inGameController.buyGoods(label.getType(), label.getAmount(), carrier);
inGameController.nextModelMessage();
initialize();
updateTitle();
return comp;
} else {
inGameController.payArrears(label.getType());
return null;
}
} else {
return null;
}
} else {
super.add(comp);
}
return null;
}
| public Component add(Component comp, boolean editState) {
if (carrier == null) {
return null;
}
if (editState) {
InGameController inGameController = getCanvas().getClient().getInGameController();
if (comp instanceof UnitLabel) {
Container oldParent = comp.getParent();
Unit unit = ((UnitLabel) comp).getUnit();
if (carrier.canAdd(unit)) {
((UnitLabel) comp).setSmall(false);
if (inGameController.boardShip(unit, carrier)) {
if (oldParent != null) {
oldParent.remove(comp);
oldParent.repaint();
}
add(comp);
updateTitle();
return comp;
}
}
} else if (comp instanceof GoodsLabel) {
Goods goods = ((GoodsLabel) comp).getGoods();
int loadableAmount = carrier.getLoadableAmount(goods.getType());
if (loadableAmount == 0) {
return null;
} else if (loadableAmount > goods.getAmount()) {
loadableAmount = goods.getAmount();
}
Goods goodsToAdd = new Goods(goods.getGame(), goods.getLocation(), goods.getType(), loadableAmount);
goods.setAmount(goods.getAmount() - loadableAmount);
inGameController.loadCargo(goodsToAdd, carrier);
initialize();
Container oldParent = comp.getParent();
if (oldParent instanceof ColonyPanel.WarehousePanel) {
((ColonyPanel.WarehousePanel) oldParent).initialize();
} else {
if(oldParent != null){
oldParent.remove(comp);
}
}
return comp;
} else if (comp instanceof MarketLabel) {
MarketLabel label = (MarketLabel) comp;
Player player = carrier.getOwner();
if (player.canTrade(label.getType())) {
inGameController.buyGoods(label.getType(), label.getAmount(), carrier);
inGameController.nextModelMessage();
initialize();
updateTitle();
return comp;
} else {
inGameController.payArrears(label.getType());
return null;
}
} else {
return null;
}
} else {
super.add(comp);
}
return null;
}
|
diff --git a/core/src/main/java/org/eigenbase/rel/metadata/ReflectiveRelMetadataProvider.java b/core/src/main/java/org/eigenbase/rel/metadata/ReflectiveRelMetadataProvider.java
index f6bbae03..a0c25c76 100644
--- a/core/src/main/java/org/eigenbase/rel/metadata/ReflectiveRelMetadataProvider.java
+++ b/core/src/main/java/org/eigenbase/rel/metadata/ReflectiveRelMetadataProvider.java
@@ -1,174 +1,175 @@
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde 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.eigenbase.rel.metadata;
import java.lang.reflect.*;
import java.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.util.*;
import net.hydromatic.optiq.BuiltinMethod;
import com.google.common.base.Function;
import com.google.common.collect.*;
/**
* Implementation of the {@link RelMetadataProvider} interface that dispatches
* metadata methods to methods on a given object via reflection.
*
* <p>The methods on the target object must be public and non-static, and have
* the same signature as the implemented metadata method except for an
* additional first parameter of type {@link RelNode} or a sub-class. That
* parameter gives this provider an indication of that relational expressions it
* can handle.</p>
*
* <p>For an example, see {@link RelMdColumnOrigins#SOURCE}.
*/
public class ReflectiveRelMetadataProvider
implements RelMetadataProvider, ReflectiveVisitor {
/** Comparator that sorts derived classes before their base classes. */
private static final Comparator<Class<RelNode>> SUPERCLASS_COMPARATOR =
new Comparator<Class<RelNode>>() {
public int compare(Class<RelNode> c1, Class<RelNode> c2) {
return c1 == c2 ? 0 : c2.isAssignableFrom(c1) ? -1 : 1;
}
};
//~ Instance fields --------------------------------------------------------
private final ImmutableMap<Class<RelNode>, Function<RelNode, Metadata>> map;
private final Class<?> metadataClass0;
//~ Constructors -----------------------------------------------------------
/**
* Creates a ReflectiveRelMetadataProvider.
*
* @param map Map
* @param metadataClass0 Metadata class
*/
protected ReflectiveRelMetadataProvider(
ImmutableMap<Class<RelNode>, Function<RelNode, Metadata>> map,
Class<?> metadataClass0) {
assert !map.isEmpty() : "are your methods named wrong?";
this.map = map;
this.metadataClass0 = metadataClass0;
}
/** Returns an implementation of {@link RelMetadataProvider} that scans for
* methods with a preceding argument.
*
* <p>For example, {@link BuiltInMetadata.Selectivity} has a method
* {@link BuiltInMetadata.Selectivity#getSelectivity(org.eigenbase.rex.RexNode)}.
* A class</p>
*
* <blockquote><pre><code>
* class RelMdSelectivity {
* public Double getSelectivity(UnionRel rel, RexNode predicate) { ... }
* public Double getSelectivity(FilterRel rel, RexNode predicate) { ... }
* </code></pre></blockquote>
*
* <p>provides implementations of selectivity for relational expressions
* that extend {@link UnionRel} or {@link FilterRel}.</p>
*/
public static RelMetadataProvider reflectiveSource(Method method,
final Object target) {
final Class<?> metadataClass0 = method.getDeclaringClass();
assert Metadata.class.isAssignableFrom(metadataClass0);
final Map<Class<RelNode>, Function<RelNode, Metadata>> treeMap =
- Maps.newTreeMap(SUPERCLASS_COMPARATOR);
+ Maps.<Class<RelNode>, Class<RelNode>, Function<RelNode, Metadata>>
+ newTreeMap(SUPERCLASS_COMPARATOR);
for (final Method method1 : target.getClass().getMethods()) {
if (method1.getName().equals(method.getName())
&& (method1.getModifiers() & Modifier.STATIC) == 0
&& (method1.getModifiers() & Modifier.PUBLIC) != 0) {
final Class<?>[] parameterTypes1 = method1.getParameterTypes();
final Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes1.length == parameterTypes.length + 1
&& RelNode.class.isAssignableFrom(parameterTypes1[0])
&& Util.skip(Arrays.asList(parameterTypes1))
.equals(Arrays.asList(parameterTypes))) {
//noinspection unchecked
final Class<RelNode> key = (Class) parameterTypes1[0];
final Function<RelNode, Metadata> function =
new Function<RelNode, Metadata>() {
public Metadata apply(final RelNode rel) {
return (Metadata) Proxy.newProxyInstance(
metadataClass0.getClassLoader(),
new Class[]{metadataClass0},
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// Suppose we are an implementation of Selectivity
// that wraps "filter", a FilterRel, Then we implement
// Selectivity.selectivity(rex)
// by calling method
// new SelectivityImpl().selectivity(filter, rex)
if (method.equals(BuiltinMethod.METADATA_REL.method))
{
return rel;
}
final Object[] args1;
if (args == null) {
args1 = new Object[]{rel};
} else {
args1 = new Object[args.length + 1];
args1[0] = rel;
System.arraycopy(args, 0, args1, 1, args.length);
}
return method1.invoke(target, args1);
}
});
}
};
treeMap.put(key, function);
}
}
}
// Due to the comparator, the TreeMap is sorted such that any derived class
// will occur before its base class. The immutable map is not a sorted map,
// but it retains the traversal order, and that is sufficient.
final ImmutableMap<Class<RelNode>, Function<RelNode, Metadata>> map =
ImmutableMap.copyOf(treeMap);
return new ReflectiveRelMetadataProvider(map, metadataClass0);
}
//~ Methods ----------------------------------------------------------------
public Function<RelNode, Metadata> apply(
Class<? extends RelNode> relClass,
Class<? extends Metadata> metadataClass) {
if (metadataClass == metadataClass0) {
//noinspection SuspiciousMethodCalls
final Function<RelNode, Metadata> function = map.get(relClass);
if (function != null) {
return function;
}
for (Map.Entry<Class<RelNode>, Function<RelNode, Metadata>> entry
: map.entrySet()) {
if (entry.getKey().isAssignableFrom(relClass)) {
// REVIEW: We are assuming that the first we find is the "best".
return entry.getValue();
}
}
}
return null;
}
}
// End ReflectiveRelMetadataProvider.java
| true | true | public static RelMetadataProvider reflectiveSource(Method method,
final Object target) {
final Class<?> metadataClass0 = method.getDeclaringClass();
assert Metadata.class.isAssignableFrom(metadataClass0);
final Map<Class<RelNode>, Function<RelNode, Metadata>> treeMap =
Maps.newTreeMap(SUPERCLASS_COMPARATOR);
for (final Method method1 : target.getClass().getMethods()) {
if (method1.getName().equals(method.getName())
&& (method1.getModifiers() & Modifier.STATIC) == 0
&& (method1.getModifiers() & Modifier.PUBLIC) != 0) {
final Class<?>[] parameterTypes1 = method1.getParameterTypes();
final Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes1.length == parameterTypes.length + 1
&& RelNode.class.isAssignableFrom(parameterTypes1[0])
&& Util.skip(Arrays.asList(parameterTypes1))
.equals(Arrays.asList(parameterTypes))) {
//noinspection unchecked
final Class<RelNode> key = (Class) parameterTypes1[0];
final Function<RelNode, Metadata> function =
new Function<RelNode, Metadata>() {
public Metadata apply(final RelNode rel) {
return (Metadata) Proxy.newProxyInstance(
metadataClass0.getClassLoader(),
new Class[]{metadataClass0},
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// Suppose we are an implementation of Selectivity
// that wraps "filter", a FilterRel, Then we implement
// Selectivity.selectivity(rex)
// by calling method
// new SelectivityImpl().selectivity(filter, rex)
if (method.equals(BuiltinMethod.METADATA_REL.method))
{
return rel;
}
final Object[] args1;
if (args == null) {
args1 = new Object[]{rel};
} else {
args1 = new Object[args.length + 1];
args1[0] = rel;
System.arraycopy(args, 0, args1, 1, args.length);
}
return method1.invoke(target, args1);
}
});
}
};
treeMap.put(key, function);
}
}
}
// Due to the comparator, the TreeMap is sorted such that any derived class
// will occur before its base class. The immutable map is not a sorted map,
// but it retains the traversal order, and that is sufficient.
final ImmutableMap<Class<RelNode>, Function<RelNode, Metadata>> map =
ImmutableMap.copyOf(treeMap);
return new ReflectiveRelMetadataProvider(map, metadataClass0);
}
| public static RelMetadataProvider reflectiveSource(Method method,
final Object target) {
final Class<?> metadataClass0 = method.getDeclaringClass();
assert Metadata.class.isAssignableFrom(metadataClass0);
final Map<Class<RelNode>, Function<RelNode, Metadata>> treeMap =
Maps.<Class<RelNode>, Class<RelNode>, Function<RelNode, Metadata>>
newTreeMap(SUPERCLASS_COMPARATOR);
for (final Method method1 : target.getClass().getMethods()) {
if (method1.getName().equals(method.getName())
&& (method1.getModifiers() & Modifier.STATIC) == 0
&& (method1.getModifiers() & Modifier.PUBLIC) != 0) {
final Class<?>[] parameterTypes1 = method1.getParameterTypes();
final Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes1.length == parameterTypes.length + 1
&& RelNode.class.isAssignableFrom(parameterTypes1[0])
&& Util.skip(Arrays.asList(parameterTypes1))
.equals(Arrays.asList(parameterTypes))) {
//noinspection unchecked
final Class<RelNode> key = (Class) parameterTypes1[0];
final Function<RelNode, Metadata> function =
new Function<RelNode, Metadata>() {
public Metadata apply(final RelNode rel) {
return (Metadata) Proxy.newProxyInstance(
metadataClass0.getClassLoader(),
new Class[]{metadataClass0},
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// Suppose we are an implementation of Selectivity
// that wraps "filter", a FilterRel, Then we implement
// Selectivity.selectivity(rex)
// by calling method
// new SelectivityImpl().selectivity(filter, rex)
if (method.equals(BuiltinMethod.METADATA_REL.method))
{
return rel;
}
final Object[] args1;
if (args == null) {
args1 = new Object[]{rel};
} else {
args1 = new Object[args.length + 1];
args1[0] = rel;
System.arraycopy(args, 0, args1, 1, args.length);
}
return method1.invoke(target, args1);
}
});
}
};
treeMap.put(key, function);
}
}
}
// Due to the comparator, the TreeMap is sorted such that any derived class
// will occur before its base class. The immutable map is not a sorted map,
// but it retains the traversal order, and that is sufficient.
final ImmutableMap<Class<RelNode>, Function<RelNode, Metadata>> map =
ImmutableMap.copyOf(treeMap);
return new ReflectiveRelMetadataProvider(map, metadataClass0);
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
index d6b058fe9..1d04f33b8 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
@@ -1,1042 +1,1042 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.Utilities;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import net.aufdemrand.denizen.utilities.depends.WorldGuardUtilities;
import net.aufdemrand.denizen.utilities.entity.Rotation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.World;
import org.bukkit.block.Sign;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dLocation extends org.bukkit.Location implements dObject {
// This pattern correctly reads both 0.9 and 0.8 notables
final static Pattern notablePattern =
Pattern.compile("(\\w+)[;,]((-?\\d+\\.?\\d*,){3,5}\\w+)",
Pattern.CASE_INSENSITIVE);
/////////////////////
// STATIC METHODS
/////////////////
public static Map<String, dLocation> uniqueObjects = new HashMap<String, dLocation>();
public static boolean isSaved(String id) {
return uniqueObjects.containsKey(id.toUpperCase());
}
public static boolean isSaved(dLocation location) {
return uniqueObjects.containsValue(location);
}
public static boolean isSaved(Location location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet())
if (i.getValue() == location) return true;
return uniqueObjects.containsValue(location);
}
public static dLocation getSaved(String id) {
if (uniqueObjects.containsKey(id.toUpperCase()))
return uniqueObjects.get(id.toUpperCase());
else return null;
}
public static String getSaved(dLocation location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet()) {
if (i.getValue().getBlockX() != location.getBlockX()) continue;
if (i.getValue().getBlockY() != location.getBlockY()) continue;
if (i.getValue().getBlockZ() != location.getBlockZ()) continue;
if (!i.getValue().getWorld().getName().equals(location.getWorld().getName())) continue;
return i.getKey();
}
return null;
}
public static String getSaved(Location location) {
dLocation dLoc = new dLocation(location);
return getSaved(dLoc);
}
public static void saveAs(dLocation location, String id) {
if (location == null) return;
uniqueObjects.put(id.toUpperCase(), location);
}
public static void remove(String id) {
uniqueObjects.remove(id.toUpperCase());
}
/*
* Called on server startup or /denizen reload locations. Should probably not be called manually.
*/
public static void _recallLocations() {
List<String> loclist = DenizenAPI.getCurrentInstance().getSaves().getStringList("dScript.Locations");
uniqueObjects.clear();
for (String location : loclist) {
Matcher m = notablePattern.matcher(location);
if (m.matches()) {
String id = m.group(1);
dLocation loc = valueOf(m.group(2));
uniqueObjects.put(id, loc);
}
}
}
/*
* Called by Denizen internally on a server shutdown or /denizen save. Should probably
* not be called manually.
*/
public static void _saveLocations() {
List<String> loclist = new ArrayList<String>();
for (Map.Entry<String, dLocation> entry : uniqueObjects.entrySet())
// Save locations in the horizontal centers of blocks
loclist.add(entry.getKey() + ";"
+ (entry.getValue().getBlockX() + 0.5)
+ "," + entry.getValue().getBlockY()
+ "," + (entry.getValue().getBlockZ() + 0.5)
+ "," + entry.getValue().getYaw()
+ "," + entry.getValue().getPitch()
+ "," + entry.getValue().getWorld().getName());
DenizenAPI.getCurrentInstance().getSaves().set("dScript.Locations", loclist);
}
//////////////////
// OBJECT FETCHER
////////////////
/**
* Gets a Location Object from a string form of id,x,y,z,world
* or a dScript argument (location:)x,y,z,world. If including an Id,
* this location will persist and can be recalled at any time.
*
* @param string the string or dScript argument String
* @return a Location, or null if incorrectly formatted
*
*/
@ObjectFetcher("l")
public static dLocation valueOf(String string) {
if (string == null) return null;
////////
// Match @object format for saved dLocations
Matcher m;
final Pattern item_by_saved = Pattern.compile("(l@)(.+)");
m = item_by_saved.matcher(string);
if (m.matches() && isSaved(m.group(2)))
return getSaved(m.group(2));
////////
// Match location formats
// Split values
String[] split = string.replace("l@", "").split(",");
if (split.length == 4)
// If 4 values, standard dScript location format
// x,y,z,world
try {
return new dLocation(Bukkit.getWorld(split[3]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]));
} catch(Exception e) {
return null;
}
else if (split.length == 6)
// If 6 values, location with pitch/yaw
// x,y,z,yaw,pitch,world
try
{ return new dLocation(Bukkit.getWorld(split[5]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]),
Float.valueOf(split[3]),
Float.valueOf(split[4]));
} catch(Exception e) {
return null;
}
dB.log("valueOf dLocation returning null: " + string);
return null;
}
public static boolean matches(String string) {
final Pattern location_by_saved = Pattern.compile("(l@)(.+)");
Matcher m = location_by_saved.matcher(string);
if (m.matches())
return true;
final Pattern location =
Pattern.compile("(-?\\d+\\.?\\d*,){3,5}\\w+",
Pattern.CASE_INSENSITIVE);
m = location.matcher(string);
return m.matches();
}
/**
* Turns a Bukkit Location into a Location, which has some helpful methods
* for working with dScript.
*
* @param location the Bukkit Location to reference
*/
public dLocation(Location location) {
// Just save the yaw and pitch as they are; don't check if they are
// higher than 0, because Minecraft yaws are weird and can have
// negative values
super(location.getWorld(), location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch());
}
/**
* Turns a world and coordinates into a Location, which has some helpful methods
* for working with dScript. If working with temporary locations, this is
* a much better method to use than {@link #dLocation(org.bukkit.World, double, double, double)}.
*
* @param world the world in which the location resides
* @param x x-coordinate of the location
* @param y y-coordinate of the location
* @param z z-coordinate of the location
*
*/
public dLocation(World world, double x, double y, double z) {
super(world, x, y, z);
}
public dLocation(World world, double x, double y, double z, float yaw, float pitch) {
super(world, x, y, z, pitch, yaw);
}
@Override
public void setPitch(float pitch) {
super.setPitch(pitch);
}
@Override
public void setYaw(float yaw) {
super.setYaw(yaw);
}
public dLocation rememberAs(String id) {
dLocation.saveAs(this, id);
return this;
}
String prefix = "Location";
@Override
public String getObjectType() {
return "Location";
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public dLocation setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (isSaved(this) ? "<G>" + prefix + "='<A>" + getSaved(this) + "(<Y>" + identify()+ "<A>)<G>' "
: "<G>" + prefix + "='<Y>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
return isSaved(this);
}
@Override
public String identify() {
if (isSaved(this))
return "l@" + getSaved(this);
else if (getYaw() != 0.0 && getPitch() != 0.0) return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getPitch() + "," + getYaw() + "," + getWorld().getName();
else return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getWorld().getName();
}
@Override
public String toString() {
return identify();
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("block.material"))
return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple formatted version of the dLocation.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <location.block.x>
// @returns Element(Number)
// @description
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
- // Returns the location of the highest block at the location that isn't solid.
+ // Returns the location of the highest solid block at the location.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
}
| true | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("block.material"))
return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple formatted version of the dLocation.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <location.block.x>
// @returns Element(Number)
// @description
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the highest block at the location that isn't solid.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(getBlock().getHumidity())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(getBlock().getTemperature())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(getBlock().getBiome().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected][x,y,z]>
// @returns dLocation
// @description
// Returns the location with the specified coordinates added to it.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--[tag]
// @attribute <[email protected]_pose[<entity>/<yaw>,<pitch>]>
// @returns dLocation
// @description
// Returns the location with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_blocks[<block>|...].within[X]>
// @returns dList
// @description
// Returns a list of matching surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of NPCs within a radius.
// -->
else if (attribute.startsWith("npcs")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dNPC> found = new ArrayList<dNPC>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (dNPC npc : DenizenAPI.getSpawnedNPCs())
if (Utilities.checkLocation(this, npc.getLocation(), radius))
found.add(npc);
Collections.sort(found, new Comparator<dNPC>() {
@Override
public int compare(dNPC npc1, dNPC npc2) {
return (int) (distanceSquared(npc1.getLocation()) - distanceSquared(npc2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected][X]>
// @returns dList
// @description
// Returns a list of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]_entities.within[X]>
// @returns dList
// @description
// Returns a list of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// Returns the dInventory of the block at the location. If the
// block is not a container, returns null.
// -->
if (attribute.startsWith("inventory")) {
if (getBlock().getState() instanceof InventoryHolder)
return new dInventory(getBlock().getState()).getAttribute(attribute.fulfill(1));
return new Element("null").getAttribute(attribute);
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the Bukkit material name of the block at the location.
// -->
if (attribute.startsWith("block.material"))
return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location's direction as a one-length vector.
// -->
if (attribute.startsWith("direction.vector")) {
double xzLen = Math.cos((getPitch() % 360) * (Math.PI/180));
double nx = xzLen * Math.cos(getYaw() * (Math.PI/180));
double ny = Math.sin(getPitch() * (Math.PI/180));
double nz = xzLen * Math.sin(-getYaw() * (Math.PI/180));
return new dLocation(getWorld(), -nx, -ny, nz).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element
// @description
// Returns the compass direction between two locations.
// If no second location is specified, returns the direction of the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected][<location>]>
// @returns Element(Number)
// @description
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--[tag]
// @attribute <[email protected][<location>].horizontal>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--[tag]
// @attribute <[email protected][<location>].horizontal.multiworld>
// @returns Element(Number)
// @description
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(this.getZ() - toLocation.getZ(), 2)))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected][<location>].vertical>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--[tag]
// @attribute <[email protected][<location>].vertical.multiworld>
// @returns Element(Number)
// @description
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(Math.abs(this.getY() - toLocation.getY()))
.getAttribute(attribute.fulfill(2));
}
else return new Element(this.distance(toLocation))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns a simple formatted version of the dLocation.
// EG: x,y,z,world
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted simple version of the dLocation.
// EG: X 'x', Y 'y', Z 'z', in world 'world'
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the formatted version of the dLocation.
// EG: 'X 'x.x', Y 'y.y', Z 'z.z', in world 'world'
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_liquid>
// @returns Element(Boolean)
// @description
// Returns whether block at the location is a liquid.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from light blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(getBlock().getLightFromBlocks())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(getBlock().getLightFromSky())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(getBlock().getLightLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(getPitch()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(getYaw())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(Rotation.normalizeYaw(getYaw()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][<entity>/<location>]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--[tag]
// @attribute <location.facing[<entity>/<location>].degrees[X]>
// @returns Element(Boolean)
// @description
// Returns whether the location's yaw is facing another
// entity or location, within a specified degree range.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the current redstone power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(getBlock().getBlockPower())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_region[<name>|...]>
// @returns Element(Boolean)
// @description
// If a region name or list of names is specified, returns whether the
// location is in one of the listed regions, otherwise returns whether
// the location is in any region.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
dList region_list = dList.valueOf(attribute.getContext(1));
for(String region: region_list)
if(WorldGuardUtilities.inRegion(this, region))
return Element.TRUE.getAttribute(attribute.fulfill(1));
return Element.FALSE.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(WorldGuardUtilities.inRegion(this))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList
// @description
// Returns a list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dWorld
// @description
// Returns the world that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <location.block.x>
// @returns Element(Number)
// @description
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_contents>
// @returns dList
// @description
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// Returns the location of the highest solid block at the location.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0))
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute);
}
|
diff --git a/src/uk/org/ponder/rsf/components/ELReference.java b/src/uk/org/ponder/rsf/components/ELReference.java
index 88d3ff5..79b0960 100644
--- a/src/uk/org/ponder/rsf/components/ELReference.java
+++ b/src/uk/org/ponder/rsf/components/ELReference.java
@@ -1,27 +1,31 @@
/*
* Created on 13-Jan-2006
*/
package uk.org.ponder.rsf.components;
import uk.org.ponder.beanutil.BeanUtil;
/** A special class to hold EL references so they may be detected in the
* component tree. When held in this member, it is devoid of the packaging #{..}
* characters - they are removed and replaced by the parser in transit from
* XML form.
* @author Antranig Basman ([email protected])
*
*/
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
public ELReference() {}
public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
+ if ("".equals(value)) {
+ throw new IllegalArgumentException(
+ "Cannot issue an EL reference to an empty path. For an empty binding please either supply null, or else provide a non-empty String as path");
+ }
}
public String value;
public static ELReference make(String value) {
return value == null? null : new ELReference(value);
}
}
| true | true | public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
}
| public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
if ("".equals(value)) {
throw new IllegalArgumentException(
"Cannot issue an EL reference to an empty path. For an empty binding please either supply null, or else provide a non-empty String as path");
}
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java
index 98a9b645d..bf61ec588 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java
@@ -1,349 +1,347 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 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
* Alexander Gurov - bug 230853
*******************************************************************************/
package org.eclipse.team.internal.ui.synchronize;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.compare.structuremergeviewer.IDiffContainer;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.*;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.team.core.synchronize.*;
import org.eclipse.team.internal.ui.*;
import org.eclipse.team.ui.synchronize.ISynchronizeModelElement;
import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
public class CompressedFoldersModelProvider extends HierarchicalModelProvider {
protected class UnchangedCompressedDiffNode extends UnchangedResourceModelElement {
public UnchangedCompressedDiffNode(IDiffContainer parent, IResource resource) {
super(parent, resource);
}
/* (non-Javadoc)
* @see org.eclipse.compare.structuremergeviewer.DiffNode#getName()
*/
public String getName() {
IResource resource = getResource();
return resource.getProjectRelativePath().toString();
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.SyncInfoModelElement#getImageDescriptor(java.lang.Object)
*/
public ImageDescriptor getImageDescriptor(Object object) {
return TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPRESSED_FOLDER);
}
}
/**
* A compressed folder appears under a project and contains out-of-sync resources
*/
public class CompressedFolderDiffNode extends SyncInfoModelElement {
public CompressedFolderDiffNode(IDiffContainer parent, SyncInfo info) {
super(parent, info);
}
/* (non-Javadoc)
* @see org.eclipse.compare.structuremergeviewer.DiffNode#getName()
*/
public String getName() {
IResource resource = getResource();
return resource.getProjectRelativePath().toString();
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.SyncInfoModelElement#getImageDescriptor(java.lang.Object)
*/
public ImageDescriptor getImageDescriptor(Object object) {
return TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPRESSED_FOLDER);
}
}
public static class CompressedFolderModelProviderDescriptor implements ISynchronizeModelProviderDescriptor {
public static final String ID = TeamUIPlugin.ID + ".modelprovider_compressedfolders"; //$NON-NLS-1$
public String getId() {
return ID;
}
public String getName() {
return TeamUIMessages.CompressedFoldersModelProvider_0;
}
public ImageDescriptor getImageDescriptor() {
return TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPRESSED_FOLDER);
}
}
private static final CompressedFolderModelProviderDescriptor compressedDescriptor = new CompressedFolderModelProviderDescriptor();
public CompressedFoldersModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) {
super(configuration, set);
}
public CompressedFoldersModelProvider(
AbstractSynchronizeModelProvider parentProvider,
ISynchronizeModelElement modelRoot,
ISynchronizePageConfiguration configuration, SyncInfoSet set) {
super(parentProvider, modelRoot, configuration, set);
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ui.synchronize.HierarchicalModelProvider#getDescriptor()
*/
public ISynchronizeModelProviderDescriptor getDescriptor() {
return compressedDescriptor;
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.SyncInfoDiffNodeRoot#getSorter()
*/
public ViewerSorter getViewerSorter() {
return new SynchronizeModelElementSorter() {
protected int compareNames(IResource resource1, IResource resource2) {
if (resource1.getType() == IResource.FOLDER && resource2.getType() == IResource.FOLDER) {
return collator.compare(resource1.getProjectRelativePath().toString(), resource2.getProjectRelativePath().toString());
}
return super.compareNames(resource1, resource2);
}
};
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.viewers.HierarchicalModelProvider#createModelObjects(org.eclipse.compare.structuremergeviewer.DiffNode)
*/
protected IDiffElement[] createModelObjects(ISynchronizeModelElement container) {
IResource resource = null;
if (container == getModelRoot()) {
resource = ResourcesPlugin.getWorkspace().getRoot();
} else {
resource = container.getResource();
}
if(resource != null) {
if (resource.getType() == IResource.PROJECT) {
return getProjectChildren(container, (IProject)resource);
}
if (resource.getType() == IResource.FOLDER) {
return getFolderChildren(container, resource);
}
}
return super.createModelObjects(container);
}
private IDiffElement[] getFolderChildren(ISynchronizeModelElement parent, IResource resource) {
// Folders will only contain out-of-sync children
IResource[] children = getSyncInfoTree().members(resource);
List result = new ArrayList();
for (int i = 0; i < children.length; i++) {
IResource child = children[i];
if (child.getType() == IResource.FILE) {
result.add(createModelObject(parent, child));
}
}
return (IDiffElement[])result.toArray(new IDiffElement[result.size()]);
}
private IDiffElement[] getProjectChildren(ISynchronizeModelElement parent, IProject project) {
// The out-of-sync elements could possibly include the project so the code
// below is written to ignore the project
SyncInfo[] outOfSync = getSyncInfoTree().getSyncInfos(project, IResource.DEPTH_INFINITE);
Set result = new HashSet();
Set resourcesToShow = new HashSet();
for (int i = 0; i < outOfSync.length; i++) {
SyncInfo info = outOfSync[i];
IResource local = info.getLocal();
if (local.getProjectRelativePath().segmentCount() == 1 && local.getType() == IResource.FILE) {
resourcesToShow.add(local);
} else {
if (local.getType() == IResource.FILE) {
resourcesToShow.add(local.getParent());
} else if (local.getType() == IResource.FOLDER){
resourcesToShow.add(local);
}
}
}
for (Iterator iter = resourcesToShow.iterator(); iter.hasNext();) {
IResource resource = (IResource) iter.next();
result.add(createModelObject(parent, resource));
}
return (IDiffElement[])result.toArray(new IDiffElement[result.size()]);
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.views.HierarchicalModelProvider#createChildNode(org.eclipse.compare.structuremergeviewer.DiffNode, org.eclipse.core.resources.IResource)
*/
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.viewers.HierarchicalModelProvider#createModelObject(org.eclipse.compare.structuremergeviewer.DiffNode, org.eclipse.core.resources.IResource)
*/
protected ISynchronizeModelElement createModelObject(ISynchronizeModelElement parent, IResource resource) {
if (resource.getType() == IResource.FOLDER) {
SyncInfo info = getSyncInfoTree().getSyncInfo(resource);
ISynchronizeModelElement newNode;
if(info != null) {
newNode = new CompressedFolderDiffNode(parent, info);
} else {
newNode = new UnchangedCompressedDiffNode(parent, resource);
}
addToViewer(newNode);
return newNode;
}
return super.createModelObject(parent, resource);
}
/**
* Update the viewer for the sync set additions in the provided event.
* This method is invoked by <code>handleChanges(ISyncInfoSetChangeEvent)</code>.
* Subclasses may override.
* @param event
*/
protected void handleResourceAdditions(ISyncInfoTreeChangeEvent event) {
SyncInfo[] infos = event.getAddedResources();
for (int i = 0; i < infos.length; i++) {
SyncInfo info = infos[i];
addResource(info);
}
}
protected void addResource(SyncInfo info) {
IResource local = info.getLocal();
ISynchronizeModelElement existingNode = getModelObject(local);
if (existingNode == null) {
if (local.getType() == IResource.FILE) {
ISynchronizeModelElement parentNode = getModelObject(local.getParent());
if (parentNode == null) {
ISynchronizeModelElement projectNode = getModelObject(local.getProject());
if (projectNode == null) {
projectNode = createModelObject(getModelRoot(), local.getProject());
}
if (local.getParent().getType() == IResource.PROJECT) {
parentNode = projectNode;
} else {
parentNode = createModelObject(projectNode, local.getParent());
}
}
createModelObject(parentNode, local);
} else {
ISynchronizeModelElement projectNode = getModelObject(local.getProject());
if (projectNode == null) {
projectNode = createModelObject(getModelRoot(), local.getProject());
}
if (local.getProject() != local) {
createModelObject(projectNode, local);
}
}
} else {
// Either The folder node was added as the parent of a newly added out-of-sync file
// or the file was somehow already there so just refresh
handleChange(existingNode, info);
}
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ui.sync.views.SyncSetContentProvider#handleResourceRemovals(org.eclipse.team.internal.ui.sync.views.SyncSetChangedEvent)
*/
protected void handleResourceRemovals(ISyncInfoTreeChangeEvent event) {
IResource[] roots = event.getRemovedSubtreeRoots();
// First, deal with any projects that have been removed
List removedProjects = new ArrayList();
for (int i = 0; i < roots.length; i++) {
IResource resource = roots[i];
if (resource.getType() == IResource.PROJECT) {
removeFromViewer(resource);
removedProjects.add(resource);
}
}
IResource[] resources = event.getRemovedResources();
List resourcesToRemove = new ArrayList();
List resourcesToAdd = new ArrayList();
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (!removedProjects.contains(resource.getProject())) {
if (resource.getType() == IResource.FILE) {
if (isCompressedParentEmpty(resource) && !isOutOfSync(resource.getParent())) {
// The parent compressed folder is also empty so remove it
resourcesToRemove.add(resource.getParent());
} else {
resourcesToRemove.add(resource);
}
} else {
// A folder has been removed (i.e. is in-sync)
// but may still contain children
resourcesToRemove.add(resource);
- if (hasFileMembers((IContainer)resource)) {
- resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource)));
- }
+ resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource)));
}
}
}
if (!resourcesToRemove.isEmpty()) {
removeFromViewer((IResource[]) resourcesToRemove.toArray(new IResource[resourcesToRemove.size()]));
}
if (!resourcesToAdd.isEmpty()) {
addResources((SyncInfo[]) resourcesToAdd.toArray(new SyncInfo[resourcesToAdd.size()]));
}
}
protected int getLogicalModelDepth(IResource resource) {
if(resource.getType() == IResource.PROJECT) {
return IResource.DEPTH_INFINITE;
} else {
return IResource.DEPTH_ONE;
}
}
private boolean isCompressedParentEmpty(IResource resource) {
IContainer parent = resource.getParent();
if (parent == null
|| parent.getType() == IResource.ROOT
|| parent.getType() == IResource.PROJECT) {
return false;
}
return !hasFileMembers(parent);
}
private boolean hasFileMembers(IContainer parent) {
// Check if the sync set has any file children of the parent
IResource[] members = getSyncInfoTree().members(parent);
for (int i = 0; i < members.length; i++) {
IResource member = members[i];
if (member.getType() == IResource.FILE) {
return true;
}
}
// The parent does not contain any files
return false;
}
private SyncInfo[] getSyncInfosForFileMembers(IContainer parent) {
// Check if the sync set has any file children of the parent
List result = new ArrayList();
IResource[] members = getSyncInfoTree().members(parent);
for (int i = 0; i < members.length; i++) {
SyncInfo info = getSyncInfoTree().getSyncInfo(members[i]);
if (info != null) {
result.add(info);
}
if (members[i] instanceof IContainer) {
result.addAll(Arrays.asList(this.getSyncInfosForFileMembers((IContainer)members[i])));
}
}
return (SyncInfo[]) result.toArray(new SyncInfo[result.size()]);
}
}
| true | true | protected void handleResourceRemovals(ISyncInfoTreeChangeEvent event) {
IResource[] roots = event.getRemovedSubtreeRoots();
// First, deal with any projects that have been removed
List removedProjects = new ArrayList();
for (int i = 0; i < roots.length; i++) {
IResource resource = roots[i];
if (resource.getType() == IResource.PROJECT) {
removeFromViewer(resource);
removedProjects.add(resource);
}
}
IResource[] resources = event.getRemovedResources();
List resourcesToRemove = new ArrayList();
List resourcesToAdd = new ArrayList();
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (!removedProjects.contains(resource.getProject())) {
if (resource.getType() == IResource.FILE) {
if (isCompressedParentEmpty(resource) && !isOutOfSync(resource.getParent())) {
// The parent compressed folder is also empty so remove it
resourcesToRemove.add(resource.getParent());
} else {
resourcesToRemove.add(resource);
}
} else {
// A folder has been removed (i.e. is in-sync)
// but may still contain children
resourcesToRemove.add(resource);
if (hasFileMembers((IContainer)resource)) {
resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource)));
}
}
}
}
if (!resourcesToRemove.isEmpty()) {
removeFromViewer((IResource[]) resourcesToRemove.toArray(new IResource[resourcesToRemove.size()]));
}
if (!resourcesToAdd.isEmpty()) {
addResources((SyncInfo[]) resourcesToAdd.toArray(new SyncInfo[resourcesToAdd.size()]));
}
}
| protected void handleResourceRemovals(ISyncInfoTreeChangeEvent event) {
IResource[] roots = event.getRemovedSubtreeRoots();
// First, deal with any projects that have been removed
List removedProjects = new ArrayList();
for (int i = 0; i < roots.length; i++) {
IResource resource = roots[i];
if (resource.getType() == IResource.PROJECT) {
removeFromViewer(resource);
removedProjects.add(resource);
}
}
IResource[] resources = event.getRemovedResources();
List resourcesToRemove = new ArrayList();
List resourcesToAdd = new ArrayList();
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (!removedProjects.contains(resource.getProject())) {
if (resource.getType() == IResource.FILE) {
if (isCompressedParentEmpty(resource) && !isOutOfSync(resource.getParent())) {
// The parent compressed folder is also empty so remove it
resourcesToRemove.add(resource.getParent());
} else {
resourcesToRemove.add(resource);
}
} else {
// A folder has been removed (i.e. is in-sync)
// but may still contain children
resourcesToRemove.add(resource);
resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource)));
}
}
}
if (!resourcesToRemove.isEmpty()) {
removeFromViewer((IResource[]) resourcesToRemove.toArray(new IResource[resourcesToRemove.size()]));
}
if (!resourcesToAdd.isEmpty()) {
addResources((SyncInfo[]) resourcesToAdd.toArray(new SyncInfo[resourcesToAdd.size()]));
}
}
|
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextRetrieveAction.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextRetrieveAction.java
index fe2ba5ceb..ce9f05f7f 100644
--- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextRetrieveAction.java
+++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextRetrieveAction.java
@@ -1,140 +1,141 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.internal.tasks.ui.wizards.ContextRetrieveWizard;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.IAttachmentHandler;
import org.eclipse.mylyn.tasks.core.RepositoryAttachment;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.ContextUiUtil;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
/**
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
*/
public class ContextRetrieveAction extends Action implements IViewActionDelegate {
private AbstractTask task;
private TaskRepository repository;
private AbstractRepositoryConnector connector;
private StructuredSelection selection;
private static final String ID_ACTION = "org.eclipse.mylyn.context.ui.repository.task.retrieve";
public ContextRetrieveAction() {
setText("Retrieve...");
setToolTipText("Retrieve Task Context");
setId(ID_ACTION);
setImageDescriptor(TasksUiImages.CONTEXT_RETRIEVE);
}
public void init(IViewPart view) {
// ignore
}
@Override
public void run() {
run(this);
}
public void run(IAction action) {
if (task != null) {
run(task);
} else {
// TODO: consider refactoring to be based on object contributions
if (selection.getFirstElement() instanceof RepositoryAttachment) {
RepositoryAttachment attachment = (RepositoryAttachment) selection.getFirstElement();
// HACK: need better way of getting task
IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
AbstractTask currentTask = null;
if (activeEditor instanceof TaskEditor) {
currentTask = ((TaskEditor) activeEditor).getTaskEditorInput().getTask();
}
if (currentTask instanceof AbstractTask) {
ContextUiUtil.downloadContext((AbstractTask) currentTask, attachment, PlatformUI
.getWorkbench().getProgressService());
} else {
MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Retrieve Context", "Can not retrieve contenxt for local tasks.");
}
}
}
}
public void run(AbstractTask task) {
ContextRetrieveWizard wizard = new ContextRetrieveWizard(task);
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (wizard != null && shell != null && !shell.isDisposed()) {
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.setTitle(ContextRetrieveWizard.WIZARD_TITLE);
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
dialog.close();
return;
}
}
}
public void selectionChanged(IAction action, ISelection selection) {
AbstractTask selectedTask = TaskListView.getSelectedTask(selection);
if (selectedTask == null) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
this.selection = structuredSelection;
if (structuredSelection.getFirstElement() instanceof RepositoryAttachment) {
RepositoryAttachment attachment = (RepositoryAttachment) structuredSelection.getFirstElement();
- if (AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION.equals(attachment.getDescription())) {
+ if (AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION.equals(attachment.getDescription())
+ || AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION_LEGACY.equals(attachment.getDescription())) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
}
} else if (selectedTask instanceof AbstractTask) {
task = (AbstractTask) selectedTask;
repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(),
task.getRepositoryUrl());
connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(task.getRepositoryKind());
IAttachmentHandler handler = connector.getAttachmentHandler();
action.setEnabled(handler != null && handler.canDownloadAttachment(repository, task)
&& connector.hasRepositoryContext(repository, task));
} else {
task = null;
action.setEnabled(false);
}
}
}
| true | true | public void selectionChanged(IAction action, ISelection selection) {
AbstractTask selectedTask = TaskListView.getSelectedTask(selection);
if (selectedTask == null) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
this.selection = structuredSelection;
if (structuredSelection.getFirstElement() instanceof RepositoryAttachment) {
RepositoryAttachment attachment = (RepositoryAttachment) structuredSelection.getFirstElement();
if (AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION.equals(attachment.getDescription())) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
}
} else if (selectedTask instanceof AbstractTask) {
task = (AbstractTask) selectedTask;
repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(),
task.getRepositoryUrl());
connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(task.getRepositoryKind());
IAttachmentHandler handler = connector.getAttachmentHandler();
action.setEnabled(handler != null && handler.canDownloadAttachment(repository, task)
&& connector.hasRepositoryContext(repository, task));
} else {
task = null;
action.setEnabled(false);
}
}
| public void selectionChanged(IAction action, ISelection selection) {
AbstractTask selectedTask = TaskListView.getSelectedTask(selection);
if (selectedTask == null) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
this.selection = structuredSelection;
if (structuredSelection.getFirstElement() instanceof RepositoryAttachment) {
RepositoryAttachment attachment = (RepositoryAttachment) structuredSelection.getFirstElement();
if (AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION.equals(attachment.getDescription())
|| AbstractRepositoryConnector.MYLAR_CONTEXT_DESCRIPTION_LEGACY.equals(attachment.getDescription())) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
}
} else if (selectedTask instanceof AbstractTask) {
task = (AbstractTask) selectedTask;
repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(),
task.getRepositoryUrl());
connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(task.getRepositoryKind());
IAttachmentHandler handler = connector.getAttachmentHandler();
action.setEnabled(handler != null && handler.canDownloadAttachment(repository, task)
&& connector.hasRepositoryContext(repository, task));
} else {
task = null;
action.setEnabled(false);
}
}
|
diff --git a/Glia/glia-examples/src/test/java/com/reversemind/glia/other/spring/GliaServerSpringContextLoader.java b/Glia/glia-examples/src/test/java/com/reversemind/glia/other/spring/GliaServerSpringContextLoader.java
index e206040..aff7a0d 100644
--- a/Glia/glia-examples/src/test/java/com/reversemind/glia/other/spring/GliaServerSpringContextLoader.java
+++ b/Glia/glia-examples/src/test/java/com/reversemind/glia/other/spring/GliaServerSpringContextLoader.java
@@ -1,104 +1,104 @@
package com.reversemind.glia.other.spring;
import com.reversemind.glia.GliaPayload;
import com.reversemind.glia.server.GliaServerFactory;
import com.reversemind.glia.server.IGliaPayloadProcessor;
import com.reversemind.glia.server.IGliaServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.Serializable;
import java.util.Map;
/**
*
*/
public class GliaServerSpringContextLoader implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(GliaServerSpringContextLoader.class);
public static void main(String... args) throws InterruptedException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/glia-server-context.xml");
GliaServerFactory.Builder builderAdvertiser = applicationContext.getBean("serverBuilderAdvertiser", GliaServerFactory.Builder.class);
LOG.debug("--------------------------------------------------------");
LOG.debug("Builder properties:");
LOG.debug("Name:" + builderAdvertiser.getName());
LOG.debug("Instance Name:" + builderAdvertiser.getInstanceName());
LOG.debug("port:" + builderAdvertiser.getPort());
LOG.debug("isAutoSelectPort:" + builderAdvertiser.isAutoSelectPort());
LOG.debug("Type:" + builderAdvertiser.getType());
LOG.debug("Zookeeper connection string:" + builderAdvertiser.getZookeeperHosts());
LOG.debug("Zookeeper base path:" + builderAdvertiser.getServiceBasePath());
IGliaServer server = builderAdvertiser.build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("After server initialization - properties");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + server.getName());
LOG.debug("Instance Name:" + server.getInstanceName());
LOG.debug("port:" + server.getPort());
server.start();
Thread.sleep(60000);
server.shutdown();
GliaServerFactory.Builder builderSimple = (GliaServerFactory.Builder) applicationContext.getBean("serverBuilderSimple");
- LOG.debug(builderSimple.port());
+ LOG.debug("" + builderSimple.port());
IGliaServer serverSimple = builderSimple
.setAutoSelectPort(true)
.setName("N A M E")
.setPort(8000)
.setPayloadWorker(new IGliaPayloadProcessor() {
@Override
public Map<Class, Class> getPojoMap() {
return null;
}
@Override
public void setPojoMap(Map<Class, Class> map) {
}
@Override
public void setEjbMap(Map<Class, String> map) {
}
@Override
public void registerPOJO(Class interfaceClass, Class pojoClass) {
}
@Override
public GliaPayload process(Object gliaPayloadObject) {
return null;
}
}).build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("Simple Glia server");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + serverSimple.getName());
LOG.debug("Instance Name:" + serverSimple.getInstanceName());
LOG.debug("port:" + serverSimple.getPort());
}
}
| true | true | public static void main(String... args) throws InterruptedException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/glia-server-context.xml");
GliaServerFactory.Builder builderAdvertiser = applicationContext.getBean("serverBuilderAdvertiser", GliaServerFactory.Builder.class);
LOG.debug("--------------------------------------------------------");
LOG.debug("Builder properties:");
LOG.debug("Name:" + builderAdvertiser.getName());
LOG.debug("Instance Name:" + builderAdvertiser.getInstanceName());
LOG.debug("port:" + builderAdvertiser.getPort());
LOG.debug("isAutoSelectPort:" + builderAdvertiser.isAutoSelectPort());
LOG.debug("Type:" + builderAdvertiser.getType());
LOG.debug("Zookeeper connection string:" + builderAdvertiser.getZookeeperHosts());
LOG.debug("Zookeeper base path:" + builderAdvertiser.getServiceBasePath());
IGliaServer server = builderAdvertiser.build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("After server initialization - properties");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + server.getName());
LOG.debug("Instance Name:" + server.getInstanceName());
LOG.debug("port:" + server.getPort());
server.start();
Thread.sleep(60000);
server.shutdown();
GliaServerFactory.Builder builderSimple = (GliaServerFactory.Builder) applicationContext.getBean("serverBuilderSimple");
LOG.debug(builderSimple.port());
IGliaServer serverSimple = builderSimple
.setAutoSelectPort(true)
.setName("N A M E")
.setPort(8000)
.setPayloadWorker(new IGliaPayloadProcessor() {
@Override
public Map<Class, Class> getPojoMap() {
return null;
}
@Override
public void setPojoMap(Map<Class, Class> map) {
}
@Override
public void setEjbMap(Map<Class, String> map) {
}
@Override
public void registerPOJO(Class interfaceClass, Class pojoClass) {
}
@Override
public GliaPayload process(Object gliaPayloadObject) {
return null;
}
}).build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("Simple Glia server");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + serverSimple.getName());
LOG.debug("Instance Name:" + serverSimple.getInstanceName());
LOG.debug("port:" + serverSimple.getPort());
}
| public static void main(String... args) throws InterruptedException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/glia-server-context.xml");
GliaServerFactory.Builder builderAdvertiser = applicationContext.getBean("serverBuilderAdvertiser", GliaServerFactory.Builder.class);
LOG.debug("--------------------------------------------------------");
LOG.debug("Builder properties:");
LOG.debug("Name:" + builderAdvertiser.getName());
LOG.debug("Instance Name:" + builderAdvertiser.getInstanceName());
LOG.debug("port:" + builderAdvertiser.getPort());
LOG.debug("isAutoSelectPort:" + builderAdvertiser.isAutoSelectPort());
LOG.debug("Type:" + builderAdvertiser.getType());
LOG.debug("Zookeeper connection string:" + builderAdvertiser.getZookeeperHosts());
LOG.debug("Zookeeper base path:" + builderAdvertiser.getServiceBasePath());
IGliaServer server = builderAdvertiser.build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("After server initialization - properties");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + server.getName());
LOG.debug("Instance Name:" + server.getInstanceName());
LOG.debug("port:" + server.getPort());
server.start();
Thread.sleep(60000);
server.shutdown();
GliaServerFactory.Builder builderSimple = (GliaServerFactory.Builder) applicationContext.getBean("serverBuilderSimple");
LOG.debug("" + builderSimple.port());
IGliaServer serverSimple = builderSimple
.setAutoSelectPort(true)
.setName("N A M E")
.setPort(8000)
.setPayloadWorker(new IGliaPayloadProcessor() {
@Override
public Map<Class, Class> getPojoMap() {
return null;
}
@Override
public void setPojoMap(Map<Class, Class> map) {
}
@Override
public void setEjbMap(Map<Class, String> map) {
}
@Override
public void registerPOJO(Class interfaceClass, Class pojoClass) {
}
@Override
public GliaPayload process(Object gliaPayloadObject) {
return null;
}
}).build();
LOG.debug("\n\n");
LOG.debug("--------------------------------------------------------");
LOG.debug("Simple Glia server");
LOG.debug("\n");
LOG.debug("Server properties:");
LOG.debug("......");
LOG.debug("Name:" + serverSimple.getName());
LOG.debug("Instance Name:" + serverSimple.getInstanceName());
LOG.debug("port:" + serverSimple.getPort());
}
|
diff --git a/xslthl/src/net/sf/xslthl/MainHighlighter.java b/xslthl/src/net/sf/xslthl/MainHighlighter.java
index a0442e5..80494cd 100644
--- a/xslthl/src/net/sf/xslthl/MainHighlighter.java
+++ b/xslthl/src/net/sf/xslthl/MainHighlighter.java
@@ -1,135 +1,137 @@
/*
* xslthl - XSLT Syntax Highlighting
* https://sourceforge.net/projects/xslthl/
* Copyright (C) 2005-2008 Michal Molhanec, Jirka Kosek, Michiel Hendriks
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Michal Molhanec <mol1111 at users.sourceforge.net>
* Jirka Kosek <kosek at users.sourceforge.net>
* Michiel Hendriks <elmuerte at users.sourceforge.net>
*/
package net.sf.xslthl;
import java.util.LinkedList;
import java.util.List;
/**
* Main source highlighter. It will call all registered highlighters.
*/
public class MainHighlighter {
/**
* Normal highlighter
*/
protected List<Highlighter> highlighters = new LinkedList<Highlighter>();
/**
*
*/
protected List<WholeHighlighter> wholehighlighters = new LinkedList<WholeHighlighter>();
public void add(Highlighter h) {
if (h instanceof WholeHighlighter) {
wholehighlighters.add((WholeHighlighter) h);
} else {
highlighters.add(h);
}
}
@Deprecated
public void addWhole(WholeHighlighter h) {
add(h);
}
/**
* Convert the input string into a collection of text blocks
*
* @param source
* @return
*/
public List<Block> highlight(String source) {
CharIter in = new CharIter(source);
List<Block> out = new LinkedList<Block>();
if (highlighters.size() > 0) {
while (!in.finished()) {
boolean found = false;
for (Highlighter h : highlighters) {
if (h.startsWith(in)) {
+ int pos = in.getPosition();
int oldMark = -2;
Block preBlock = null;
if (in.isMarked()) {
oldMark = in.getMark();
preBlock = in.markedToBlock();
out.add(preBlock);
}
found = h.highlight(in, out);
if (found) {
break;
} else {
// undo last action when it was a false positive
+ in.moveNext(pos - in.getPosition());
if (preBlock != null) {
out.remove(preBlock);
}
if (oldMark != -2) {
in.setMark(oldMark);
}
}
}
}
if (!found) {
in.moveNext();
}
}
} else {
in.moveToEnd();
}
if (in.isMarked()) {
out.add(in.markedToBlock());
}
if (wholehighlighters.size() > 0) {
for (WholeHighlighter h : wholehighlighters) {
List<Block> oldout = out;
out = new LinkedList<Block>();
for (Block b : oldout) {
if (b.isStyled()
&& (h.appliesOnAllStyles() || h
.appliesOnStyle(((StyledBlock) b)
.getStyle())) || !b.isStyled()
&& h.appliesOnEmptyStyle()) {
h.highlight(new CharIter(b.getText()), out);
} else {
out.add(b);
}
}
}
}
for (Highlighter h : highlighters) {
h.reset();
}
for (WholeHighlighter h : wholehighlighters) {
h.reset();
}
return out;
}
}
| false | true | public List<Block> highlight(String source) {
CharIter in = new CharIter(source);
List<Block> out = new LinkedList<Block>();
if (highlighters.size() > 0) {
while (!in.finished()) {
boolean found = false;
for (Highlighter h : highlighters) {
if (h.startsWith(in)) {
int oldMark = -2;
Block preBlock = null;
if (in.isMarked()) {
oldMark = in.getMark();
preBlock = in.markedToBlock();
out.add(preBlock);
}
found = h.highlight(in, out);
if (found) {
break;
} else {
// undo last action when it was a false positive
if (preBlock != null) {
out.remove(preBlock);
}
if (oldMark != -2) {
in.setMark(oldMark);
}
}
}
}
if (!found) {
in.moveNext();
}
}
} else {
in.moveToEnd();
}
if (in.isMarked()) {
out.add(in.markedToBlock());
}
if (wholehighlighters.size() > 0) {
for (WholeHighlighter h : wholehighlighters) {
List<Block> oldout = out;
out = new LinkedList<Block>();
for (Block b : oldout) {
if (b.isStyled()
&& (h.appliesOnAllStyles() || h
.appliesOnStyle(((StyledBlock) b)
.getStyle())) || !b.isStyled()
&& h.appliesOnEmptyStyle()) {
h.highlight(new CharIter(b.getText()), out);
} else {
out.add(b);
}
}
}
}
for (Highlighter h : highlighters) {
h.reset();
}
for (WholeHighlighter h : wholehighlighters) {
h.reset();
}
return out;
}
| public List<Block> highlight(String source) {
CharIter in = new CharIter(source);
List<Block> out = new LinkedList<Block>();
if (highlighters.size() > 0) {
while (!in.finished()) {
boolean found = false;
for (Highlighter h : highlighters) {
if (h.startsWith(in)) {
int pos = in.getPosition();
int oldMark = -2;
Block preBlock = null;
if (in.isMarked()) {
oldMark = in.getMark();
preBlock = in.markedToBlock();
out.add(preBlock);
}
found = h.highlight(in, out);
if (found) {
break;
} else {
// undo last action when it was a false positive
in.moveNext(pos - in.getPosition());
if (preBlock != null) {
out.remove(preBlock);
}
if (oldMark != -2) {
in.setMark(oldMark);
}
}
}
}
if (!found) {
in.moveNext();
}
}
} else {
in.moveToEnd();
}
if (in.isMarked()) {
out.add(in.markedToBlock());
}
if (wholehighlighters.size() > 0) {
for (WholeHighlighter h : wholehighlighters) {
List<Block> oldout = out;
out = new LinkedList<Block>();
for (Block b : oldout) {
if (b.isStyled()
&& (h.appliesOnAllStyles() || h
.appliesOnStyle(((StyledBlock) b)
.getStyle())) || !b.isStyled()
&& h.appliesOnEmptyStyle()) {
h.highlight(new CharIter(b.getText()), out);
} else {
out.add(b);
}
}
}
}
for (Highlighter h : highlighters) {
h.reset();
}
for (WholeHighlighter h : wholehighlighters) {
h.reset();
}
return out;
}
|
diff --git a/src/main/java/org/mcmmo/mcmmomc/mcMMOmc.java b/src/main/java/org/mcmmo/mcmmomc/mcMMOmc.java
index 712e73c..85e8831 100644
--- a/src/main/java/org/mcmmo/mcmmomc/mcMMOmc.java
+++ b/src/main/java/org/mcmmo/mcmmomc/mcMMOmc.java
@@ -1,56 +1,56 @@
package org.mcmmo.mcmmomc;
import java.io.IOException;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcmmo.mcmmomc.commands.TradeCommand;
import org.mcstats.Metrics;
public class mcMMOmc extends JavaPlugin {
// Player -> Channel
private HashMap<String, String> enabled = new HashMap<String, String>();
@Override
public void onEnable() {
PluginCommand tradeCommand = getCommand("tradechat");
tradeCommand.setPermission("mcmmomc.trade");
tradeCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
tradeCommand.setExecutor(new TradeCommand(this));
PluginCommand miscCommand = getCommand("miscchat");
- tradeCommand.setPermission("mcmmomc.misc");
- tradeCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
- tradeCommand.setExecutor(new MiscCommand(this));
+ miscCommand.setPermission("mcmmomc.misc");
+ miscCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
+ miscCommand.setExecutor(new MiscCommand(this));
metrics();
getLogger().info("Finished Loading " + getDescription().getFullName());
}
@Override
public void onDisable() {
getLogger().info("Finished Unloading " + getDescription().getFullName());
}
public boolean hasEnabled(String playerName, String channelName) {
return enabled.containsKey(playerName) && enabled.get(playerName) != null && enabled.get(playerName).equals(channelName);
}
public void enable(String playerName, String channelName) {
enabled.put(playerName, channelName);
}
public void disable(String playerName, String channelName) {
if(hasEnabled(playerName, channelName)) enabled.remove(playerName);
}
private void metrics() {
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) { }
}
}
| true | true | public void onEnable() {
PluginCommand tradeCommand = getCommand("tradechat");
tradeCommand.setPermission("mcmmomc.trade");
tradeCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
tradeCommand.setExecutor(new TradeCommand(this));
PluginCommand miscCommand = getCommand("miscchat");
tradeCommand.setPermission("mcmmomc.misc");
tradeCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
tradeCommand.setExecutor(new MiscCommand(this));
metrics();
getLogger().info("Finished Loading " + getDescription().getFullName());
}
| public void onEnable() {
PluginCommand tradeCommand = getCommand("tradechat");
tradeCommand.setPermission("mcmmomc.trade");
tradeCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
tradeCommand.setExecutor(new TradeCommand(this));
PluginCommand miscCommand = getCommand("miscchat");
miscCommand.setPermission("mcmmomc.misc");
miscCommand.setPermissionMessage(ChatColor.DARK_RED + "Insufficient permissions.");
miscCommand.setExecutor(new MiscCommand(this));
metrics();
getLogger().info("Finished Loading " + getDescription().getFullName());
}
|
diff --git a/source/de/tuclausthal/submissioninterface/authfilter/authentication/login/impl/Form.java b/source/de/tuclausthal/submissioninterface/authfilter/authentication/login/impl/Form.java
index 4e89995..3ebedb3 100644
--- a/source/de/tuclausthal/submissioninterface/authfilter/authentication/login/impl/Form.java
+++ b/source/de/tuclausthal/submissioninterface/authfilter/authentication/login/impl/Form.java
@@ -1,103 +1,103 @@
/*
* Copyright 2009 Sven Strickroth <[email protected]>
*
* This file is part of the SubmissionInterface.
*
* SubmissionInterface is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tuclausthal.submissioninterface.authfilter.authentication.login.impl;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.tuclausthal.submissioninterface.authfilter.authentication.login.LoginData;
import de.tuclausthal.submissioninterface.authfilter.authentication.login.LoginIf;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
/**
* Form-based login method implementation
* @author Sven Strickroth
*/
public class Form implements LoginIf {
public Form(FilterConfig filterConfig) {}
@Override
public void failNoData(HttpServletRequest request, HttpServletResponse response) throws IOException {
failNoData("", request, response);
}
@Override
public void failNoData(String error, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.addHeader("Cache-Control", "no-cache, must-revalidate");
Template template = TemplateFactory.getTemplate(request, response);
- template.addHead("<script type=\"text/javascript\"><!-- document.login.username.focus(); // --></script>");
template.printTemplateHeader("Login erforderlich", "Login erforderlich");
PrintWriter out = response.getWriter();
if (!error.isEmpty()) {
out.println("<div class=\"red,mid\">" + error + "</div>");
}
out.print("<form action=\"");
//out.print(response.encodeURL(MainBetterNameHereRequired.getServletRequest().getRequestURL().toString()));
out.println("\" method=POST name=login>");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>");
out.println("Benutzername:");
- out.println("</td>");
+ out.println("</th>");
out.println("<td>");
out.println("<input type=text size=20 name=username>");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>");
out.println("Passwort:");
- out.println("</td>");
+ out.println("</th>");
out.println("<td>");
out.println("<input type=password size=20 name=password>");
out.println("</td>");
out.println("<tr>");
out.println("<td colspan=2 class=mid>");
out.println("<input type=submit value=\"Log in\">");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
+ out.println("<script type=\"text/javascript\"><!--\ndocument.login.username.focus();\n// --></script>");
out.println("</form>");
template.printTemplateFooter();
out.close();
}
@Override
public LoginData getLoginData(HttpServletRequest request) {
if (request.getParameter("username") != null && !request.getParameter("username").isEmpty() && request.getParameter("password") != null && !request.getParameter("password").isEmpty()) {
return new LoginData(request.getParameter("username"), request.getParameter("password"));
} else {
return null;
}
}
@Override
public boolean requiresVerification() {
return true;
}
@Override
public boolean redirectAfterLogin() {
return true;
}
}
| false | true | public void failNoData(String error, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.addHeader("Cache-Control", "no-cache, must-revalidate");
Template template = TemplateFactory.getTemplate(request, response);
template.addHead("<script type=\"text/javascript\"><!-- document.login.username.focus(); // --></script>");
template.printTemplateHeader("Login erforderlich", "Login erforderlich");
PrintWriter out = response.getWriter();
if (!error.isEmpty()) {
out.println("<div class=\"red,mid\">" + error + "</div>");
}
out.print("<form action=\"");
//out.print(response.encodeURL(MainBetterNameHereRequired.getServletRequest().getRequestURL().toString()));
out.println("\" method=POST name=login>");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>");
out.println("Benutzername:");
out.println("</td>");
out.println("<td>");
out.println("<input type=text size=20 name=username>");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>");
out.println("Passwort:");
out.println("</td>");
out.println("<td>");
out.println("<input type=password size=20 name=password>");
out.println("</td>");
out.println("<tr>");
out.println("<td colspan=2 class=mid>");
out.println("<input type=submit value=\"Log in\">");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
template.printTemplateFooter();
out.close();
}
| public void failNoData(String error, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.addHeader("Cache-Control", "no-cache, must-revalidate");
Template template = TemplateFactory.getTemplate(request, response);
template.printTemplateHeader("Login erforderlich", "Login erforderlich");
PrintWriter out = response.getWriter();
if (!error.isEmpty()) {
out.println("<div class=\"red,mid\">" + error + "</div>");
}
out.print("<form action=\"");
//out.print(response.encodeURL(MainBetterNameHereRequired.getServletRequest().getRequestURL().toString()));
out.println("\" method=POST name=login>");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>");
out.println("Benutzername:");
out.println("</th>");
out.println("<td>");
out.println("<input type=text size=20 name=username>");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>");
out.println("Passwort:");
out.println("</th>");
out.println("<td>");
out.println("<input type=password size=20 name=password>");
out.println("</td>");
out.println("<tr>");
out.println("<td colspan=2 class=mid>");
out.println("<input type=submit value=\"Log in\">");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
out.println("<script type=\"text/javascript\"><!--\ndocument.login.username.focus();\n// --></script>");
out.println("</form>");
template.printTemplateFooter();
out.close();
}
|
diff --git a/src/com/nononsenseapps/notepad/NotesListFragment.java b/src/com/nononsenseapps/notepad/NotesListFragment.java
index dd35e1fd..265a24cb 100644
--- a/src/com/nononsenseapps/notepad/NotesListFragment.java
+++ b/src/com/nononsenseapps/notepad/NotesListFragment.java
@@ -1,2028 +1,2026 @@
/*
* Copyright (C) 2012 Jonas Kalderstam
*
* 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.nononsenseapps.notepad;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import com.nononsenseapps.helpers.UpdateNotifier;
import com.nononsenseapps.helpers.dualpane.DualLayoutActivity;
import com.nononsenseapps.helpers.dualpane.NoNonsenseListFragment;
import com.nononsenseapps.notepad.interfaces.OnModalDeleteListener;
import com.nononsenseapps.notepad.prefs.MainPrefs;
import com.nononsenseapps.notepad.prefs.SyncPrefs;
import com.nononsenseapps.notepad.sync.SyncAdapter;
import com.nononsenseapps.ui.NoteCheckBox;
import com.nononsenseapps.ui.SectionAdapter;
import com.nononsenseapps.util.TimeHelper;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import android.text.format.Time;
import com.nononsenseapps.helpers.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
public class NotesListFragment extends NoNonsenseListFragment implements
SearchView.OnQueryTextListener, OnItemLongClickListener,
OnModalDeleteListener, LoaderManager.LoaderCallbacks<Cursor>,
OnSharedPreferenceChangeListener {
private Callbacks mCallbacks = sDummyCallbacks;
private int mActivatedPosition = 0; // ListView.INVALID_POSITION;
public interface Callbacks {
public void onItemSelected(long id);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(long id) {
}
};
// Parent, list used for dragdrop
private static final String[] PROJECTION = new String[] {
NotePad.Notes._ID, NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE,
NotePad.Notes.COLUMN_NAME_DUE_DATE,
NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_LIST };
// public static final String SELECTEDPOS = "selectedpos";
// public static final String SELECTEDID = "selectedid";
// For logging and debugging
private static final String TAG = "NotesListFragment";
private static final int CHECK_SINGLE = 1;
private static final int CHECK_MULTI = 2;
private static final int CHECK_SINGLE_FUTURE = 3;
private static final String SAVEDPOS = "listSavedPos";
private static final String SAVEDID = "listSavedId";
private static final String SHOULD_OPEN_NOTE = "shouldOpenNote";
public static final String SECTION_STATE_LISTS = "listnames";
private static final int LOADER_LISTNAMES = -78;
// Will sort modification dates
private final Comparator<String> alphaComparator = new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
};
private static final int LOADER_REGULARLIST = -99;
// Date loaders
public static final String SECTION_STATE_DATE = MainPrefs.DUEDATESORT;
private static final int LOADER_DATEOVERDUE = -101;
private static final int LOADER_DATETODAY = -102;
private static final int LOADER_DATETOMORROW = -103;
private static final int LOADER_DATEWEEK = -104;
private static final int LOADER_DATEFUTURE = -105;
private static final int LOADER_DATENONE = -106;
private static final int LOADER_DATECOMPLETED = -107;
// This will sort date headers properly
private Comparator<String> dateComparator;
// Modification loaders
public static final String SECTION_STATE_MOD = MainPrefs.MODIFIEDSORT;
private static final int LOADER_MODTODAY = -201;
private static final int LOADER_MODYESTERDAY = -202;
private static final int LOADER_MODWEEK = -203;
private static final int LOADER_MODPAST = -204;
public static final String LISTID = "com.nononsenseapps.notepad.ListId";
// Will sort modification dates
private Comparator<String> modComparator;
private final Map<Long, String> listNames = new LinkedHashMap<Long, String>();
private long mCurId;
private boolean idInvalid = false;
public SearchView mSearchView;
public MenuItem mSearchItem;
private String currentQuery = "";
private int checkMode = CHECK_SINGLE;
private ModeCallbackHC modeCallback;
private long mCurListId = -1;
// private OnEditorDeleteListener onDeleteListener;
// private SimpleCursorAdapter mAdapter;
private SectionAdapter mSectionAdapter;
private final HashSet<Integer> activeLoaders = new HashSet<Integer>();
private boolean autoOpenNote = false;
private long newNoteIdToSelect = -1;
private Menu mOptionsMenu;
private View mRefreshIndeterminateProgressView = null;
private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SyncAdapter.SYNC_STARTED)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
setRefreshActionItemState(true);
}
});
} else if (intent.getAction().equals(SyncAdapter.SYNC_FINISHED)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
setRefreshActionItemState(false);
}
});
tellUser(context,
intent.getExtras().getInt(SyncAdapter.SYNC_RESULT));
}
}
private void tellUser(Context context, int result) {
int text = R.string.sync_failed;
switch (result) {
case SyncAdapter.ERROR:
text = R.string.sync_failed;
break;
case SyncAdapter.LOGIN_FAIL:
text = R.string.sync_login_failed;
break;
case SyncAdapter.SUCCESS:
default:
return;
}
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
}
};
private static String sortType = NotePad.Notes.DUEDATE_SORT_TYPE;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
this.activity = (DualLayoutActivity) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
activity = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (this.mCurListId != -1) {
//activity.findViewById(R.id.listContainer).setVisibility(View.VISIBLE);
//activity.findViewById(R.id.progressContainer).setVisibility(View.GONE);
Bundle args = new Bundle();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL))
args.putBoolean(SHOULD_OPEN_NOTE, true);
refreshList(args);
} else {
//activity.findViewById(R.id.listContainer).setVisibility(View.GONE);
//activity.findViewById(R.id.progressContainer).setVisibility(View.VISIBLE);
}
// Set list preferences
setSingleCheck();
}
public void handleNoteIntent(Intent intent) {
Log.d(TAG, "handleNoteIntent");
if (intent != null
&& (Intent.ACTION_EDIT.equals(intent.getAction()) || Intent.ACTION_VIEW
.equals(intent.getAction()))) {
// Are we displaying the correct list already?
long listId = -1;
if (null != intent.getExtras())
listId = intent.getExtras().getLong(
NotePad.Notes.COLUMN_NAME_LIST, -1);
if (listId == mCurListId || mCurListId == MainActivity.ALL_NOTES_ID) {
// just highlight it
String newId = intent.getData().getPathSegments()
.get(NotePad.Notes.NOTE_ID_PATH_POSITION);
long noteId = Long.parseLong(newId);
int pos = getPosOfId(noteId);
if (pos > -1) {
setActivatedPosition(showNote(pos));
} else {
newNoteIdToSelect = noteId;
}
} else {
// it's something we have to handle once the list has been
// loaded
String newId = intent.getData().getPathSegments()
.get(NotePad.Notes.NOTE_ID_PATH_POSITION);
long noteId = Long.parseLong(newId);
if (noteId > -1) {
newNoteIdToSelect = noteId;
}
}
}
}
/**
* Will try to open the previously open note, but will default to first note
* if none was open
*/
private void showFirstBestNote() {
if (mSectionAdapter != null) {
if (mSectionAdapter.isEmpty()) {
// DOn't do shit
} else {
setActivatedPosition(showNote(mActivatedPosition));
}
}
}
private void setupSearchView() {
Log.d("NotesListFragment", "setup search view");
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.search_hint));
}
}
private int getPosOfId(long id) {
if (mSectionAdapter != null)
return -1;
int length = mSectionAdapter.getCount();
int position;
for (position = 0; position < length; position++) {
if (id == mSectionAdapter.getItemId(position)) {
break;
}
}
if (position == length) {
// Happens both if list is empty
// and if id is -1
position = -1;
}
return position;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate menu from XML resource
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_options_menu_light, menu);
// else
mOptionsMenu = menu;
inflater.inflate(R.menu.list_options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) activity
.getSystemService(Context.SEARCH_SERVICE);
mSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) mSearchItem.getActionView();
if (mSearchView != null)
mSearchView.setSearchableInfo(searchManager
.getSearchableInfo(activity.getComponentName()));
// searchView.setIconifiedByDefault(true); // Do iconify the widget;
// Don't
// // expand by default
// searchView.setSubmitButtonEnabled(false);
// searchView.setOnCloseListener(this);
// searchView.setOnQueryTextListener(this);
setupSearchView();
// Generate any additional actions that can be performed on the
// overall list. In a normal install, there are no additional
// actions found here, but this allows other applications to extend
// our menu with their own actions.
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
public static int getNoteIdFromUri(Uri noteUri) {
if (noteUri != null)
return Integer.parseInt(noteUri.getPathSegments().get(
NotePad.Notes.NOTE_ID_PATH_POSITION));
else
return -1;
}
private void handleNoteCreation(long listId) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSERT);
intent.setData(NotePad.Notes.CONTENT_VISIBLE_URI);
intent.putExtra(NotePad.Notes.COLUMN_NAME_LIST, listId);
// If tablet mode, deliver directly
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
((MainActivity) activity).onNewIntent(intent);
}
// Otherwise start a new editor activity
else {
intent.setClass(activity, RightActivity.class);
startActivity(intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
handleNoteCreation(mCurListId);
return true;
case R.id.menu_clearcompleted:
ContentValues values = new ContentValues();
values.put(NotePad.Notes.COLUMN_NAME_MODIFIED, -1); // -1 anything
// that isnt 0
// or 1
// indicates
// that we dont
// want to
// change the
// current value
values.put(NotePad.Notes.COLUMN_NAME_LOCALHIDDEN, 1);
// Handle all notes showing
String inList;
String[] args;
if (mCurListId == MainActivity.ALL_NOTES_ID) {
inList = "";
args = new String[] { getText(R.string.gtask_status_completed)
.toString() };
} else {
inList = " AND " + NotePad.Notes.COLUMN_NAME_LIST + " IS ?";
args = new String[] {
getText(R.string.gtask_status_completed).toString(),
Long.toString(mCurListId) };
}
activity.getContentResolver().update(NotePad.Notes.CONTENT_URI,
values,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?" + inList,
args);
UpdateNotifier.notifyChangeNote(activity);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To get the call back to add items to the menu
setHasOptionsMenu(true);
// Listen to changes to sort order
PreferenceManager.getDefaultSharedPreferences(activity)
.registerOnSharedPreferenceChangeListener(this);
if (getResources().getBoolean(R.bool.atLeast14)) {
// Share action provider
modeCallback = new ModeCallbackICS(this);
} else {
// Share button
modeCallback = new ModeCallbackHC(this);
}
if (modeCallback != null)
modeCallback.setDeleteListener(this);
this.mCurListId = -1;
if (getArguments()!= null && getArguments().containsKey(LISTID)) {
mCurListId = getArguments().getLong(LISTID);
}
if (savedInstanceState != null) {
Log.d("NotesListFragment", "onCreate saved not null");
mCurListId = savedInstanceState.getLong(LISTID);
mActivatedPosition = savedInstanceState.getInt(SAVEDPOS, 0);
mCurId = savedInstanceState.getLong(SAVEDID, -1);
} else {
mActivatedPosition = 0;
mCurId = -1;
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("NotesListFragment", "onSaveInstanceState");
outState.putInt(SAVEDPOS, mActivatedPosition);
outState.putLong(SAVEDID, mCurId);
outState.putLong(LISTID, mCurListId);
}
@Override
public void onPause() {
super.onPause();
activity.unregisterReceiver(syncFinishedReceiver);
}
@Override
public void onDestroy() {
super.onDestroy();
destroyActiveLoaders();
destroyDateLoaders();
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
@Override
public void onResume() {
super.onResume();
Log.d("NotesListFragment", "onResume");
activity.registerReceiver(syncFinishedReceiver, new IntentFilter(
SyncAdapter.SYNC_FINISHED));
activity.registerReceiver(syncFinishedReceiver, new IntentFilter(
SyncAdapter.SYNC_STARTED));
String accountName = PreferenceManager.getDefaultSharedPreferences(
activity).getString(SyncPrefs.KEY_ACCOUNT, "");
// Sync state might have changed, make sure we're spinning when we
// should
if (accountName != null && !accountName.isEmpty())
setRefreshActionItemState(ContentResolver.isSyncActive(SyncPrefs
.getAccount(AccountManager.get(activity), accountName),
NotePad.AUTHORITY));
}
@Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
Log.d("listproto", "OnListItemClick pos " + position + " id " + id);
// Will tell the activity to open the note
mActivatedPosition = showNote(position);
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
public void setActivatedPosition(int position) {
if (checkMode == CHECK_SINGLE_FUTURE) {
setSingleCheck();
}
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* Larger values than the list contains are re-calculated to valid
* positions. If list is empty, no note is opened.
*
* returns position of note in list
*/
private int showNote(int index) {
// if it's -1 to start with, we try with zero
if (index < 0) {
index = 0;
}
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "showNote valid index to show is: " + index);
if (index > -1) {
Log.d("listproto", "Going to try and open index: " + index);
Log.d("listproto", "Section adapter gave me this id: " + mCurId);
mCurId = mSectionAdapter.getItemId(index);
mCallbacks.onItemSelected(mCurId);
} else {
// Empty search, do NOT display new note.
mActivatedPosition = 0;
mCurId = -1;
// Default show first note when search is cancelled.
}
}
return index;
}
/**
* Will re-list all notes, and show the note with closest position to
* original
*/
public void onDelete() {
Log.d(TAG, "onDelete");
// Only do anything if id is valid!
if (mCurId > -1) {
// if (onDeleteListener != null) {
// // Tell fragment to delete the current note
// onDeleteListener.onEditorDelete(mCurId);
// }
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
autoOpenNote = true;
}
// if (FragmentLayout.LANDSCAPE_MODE) {
// } else {
// // Get the id of the currently "selected" note
// // This matters if we switch to landscape mode
// reCalculateValidValuesAfterDelete();
// }
}
}
private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
// This happens in a search. Don't destroy id information in selectPos
// when it is invalid
if (pos != -1) {
setActivatedPosition(pos);
}
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
if (activity != null) {
if (PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTITEM, true)) {
themed_item = R.layout.noteslist_item;
} else {
themed_item = R.layout.noteslist_item_doublenote;
}
}
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty()) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
// lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
if (checkedCount == 0) {
mode.setSubtitle(null);
} else {
mode.setSubtitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
- if (mCurListId == MainActivity.ALL_NOTES_ID
- && PreferenceManager.getDefaultSharedPreferences(activity)
- .getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
+ if (mCurListId == MainActivity.ALL_NOTES_ID) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
if (args.containsKey(SHOULD_OPEN_NOTE)
&& args.getBoolean(SHOULD_OPEN_NOTE)) {
autoOpenNote = true;
}
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
activity.findViewById(R.id.listContainer).setVisibility(View.VISIBLE);
activity.findViewById(R.id.hintContainer).setVisibility(View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
activity.findViewById(R.id.listContainer).setVisibility(View.GONE);
activity.findViewById(R.id.hintContainer).setVisibility(View.VISIBLE);
}
// Reselect current note in list, if possible
// This happens in delete
if (idInvalid) {
idInvalid = false;
// Note is invalid, so recalculate a valid position and index
reCalculateValidValuesAfterDelete();
reSelectId();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL))
autoOpenNote = true;
}
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
else if (autoOpenNote) {
autoOpenNote = false;
showFirstBestNote();
} else {
reSelectId();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
| true | true | private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
// This happens in a search. Don't destroy id information in selectPos
// when it is invalid
if (pos != -1) {
setActivatedPosition(pos);
}
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
if (activity != null) {
if (PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTITEM, true)) {
themed_item = R.layout.noteslist_item;
} else {
themed_item = R.layout.noteslist_item_doublenote;
}
}
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty()) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
// lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
if (checkedCount == 0) {
mode.setSubtitle(null);
} else {
mode.setSubtitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
if (args.containsKey(SHOULD_OPEN_NOTE)
&& args.getBoolean(SHOULD_OPEN_NOTE)) {
autoOpenNote = true;
}
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
activity.findViewById(R.id.listContainer).setVisibility(View.VISIBLE);
activity.findViewById(R.id.hintContainer).setVisibility(View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
activity.findViewById(R.id.listContainer).setVisibility(View.GONE);
activity.findViewById(R.id.hintContainer).setVisibility(View.VISIBLE);
}
// Reselect current note in list, if possible
// This happens in delete
if (idInvalid) {
idInvalid = false;
// Note is invalid, so recalculate a valid position and index
reCalculateValidValuesAfterDelete();
reSelectId();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL))
autoOpenNote = true;
}
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
else if (autoOpenNote) {
autoOpenNote = false;
showFirstBestNote();
} else {
reSelectId();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
| private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
// This happens in a search. Don't destroy id information in selectPos
// when it is invalid
if (pos != -1) {
setActivatedPosition(pos);
}
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
if (activity != null) {
if (PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTITEM, true)) {
themed_item = R.layout.noteslist_item;
} else {
themed_item = R.layout.noteslist_item_doublenote;
}
}
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty()) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
// lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
if (checkedCount == 0) {
mode.setSubtitle(null);
} else {
mode.setSubtitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle(getString(R.string.mode_choose));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
if (mCurListId == MainActivity.ALL_NOTES_ID) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
if (args.containsKey(SHOULD_OPEN_NOTE)
&& args.getBoolean(SHOULD_OPEN_NOTE)) {
autoOpenNote = true;
}
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
activity.findViewById(R.id.listContainer).setVisibility(View.VISIBLE);
activity.findViewById(R.id.hintContainer).setVisibility(View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
activity.findViewById(R.id.listContainer).setVisibility(View.GONE);
activity.findViewById(R.id.hintContainer).setVisibility(View.VISIBLE);
}
// Reselect current note in list, if possible
// This happens in delete
if (idInvalid) {
idInvalid = false;
// Note is invalid, so recalculate a valid position and index
reCalculateValidValuesAfterDelete();
reSelectId();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL))
autoOpenNote = true;
}
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
else if (autoOpenNote) {
autoOpenNote = false;
showFirstBestNote();
} else {
reSelectId();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
|
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
index cc27f706..0ee45840 100644
--- a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
+++ b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
@@ -1,180 +1,181 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.recorder.ui;
import org.cubictest.common.utils.ErrorHandler;
import org.cubictest.common.utils.UserInfo;
import org.cubictest.export.exceptions.ExporterException;
import org.cubictest.export.utils.exported.ExportUtils;
import org.cubictest.exporters.selenium.ui.RunSeleniumRunnerAction;
import org.cubictest.model.ExtensionPoint;
import org.cubictest.model.ExtensionStartPoint;
import org.cubictest.model.ExtensionTransition;
import org.cubictest.model.Page;
import org.cubictest.model.SubTest;
import org.cubictest.model.Test;
import org.cubictest.model.Transition;
import org.cubictest.model.UrlStartPoint;
import org.cubictest.recorder.CubicRecorder;
import org.cubictest.recorder.GUIAwareRecorder;
import org.cubictest.recorder.IRecorder;
import org.cubictest.recorder.selenium.SeleniumRecorder;
import org.cubictest.ui.gef.interfaces.exported.IDisposeListener;
import org.cubictest.ui.gef.interfaces.exported.ITestEditor;
import org.cubictest.ui.gef.layout.AutoLayout;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
/**
* Action for starting / stopping the CubicRecorder.
*
*/
public class RecordEditorAction implements IEditorActionDelegate {
IResource currentFile;
private boolean running;
private SeleniumRecorder seleniumRecorder;
private ITestEditor testEditor;
public RecordEditorAction() {
super();
}
/**
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
UserInfo.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
+ runner.setActiveEditor(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
private void stopSelenium(AutoLayout autoLayout) {
try {
setRunning(false);
if (seleniumRecorder != null) {
seleniumRecorder.stop();
}
if (autoLayout != null) {
autoLayout.setPageSelected(null);
}
}
catch(Exception e) {
ErrorHandler.logAndRethrow(e);
}
}
/**
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {}
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
this.testEditor = (ITestEditor) targetEditor;
}
private void setRunning(boolean run) {
running = run;
}
/**
* Get the initial URL start point of the test (expands subtests).
*/
private UrlStartPoint getInitialUrlStartPoint(Test test) {
if (test.getStartPoint() instanceof UrlStartPoint) {
return (UrlStartPoint) test.getStartPoint();
}
else {
//ExtensionStartPoint, get url start point recursively:
return getInitialUrlStartPoint(((ExtensionStartPoint) test.getStartPoint()).getTest(true));
}
}
public boolean firstPageIsEmpty(Test test) {
for(Transition t : test.getStartPoint().getOutTransitions()) {
if(t.getEnd() instanceof Page && ((Page)t.getEnd()).getElements().size() == 0) {
return true;
}
}
return false;
}
}
| true | true | public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
UserInfo.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
| public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
UserInfo.showErrorDialog("The test must be empty to use the recorder.");
return;
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser will be forwarded to start point for test.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActiveEditor(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
|
diff --git a/tycho-core/src/main/java/org/eclipse/tycho/osgi/configuration/MavenContextConfigurator.java b/tycho-core/src/main/java/org/eclipse/tycho/osgi/configuration/MavenContextConfigurator.java
index 0741f3b6..cde12ada 100644
--- a/tycho-core/src/main/java/org/eclipse/tycho/osgi/configuration/MavenContextConfigurator.java
+++ b/tycho-core/src/main/java/org/eclipse/tycho/osgi/configuration/MavenContextConfigurator.java
@@ -1,63 +1,66 @@
/*******************************************************************************
* Copyright (c) 2011 SAP AG 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:
* SAP AG - initial API and implementation
*******************************************************************************/
package org.eclipse.tycho.osgi.configuration;
import java.io.File;
import java.util.Map;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.settings.Profile;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import org.eclipse.sisu.equinox.embedder.EmbeddedEquinox;
import org.eclipse.sisu.equinox.embedder.EquinoxLifecycleListener;
import org.eclipse.tycho.core.facade.MavenContext;
import org.eclipse.tycho.core.facade.MavenContextImpl;
import org.eclipse.tycho.osgi.adapters.MavenLoggerAdapter;
@Component(role = EquinoxLifecycleListener.class, hint = "MavenContextConfigurator")
public class MavenContextConfigurator extends EquinoxLifecycleListener {
@Requirement
private Logger logger;
@Requirement
private LegacySupport context;
@Override
public void afterFrameworkStarted(EmbeddedEquinox framework) {
MavenSession session = context.getSession();
File localRepoRoot = new File(session.getLocalRepository().getBasedir());
MavenLoggerAdapter mavenLogger = new MavenLoggerAdapter(logger, false);
Properties globalProps = getGlobalProperties(session);
MavenContext mavenContext = new MavenContextImpl(localRepoRoot, session.isOffline(), mavenLogger, globalProps);
framework.registerService(MavenContext.class, mavenContext);
}
private Properties getGlobalProperties(MavenSession session) {
Properties globalProps = new Properties();
// 1. system
globalProps.putAll(session.getSystemProperties());
Settings settings = session.getSettings();
// 2. active profiles
Map<String, Profile> profileMap = settings.getProfilesAsMap();
for (String profileId : settings.getActiveProfiles()) {
- globalProps.putAll(profileMap.get(profileId).getProperties());
+ Profile profile = profileMap.get(profileId);
+ if (profile != null) {
+ globalProps.putAll(profile.getProperties());
+ }
}
// 3. user
globalProps.putAll(session.getUserProperties());
return globalProps;
}
}
| true | true | private Properties getGlobalProperties(MavenSession session) {
Properties globalProps = new Properties();
// 1. system
globalProps.putAll(session.getSystemProperties());
Settings settings = session.getSettings();
// 2. active profiles
Map<String, Profile> profileMap = settings.getProfilesAsMap();
for (String profileId : settings.getActiveProfiles()) {
globalProps.putAll(profileMap.get(profileId).getProperties());
}
// 3. user
globalProps.putAll(session.getUserProperties());
return globalProps;
}
| private Properties getGlobalProperties(MavenSession session) {
Properties globalProps = new Properties();
// 1. system
globalProps.putAll(session.getSystemProperties());
Settings settings = session.getSettings();
// 2. active profiles
Map<String, Profile> profileMap = settings.getProfilesAsMap();
for (String profileId : settings.getActiveProfiles()) {
Profile profile = profileMap.get(profileId);
if (profile != null) {
globalProps.putAll(profile.getProperties());
}
}
// 3. user
globalProps.putAll(session.getUserProperties());
return globalProps;
}
|
diff --git a/src/java/com/splunk/shep/archiver/archive/ArchiveConfiguration.java b/src/java/com/splunk/shep/archiver/archive/ArchiveConfiguration.java
index 424950c5..216c1c01 100644
--- a/src/java/com/splunk/shep/archiver/archive/ArchiveConfiguration.java
+++ b/src/java/com/splunk/shep/archiver/archive/ArchiveConfiguration.java
@@ -1,78 +1,77 @@
package com.splunk.shep.archiver.archive;
import java.lang.ref.SoftReference;
import java.net.URI;
import org.apache.hadoop.fs.Path;
// CONFIG This whole class should use MBeans
public class ArchiveConfiguration {
/**
* Soft link so the memory can be used if needed. (Soft links are
* GarbageCollected only if there is really need for the memory)
*/
private static SoftReference<ArchiveConfiguration> sharedInstanceRef;
private static final String ARCHIVING_ROOT = "archiving_root";
private static final String CLUSTER_NAME = "cluster_name";
private static final String SERVER_NAME = "server_name";
private static final String TMP_DIRECTORY_OF_ARCHIVER = "/archiver-tmp";
private static final URI archiverHadoopURI = URI
.create("hdfs://localhost:9000");
protected ArchiveConfiguration() {
super();
/*
* If the configuration of ArchiveConfiguration is time consuming maybe
* the shared instance should be hardlinked.
*/
}
public static ArchiveConfiguration getSharedInstance() {
ArchiveConfiguration sharedInstance = null;
if (sharedInstanceRef != null) {
sharedInstance = sharedInstanceRef.get();
}
if (sharedInstance == null) {
sharedInstance = new ArchiveConfiguration();
sharedInstanceRef = new SoftReference<ArchiveConfiguration>(
sharedInstance);
}
- System.err.println(sharedInstanceRef);
return sharedInstance;
}
public BucketFormat getArchiveFormat() {
return BucketFormat.SPLUNK_BUCKET;
}
public String getArchivingRoot() {
return ARCHIVING_ROOT;
}
public String getClusterName() {
return CLUSTER_NAME;
}
public String getServerName() {
return SERVER_NAME;
}
/**
* @return The Path on hadoop filesystem that is used as a temp directory
*/
public Path getTmpDirectory() {
return new Path(new Path(getArchiverHadoopURI()),
TMP_DIRECTORY_OF_ARCHIVER);
}
/**
* @return URI pointing to the hadoop filesystem instance that is used for
* archiving.
*/
public URI getArchiverHadoopURI() {
return archiverHadoopURI;
}
}
| true | true | public static ArchiveConfiguration getSharedInstance() {
ArchiveConfiguration sharedInstance = null;
if (sharedInstanceRef != null) {
sharedInstance = sharedInstanceRef.get();
}
if (sharedInstance == null) {
sharedInstance = new ArchiveConfiguration();
sharedInstanceRef = new SoftReference<ArchiveConfiguration>(
sharedInstance);
}
System.err.println(sharedInstanceRef);
return sharedInstance;
}
| public static ArchiveConfiguration getSharedInstance() {
ArchiveConfiguration sharedInstance = null;
if (sharedInstanceRef != null) {
sharedInstance = sharedInstanceRef.get();
}
if (sharedInstance == null) {
sharedInstance = new ArchiveConfiguration();
sharedInstanceRef = new SoftReference<ArchiveConfiguration>(
sharedInstance);
}
return sharedInstance;
}
|
diff --git a/app/models/Photo.java b/app/models/Photo.java
index f38f671..f6c8838 100644
--- a/app/models/Photo.java
+++ b/app/models/Photo.java
@@ -1,94 +1,93 @@
package models;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import javax.persistence.*;
import play.libs.*;
import play.db.jpa.*;
import play.data.validation.*;
import net.coobird.thumbnailator.*;
import net.coobird.thumbnailator.geometry.*;
import net.coobird.thumbnailator.name.*;
@Entity
public class Photo extends Post {
public static final int MAX_PIXEL_SIZE = 1024;
@Required
public Blob image;
@Required
public Blob thumbnail120x120,
thumbnail50x50,
thumbnail30x30;
public Photo(User owner, File image) throws IOException,
FileNotFoundException {
this(owner, image, "");
}
public Photo(User owner, File image, String caption)
throws IOException,
FileNotFoundException {
super(owner, owner, caption);
shrinkImage(image);
this.image = fileToBlob(image);
this.createThumbnails();
}
public void updateImage(File image) throws IOException,
FileNotFoundException {
shrinkImage(image);
this.image = fileToBlob(image);
this.createThumbnails();
}
private void createThumbnails() throws IOException {
this.thumbnail120x120 = this.createThumbnailBlob(120, 120);
this.thumbnail50x50 = this.createThumbnailBlob(50, 50);
this.thumbnail30x30 = this.createThumbnailBlob(30, 30);
}
private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
- .outputFormat("jpg")
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
/**
* Shrink the image to MAX_PIXEL_SIZE if necessary.
*
* @param image the file to convert.
* @throws IOException
*/
private static void shrinkImage(File image) throws IOException {
BufferedImage bufferedImage = ImageIO.read(image);
if (bufferedImage != null && (bufferedImage.getWidth() > MAX_PIXEL_SIZE ||
bufferedImage.getHeight() > MAX_PIXEL_SIZE)) {
Thumbnailator.createThumbnail(image, image,
MAX_PIXEL_SIZE, MAX_PIXEL_SIZE);
}
}
/**
* Convert a given File to a Photo model.
*
* @param image the file to convert.
* @return the newly created Photo model.
* @throws FileNotFoundException
*/
private static Blob fileToBlob(File image) throws FileNotFoundException {
Blob blob = new Blob();
blob.set(new FileInputStream(image),
MimeTypes.getContentType(image.getName()));
return blob;
}
}
| true | true | private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
.outputFormat("jpg")
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
| private Blob createThumbnailBlob(int width, int height) throws IOException {
File image = this.image.getFile();
File thumbnail = Thumbnails.of(image)
.size(width, height)
.crop(Positions.CENTER)
.asFiles(Rename.NO_CHANGE)
.get(0);
return fileToBlob(thumbnail);
}
|
diff --git a/src/com/zemariamm/appirater/AppirateUtils.java b/src/com/zemariamm/appirater/AppirateUtils.java
index 916ec67..9f185d9 100644
--- a/src/com/zemariamm/appirater/AppirateUtils.java
+++ b/src/com/zemariamm/appirater/AppirateUtils.java
@@ -1,123 +1,123 @@
package com.zemariamm.appirater;
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.content.DialogInterface.OnClickListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class AppirateUtils {
public static final int SHOW_APPIRATER = 4;
public static final String DB_PREFERENCES="DB_APPIRATER";
private static SharedPreferences getPreferences(Context context) {
int mode = Activity.MODE_PRIVATE;
return context.getSharedPreferences(DB_PREFERENCES, mode);
}
private static boolean isNeverShowAppirater(Context context){
SharedPreferences prefs = AppirateUtils.getPreferences(context);
return prefs.getBoolean("neverrate", false);
}
public static void markNeverRate(Context context) {
SharedPreferences.Editor editor = AppirateUtils.getPreferences(context).edit();
editor.putBoolean("neverrate", true);
editor.commit();
}
private static int getTimesOpened(Context context)
{
SharedPreferences prefs = AppirateUtils.getPreferences(context);
int times = prefs.getInt("times", 0);
times++;
//Log.d("Hooligans AppiraterUtils"," ******************************************* Current number: " + times);
SharedPreferences.Editor editor = AppirateUtils.getPreferences(context).edit();
editor.putInt("times", times);
editor.commit();
return times;
}
private static int getShowAppirater(Context context) {
int default_times = AppirateUtils.SHOW_APPIRATER;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Bundle aBundle=ai.metaData;
default_times = aBundle.getInt("appirater");
// no divide by zero!
if (default_times == 0)
default_times = AppirateUtils.SHOW_APPIRATER;
}
catch (Exception e) {
e.printStackTrace();
}
return default_times;
}
public static boolean shouldAppirater(Context context) {
int times = AppirateUtils.getTimesOpened(context);
boolean shouldShow = false;
if (times % getShowAppirater(context) == 0)
{
shouldShow = true;
}
if (AppirateUtils.isNeverShowAppirater(context))
{
//Log.d("Hooligans AppiraterUtils"," ******************************************* He once clicked NEVER RATE THIS APP or ALREADY Rated it");
shouldShow = false;
}
return shouldShow;
}
public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
- String title = context.getString(R.string.appirate_utils_message_before_appname) + appName + context.getString(R.string.appirate_utils_message_after_appname);
+ String title = context.getString(R.string.appirate_utils_message_before_appname) + " " + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
}
| true | true | public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
String title = context.getString(R.string.appirate_utils_message_before_appname) + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
| public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
String title = context.getString(R.string.appirate_utils_message_before_appname) + " " + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
|
diff --git a/src/main/java/com/morgan/design/android/service/ReloadingAlarmService.java b/src/main/java/com/morgan/design/android/service/ReloadingAlarmService.java
index 406e0dd..20bffde 100644
--- a/src/main/java/com/morgan/design/android/service/ReloadingAlarmService.java
+++ b/src/main/java/com/morgan/design/android/service/ReloadingAlarmService.java
@@ -1,63 +1,63 @@
package com.morgan.design.android.service;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.morgan.design.Constants;
import com.morgan.design.android.dao.WeatherChoiceDao;
import com.morgan.design.android.repository.DatabaseHelper;
import com.morgan.design.android.util.Logger;
import com.morgan.design.android.util.PreferenceUtils;
public class ReloadingAlarmService extends IntentService {
private static final String LOG_TAG = "ReloadingAlarmService";
public ReloadingAlarmService() {
super("com.morgan.design.android.service.ReloadingAlarmService");
}
// http://it-ride.blogspot.com/2010/10/android-implementing-notification.html
@Override
protected void onHandleIntent(final Intent intent) {
Logger.d(LOG_TAG, "Reloading Alarm Service Initiated -> may set new one");
final AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
- final PendingIntent pi = PendingIntent.getService(this, 0, new Intent("com.morgan.design.android.broadcast.LOOPING_ALARM"), 0);
+ final PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("com.morgan.design.android.broadcast.LOOPING_ALARM"), 0);
boolean hasNotifications = false;
try {
// Cancel any existing alarms
mAlarmManager.cancel(pi);
final WeatherChoiceDao dao = new WeatherChoiceDao(OpenHelperManager.getHelper(getApplicationContext(), DatabaseHelper.class));
if (dao.hasActiveNotifications()) {
hasNotifications = true;
// Initiate reload existing broadcast
sendBroadcast(new Intent(Constants.RELOAD_WEATHER_BROADCAST));
}
}
catch (final Exception exception) {
Logger.logSlientExcpetion(exception);
}
finally {
// Start new alarm to launch this if active notifications present
if (hasNotifications) {
Logger.d(LOG_TAG, "Setting next reloading alarm");
final long schedule = PreferenceUtils.getPollingSchedule(this) * 60 * 1000;
final long futureAlarm = SystemClock.elapsedRealtime() + schedule;
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureAlarm, schedule, pi);
}
}
}
}
| true | true | protected void onHandleIntent(final Intent intent) {
Logger.d(LOG_TAG, "Reloading Alarm Service Initiated -> may set new one");
final AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final PendingIntent pi = PendingIntent.getService(this, 0, new Intent("com.morgan.design.android.broadcast.LOOPING_ALARM"), 0);
boolean hasNotifications = false;
try {
// Cancel any existing alarms
mAlarmManager.cancel(pi);
final WeatherChoiceDao dao = new WeatherChoiceDao(OpenHelperManager.getHelper(getApplicationContext(), DatabaseHelper.class));
if (dao.hasActiveNotifications()) {
hasNotifications = true;
// Initiate reload existing broadcast
sendBroadcast(new Intent(Constants.RELOAD_WEATHER_BROADCAST));
}
}
catch (final Exception exception) {
Logger.logSlientExcpetion(exception);
}
finally {
// Start new alarm to launch this if active notifications present
if (hasNotifications) {
Logger.d(LOG_TAG, "Setting next reloading alarm");
final long schedule = PreferenceUtils.getPollingSchedule(this) * 60 * 1000;
final long futureAlarm = SystemClock.elapsedRealtime() + schedule;
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureAlarm, schedule, pi);
}
}
}
| protected void onHandleIntent(final Intent intent) {
Logger.d(LOG_TAG, "Reloading Alarm Service Initiated -> may set new one");
final AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("com.morgan.design.android.broadcast.LOOPING_ALARM"), 0);
boolean hasNotifications = false;
try {
// Cancel any existing alarms
mAlarmManager.cancel(pi);
final WeatherChoiceDao dao = new WeatherChoiceDao(OpenHelperManager.getHelper(getApplicationContext(), DatabaseHelper.class));
if (dao.hasActiveNotifications()) {
hasNotifications = true;
// Initiate reload existing broadcast
sendBroadcast(new Intent(Constants.RELOAD_WEATHER_BROADCAST));
}
}
catch (final Exception exception) {
Logger.logSlientExcpetion(exception);
}
finally {
// Start new alarm to launch this if active notifications present
if (hasNotifications) {
Logger.d(LOG_TAG, "Setting next reloading alarm");
final long schedule = PreferenceUtils.getPollingSchedule(this) * 60 * 1000;
final long futureAlarm = SystemClock.elapsedRealtime() + schedule;
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureAlarm, schedule, pi);
}
}
}
|
diff --git a/document/fr.opensagres.xdocreport.document.textstyling.wiki/src/test/java/fr/opensagres/xdocreport/document/textstyling/wiki/gwiki/GWikiTextStylingTransformerTestCase.java b/document/fr.opensagres.xdocreport.document.textstyling.wiki/src/test/java/fr/opensagres/xdocreport/document/textstyling/wiki/gwiki/GWikiTextStylingTransformerTestCase.java
index 56370c25..8b408237 100644
--- a/document/fr.opensagres.xdocreport.document.textstyling.wiki/src/test/java/fr/opensagres/xdocreport/document/textstyling/wiki/gwiki/GWikiTextStylingTransformerTestCase.java
+++ b/document/fr.opensagres.xdocreport.document.textstyling.wiki/src/test/java/fr/opensagres/xdocreport/document/textstyling/wiki/gwiki/GWikiTextStylingTransformerTestCase.java
@@ -1,31 +1,31 @@
package fr.opensagres.xdocreport.document.textstyling.wiki.gwiki;
import junit.framework.Assert;
import org.junit.Test;
import fr.opensagres.xdocreport.document.textstyling.IDocumentHandler;
import fr.opensagres.xdocreport.document.textstyling.ITextStylingTransformer;
import fr.opensagres.xdocreport.document.textstyling.wiki.gwiki.GWikiTextStylingTransformer;
public class GWikiTextStylingTransformerTestCase {
@Test
public void testGWiki2HTML() throws Exception {
ITextStylingTransformer formatter = GWikiTextStylingTransformer.INSTANCE;
IDocumentHandler handler = new HTMLDocumentHandler();
formatter.transform("Here are severals styles"
+"\n * *Bold* style."
+"\n * _Italic_ style."
+"\n * _*BoldAndItalic*_ style."
+"\n\n Here are 3 styles"
+"\n # *Bold* style."
+"\n # _Italic_ style."
+"\n # _*BoldAndItalic*_ style.", handler);
Assert.assertEquals(
"<p>Here are severals styles</p><ul><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ul>Here are 3 styles<ol><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ol>",
- handler.toString());
+ handler.getTextBody());
}
}
| true | true | public void testGWiki2HTML() throws Exception {
ITextStylingTransformer formatter = GWikiTextStylingTransformer.INSTANCE;
IDocumentHandler handler = new HTMLDocumentHandler();
formatter.transform("Here are severals styles"
+"\n * *Bold* style."
+"\n * _Italic_ style."
+"\n * _*BoldAndItalic*_ style."
+"\n\n Here are 3 styles"
+"\n # *Bold* style."
+"\n # _Italic_ style."
+"\n # _*BoldAndItalic*_ style.", handler);
Assert.assertEquals(
"<p>Here are severals styles</p><ul><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ul>Here are 3 styles<ol><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ol>",
handler.toString());
}
| public void testGWiki2HTML() throws Exception {
ITextStylingTransformer formatter = GWikiTextStylingTransformer.INSTANCE;
IDocumentHandler handler = new HTMLDocumentHandler();
formatter.transform("Here are severals styles"
+"\n * *Bold* style."
+"\n * _Italic_ style."
+"\n * _*BoldAndItalic*_ style."
+"\n\n Here are 3 styles"
+"\n # *Bold* style."
+"\n # _Italic_ style."
+"\n # _*BoldAndItalic*_ style.", handler);
Assert.assertEquals(
"<p>Here are severals styles</p><ul><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ul>Here are 3 styles<ol><li><strong>Bold</strong> style</li><li><i>Italic</i> style</li><li><i><strong>BoldAndItalic</i></strong> style</li></ol>",
handler.getTextBody());
}
|
diff --git a/src/core/schedule/ui/HoursStrip.java b/src/core/schedule/ui/HoursStrip.java
index 5256a8a..6615810 100644
--- a/src/core/schedule/ui/HoursStrip.java
+++ b/src/core/schedule/ui/HoursStrip.java
@@ -1,142 +1,142 @@
package core.schedule.ui;
import core.utils.Hour;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.border.Border;
/**
*
* @author kiira
*/
public class HoursStrip extends javax.swing.JPanel {
private static final int DEFAULT_SIZE = 100;
private static final int DEFAULT_TIME_FRACTION = 60;
/** Creates new form HoursStrip */
public HoursStrip( int size, int timeFraction, int direction ) {
if ( direction != BoxLayout.X_AXIS && direction != BoxLayout.Y_AXIS )
throw new IllegalArgumentException(
"Solo se puede especificar Y_AXIS o X_AXIS como dirección." );
initComponents();
//dependiendo de la dirección, generamos el strip
if ( direction == BoxLayout.X_AXIS )
this.initializeHorizontalStrip( size, timeFraction );
else
this.initializeVerticalStrip( size, timeFraction );
}
public HoursStrip( int size, int timeFraction ) {
this( size, timeFraction, BoxLayout.Y_AXIS );
}
public HoursStrip( int size ) {
this( size, HoursStrip.DEFAULT_TIME_FRACTION, BoxLayout.Y_AXIS );
}
public HoursStrip() {
this( HoursStrip.DEFAULT_SIZE );
}
/** 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() {
jPMain = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
jPMain.setName("jPMain"); // NOI18N
jPMain.setLayout(null);
add(jPMain, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void initializeVerticalStrip( int size, int timeFraction ) {
//asignamos el layout al strip de acuerdo a la dirección
jPMain.setLayout( new BoxLayout( jPMain, BoxLayout.Y_AXIS ) );
//creamos los labels
Hour h = new Hour();
JLabel label;
Border border = BorderFactory.
createMatteBorder( 0, 0, 1, 1, Color.black );
Dimension dim;
//según el fraccionamiento de tiempo, generamos un label por cada
//intervalo
for ( int i = Hour.HOURS * Hour.MINS / timeFraction; i > 0; i-- ) {
//creamos el label
label = new JLabel( String.format( "<html><br/>%s</html>",
h.toString() ) );
//creamos la dimensión
dim = new Dimension( label.getPreferredSize().width + 10,
size );
//asignamos los valores generados
- label.setHorizontalAlignment( JLabel.TOP );
+ label.setVerticalAlignment( JLabel.TOP );
label.setMaximumSize( dim );
label.setPreferredSize( dim );
//asignamos el border
label.setBorder( border );
//agregamos el nuevo label
this.jPMain.add( label );
//avanzamos el horario en la cantidad asignada por el fraccionamiento
h.addMins( timeFraction );
}
}
private void initializeHorizontalStrip( int size, int timeFraction ) {
//asignamos el layout al strip de acuerdo a la dirección
jPMain.setLayout( new BoxLayout( jPMain, BoxLayout.X_AXIS ) );
//creamos los labels
Hour h = new Hour();
JLabel label;
Border border = BorderFactory.
createMatteBorder( 0, 0, 1, 1, Color.black );
Dimension dim;
//según el fraccionamiento de tiempo, generamos un label por cada
//intervalo
for ( int i = Hour.HOURS * Hour.MINS / timeFraction; i > 0; i-- ) {
label = new JLabel( String.format( "<html> %s</html>", h.
toString() ) );
dim = new Dimension( size,
label.getPreferredSize().height + 10 );
//asignamos los valores generados
label.setHorizontalAlignment( JLabel.LEFT );
label.setMaximumSize( dim );
label.setPreferredSize( dim );
//asignamos el border
label.setBorder( border );
//agregamos el nuevo label
this.jPMain.add( label );
//avanzamos el horario en la cantidad asignada por el fraccionamiento
h.addMins( timeFraction );
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPMain;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initializeVerticalStrip( int size, int timeFraction ) {
//asignamos el layout al strip de acuerdo a la dirección
jPMain.setLayout( new BoxLayout( jPMain, BoxLayout.Y_AXIS ) );
//creamos los labels
Hour h = new Hour();
JLabel label;
Border border = BorderFactory.
createMatteBorder( 0, 0, 1, 1, Color.black );
Dimension dim;
//según el fraccionamiento de tiempo, generamos un label por cada
//intervalo
for ( int i = Hour.HOURS * Hour.MINS / timeFraction; i > 0; i-- ) {
//creamos el label
label = new JLabel( String.format( "<html><br/>%s</html>",
h.toString() ) );
//creamos la dimensión
dim = new Dimension( label.getPreferredSize().width + 10,
size );
//asignamos los valores generados
label.setHorizontalAlignment( JLabel.TOP );
label.setMaximumSize( dim );
label.setPreferredSize( dim );
//asignamos el border
label.setBorder( border );
//agregamos el nuevo label
this.jPMain.add( label );
//avanzamos el horario en la cantidad asignada por el fraccionamiento
h.addMins( timeFraction );
}
}
| private void initializeVerticalStrip( int size, int timeFraction ) {
//asignamos el layout al strip de acuerdo a la dirección
jPMain.setLayout( new BoxLayout( jPMain, BoxLayout.Y_AXIS ) );
//creamos los labels
Hour h = new Hour();
JLabel label;
Border border = BorderFactory.
createMatteBorder( 0, 0, 1, 1, Color.black );
Dimension dim;
//según el fraccionamiento de tiempo, generamos un label por cada
//intervalo
for ( int i = Hour.HOURS * Hour.MINS / timeFraction; i > 0; i-- ) {
//creamos el label
label = new JLabel( String.format( "<html><br/>%s</html>",
h.toString() ) );
//creamos la dimensión
dim = new Dimension( label.getPreferredSize().width + 10,
size );
//asignamos los valores generados
label.setVerticalAlignment( JLabel.TOP );
label.setMaximumSize( dim );
label.setPreferredSize( dim );
//asignamos el border
label.setBorder( border );
//agregamos el nuevo label
this.jPMain.add( label );
//avanzamos el horario en la cantidad asignada por el fraccionamiento
h.addMins( timeFraction );
}
}
|
diff --git a/src/com/android/providers/downloads/DownloadThread.java b/src/com/android/providers/downloads/DownloadThread.java
index fefbe1d..8b8d8bd 100644
--- a/src/com/android/providers/downloads/DownloadThread.java
+++ b/src/com/android/providers/downloads/DownloadThread.java
@@ -1,922 +1,919 @@
/*
* 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.providers.downloads;
import org.apache.http.conn.params.ConnRouteParams;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.drm.mobile1.DrmRawContent;
import android.net.http.AndroidHttpClient;
import android.net.Proxy;
import android.os.FileUtils;
import android.os.PowerManager;
import android.os.Process;
import android.provider.Downloads;
import android.provider.DrmStore;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SyncFailedException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
/**
* Runs an actual download
*/
public class DownloadThread extends Thread {
private final Context mContext;
private final DownloadInfo mInfo;
private final SystemFacade mSystemFacade;
private final StorageManager mStorageManager;
public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo info,
StorageManager storageManager) {
mContext = context;
mSystemFacade = systemFacade;
mInfo = info;
mStorageManager = storageManager;
}
/**
* Returns the user agent provided by the initiating app, or use the default one
*/
private String userAgent() {
String userAgent = mInfo.mUserAgent;
if (userAgent != null) {
}
if (userAgent == null) {
userAgent = Constants.DEFAULT_USER_AGENT;
}
return userAgent;
}
/**
* State for the entire run() method.
*/
static class State {
public String mFilename;
public FileOutputStream mStream;
public String mMimeType;
public boolean mCountRetry = false;
public int mRetryAfter = 0;
public int mRedirectCount = 0;
public String mNewUri;
public boolean mGotData = false;
public String mRequestUri;
public State(DownloadInfo info) {
mMimeType = sanitizeMimeType(info.mMimeType);
mRedirectCount = info.mRedirectCount;
mRequestUri = info.mUri;
mFilename = info.mFileName;
}
}
/**
* State within executeDownload()
*/
private static class InnerState {
public int mBytesSoFar = 0;
public String mHeaderETag;
public boolean mContinuingDownload = false;
public String mHeaderContentLength;
public String mHeaderContentDisposition;
public String mHeaderContentLocation;
public int mBytesNotified = 0;
public long mTimeLastNotification = 0;
}
/**
* Raised from methods called by executeDownload() to indicate that the download should be
* retried immediately.
*/
private class RetryDownload extends Throwable {}
/**
* Executes the download in a separate thread
*/
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
String errorMsg = null;
try {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while(!finished) {
Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
// Set or unset proxy, which may have changed since last GET request.
// setDefaultProxy() supports null as proxy parameter.
ConnRouteParams.setDefaultProxy(client.getParams(),
Proxy.getPreferredHttpHost(mContext, state.mRequestUri));
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = Downloads.Impl.STATUS_SUCCESS;
} catch (StopRequestException error) {
// remove the cause before printing, in case it contains PII
errorMsg = "Aborting request for download " + mInfo.mId + ": " + error.getMessage();
Log.w(Constants.TAG, errorMsg);
if (Constants.LOGV) {
Log.w(Constants.TAG, errorMsg, error);
}
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
errorMsg = "Exception for id " + mInfo.mId + ": " + ex.getMessage();
- Log.w(Constants.TAG, errorMsg);
+ Log.w(Constants.TAG, errorMsg, ex);
finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
- if (Constants.LOGV) {
- Log.w(Constants.TAG, errorMsg, ex);
- }
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
state.mRedirectCount, state.mGotData, state.mFilename,
state.mNewUri, state.mMimeType, errorMsg);
mInfo.mHasActiveThread = false;
}
mStorageManager.incrementNumDownloadsSoFar();
}
/**
* Fully execute a single download request - setup and send the request, handle the response,
* and transfer the data to the destination file.
*/
private void executeDownload(State state, AndroidHttpClient client, HttpGet request)
throws StopRequestException, RetryDownload {
InnerState innerState = new InnerState();
byte data[] = new byte[Constants.BUFFER_SIZE];
setupDestinationFile(state, innerState);
addRequestHeaders(innerState, request);
// check just before sending the request to avoid using an invalid connection at all
checkConnectivity(state);
HttpResponse response = sendRequest(state, client, request);
handleExceptionalStatus(state, innerState, response);
if (Constants.LOGV) {
Log.v(Constants.TAG, "received response for " + mInfo.mUri);
}
processResponseHeaders(state, innerState, response);
InputStream entityStream = openResponseEntity(state, response);
transferData(state, innerState, data, entityStream);
}
/**
* Check if current connectivity is valid for this request.
*/
private void checkConnectivity(State state) throws StopRequestException {
int networkUsable = mInfo.checkCanUseNetwork();
if (networkUsable != DownloadInfo.NETWORK_OK) {
int status = Downloads.Impl.STATUS_WAITING_FOR_NETWORK;
if (networkUsable == DownloadInfo.NETWORK_UNUSABLE_DUE_TO_SIZE) {
status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
mInfo.notifyPauseDueToSize(true);
} else if (networkUsable == DownloadInfo.NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE) {
status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
mInfo.notifyPauseDueToSize(false);
}
throw new StopRequestException(status,
mInfo.getLogMessageForNetworkError(networkUsable));
}
}
/**
* Transfer as much data as possible from the HTTP response to the destination file.
* @param data buffer to use to read data
* @param entityStream stream for reading the HTTP response entity
*/
private void transferData(State state, InnerState innerState, byte[] data,
InputStream entityStream) throws StopRequestException {
for (;;) {
int bytesRead = readFromResponse(state, innerState, data, entityStream);
if (bytesRead == -1) { // success, end of stream already reached
handleEndOfStream(state, innerState);
return;
}
state.mGotData = true;
writeDataToDestination(state, data, bytesRead);
innerState.mBytesSoFar += bytesRead;
reportProgress(state, innerState);
if (Constants.LOGVV) {
Log.v(Constants.TAG, "downloaded " + innerState.mBytesSoFar + " for "
+ mInfo.mUri);
}
checkPausedOrCanceled(state);
}
}
/**
* Called after a successful completion to take any necessary action on the downloaded file.
*/
private void finalizeDestinationFile(State state) throws StopRequestException {
if (isDrmFile(state)) {
transferToDrm(state);
} else {
// make sure the file is readable
FileUtils.setPermissions(state.mFilename, 0644, -1, -1);
syncDestination(state);
}
}
/**
* Called just before the thread finishes, regardless of status, to take any necessary action on
* the downloaded file.
*/
private void cleanupDestination(State state, int finalStatus) {
closeDestination(state);
if (state.mFilename != null && Downloads.Impl.isStatusError(finalStatus)) {
new File(state.mFilename).delete();
state.mFilename = null;
}
}
/**
* Sync the destination file to storage.
*/
private void syncDestination(State state) {
FileOutputStream downloadedFileStream = null;
try {
downloadedFileStream = new FileOutputStream(state.mFilename, true);
downloadedFileStream.getFD().sync();
} catch (FileNotFoundException ex) {
Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex);
} catch (SyncFailedException ex) {
Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex);
} catch (IOException ex) {
Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex);
} catch (RuntimeException ex) {
Log.w(Constants.TAG, "exception while syncing file: ", ex);
} finally {
if(downloadedFileStream != null) {
try {
downloadedFileStream.close();
} catch (IOException ex) {
Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
} catch (RuntimeException ex) {
Log.w(Constants.TAG, "exception while closing file: ", ex);
}
}
}
}
/**
* @return true if the current download is a DRM file
*/
private boolean isDrmFile(State state) {
return DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(state.mMimeType);
}
/**
* Transfer the downloaded destination file to the DRM store.
*/
private void transferToDrm(State state) throws StopRequestException {
File file = new File(state.mFilename);
Intent item = DrmStore.addDrmFile(mContext.getContentResolver(), file, null);
file.delete();
if (item == null) {
throw new StopRequestException(Downloads.Impl.STATUS_UNKNOWN_ERROR,
"unable to add file to DrmProvider");
} else {
state.mFilename = item.getDataString();
state.mMimeType = item.getType();
}
}
/**
* Close the destination output stream.
*/
private void closeDestination(State state) {
try {
// close the file
if (state.mStream != null) {
state.mStream.close();
state.mStream = null;
}
} catch (IOException ex) {
if (Constants.LOGV) {
Log.v(Constants.TAG, "exception when closing the file after download : " + ex);
}
// nothing can really be done if the file can't be closed
}
}
/**
* Check if the download has been paused or canceled, stopping the request appropriately if it
* has been.
*/
private void checkPausedOrCanceled(State state) throws StopRequestException {
synchronized (mInfo) {
if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) {
throw new StopRequestException(Downloads.Impl.STATUS_PAUSED_BY_APP,
"download paused by owner");
}
}
if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) {
throw new StopRequestException(Downloads.Impl.STATUS_CANCELED, "download canceled");
}
}
/**
* Report download progress through the database if necessary.
*/
private void reportProgress(State state, InnerState innerState) {
long now = mSystemFacade.currentTimeMillis();
if (innerState.mBytesSoFar - innerState.mBytesNotified
> Constants.MIN_PROGRESS_STEP
&& now - innerState.mTimeLastNotification
> Constants.MIN_PROGRESS_TIME) {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
innerState.mBytesNotified = innerState.mBytesSoFar;
innerState.mTimeLastNotification = now;
}
}
/**
* Write a data buffer to the destination file.
* @param data buffer containing the data to write
* @param bytesRead how many bytes to write from the buffer
*/
private void writeDataToDestination(State state, byte[] data, int bytesRead)
throws StopRequestException {
for (;;) {
try {
if (state.mStream == null) {
state.mStream = new FileOutputStream(state.mFilename, true);
}
mStorageManager.verifySpaceBeforeWritingToFile(mInfo.mDestination, null, bytesRead);
state.mStream.write(data, 0, bytesRead);
if (mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
&& !isDrmFile(state)) {
closeDestination(state);
}
return;
} catch (IOException ex) {
mStorageManager.verifySpace(mInfo.mDestination, null, bytesRead);
}
}
}
/**
* Called when we've reached the end of the HTTP response stream, to update the database and
* check for consistency.
*/
private void handleEndOfStream(State state, InnerState innerState) throws StopRequestException {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
if (innerState.mHeaderContentLength == null) {
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, innerState.mBytesSoFar);
}
mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
boolean lengthMismatched = (innerState.mHeaderContentLength != null)
&& (innerState.mBytesSoFar != Integer.parseInt(innerState.mHeaderContentLength));
if (lengthMismatched) {
if (cannotResume(innerState)) {
throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
"mismatched content length");
} else {
throw new StopRequestException(getFinalStatusForHttpError(state),
"closed socket before end of file");
}
}
}
private boolean cannotResume(InnerState innerState) {
return innerState.mBytesSoFar > 0 && !mInfo.mNoIntegrity && innerState.mHeaderETag == null;
}
/**
* Read some data from the HTTP response stream, handling I/O errors.
* @param data buffer to use to read data
* @param entityStream stream for reading the HTTP response entity
* @return the number of bytes actually read or -1 if the end of the stream has been reached
*/
private int readFromResponse(State state, InnerState innerState, byte[] data,
InputStream entityStream) throws StopRequestException {
try {
return entityStream.read(data);
} catch (IOException ex) {
logNetworkState();
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
if (cannotResume(innerState)) {
String message = "while reading response: " + ex.toString()
+ ", can't resume interrupted download with no ETag";
throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
message, ex);
} else {
throw new StopRequestException(getFinalStatusForHttpError(state),
"while reading response: " + ex.toString(), ex);
}
}
}
/**
* Open a stream for the HTTP response entity, handling I/O errors.
* @return an InputStream to read the response entity
*/
private InputStream openResponseEntity(State state, HttpResponse response)
throws StopRequestException {
try {
return response.getEntity().getContent();
} catch (IOException ex) {
logNetworkState();
throw new StopRequestException(getFinalStatusForHttpError(state),
"while getting entity: " + ex.toString(), ex);
}
}
private void logNetworkState() {
if (Constants.LOGX) {
Log.i(Constants.TAG,
"Net " + (Helpers.isNetworkAvailable(mSystemFacade) ? "Up" : "Down"));
}
}
/**
* Read HTTP response headers and take appropriate action, including setting up the destination
* file and updating the database.
*/
private void processResponseHeaders(State state, InnerState innerState, HttpResponse response)
throws StopRequestException {
if (innerState.mContinuingDownload) {
// ignore response headers on resume requests
return;
}
readResponseHeaders(state, innerState, response);
state.mFilename = Helpers.generateSaveFile(
mContext,
mInfo.mUri,
mInfo.mHint,
innerState.mHeaderContentDisposition,
innerState.mHeaderContentLocation,
state.mMimeType,
mInfo.mDestination,
(innerState.mHeaderContentLength != null) ?
Long.parseLong(innerState.mHeaderContentLength) : 0,
mInfo.mIsPublicApi, mStorageManager);
try {
state.mStream = new FileOutputStream(state.mFilename);
} catch (FileNotFoundException exc) {
throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
"while opening destination file: " + exc.toString(), exc);
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + state.mFilename);
}
updateDatabaseFromHeaders(state, innerState);
// check connectivity again now that we know the total size
checkConnectivity(state);
}
/**
* Update necessary database fields based on values of HTTP response headers that have been
* read.
*/
private void updateDatabaseFromHeaders(State state, InnerState innerState) {
ContentValues values = new ContentValues();
values.put(Downloads.Impl._DATA, state.mFilename);
if (innerState.mHeaderETag != null) {
values.put(Constants.ETAG, innerState.mHeaderETag);
}
if (state.mMimeType != null) {
values.put(Downloads.Impl.COLUMN_MIME_TYPE, state.mMimeType);
}
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, mInfo.mTotalBytes);
mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
}
/**
* Read headers from the HTTP response and store them into local state.
*/
private void readResponseHeaders(State state, InnerState innerState, HttpResponse response)
throws StopRequestException {
Header header = response.getFirstHeader("Content-Disposition");
if (header != null) {
innerState.mHeaderContentDisposition = header.getValue();
}
header = response.getFirstHeader("Content-Location");
if (header != null) {
innerState.mHeaderContentLocation = header.getValue();
}
if (state.mMimeType == null) {
header = response.getFirstHeader("Content-Type");
if (header != null) {
state.mMimeType = sanitizeMimeType(header.getValue());
}
}
header = response.getFirstHeader("ETag");
if (header != null) {
innerState.mHeaderETag = header.getValue();
}
String headerTransferEncoding = null;
header = response.getFirstHeader("Transfer-Encoding");
if (header != null) {
headerTransferEncoding = header.getValue();
}
if (headerTransferEncoding == null) {
header = response.getFirstHeader("Content-Length");
if (header != null) {
innerState.mHeaderContentLength = header.getValue();
mInfo.mTotalBytes = Long.parseLong(innerState.mHeaderContentLength);
}
} else {
// Ignore content-length with transfer-encoding - 2616 4.4 3
if (Constants.LOGVV) {
Log.v(Constants.TAG,
"ignoring content-length because of xfer-encoding");
}
}
if (Constants.LOGVV) {
Log.v(Constants.TAG, "Content-Disposition: " +
innerState.mHeaderContentDisposition);
Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
Log.v(Constants.TAG, "Content-Type: " + state.mMimeType);
Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
}
boolean noSizeInfo = innerState.mHeaderContentLength == null
&& (headerTransferEncoding == null
|| !headerTransferEncoding.equalsIgnoreCase("chunked"));
if (!mInfo.mNoIntegrity && noSizeInfo) {
throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
"can't know size of download, giving up");
}
}
/**
* Check the HTTP response status and handle anything unusual (e.g. not 200/206).
*/
private void handleExceptionalStatus(State state, InnerState innerState, HttpResponse response)
throws StopRequestException, RetryDownload {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
handleServiceUnavailable(state, response);
}
if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
handleRedirect(state, response, statusCode);
}
if (Constants.LOGV) {
Log.i(Constants.TAG, "recevd_status = " + statusCode +
", mContinuingDownload = " + innerState.mContinuingDownload);
}
int expectedStatus = innerState.mContinuingDownload ? 206 : Downloads.Impl.STATUS_SUCCESS;
if (statusCode != expectedStatus) {
handleOtherStatus(state, innerState, statusCode);
}
}
/**
* Handle a status that we don't know how to deal with properly.
*/
private void handleOtherStatus(State state, InnerState innerState, int statusCode)
throws StopRequestException {
int finalStatus;
if (Downloads.Impl.isStatusError(statusCode)) {
finalStatus = statusCode;
} else if (statusCode >= 300 && statusCode < 400) {
finalStatus = Downloads.Impl.STATUS_UNHANDLED_REDIRECT;
} else if (innerState.mContinuingDownload && statusCode == Downloads.Impl.STATUS_SUCCESS) {
finalStatus = Downloads.Impl.STATUS_CANNOT_RESUME;
} else {
finalStatus = Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE;
}
throw new StopRequestException(finalStatus, "http error " +
statusCode + ", mContinuingDownload: " + innerState.mContinuingDownload);
}
/**
* Handle a 3xx redirect status.
*/
private void handleRedirect(State state, HttpResponse response, int statusCode)
throws StopRequestException, RetryDownload {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "got HTTP redirect " + statusCode);
}
if (state.mRedirectCount >= Constants.MAX_REDIRECTS) {
throw new StopRequestException(Downloads.Impl.STATUS_TOO_MANY_REDIRECTS,
"too many redirects");
}
Header header = response.getFirstHeader("Location");
if (header == null) {
return;
}
if (Constants.LOGVV) {
Log.v(Constants.TAG, "Location :" + header.getValue());
}
String newUri;
try {
newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
} catch(URISyntaxException ex) {
if (Constants.LOGV) {
Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue()
+ " for " + mInfo.mUri);
}
throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
"Couldn't resolve redirect URI");
}
++state.mRedirectCount;
state.mRequestUri = newUri;
if (statusCode == 301 || statusCode == 303) {
// use the new URI for all future requests (should a retry/resume be necessary)
state.mNewUri = newUri;
}
throw new RetryDownload();
}
/**
* Handle a 503 Service Unavailable status by processing the Retry-After header.
*/
private void handleServiceUnavailable(State state, HttpResponse response)
throws StopRequestException {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "got HTTP response code 503");
}
state.mCountRetry = true;
Header header = response.getFirstHeader("Retry-After");
if (header != null) {
try {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "Retry-After :" + header.getValue());
}
state.mRetryAfter = Integer.parseInt(header.getValue());
if (state.mRetryAfter < 0) {
state.mRetryAfter = 0;
} else {
if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
state.mRetryAfter = Constants.MIN_RETRY_AFTER;
} else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
state.mRetryAfter = Constants.MAX_RETRY_AFTER;
}
state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
state.mRetryAfter *= 1000;
}
} catch (NumberFormatException ex) {
// ignored - retryAfter stays 0 in this case.
}
}
throw new StopRequestException(Downloads.Impl.STATUS_WAITING_TO_RETRY,
"got 503 Service Unavailable, will retry later");
}
/**
* Send the request to the server, handling any I/O exceptions.
*/
private HttpResponse sendRequest(State state, AndroidHttpClient client, HttpGet request)
throws StopRequestException {
try {
return client.execute(request);
} catch (IllegalArgumentException ex) {
throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
"while trying to execute request: " + ex.toString(), ex);
} catch (IOException ex) {
logNetworkState();
throw new StopRequestException(getFinalStatusForHttpError(state),
"while trying to execute request: " + ex.toString(), ex);
}
}
private int getFinalStatusForHttpError(State state) {
if (!Helpers.isNetworkAvailable(mSystemFacade)) {
return Downloads.Impl.STATUS_WAITING_FOR_NETWORK;
} else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
state.mCountRetry = true;
return Downloads.Impl.STATUS_WAITING_TO_RETRY;
} else {
Log.w(Constants.TAG, "reached max retries for " + mInfo.mId);
return Downloads.Impl.STATUS_HTTP_DATA_ERROR;
}
}
/**
* Prepare the destination file to receive data. If the file already exists, we'll set up
* appropriately for resumption.
*/
private void setupDestinationFile(State state, InnerState innerState)
throws StopRequestException {
if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download
if (Constants.LOGV) {
Log.i(Constants.TAG, "have run thread before for id: " + mInfo.mId +
", and state.mFilename: " + state.mFilename);
}
if (!Helpers.isFilenameValid(state.mFilename,
mStorageManager.getDownloadDataDirectory())) {
// this should never happen
throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
"found invalid internal destination filename");
}
// We're resuming a download that got interrupted
File f = new File(state.mFilename);
if (f.exists()) {
if (Constants.LOGV) {
Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
", and state.mFilename: " + state.mFilename);
}
long fileLength = f.length();
if (fileLength == 0) {
// The download hadn't actually started, we can restart from scratch
f.delete();
state.mFilename = null;
if (Constants.LOGV) {
Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
", BUT starting from scratch again: ");
}
} else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
// This should've been caught upon failure
f.delete();
throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
"Trying to resume a download that can't be resumed");
} else {
// All right, we'll be able to resume this download
if (Constants.LOGV) {
Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
", and starting with file of length: " + fileLength);
}
try {
state.mStream = new FileOutputStream(state.mFilename, true);
} catch (FileNotFoundException exc) {
throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
"while opening destination for resuming: " + exc.toString(), exc);
}
innerState.mBytesSoFar = (int) fileLength;
if (mInfo.mTotalBytes != -1) {
innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
}
innerState.mHeaderETag = mInfo.mETag;
innerState.mContinuingDownload = true;
if (Constants.LOGV) {
Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
", and setting mContinuingDownload to true: ");
}
}
}
}
if (state.mStream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
&& !isDrmFile(state)) {
closeDestination(state);
}
}
/**
* Add custom headers for this download to the HTTP request.
*/
private void addRequestHeaders(InnerState innerState, HttpGet request) {
for (Pair<String, String> header : mInfo.getHeaders()) {
request.addHeader(header.first, header.second);
}
if (innerState.mContinuingDownload) {
if (innerState.mHeaderETag != null) {
request.addHeader("If-Match", innerState.mHeaderETag);
}
request.addHeader("Range", "bytes=" + innerState.mBytesSoFar + "-");
}
}
/**
* Stores information about the completed download, and notifies the initiating application.
*/
private void notifyDownloadCompleted(
int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
String filename, String uri, String mimeType, String errorMsg) {
notifyThroughDatabase(
status, countRetry, retryAfter, redirectCount, gotData, filename, uri, mimeType,
errorMsg);
if (Downloads.Impl.isStatusCompleted(status)) {
mInfo.sendIntentIfRequested();
}
}
private void notifyThroughDatabase(
int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
String filename, String uri, String mimeType, String errorMsg) {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_STATUS, status);
values.put(Downloads.Impl._DATA, filename);
if (uri != null) {
values.put(Downloads.Impl.COLUMN_URI, uri);
}
values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimeType);
values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, mSystemFacade.currentTimeMillis());
values.put(Constants.RETRY_AFTER_X_REDIRECT_COUNT, retryAfter + (redirectCount << 28));
if (!countRetry) {
values.put(Constants.FAILED_CONNECTIONS, 0);
} else if (gotData) {
values.put(Constants.FAILED_CONNECTIONS, 1);
} else {
values.put(Constants.FAILED_CONNECTIONS, mInfo.mNumFailed + 1);
}
// STOPSHIP begin delete the following lines
if (!TextUtils.isEmpty(errorMsg)) {
values.put(Downloads.Impl.COLUMN_ERROR_MSG, errorMsg);
}
// STOPSHIP end
mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
}
/**
* Clean up a mimeType string so it can be used to dispatch an intent to
* view a downloaded asset.
* @param mimeType either null or one or more mime types (semi colon separated).
* @return null if mimeType was null. Otherwise a string which represents a
* single mimetype in lowercase and with surrounding whitespaces trimmed.
*/
private static String sanitizeMimeType(String mimeType) {
try {
mimeType = mimeType.trim().toLowerCase(Locale.ENGLISH);
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
return mimeType;
} catch (NullPointerException npe) {
return null;
}
}
}
| false | true | public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
String errorMsg = null;
try {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while(!finished) {
Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
// Set or unset proxy, which may have changed since last GET request.
// setDefaultProxy() supports null as proxy parameter.
ConnRouteParams.setDefaultProxy(client.getParams(),
Proxy.getPreferredHttpHost(mContext, state.mRequestUri));
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = Downloads.Impl.STATUS_SUCCESS;
} catch (StopRequestException error) {
// remove the cause before printing, in case it contains PII
errorMsg = "Aborting request for download " + mInfo.mId + ": " + error.getMessage();
Log.w(Constants.TAG, errorMsg);
if (Constants.LOGV) {
Log.w(Constants.TAG, errorMsg, error);
}
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
errorMsg = "Exception for id " + mInfo.mId + ": " + ex.getMessage();
Log.w(Constants.TAG, errorMsg);
finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
if (Constants.LOGV) {
Log.w(Constants.TAG, errorMsg, ex);
}
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
state.mRedirectCount, state.mGotData, state.mFilename,
state.mNewUri, state.mMimeType, errorMsg);
mInfo.mHasActiveThread = false;
}
mStorageManager.incrementNumDownloadsSoFar();
}
| public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
String errorMsg = null;
try {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while(!finished) {
Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
// Set or unset proxy, which may have changed since last GET request.
// setDefaultProxy() supports null as proxy parameter.
ConnRouteParams.setDefaultProxy(client.getParams(),
Proxy.getPreferredHttpHost(mContext, state.mRequestUri));
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = Downloads.Impl.STATUS_SUCCESS;
} catch (StopRequestException error) {
// remove the cause before printing, in case it contains PII
errorMsg = "Aborting request for download " + mInfo.mId + ": " + error.getMessage();
Log.w(Constants.TAG, errorMsg);
if (Constants.LOGV) {
Log.w(Constants.TAG, errorMsg, error);
}
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
errorMsg = "Exception for id " + mInfo.mId + ": " + ex.getMessage();
Log.w(Constants.TAG, errorMsg, ex);
finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
state.mRedirectCount, state.mGotData, state.mFilename,
state.mNewUri, state.mMimeType, errorMsg);
mInfo.mHasActiveThread = false;
}
mStorageManager.incrementNumDownloadsSoFar();
}
|
diff --git a/src/main/java/org/sjmvc/binding/RequestParameterBinder.java b/src/main/java/org/sjmvc/binding/RequestParameterBinder.java
index 4a6a9c6..edba997 100644
--- a/src/main/java/org/sjmvc/binding/RequestParameterBinder.java
+++ b/src/main/java/org/sjmvc/binding/RequestParameterBinder.java
@@ -1,81 +1,82 @@
/**
* Copyright (c) 2010 Ignasi Barrera
*
* 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 org.sjmvc.binding;
import java.util.Map;
import javax.servlet.ServletRequest;
/**
* {@link Binder} implementation that binds request parameters to the defined
* target object.
*
* @author Ignasi Barrera
*
* @see Binder
* @see BindingResult
* @see BindingError
*/
public class RequestParameterBinder<T> extends
AbstractBinder<T, ServletRequest>
{
/** Prefix for the parameters that will be included in the binding process. */
private static final String BIND_PARAMETER_PREFIX = "model.";
/**
* Creates the binder.
*
* @param target The target of the binding.
* @param source The request source of the binding.
*/
public RequestParameterBinder(T target, ServletRequest source)
{
super(target, source);
}
/**
* Bind the given parameter map to the target object.
*
* @param parameters The parameter map to bind.
* @return The binding result.
*/
@Override
protected void doBind()
{
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = source.getParameterMap();
for (Map.Entry<String, String[]> param : parameters.entrySet())
{
- String name = param.getKey();
+ String paramName = param.getKey();
String[] values = param.getValue();
// Only bind the bindable parameters
- if (name.startsWith(BIND_PARAMETER_PREFIX))
+ if (paramName.startsWith(BIND_PARAMETER_PREFIX))
{
+ String name = paramName.replaceFirst(BIND_PARAMETER_PREFIX, "");
bindField(target, name, values);
}
}
}
}
| false | true | protected void doBind()
{
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = source.getParameterMap();
for (Map.Entry<String, String[]> param : parameters.entrySet())
{
String name = param.getKey();
String[] values = param.getValue();
// Only bind the bindable parameters
if (name.startsWith(BIND_PARAMETER_PREFIX))
{
bindField(target, name, values);
}
}
}
| protected void doBind()
{
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = source.getParameterMap();
for (Map.Entry<String, String[]> param : parameters.entrySet())
{
String paramName = param.getKey();
String[] values = param.getValue();
// Only bind the bindable parameters
if (paramName.startsWith(BIND_PARAMETER_PREFIX))
{
String name = paramName.replaceFirst(BIND_PARAMETER_PREFIX, "");
bindField(target, name, values);
}
}
}
|
diff --git a/src/main/java/com/ndpar/spring/rabbitmq/MessageHandler.java b/src/main/java/com/ndpar/spring/rabbitmq/MessageHandler.java
index a45d4ab..a658116 100644
--- a/src/main/java/com/ndpar/spring/rabbitmq/MessageHandler.java
+++ b/src/main/java/com/ndpar/spring/rabbitmq/MessageHandler.java
@@ -1,13 +1,13 @@
package com.ndpar.spring.rabbitmq;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MessageHandler implements MessageListener {
@Override
public void onMessage(Message message) {
-// System.out.println("Received message: " + message);
+ System.out.println("Received message: " + message);
System.out.println("Text: " + new String(message.getBody()));
}
}
| true | true | public void onMessage(Message message) {
// System.out.println("Received message: " + message);
System.out.println("Text: " + new String(message.getBody()));
}
| public void onMessage(Message message) {
System.out.println("Received message: " + message);
System.out.println("Text: " + new String(message.getBody()));
}
|
diff --git a/warc-indexer/src/test/java/uk/bl/wa/indexer/WARCIndexerEmbeddedSolrTest.java b/warc-indexer/src/test/java/uk/bl/wa/indexer/WARCIndexerEmbeddedSolrTest.java
index 7a3a96c4..d50e49f6 100755
--- a/warc-indexer/src/test/java/uk/bl/wa/indexer/WARCIndexerEmbeddedSolrTest.java
+++ b/warc-indexer/src/test/java/uk/bl/wa/indexer/WARCIndexerEmbeddedSolrTest.java
@@ -1,186 +1,186 @@
/**
*
*/
package uk.bl.wa.indexer;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreContainer;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveReaderFactory;
import org.archive.io.ArchiveRecord;
import org.archive.wayback.exception.ResourceNotAvailableException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.bl.wa.indexer.WARCIndexer;
import uk.bl.wa.util.solr.SolrRecord;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class WARCIndexerEmbeddedSolrTest {
private String testWarc = "src/test/resources/wikipedia-mona-lisa/flashfrozen-jwat-recompressed.warc.gz";
//private String testWarc = "src/test/resources/wikipedia-mona-lisa/flashfrozen-jwat-recompressed.warc";
//private String testWarc = "src/test/resources/variations.warc.gz";
//private String testWarc = "src/test/resources/TEST.arc.gz";
private EmbeddedSolrServer server;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
// Note that the following property could be set through JVM level arguments too
System.setProperty("solr.solr.home", "src/main/solr/solr");
System.setProperty("solr.data.dir", "target/solr-test-home");
CoreContainer coreContainer = new CoreContainer();
coreContainer.load();
server = new EmbeddedSolrServer(coreContainer, "");
// Remove any items from previous executions:
server.deleteByQuery("*:*");
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
server.shutdown();
}
/**
*
* @throws SolrServerException
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws TransformerFactoryConfigurationError
* @throws TransformerException
* @throws ResourceNotAvailableException
*/
@Test
public void testEmbeddedServer() throws SolrServerException, IOException, NoSuchAlgorithmException, TransformerFactoryConfigurationError, TransformerException, ResourceNotAvailableException {
// Fire up a SOLR:
String url = "http://www.lafromagerie.co.uk/cheese-room/?milk=buffalo&%3Bamp%3Bamp%3Bamp%3Borigin=wales&%3Bamp%3Bamp%3Borigin=switzerland&%3Bamp%3Borigin=germany&%3Bstyle=semi-hard&style=blue";
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "1");
document.addField("name", "my name");
document.addField( "url", url );
System.out.println("Adding document: "+document);
server.add(document);
server.commit();
System.out.println("Querying for document...");
SolrParams params = new SolrQuery("name:name");
QueryResponse response = server.query(params);
assertEquals(1L, response.getResults().getNumFound());
assertEquals("1", response.getResults().get(0).get("id"));
// Check that URLs are encoding correctly.
assertEquals( url, document.getFieldValue( "url" ) );
assertEquals( url, response.getResults().get( 0 ).get( "url" ) );
// Now generate some Solr documents from WARCs:
List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
/*
*
org.archive.format.gzip.GZIPFormatException: Invalid FExtra length/records
at org.archive.format.gzip.GZIPFExtraRecords.readRecords(GZIPFExtraRecords.java:59)
at org.archive.format.gzip.GZIPFExtraRecords.<init>(GZIPFExtraRecords.java:17)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:151)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:126)
at uk.bl.wap.indexer.WARCIndexerEmbeddedSolrTest.test(WARCIndexerEmbeddedSolrTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
FileInputStream is = new FileInputStream("src/test/resources/wikipedia-mona-lisa/flashfrozen.warc.gz");
new GZIPDecoder().parseHeader(is);
System.out.println("COMPRESSED? "+ArchiveUtils.isGzipped(is));
*/
WARCIndexer windex = new WARCIndexer();
ArchiveReader reader = ArchiveReaderFactory.get( new File(testWarc) );
Iterator<ArchiveRecord> ir = reader.iterator();
while( ir.hasNext() ) {
ArchiveRecord rec = ir.next();
SolrRecord doc = windex.extract("",rec);
if( doc != null ) {
//System.out.println(doc.toXml());
//break;
docs.add(doc.doc);
} else {
System.out.println("Got a NULL document for: "+rec.getHeader().getUrl());
}
//System.out.println(" ---- ---- ");
}
System.out.println("Added "+docs.size()+" docs.");
// Check the read worked:
- assertEquals(21L, docs.size());
+ assertEquals(39L, docs.size());
server.add(docs);
server.commit();
// Now query:
params = new SolrQuery("content_type:image*");
//params = new SolrQuery("generator:*");
response = server.query(params);
for( SolrDocument result : response.getResults() ) {
for( String f : result.getFieldNames() ) {
System.out.println(f + " -> " + result.get(f));
}
}
assertEquals(21L, response.getResults().getNumFound());
}
}
| true | true | public void testEmbeddedServer() throws SolrServerException, IOException, NoSuchAlgorithmException, TransformerFactoryConfigurationError, TransformerException, ResourceNotAvailableException {
// Fire up a SOLR:
String url = "http://www.lafromagerie.co.uk/cheese-room/?milk=buffalo&%3Bamp%3Bamp%3Bamp%3Borigin=wales&%3Bamp%3Bamp%3Borigin=switzerland&%3Bamp%3Borigin=germany&%3Bstyle=semi-hard&style=blue";
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "1");
document.addField("name", "my name");
document.addField( "url", url );
System.out.println("Adding document: "+document);
server.add(document);
server.commit();
System.out.println("Querying for document...");
SolrParams params = new SolrQuery("name:name");
QueryResponse response = server.query(params);
assertEquals(1L, response.getResults().getNumFound());
assertEquals("1", response.getResults().get(0).get("id"));
// Check that URLs are encoding correctly.
assertEquals( url, document.getFieldValue( "url" ) );
assertEquals( url, response.getResults().get( 0 ).get( "url" ) );
// Now generate some Solr documents from WARCs:
List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
/*
*
org.archive.format.gzip.GZIPFormatException: Invalid FExtra length/records
at org.archive.format.gzip.GZIPFExtraRecords.readRecords(GZIPFExtraRecords.java:59)
at org.archive.format.gzip.GZIPFExtraRecords.<init>(GZIPFExtraRecords.java:17)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:151)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:126)
at uk.bl.wap.indexer.WARCIndexerEmbeddedSolrTest.test(WARCIndexerEmbeddedSolrTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
FileInputStream is = new FileInputStream("src/test/resources/wikipedia-mona-lisa/flashfrozen.warc.gz");
new GZIPDecoder().parseHeader(is);
System.out.println("COMPRESSED? "+ArchiveUtils.isGzipped(is));
*/
WARCIndexer windex = new WARCIndexer();
ArchiveReader reader = ArchiveReaderFactory.get( new File(testWarc) );
Iterator<ArchiveRecord> ir = reader.iterator();
while( ir.hasNext() ) {
ArchiveRecord rec = ir.next();
SolrRecord doc = windex.extract("",rec);
if( doc != null ) {
//System.out.println(doc.toXml());
//break;
docs.add(doc.doc);
} else {
System.out.println("Got a NULL document for: "+rec.getHeader().getUrl());
}
//System.out.println(" ---- ---- ");
}
System.out.println("Added "+docs.size()+" docs.");
// Check the read worked:
assertEquals(21L, docs.size());
server.add(docs);
server.commit();
// Now query:
params = new SolrQuery("content_type:image*");
//params = new SolrQuery("generator:*");
response = server.query(params);
for( SolrDocument result : response.getResults() ) {
for( String f : result.getFieldNames() ) {
System.out.println(f + " -> " + result.get(f));
}
}
assertEquals(21L, response.getResults().getNumFound());
}
| public void testEmbeddedServer() throws SolrServerException, IOException, NoSuchAlgorithmException, TransformerFactoryConfigurationError, TransformerException, ResourceNotAvailableException {
// Fire up a SOLR:
String url = "http://www.lafromagerie.co.uk/cheese-room/?milk=buffalo&%3Bamp%3Bamp%3Bamp%3Borigin=wales&%3Bamp%3Bamp%3Borigin=switzerland&%3Bamp%3Borigin=germany&%3Bstyle=semi-hard&style=blue";
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "1");
document.addField("name", "my name");
document.addField( "url", url );
System.out.println("Adding document: "+document);
server.add(document);
server.commit();
System.out.println("Querying for document...");
SolrParams params = new SolrQuery("name:name");
QueryResponse response = server.query(params);
assertEquals(1L, response.getResults().getNumFound());
assertEquals("1", response.getResults().get(0).get("id"));
// Check that URLs are encoding correctly.
assertEquals( url, document.getFieldValue( "url" ) );
assertEquals( url, response.getResults().get( 0 ).get( "url" ) );
// Now generate some Solr documents from WARCs:
List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
/*
*
org.archive.format.gzip.GZIPFormatException: Invalid FExtra length/records
at org.archive.format.gzip.GZIPFExtraRecords.readRecords(GZIPFExtraRecords.java:59)
at org.archive.format.gzip.GZIPFExtraRecords.<init>(GZIPFExtraRecords.java:17)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:151)
at org.archive.format.gzip.GZIPDecoder.parseHeader(GZIPDecoder.java:126)
at uk.bl.wap.indexer.WARCIndexerEmbeddedSolrTest.test(WARCIndexerEmbeddedSolrTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
FileInputStream is = new FileInputStream("src/test/resources/wikipedia-mona-lisa/flashfrozen.warc.gz");
new GZIPDecoder().parseHeader(is);
System.out.println("COMPRESSED? "+ArchiveUtils.isGzipped(is));
*/
WARCIndexer windex = new WARCIndexer();
ArchiveReader reader = ArchiveReaderFactory.get( new File(testWarc) );
Iterator<ArchiveRecord> ir = reader.iterator();
while( ir.hasNext() ) {
ArchiveRecord rec = ir.next();
SolrRecord doc = windex.extract("",rec);
if( doc != null ) {
//System.out.println(doc.toXml());
//break;
docs.add(doc.doc);
} else {
System.out.println("Got a NULL document for: "+rec.getHeader().getUrl());
}
//System.out.println(" ---- ---- ");
}
System.out.println("Added "+docs.size()+" docs.");
// Check the read worked:
assertEquals(39L, docs.size());
server.add(docs);
server.commit();
// Now query:
params = new SolrQuery("content_type:image*");
//params = new SolrQuery("generator:*");
response = server.query(params);
for( SolrDocument result : response.getResults() ) {
for( String f : result.getFieldNames() ) {
System.out.println(f + " -> " + result.get(f));
}
}
assertEquals(21L, response.getResults().getNumFound());
}
|
diff --git a/WEB-INF/src/com/astrider/sfc/src/model/dao/WeeklyLogDao.java b/WEB-INF/src/com/astrider/sfc/src/model/dao/WeeklyLogDao.java
index 7ea3091..b04f58f 100644
--- a/WEB-INF/src/com/astrider/sfc/src/model/dao/WeeklyLogDao.java
+++ b/WEB-INF/src/com/astrider/sfc/src/model/dao/WeeklyLogDao.java
@@ -1,124 +1,123 @@
package com.astrider.sfc.src.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.astrider.sfc.app.lib.BaseDao;
import com.astrider.sfc.app.lib.Mapper;
import com.astrider.sfc.src.model.vo.db.WeeklyLogVo;
public class WeeklyLogDao extends BaseDao {
public WeeklyLogDao() {
super();
}
public WeeklyLogDao(Connection con) {
super(con);
}
public WeeklyLogVo selectNewest(int userId) {
WeeklyLogVo week = null;
PreparedStatement pstmt = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM weekly_nut_amounts WHERE user_id = ? ");
sb.append("AND first_date = (SELECT MAX(first_date) FROM weekly_nut_amounts WHERE user_id = ?)");
pstmt = con.prepareStatement(sb.toString());
pstmt.setInt(1, userId);
pstmt.setInt(2, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Mapper<WeeklyLogVo> mapper = new Mapper<WeeklyLogVo>();
week = mapper.fromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return week;
}
public WeeklyLogVo selectCurrentWeek(int userId) {
WeeklyLogVo week = null;
PreparedStatement pstmt = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM weekly_nut_amounts WHERE user_id = ? AND first_date BETWEEN ");
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND (SELECT TRUNC(SYSDATE+7 , 'Day') FROM dual)");
pstmt = con.prepareStatement(sb.toString());
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Mapper<WeeklyLogVo> mapper = new Mapper<WeeklyLogVo>();
week = mapper.fromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return week;
}
public WeeklyLogVo selectByWeekAgo(int userId, int weekAgo) {
WeeklyLogVo week = null;
PreparedStatement pstmt = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM weekly_nut_amounts WHERE user_id = ? AND first_date BETWEEN ");
if (0 < weekAgo) {
int start = -7 * weekAgo;
int end = start + 7;
if (start != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + start + ", 'Day') FROM dual) AND ");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND ");
}
if (end != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + end + ", 'Day') FROM dual)");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual)");
}
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND (SELECT TRUNC(SYSDATE + 7, 'Day') FROM dual)");
}
- System.out.println(sb.toString());
pstmt = con.prepareStatement(sb.toString());
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Mapper<WeeklyLogVo> mapper = new Mapper<WeeklyLogVo>();
week = mapper.fromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return week;
}
}
| true | true | public WeeklyLogVo selectByWeekAgo(int userId, int weekAgo) {
WeeklyLogVo week = null;
PreparedStatement pstmt = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM weekly_nut_amounts WHERE user_id = ? AND first_date BETWEEN ");
if (0 < weekAgo) {
int start = -7 * weekAgo;
int end = start + 7;
if (start != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + start + ", 'Day') FROM dual) AND ");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND ");
}
if (end != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + end + ", 'Day') FROM dual)");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual)");
}
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND (SELECT TRUNC(SYSDATE + 7, 'Day') FROM dual)");
}
System.out.println(sb.toString());
pstmt = con.prepareStatement(sb.toString());
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Mapper<WeeklyLogVo> mapper = new Mapper<WeeklyLogVo>();
week = mapper.fromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return week;
}
| public WeeklyLogVo selectByWeekAgo(int userId, int weekAgo) {
WeeklyLogVo week = null;
PreparedStatement pstmt = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM weekly_nut_amounts WHERE user_id = ? AND first_date BETWEEN ");
if (0 < weekAgo) {
int start = -7 * weekAgo;
int end = start + 7;
if (start != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + start + ", 'Day') FROM dual) AND ");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND ");
}
if (end != 0) {
sb.append("(SELECT TRUNC(SYSDATE " + end + ", 'Day') FROM dual)");
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual)");
}
} else {
sb.append("(SELECT TRUNC(SYSDATE, 'Day') FROM dual) AND (SELECT TRUNC(SYSDATE + 7, 'Day') FROM dual)");
}
pstmt = con.prepareStatement(sb.toString());
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Mapper<WeeklyLogVo> mapper = new Mapper<WeeklyLogVo>();
week = mapper.fromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return week;
}
|
diff --git a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
index a4ba26e3..4cedac38 100644
--- a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
+++ b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
@@ -1,9254 +1,9254 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.assignment.tool;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementMessageEdit;
import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.Assignment;
import org.sakaiproject.assignment.api.AssignmentContentEdit;
import org.sakaiproject.assignment.api.AssignmentEdit;
import org.sakaiproject.assignment.api.AssignmentSubmission;
import org.sakaiproject.assignment.api.AssignmentSubmissionEdit;
import org.sakaiproject.assignment.cover.AssignmentService;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo;
import org.sakaiproject.assignment.taggable.api.TaggingManager;
import org.sakaiproject.assignment.taggable.api.TaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentTypeImageService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.contentreview.service.ContentReviewService;
/**
* <p>
* AssignmentAction is the action class for the assignment tool.
* </p>
*/
public class AssignmentAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("assignment");
private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false);
/** Is the review service available? */
private static final String ALLOW_REVIEW_SERVICE = "allow_review_service";
/** Is review service enabled? */
private static final String ENABLE_REVIEW_SERVICE = "enable_review_service";
private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service";
private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view";
/** The attachments */
private static final String ATTACHMENTS = "Assignment.attachments";
/** The content type image lookup service in the State. */
private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service";
/** The calendar service in the State. */
private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service";
/** The announcement service in the State. */
private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service";
/** The calendar object */
private static final String CALENDAR = "calendar";
/** The announcement channel */
private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel";
/** The state mode */
private static final String STATE_MODE = "Assignment.mode";
/** The context string */
private static final String STATE_CONTEXT_STRING = "Assignment.context_string";
/** The user */
private static final String STATE_USER = "Assignment.user";
// SECTION MOD
/** Used to keep track of the section info not currently being used. */
private static final String STATE_SECTION_STRING = "Assignment.section_string";
/** **************************** sort assignment ********************** */
/** state sort * */
private static final String SORTED_BY = "Assignment.sorted_by";
/** state sort ascendingly * */
private static final String SORTED_ASC = "Assignment.sorted_asc";
/** default sorting */
private static final String SORTED_BY_DEFAULT = "default";
/** sort by assignment title */
private static final String SORTED_BY_TITLE = "title";
/** sort by assignment section */
private static final String SORTED_BY_SECTION = "section";
/** sort by assignment due date */
private static final String SORTED_BY_DUEDATE = "duedate";
/** sort by assignment open date */
private static final String SORTED_BY_OPENDATE = "opendate";
/** sort by assignment status */
private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status";
/** sort by assignment submission status */
private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status";
/** sort by assignment number of submissions */
private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions";
/** sort by assignment number of ungraded submissions */
private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded";
/** sort by assignment submission grade */
private static final String SORTED_BY_GRADE = "grade";
/** sort by assignment maximun grade available */
private static final String SORTED_BY_MAX_GRADE = "max_grade";
/** sort by assignment range */
private static final String SORTED_BY_FOR = "for";
/** sort by group title */
private static final String SORTED_BY_GROUP_TITLE = "group_title";
/** sort by group description */
private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description";
/** *************************** sort submission in instructor grade view *********************** */
/** state sort submission* */
private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time";
/** state sort submission by submission status * */
private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status";
/** state sort submission by submission grade * */
private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade";
/** state sort submission by submission released * */
private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released";
/** state sort submissuib by content review score **/
private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview";
/** *************************** sort submission *********************** */
/** state sort submission* */
private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time";
/** state sort submission by submission grade * */
private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade";
/** state sort submission by submission status * */
private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status";
/** state sort submission by submission released * */
private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released";
/** state sort submission by assignment title */
private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment";
/** state sort submission by max grade */
private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade";
/** ******************** student's view assignment submission ****************************** */
/** the assignment object been viewing * */
private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference";
/** the submission text to the assignment * */
private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text";
/** the submission answer to Honor Pledge * */
private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes";
/** ***************** student's preview of submission *************************** */
/** the assignment id * */
private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference";
/** the submission text * */
private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text";
/** the submission honor pledge answer * */
private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes";
/** the submission attachments * */
private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments";
/** the flag indicate whether the to show the student view or not */
private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag";
/** the flag indicate whether the to show the assignment info or not */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag";
/** the assignment id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id";
/** the assignment content id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id";
/** ************** view assignment ***************************************** */
/** the hide assignment flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag";
/** the hide student view flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag";
/** ******************* instructor's view assignment ***************************** */
private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id";
/** ******************* instructor's edit assignment ***************************** */
private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id";
/** ******************* instructor's delete assignment ids ***************************** */
private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids";
/** ******************* flags controls the grade assignment page layout ******************* */
private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag";
private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag";
private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade";
/** ******************* instructor's grade submission ***************************** */
private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id";
private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id";
private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment";
private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text";
private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment";
private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade";
private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag";
private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit";
/** ******************* instructor's export assignment ***************************** */
private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref";
private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id";
/** ****************** instructor's new assignment ****************************** */
private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title";
// assignment order for default view
private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order";
// open date
private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth";
private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday";
private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear";
private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour";
private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin";
private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm";
// due date
private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth";
private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday";
private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear";
private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour";
private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin";
private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm";
// close date
private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate";
private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth";
private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday";
private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear";
private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour";
private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin";
private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm";
private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment";
private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section";
private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type";
private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type";
private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points";
private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions";
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced";
private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge";
private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag";
private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus";
private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty";
private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook";
private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range";
private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups";
/**************************** assignment year range *************************/
private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from";
private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to";
// submission level of resubmit due time
private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth";
private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay";
private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear";
private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour";
private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin";
private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM";
private static final String ATTACHMENTS_MODIFIED = "attachments_modified";
/** **************************** instructor's view student submission ***************** */
// the show/hide table based on member id
private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE";
/** **************************** student view grade submission id *********** */
private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id";
// alert for grade exceeds max grade setting
private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert";
/** **************************** modes *************************** */
/** The list view of assignments */
private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template
/** The student view of an assignment submission */
private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission";
/** The student view of an assignment submission confirmation */
private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation";
/** The student preview of an assignment submission */
private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade";
/** The student view of assignments */
private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment";
/** The instructor view of creating a new assignment or editing an existing one */
private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment";
/** The instructor view to reorder assignments */
private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder";
/** The instructor view to delete an assignment */
private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment";
/** The instructor view to grade an assignment */
private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment";
/** The instructor view to grade a submission */
private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission";
/** The instructor view of preview grading a submission */
private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission";
/** The instructor preview of one assignment */
private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments";
/** The instructor view of one assignment */
private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments";
/** The instructor view to list students of an assignment */
private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template
/** The instructor view of assignment submission report */
private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template
/** The instructor view of uploading all from archive file */
private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll";
/** The student view of assignment submission report */
private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template
/** ************************* vm names ************************** */
/** The list view of assignments */
private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments";
/** The student view of assignment */
private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment";
/** The student view of showing an assignment submission */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission";
/** The student view of an assignment submission confirmation */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation";
/** The student preview an assignment submission */
private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission";
/** The student view of graded submission */
private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade";
/** The instructor view to create a new assignment or edit an existing one */
private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment";
/** The instructor view to reorder the default assignments */
private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission";
/** The instructor preview to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission";
/** The instructor view to grade the assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions";
/** The instructor preview of assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment";
/** The instructor view of assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions";
/** The instructor view to assignment submission report */
private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions";
/** The instructor view to upload all information from archive file */
private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll";
/** The opening mark comment */
private static final String COMMENT_OPEN = "{{";
/** The closing mark for comment */
private static final String COMMENT_CLOSE = "}}";
/** The selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** The configuration choice of with grading option or not */
private static final String WITH_GRADES = "with_grades";
/** The alert flag when doing global navigation from improper mode */
private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation";
/** The total list item before paging */
private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items";
/** is current user allowed to grade assignment? */
private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission";
/** property for previous feedback attachments **/
private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments";
/** the user and submission list for list of submissions page */
private static final String USER_SUBMISSIONS = "user_submissions";
/** ************************* Taggable constants ************************** */
/** identifier of tagging provider that will provide the appropriate helper */
private static final String PROVIDER_ID = "providerId";
/** Reference to an activity */
private static final String ACTIVITY_REF = "activityRef";
/** Reference to an item */
private static final String ITEM_REF = "itemRef";
/** session attribute for list of decorated tagging providers */
private static final String PROVIDER_LIST = "providerList";
// whether the choice of emails instructor submission notification is available in the installation
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications";
// default for whether or how the instructor receive submission notification emails, none(default)|each|digest
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default";
/****************************** Upload all screen ***************************/
private static final String UPLOAD_ALL_HAS_SUBMISSIONS = "upload_all_has_submissions";
private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile";
private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments";
private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades";
/**
* central place for dispatching the build routines based on the state name
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
String template = null;
context.put("tlang", rb);
context.put("cheffeedbackhelper", this);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// allow add assignment?
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment));
Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION);
// allow update site?
context.put("allowUpdateSite", Boolean
.valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))));
// allow all.groups?
boolean allowAllGroups = AssignmentService.allowAllGroups(contextString);
context.put("allowAllGroups", Boolean.valueOf(allowAllGroups));
// this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files
Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state.getAttribute(STATE_CONTEXT_STRING)));
boolean assignmentscheck = (assignments.size() > 0) ? true : false;
context.put("assignmentscheck", Boolean.valueOf(assignmentscheck));
//Is the review service allowed?
context.put("allowReviewService", allowReviewService);
// grading option
context.put("withGrade", state.getAttribute(WITH_GRADES));
String mode = (String) state.getAttribute(STATE_MODE);
if (!mode.equals(MODE_LIST_ASSIGNMENTS))
{
// allow grade assignment?
if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null)
{
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE);
}
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
}
if (mode.equals(MODE_LIST_ASSIGNMENTS))
{
// build the context for the student assignment view
template = build_list_assignments_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT))
{
// the student view of assignment
template = build_student_view_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one assignment submission
template = build_student_view_submission_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION))
{
// build the context for showing one assignment submission confirmation
template = build_student_view_submission_confirmation_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION))
{
// build the context for showing one assignment submission
template = build_student_preview_submission_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_GRADE))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one graded submission
template = build_student_view_grade_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
// allow add assignment?
boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString);
context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment));
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_new_edit_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT))
{
if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null)
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's delete assignment
template = build_instructor_delete_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's grade assignment
template = build_instructor_grade_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's grade submission
template = build_instructor_grade_submission_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's preview grade submission
template = build_instructor_preview_grade_submission_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT))
{
// build the context for preview one assignment
template = build_instructor_preview_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for view one assignment
template = build_instructor_view_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's create new assignment view
template = build_instructor_view_students_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of report submissions
template = build_instructor_report_submissions(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_UPLOAD_ALL))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_upload_all(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_reorder_assignment_context(portlet, context, data, state);
}
if (template == null)
{
// default to student list view
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
template = build_list_assignments_context(portlet, context, data, state);
}
return template;
} // buildNormalContext
/**
* build the student view of showing an assignment submission
*/
protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
User user = (User) state.getAttribute(STATE_USER);
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment(currentAssignmentReference);
context.put("assignment", assignment);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment)));
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user);
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
// name value pairs for the vm
context.put("name_submission_text", VIEW_SUBMISSION_TEXT);
context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT));
context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES);
context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("currentTime", TimeService.newTime());
boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING));
if (!allowSubmit)
{
addAlert(state, rb.getString("not_allowed_to_submit"));
}
context.put("allowSubmit", new Boolean(allowSubmit));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION;
} // build_student_view_submission_context
/**
* build the student view of showing an assignment submission confirmation
*/
protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
// get user information
User user = (User) state.getAttribute(STATE_USER);
context.put("user_name", user.getDisplayName());
context.put("user_id", user.getDisplayId());
// get site information
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site_title", site.getTitle());
}
catch (Exception ignore)
{
Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString);
}
// get assignment and submission information
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
try
{
Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference);
context.put("assignment_title", currentAssignment.getTitle());
AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user);
if (s != null)
{
context.put("submission_id", s.getId());
context.put("submit_time", s.getTimeSubmitted().toStringLocalFull());
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size()>0)
{
context.put("submit_attachments", s.getSubmittedAttachments());
}
context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText()));
context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true)));
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION;
} // build_student_view_submission_confirmation_context
/**
* build the student view of assignment
*/
protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment(aId);
context.put("assignment", assignment);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("gradeTypeTable", gradeTypeTable());
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT;
} // build_student_view_submission_context
/**
* build the student preview of showing an assignment submission
*/
protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
User user = (User) state.getAttribute(STATE_USER);
String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
try
{
context.put("assignment", AssignmentService.getAssignment(aReference));
context.put("submission", AssignmentService.getSubmission(aReference, user));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT));
context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION;
} // build_student_preview_submission_context
/**
* build the student view of showing a graded submission
*/
protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
AssignmentSubmission submission = null;
try
{
submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID));
context.put("assignment", submission.getAssignment());
context.put("submission", submission);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_get_submission"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && submission != null)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>();
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getItemHelperInfo(
assignmentActivityProducer.getItem(
submission,
UserDirectoryService.getCurrentUser()
.getId()).getReference());
if (helper != null)
{
itemHelpers.add(helper);
}
}
addItem(context, submission, UserDirectoryService.getCurrentUser().getId());
addActivity(context, submission.getAssignment());
context.put("itemHelpers", itemHelpers);
context.put("taggable", Boolean.valueOf(true));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_GRADE;
} // build_student_view_grade_context
/**
* build the view of assignments list
*/
protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable())
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
context.put("providers", taggingManager.getProviders());
context.put("taggable", Boolean.valueOf(true));
}
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("contextString", contextString);
context.put("user", state.getAttribute(STATE_USER));
context.put("service", AssignmentService.getInstance());
context.put("TimeService", TimeService.getInstance());
context.put("LongObject", new Long(TimeService.newTime().getTime()));
context.put("currentTime", TimeService.newTime());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
// clean sort criteria
if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION))
{
sortedBy = SORTED_BY_DUEDATE;
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sortedBy);
state.setAttribute(SORTED_ASC, sortedAsc);
}
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
context.put("view", state.getAttribute(STATE_SELECTED_VIEW));
}
List assignments = prepPage(state);
// make sure for all non-electronic submission type of assignment, the submission number matches the number of site members
for (int i = 0; i < assignments.size(); i++)
{
Assignment a = (Assignment) assignments.get(i);
if (a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference());
List submissions = AssignmentService.getSubmissions(a);
if (submissions != null && allowAddSubmissionUsers != null && allowAddSubmissionUsers.size() != submissions.size())
{
// if there is any newly added user who doesn't have a submission object yet, add the submission
try
{
addSubmissionsForNonElectronicAssignment(state, AssignmentService.editAssignment(a.getReference()));
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage());
}
}
}
}
context.put("assignments", assignments.iterator());
// allow get assignment
context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString)));
// test whether user user can grade at least one assignment
// and update the state variable.
boolean allowGradeSubmission = false;
for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); )
{
if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference()))
{
allowGradeSubmission = true;
}
}
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission));
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
// allow remove assignment?
boolean allowRemoveAssignment = false;
for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); )
{
if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference()))
{
allowRemoveAssignment = true;
}
}
context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment));
add2ndToolbarFields(data, context);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
pagingInfoToContext(state, context);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site", site);
// any group in the site?
Collection groups = site.getGroups();
context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE);
// add active user list
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
if (realm != null)
{
context.put("activeUserIds", realm.getUsers());
}
}
catch (Exception ignore)
{
Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString);
}
boolean allowSubmit = AssignmentService.allowAddSubmission(contextString);
context.put("allowSubmit", new Boolean(allowSubmit));
// related to resubmit settings
context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// the type int for non-electronic submission
context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_LIST_ASSIGNMENTS;
} // build_list_assignments_context
/**
* build the instructor view of creating a new assignment or editing an existing one
*/
protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// is the assignment an new assignment
String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentId != null)
{
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
context.put("assignment", a);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14") + ": " + assignmentId);
}
}
// set up context variables
setAssignmentFormContext(state, context);
context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS));
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT;
} // build_instructor_new_assignment_context
protected void setAssignmentFormContext(SessionState state, Context context)
{
// put the names and values into vm file
context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
context.put("name_title", NEW_ASSIGNMENT_TITLE);
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("name_OpenMonth", NEW_ASSIGNMENT_OPENMONTH);
context.put("name_OpenDay", NEW_ASSIGNMENT_OPENDAY);
context.put("name_OpenYear", NEW_ASSIGNMENT_OPENYEAR);
context.put("name_OpenHour", NEW_ASSIGNMENT_OPENHOUR);
context.put("name_OpenMin", NEW_ASSIGNMENT_OPENMIN);
context.put("name_OpenAMPM", NEW_ASSIGNMENT_OPENAMPM);
context.put("name_DueMonth", NEW_ASSIGNMENT_DUEMONTH);
context.put("name_DueDay", NEW_ASSIGNMENT_DUEDAY);
context.put("name_DueYear", NEW_ASSIGNMENT_DUEYEAR);
context.put("name_DueHour", NEW_ASSIGNMENT_DUEHOUR);
context.put("name_DueMin", NEW_ASSIGNMENT_DUEMIN);
context.put("name_DueAMPM", NEW_ASSIGNMENT_DUEAMPM);
context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("name_CloseMonth", NEW_ASSIGNMENT_CLOSEMONTH);
context.put("name_CloseDay", NEW_ASSIGNMENT_CLOSEDAY);
context.put("name_CloseYear", NEW_ASSIGNMENT_CLOSEYEAR);
context.put("name_CloseHour", NEW_ASSIGNMENT_CLOSEHOUR);
context.put("name_CloseMin", NEW_ASSIGNMENT_CLOSEMIN);
context.put("name_CloseAMPM", NEW_ASSIGNMENT_CLOSEAMPM);
context.put("name_Section", NEW_ASSIGNMENT_SECTION);
context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE);
context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE);
context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS);
context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION);
// do not show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
//don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// number of resubmissions allowed
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// set the values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER));
context.put("value_OpenMonth", state.getAttribute(NEW_ASSIGNMENT_OPENMONTH));
context.put("value_OpenDay", state.getAttribute(NEW_ASSIGNMENT_OPENDAY));
context.put("value_OpenYear", state.getAttribute(NEW_ASSIGNMENT_OPENYEAR));
context.put("value_OpenHour", state.getAttribute(NEW_ASSIGNMENT_OPENHOUR));
context.put("value_OpenMin", state.getAttribute(NEW_ASSIGNMENT_OPENMIN));
context.put("value_OpenAMPM", state.getAttribute(NEW_ASSIGNMENT_OPENAMPM));
context.put("value_DueMonth", state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
context.put("value_DueDay", state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
context.put("value_DueYear", state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
context.put("value_DueHour", state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
context.put("value_DueMin", state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
context.put("value_DueAMPM", state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE));
context.put("value_CloseMonth", state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH));
context.put("value_CloseDay", state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY));
context.put("value_CloseYear", state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR));
context.put("value_CloseHour", state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR));
context.put("value_CloseMin", state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN));
context.put("value_CloseAMPM", state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM));
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length);
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
// format to show one decimal place
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
// Keep the use review service setting
context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// don't show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
// don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
if (s == null) s = "1";
context.put("value_CheckAddHonorPledge", s);
// number of resubmissions allowed
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)));
}
else
{
// defaults to 0
context.put("value_allowResubmitNumber", Integer.valueOf(0));
}
// get all available assignments from Gradebook tool except for those created from
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
try
{
// get all assignments in Gradebook
List gradebookAssignments = g.getAssignments(gradebookUid);
List gradebookAssignmentsExceptSamigo = new Vector();
// filtering out those from Samigo
for (Iterator i=gradebookAssignments.iterator(); i.hasNext();)
{
org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next();
if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle()))
{
gradebookAssignmentsExceptSamigo.add(gAssignment);
}
}
context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo);
if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
context.put("withGradebook", Boolean.TRUE);
// offer the gradebook integration choice only in the Assignments with Grading tool
boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue();
if (withGrade)
{
context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
}
context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO);
context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD);
context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
}
catch (Exception e)
{
// not able to link to Gradebook
Log.warn("chef", this + e.getMessage());
}
if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
}
context.put("monthTable", monthTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
}
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString);
if (AssignmentService.allowAddSiteAssignment(contextString))
{
// default to make site selection
context.put("range", "site");
}
else if (groupsAllowAddAssignment.size() > 0)
{
// to group otherwise
context.put("range", "groups");
}
// group list which user can add message to
if (groupsAllowAddAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS));
}
}
context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook()));
// the notification email choices
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue())
{
context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null)
{
// set the notification value using site default
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT));
}
context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
// the option values
context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE);
context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH);
context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST);
}
} // setAssignmentFormContext
/**
* build the instructor view of create a new assignment
*/
protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("time", TimeService.newTime());
context.put("user", UserDirectoryService.getCurrentUser());
context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER));
Time openTime = getOpenTime(state);
context.put("value_OpenDate", openTime);
// due time
int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue();
int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue();
int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue();
int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue();
int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue();
String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
context.put("value_DueDate", dueTime);
// close time
Time closeTime = TimeService.newTime();
Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("value_EnableCloseDate", enableCloseDate);
if ((enableCloseDate).booleanValue())
{
int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
context.put("value_CloseDate", closeTime);
}
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE));
// get all available assignments from Gradebook tool except for those created from
if (isGradebookDefined())
{
context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
}
context.put("monthTable", monthTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG));
context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG));
context.put("value_assignment_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID));
context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID));
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT;
} // build_instructor_preview_assignment_context
/**
* build the instructor view to delete an assignment
*/
protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
Vector assignments = new Vector();
Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < assignmentIds.size(); i++)
{
try
{
Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i));
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
// if there is submission to the assignment, show the alert
addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n");
}
assignments.add(a);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
context.put("assignments", assignments);
context.put("service", AssignmentService.getInstance());
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT;
} // build_instructor_delete_assignment_context
/**
* build the instructor view to grade an submission
*/
protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
int gradeType = -1;
// assignment
Assignment a = null;
try
{
a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
// assignment submission
try
{
AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID));
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// get the submission level of close date setting
context.put("name_CloseMonth", ALLOW_RESUBMIT_CLOSEMONTH);
context.put("name_CloseDay", ALLOW_RESUBMIT_CLOSEDAY);
context.put("name_CloseYear", ALLOW_RESUBMIT_CLOSEYEAR);
context.put("name_CloseHour", ALLOW_RESUBMIT_CLOSEHOUR);
context.put("name_CloseMin", ALLOW_RESUBMIT_CLOSEMIN);
context.put("name_CloseAMPM", ALLOW_RESUBMIT_CLOSEAMPM);
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
Time time = null;
if (closeTimeString != null)
{
// if there is a local setting
time = TimeService.newTime(Long.parseLong(closeTimeString));
}
else if (a != null)
{
// if there is no local setting, default to assignment close time
time = a.getCloseTime();
}
TimeBreakdown closeTime = time.breakdownLocal();
context.put("value_CloseMonth", new Integer(closeTime.getMonth()));
context.put("value_CloseDay", new Integer(closeTime.getDay()));
context.put("value_CloseYear", new Integer(closeTime.getYear()));
int closeHour = closeTime.getHour();
if (closeHour >= 12)
{
context.put("value_CloseAMPM", "PM");
}
else
{
context.put("value_CloseAMPM", "AM");
}
if (closeHour == 0)
{
// for midnight point, we mark it as 12AM
closeHour = 12;
}
context.put("value_CloseHour", new Integer((closeHour > 12) ? closeHour - 12 : closeHour));
context.put("value_CloseMin", new Integer(closeTime.getMin()));
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
context.put("user", state.getAttribute(STATE_USER));
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("instructorAttachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// names
context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID);
context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT);
context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
context.put("name_grade", GRADE_SUBMISSION_GRADE);
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT));
context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS));
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)));
}
// format to show one decimal place in grade
context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE))
: state.getAttribute(GRADE_SUBMISSION_GRADE));
context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG));
context.put("gradingAttachments", state.getAttribute(ATTACHMENTS));
// is this a non-electronic submission type of assignment
context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION;
} // build_instructor_grade_submission_context
private List getPrevFeedbackAttachments(ResourceProperties p) {
String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS);
String[] attachmentsReferences = attachmentsString.split(",");
List prevFeedbackAttachments = EntityManager.newReferenceList();
for (int k =0; k < attachmentsReferences.length; k++)
{
prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k]));
}
return prevFeedbackAttachments;
}
/**
* build the instructor preview of grading submission
*/
protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// assignment
int gradeType = -1;
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
// submission
try
{
context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
User user = (User) state.getAttribute(STATE_USER);
context.put("user", user);
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// filter the feedback text for the instructor comment and mark it as red
String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("feedback_text", feedbackText);
context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT));
// format to show one decimal place
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
if (gradeType == 3)
{
grade = displayGrade(state, grade);
}
context.put("grade", grade);
context.put("comment_open", COMMENT_OPEN);
context.put("comment_close", COMMENT_CLOSE);
context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
if (closeTimeString != null)
{
// close time for resubmit
Time time = TimeService.newTime(Long.parseLong(closeTimeString));
context.put("allowResubmitCloseTime", time.toStringLocalFull());
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION;
} // build_instructor_preview_grade_submission_context
/**
* build the instructor view to grade an assignment
*/
protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("user", state.getAttribute(STATE_USER));
// sorting related fields
context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY));
context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC));
context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME);
context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME);
context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS);
context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE);
context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED);
context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
context.put("assignment", assignment);
state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId());
List userSubmissions = prepPage(state);
state.setAttribute(USER_SUBMISSIONS, userSubmissions);
context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS));
// ever set the default grade for no-submissions
String noSubmissionDefaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE);
if (noSubmissionDefaultGrade != null)
{
context.put("noSubmissionDefaultGrade", noSubmissionDefaultGrade);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
// Get turnitin results for instructors
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG));
context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG));
// the user directory service
context.put("userDirectoryService", UserDirectoryService.getInstance());
add2ndToolbarFields(data, context);
pagingInfoToContext(state, context);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT;
} // build_instructor_grade_assignment_context
/**
* build the instructor view of an assignment
*/
protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("tlang", rb);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID));
context.put("assignment", assignment);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>();
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getActivityHelperInfo(
assignmentActivityProducer.getActivity(
assignment).getReference());
if (helper != null)
{
activityHelpers.add(helper);
}
}
addActivity(context, assignment);
context.put("activityHelpers", activityHelpers);
context.put("taggable", Boolean.valueOf(true));
}
context.put("currentTime", TimeService.newTime());
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG));
context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
// the user directory service
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT;
} // build_instructor_view_assignment_context
/**
* build the instructor view of reordering assignments
*/
protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
context.put("assignmentsize", assignments.size());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("gradeTypeTable", gradeTypeTable());
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT;
} // build_instructor_reorder_assignment_context
/**
* build the instructor view to view the list of students for an assignment
*/
protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// get the realm and its member
List studentMembers = new Vector();
String realmId = SiteService.siteReference((String) state.getAttribute(STATE_CONTEXT_STRING));
try
{
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
Set allowSubmitMembers = realm.getUsersIsAllowed(AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION);
for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();)
{
// get user
try
{
String userId = (String) allowSubmitMembersIterator.next();
User user = UserDirectoryService.getUser(userId);
studentMembers.add(user);
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
}
catch (GroupNotDefinedException e)
{
Log.warn("chef", this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm") + realmId);
}
context.put("studentMembers", studentMembers);
context.put("assignmentService", AssignmentService.getInstance());
Hashtable showStudentAssignments = new Hashtable();
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null)
{
Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
context.put("studentListShowSet", showStudentListSet);
for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();)
{
// get user
try
{
String userId = (String) showStudentListSetIterator.next();
User user = UserDirectoryService.getUser(userId);
showStudentAssignments.put(user, AssignmentService.getAssignmentsForContext(contextString, userId));
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
}
context.put("studentAssignmentsTable", showStudentAssignments);
add2ndToolbarFields(data, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT;
} // build_instructor_view_students_assignment_context
/**
* build the instructor view to report the submissions
*/
protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("submissions", prepPage(state));
context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY));
context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC));
context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME);
context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME);
context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE);
context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS);
context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED);
context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT);
context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE);
add2ndToolbarFields(data, context);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", ServerConfigurationService.getAccessUrl()
+ AssignmentService.gradesSpreadsheetReference(contextString, null));
pagingInfoToContext(state, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS;
} // build_instructor_report_submissions
// Is Gradebook defined for the site?
protected boolean isGradebookDefined()
{
boolean rv = false;
try
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager
.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid))
{
rv = true;
}
}
catch (Exception e)
{
Log.debug("chef", this + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage());
}
return rv;
} // isGradebookDefined()
/**
* build the instructor view to upload information from archive file
*/
protected String build_instructor_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("hasSubmissions", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSIONS));
context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE));
context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS));
context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL;
} // build_instructor_upload_all
/**
** Retrieve tool title from Tool configuration file or use default
** (This should return i18n version of tool title if available)
**/
private String getToolTitle()
{
Tool tool = ToolManager.getTool("sakai.assignment.grades");
String toolTitle = null;
if (tool == null)
toolTitle = "Assignments";
else
toolTitle = tool.getTitle();
return toolTitle;
}
/**
* integration with gradebook
*
* @param state
* @param assignmentRef Assignment reference
* @param associateGradebookAssignment The title for the associated GB assignment
* @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment
* @param oldAssignment_title The original assignment title
* @param newAssignment_title The updated assignment title
* @param newAssignment_maxPoints The maximum point of the assignment
* @param newAssignment_dueTime The due time of the assignment
* @param submissionRef Any submission grade need to be updated? Do bulk update if null
* @param updateRemoveSubmission "update" for update submission;"remove" for remove submission
*/
protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission)
{
associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment);
// add or remove external grades to gradebook
// a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden
// b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The
// exception are indication that the assessment is already in the Gradebook or there is nothing
// to remove.
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
String assignmentToolTitle = getToolTitle();
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, assignmentRef);
boolean isExternalAssociateAssignmentDefined = g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (addUpdateRemoveAssignment != null)
{
// add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet
if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || (addUpdateRemoveAssignment.equals("update") && !isExternalAssignmentDefined)) && associateGradebookAssignment == null)
{
// add assignment into gradebook
try
{
// add assignment to gradebook
g.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title,
newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
}
catch (ConflictingAssignmentNameException e)
{
// add alert prompting for change assignment title
addAlert(state, rb.getString("addtogradebook.nonUniqueTitle"));
}
catch (ConflictingExternalIdException e)
{
// this shouldn't happen, as we have already checked for assignment reference before. Log the error
Log.warn("chef", this + e.getMessage());
}
catch (GradebookNotFoundException e)
{
// this shouldn't happen, as we have checked for gradebook existence before
Log.warn("chef", this + e.getMessage());
}
catch (Exception e)
{
// ignore
Log.warn("chef", this + e.getMessage());
}
}
else if (addUpdateRemoveAssignment.equals("update"))
{
// is there such record in gradebook?
if (isExternalAssignmentDefined && associateGradebookAssignment == null)
{
try
{
Assignment a = AssignmentService.getAssignment(assignmentRef);
// update attributes for existing assignment
g.updateExternalAssessment(gradebookUid, assignmentRef, null, a.getTitle(), a.getContent().getMaxGradePoint()/10.0, new Date(a.getDueTime().getTime()));
}
catch(Exception e)
{
Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage());
}
}
else if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined)
{
try
{
Assignment a = AssignmentService.getAssignment(associateGradebookAssignment);
// update attributes for existing assignment
g.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()));
}
catch(Exception e)
{
Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage());
}
}
} // addUpdateRemove != null
else if (addUpdateRemoveAssignment.equals("remove"))
{
// remove assignment and all submission grades
if (isExternalAssignmentDefined)
{
try
{
g.removeExternalAssessment(gradebookUid, assignmentRef);
}
catch (Exception e)
{
Log.warn("chef", "Exception when removing assignment " + assignmentRef + " and its submissions:"
+ e.getMessage());
}
}
}
}
if (updateRemoveSubmission != null)
{
try
{
Assignment a = AssignmentService.getAssignment(assignmentRef);
if (updateRemoveSubmission.equals("update")
&& a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null
&& !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)
&& a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (submissionRef == null)
{
// bulk add all grades for assignment into gradebook
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
Map m = new HashMap();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null;
m.put(submitterId, grade);
}
// need to update only when there is at least one submission
if (m.size()>0)
{
if (associateGradebookAssignment != null)
{
if (isExternalAssociateAssignmentDefined)
{
// the associated assignment is externally maintained
g.updateExternalAssessmentScores(gradebookUid, associateGradebookAssignment, m);
}
else if (isAssignmentDefined)
{
// the associated assignment is internal one, update records one by one
submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null;
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitterId, grade, assignmentToolTitle);
}
}
}
else if (isExternalAssignmentDefined)
{
g.updateExternalAssessmentScores(gradebookUid, assignmentRef, m);
}
}
}
else
{
try
{
// only update one submission
AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService
.getSubmission(submissionRef);
User[] submitters = aSubmission.getSubmitters();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
if (associateGradebookAssignment != null)
{
if (g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is externally maintained
g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null);
}
else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is internal one, update records
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null, assignmentToolTitle);
}
}
else
{
g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null);
}
}
catch (Exception e)
{
Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage());
}
}
}
else if (updateRemoveSubmission.equals("remove"))
{
if (submissionRef == null)
{
// remove all submission grades (when changing the associated entry in Gradebook)
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
if (isExternalAssociateAssignmentDefined)
{
// if the old associated assignment is an external maintained one
g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null);
}
else if (isAssignmentDefined)
{
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle);
}
}
}
else
{
// remove only one submission grade
try
{
AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService
.getSubmission(submissionRef);
User[] submitters = aSubmission.getSubmitters();
g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null);
}
catch (Exception e)
{
Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage());
}
}
}
}
catch (Exception e)
{
Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage());
}
} // updateRemoveSubmission != null
} // if gradebook exists
} // integrateGradebook
/**
* Go to the instructor view
*/
public void doView_instructor(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doView_instructor
/**
* Go to the student view
*/
public void doView_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// to the student list of assignment view
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doView_student
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentReference = params.getString("assignmentReference");
state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference);
User u = (User) state.getAttribute(STATE_USER);
try
{
AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u);
if (submission != null)
{
state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText());
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString());
List v = EntityManager.newReferenceList();
Iterator l = submission.getSubmittedAttachments().iterator();
while (l.hasNext())
{
v.add(l.next());
}
state.setAttribute(ATTACHMENTS, v);
}
else
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
} // try
} // doView_submission
/**
* Preview of the submission
*/
public void doPreview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// String assignmentId = params.getString(assignmentId);
state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE));
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
state.setAttribute(PREVIEW_SUBMISSION_TEXT, text);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
// assign the honor pledge attribute
String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honor_pledge_yes == null)
{
honor_pledge_yes = "false";
}
state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION);
}
} // doPreview_submission
/**
* Preview of the grading of submission
*/
public void doPreview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read user input
readGradeForm(data, state, "read");
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION);
}
} // doPreview_grade_submission
/**
* Action is to end the preview submission process
*/
public void doDone_preview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
} // doDone_preview_submission
/**
* Action is to end the view assignment process
*/
public void doDone_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doDone_view_assignments
/**
* Action is to end the preview new assignment process
*/
public void doDone_preview_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the new assignment page
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doDone_preview_new_assignment
/**
* Action is to end the preview edit assignment process
*/
public void doDone_preview_edit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the edit assignment page
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doDone_preview_edit_assignment
/**
* Action is to end the user view assignment process and redirect him to the assignment list view
*/
public void doCancel_student_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_student_view_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_show_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_show_submission
/**
* Action is to cancel the delete assignment process
*/
public void doCancel_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the show assignment object
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
// back to the instructor list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_delete_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_edit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_edit_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_new_assignment
/**
* Action is to cancel the grade submission process
*/
public void doCancel_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
// resetAssignment (state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
} // doCancel_grade_submission
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_preview_grade_submission
/**
* Action is to cancel the reorder process
*/
public void doCancel_reorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_reorder
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_to_list_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
} // doCancel_preview_to_list_submission
/**
* Action is to return to the view of list assignments
*/
public void doList_assignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute(SORTED_ASC, Boolean.FALSE.toString());
} // doList_assignments
/**
* Action is to cancel the student view grade process
*/
public void doCancel_view_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view grade submission id
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_view_grade
/**
* Action is to save the grade to submission
*/
public void doSave_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "save");
}
} // doSave_grade_submission
/**
* Action is to release the grade to submission
*/
public void doRelease_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "release");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "release");
}
} // doRelease_grade_submission
/**
* Action is to return submission with or without grade
*/
public void doReturn_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "return");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "return");
}
} // doReturn_grade_submission
/**
* Action is to return submission with or without grade from preview
*/
public void doReturn_preview_grade_submission(RunData data)
{
grade_submission_option(data, "return");
} // doReturn_grade_preview_submission
/**
* Action is to save submission with or without grade from preview
*/
public void doSave_preview_grade_submission(RunData data)
{
grade_submission_option(data, "save");
} // doSave_grade_preview_submission
/**
* Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade.
*/
private void grade_submission_option(RunData data, String gradeOption)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false;
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
try
{
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId);
Assignment a = sEdit.getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (!withGrade)
{
// no grade input needed for the without-grade version of assignment tool
sEdit.setGraded(true);
if (gradeOption.equals("return") || gradeOption.equals("release"))
{
sEdit.setGradeReleased(true);
}
}
else if (grade == null)
{
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
}
else
{
if (typeOfGrade == 1)
{
sEdit.setGrade("no grade");
sEdit.setGraded(true);
}
else
{
if (!grade.equals(""))
{
if (typeOfGrade == 3)
{
sEdit.setGrade(grade);
}
else
{
sEdit.setGrade(grade);
}
sEdit.setGraded(true);
}
}
}
if (gradeOption.equals("release"))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
// clear the returned flag
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
else if (gradeOption.equals("return"))
{
if (StringUtil.trimToNull(grade) != null)
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
}
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
}
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// get resubmit number
ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit();
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getAllowSubmitCloseTime(state);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
// the instructor comment
String feedbackCommentString = StringUtil
.trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
if (feedbackCommentString != null)
{
sEdit.setFeedbackComment(feedbackCommentString);
}
// the instructor inline feedback
String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
if (feedbackTextString != null)
{
sEdit.setFeedbackText(feedbackTextString);
}
List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
if (v != null)
{
// clear the old attachments first
sEdit.clearFeedbackAttachments();
for (int i = 0; i < v.size(); i++)
{
sEdit.addFeedbackAttachment((Reference) v.get(i));
}
}
String sReference = sEdit.getReference();
AssignmentService.commitEdit(sEdit);
// update grades in gradebook
String aReference = a.getReference();
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (gradeOption.equals("release") || gradeOption.equals("return"))
{
// update grade in gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update");
}
else
{
// remove grade from gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove");
}
}
catch (IdUnusedException e)
{
}
catch (PermissionException e)
{
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
} // try
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
} // grade_submission_option
/**
* Action is to save the submission as a draft
*/
public void doSave_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
User u = (User) state.getAttribute(STATE_USER);
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
Assignment a = AssignmentService.getAssignment(aReference);
String assignmentId = a.getId();
AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, save as draft
try
{
AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setSubmitted(false);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// clear the old attachments first
edit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(edit);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot12"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
}
else
{
// new submission, save as draft
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state
.getAttribute(STATE_CONTEXT_STRING), assignmentId);
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setSubmitted(false);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot4"));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
} // doSave_submission
/**
* Action is to post the submission
*/
public void doPost_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment a = null;
try
{
a = AssignmentService.getAssignment(aReference);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
if (AssignmentService.canSubmit(contextString, a))
{
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
else
{
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
}
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
User u = (User) state.getAttribute(STATE_USER);
String assignmentId = "";
if (state.getAttribute(STATE_MESSAGE) == null)
{
assignmentId = a.getId();
if (a.getContent().getHonorPledge() != 1)
{
if (!Boolean.valueOf(honorPledgeYes).booleanValue())
{
addAlert(state, rb.getString("youarenot18"));
}
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes);
}
// check the submission inputs based on the submission type
int submissionType = a.getContent().getTypeOfSubmission();
if (submissionType == 1)
{
// for the inline only submission
if (text.length() == 0)
{
addAlert(state, rb.getString("youmust7"));
}
}
else if (submissionType == 2)
{
// for the attachment only submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((v == null) || (v.size() == 0))
{
addAlert(state, rb.getString("youmust1"));
}
}
else if (submissionType == 3)
{
// for the inline and attachment submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((text.length() == 0) && ((v == null) || (v.size() == 0)))
{
addAlert(state, rb.getString("youmust2"));
}
}
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null))
{
try
{
AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, post it
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference());
sEdit.setSubmittedText(text);
sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
sEdit.setTimeSubmitted(TimeService.newTime());
sEdit.setSubmitted(true);
// for resubmissions
// when resubmit, keep the Returned flag on till the instructor grade again.
if (sEdit.getReturned())
{
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
if (sEdit.getGraded())
{
// add the current grade into previous grade histroy
String previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES);
if (previousGrades == null)
{
previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
if (previousGrades != null)
{
int typeOfGrade = a.getContent().getTypeOfGrade();
if (typeOfGrade == 3)
{
// point grade assignment type
// some old unscaled grades, need to scale the number and remove the old property
String[] grades = StringUtil.split(previousGrades, " ");
String newGrades = "";
for (int jj = 0; jj < grades.length; jj++)
{
String grade = grades[jj];
if (grade.indexOf(".") == -1)
{
// show the grade with decimal point
grade = grade.concat(".0");
}
newGrades = newGrades.concat(grade + " ");
}
previousGrades = newGrades;
}
sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
}
else
{
previousGrades = "";
}
}
previousGrades = previousGrades.concat(sEdit.getGradeDisplay() + " ");
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES,
previousGrades);
// clear the current grade and make the submission ungraded
sEdit.setGraded(false);
sEdit.setGrade("");
sEdit.setGradeReleased(false);
}
// keep the history of assignment feed back text
String feedbackTextHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)
: "";
feedbackTextHistory = sEdit.getFeedbackText() + "\n" + feedbackTextHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT,
feedbackTextHistory);
// keep the history of assignment feed back comment
String feedbackCommentHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)
: "";
feedbackCommentHistory = sEdit.getFeedbackComment() + "\n" + feedbackCommentHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT,
feedbackCommentHistory);
// keep the history of assignment feed back comment
String feedbackAttachmentHistory = sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS)
: "";
List feedbackAttachments = sEdit.getFeedbackAttachments();
for (int k = 0; k<feedbackAttachments.size();k++)
{
feedbackAttachmentHistory = ((Reference) feedbackAttachments.get(k)).getReference() + "," + feedbackAttachmentHistory;
}
sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS,
feedbackAttachmentHistory);
// reset the previous grading context
sEdit.setFeedbackText("");
sEdit.setFeedbackComment("");
sEdit.clearFeedbackAttachments();
// decrease the allow_resubmit_number
if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
// minus 1 from the submit number
if (number>=1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1));
}
else if (number == -1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(-1));
}
}
}
// sEdit.addSubmitter (u);
sEdit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
//Post the attachments before clearing so that we don't sumbit duplicate attachments
//Check if we need to post the attachments
if (a.getContent().getAllowReviewService()) {
if (!attachments.isEmpty()) {
sEdit.postAttachment((Reference) attachments.get(0));
}
}
// clear the old attachments first
sEdit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
sEdit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(sEdit);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("no_permissiion_to_edit_submission"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
}
else
{
// new submission, post it
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId);
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setTimeSubmitted(TimeService.newTime());
edit.setSubmitted(true);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService())
edit.postAttachment((Reference) attachments.get(0));
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
// get the assignment setting for resubmitting
if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
}
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot13"));
}
} // if -else
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
} // if
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION);
}
} // if
} // doPost_submission
/**
* Action is to confirm the submission and return to list view
*/
public void doConfirm_assignment_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
/**
* Action is to show the new assignment screen
*/
public void doNew_assignment(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
resetAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot2"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
}
} // doNew_Assignment
/**
* Action is to show the reorder assignment screen
*/
public void doReorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// this insures the default order is loaded into the reordering tool
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
resetAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot19"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
}
} // doReorder
/**
* Action is to save the input infos for assignment fields
*
* @param validify
* Need to validify the inputs or not
*/
protected void setNewAssignmentParameters(RunData data, boolean validify)
{
// read the form inputs
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// put the input value into the state attributes
String title = params.getString(NEW_ASSIGNMENT_TITLE);
state.setAttribute(NEW_ASSIGNMENT_TITLE, title);
String order = params.getString(NEW_ASSIGNMENT_ORDER);
state.setAttribute(NEW_ASSIGNMENT_ORDER, order);
if (title.length() == 0)
{
// empty assignment title
addAlert(state, rb.getString("plespethe1"));
}
// open time
int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth));
int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay));
int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear));
int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour));
int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin));
String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM);
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM);
if ((openAMPM.equals("PM")) && (openHour != 12))
{
openHour = openHour + 12;
}
if ((openHour == 12) && (openAMPM.equals("AM")))
{
openHour = 0;
}
Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0);
// validate date
if (!Validator.checkDate(openDay, openMonth, openYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + ".");
}
// due time
int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth));
int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay));
int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear));
int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour));
int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin));
String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM);
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
// validate date
if (dueTime.before(TimeService.newTime()))
{
addAlert(state, rb.getString("assig4"));
}
if (!Validator.checkDate(dueDay, dueMonth, dueYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + ".");
}
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
// close time
int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth));
int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay));
int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear));
int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour));
int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin));
String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM);
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
// validate date
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + ".");
}
if (closeTime.before(openTime))
{
addAlert(state, rb.getString("acesubdea3"));
}
if (closeTime.before(dueTime))
{
addAlert(state, rb.getString("acesubdea2"));
}
// SECTION MOD
String sections_string = "";
String mode = (String) state.getAttribute(STATE_MODE);
if (mode == null) mode = "";
state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string);
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)));
int gradeType = -1;
// grade type and grade points
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType));
}
String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
String b;
// set whether we use the review service or not
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b);
//set whether students can view the review service results
r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b);
// treat the new assignment description as formatted text
boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors
String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION),
checkForFormattingErrors);
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description);
if (state.getAttribute(CALENDAR) != null)
{
// calendar enabled for the site
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
}
}
else
{
// no calendar yet for the site
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)
.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
}
String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the honor pledge to be "no honor pledge"
if (s == null) s = "1";
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s);
String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading);
// only when choose to associate with assignment in Gradebook
String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (grading != null)
{
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment);
}
else
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, "");
}
if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// gradebook integration only available to point-grade assignment
if (gradeType != Assignment.SCORE_GRADE_TYPE)
{
addAlert(state, rb.getString("addtogradebook.wrongGradeScale"));
}
// if chosen as "associate", have to choose one assignment from Gradebook
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null)
{
addAlert(state, rb.getString("grading.associate.alert"));
}
}
}
List attachments = (List) state.getAttribute(ATTACHMENTS);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments);
// correct inputs
// checks on the times
if (validify && dueTime.before(openTime))
{
addAlert(state, rb.getString("assig3"));
}
if (validify)
{
if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0)))
{
// if there is no description nor an attachment, show the following alert message.
// One could ignore the message and still post the assignment
if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null)
{
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString());
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null)
{
addAlert(state, rb.getString("thiasshas"));
}
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
// the grade point
String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS);
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
if (gradePoints != null)
{
if (gradeType == 3)
{
if ((gradePoints.length() == 0))
{
// in case of point grade assignment, user must specify maximum grade point
addAlert(state, rb.getString("plespethe3"));
}
else
{
validPointGrade(state, gradePoints);
// when scale is points, grade must be integer and less than maximum value
if (state.getAttribute(STATE_MESSAGE) == null)
{
gradePoints = scalePointGrade(state, gradePoints);
}
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
}
}
}
}
// assignment range?
String range = data.getParameters().getString("range");
state.setAttribute(NEW_ASSIGNMENT_RANGE, range);
if (range.equals("groups"))
{
String[] groupChoice = data.getParameters().getStrings("selectedGroups");
if (groupChoice != null && groupChoice.length != 0)
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, null);
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
}
// allow resubmission numbers
String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (nString != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString);
}
// assignment notification option
String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (notiOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption);
}
} // setNewAssignmentParameters
/**
* Action is to hide the preview assignment student view
*/
public void doHide_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
// save user input
readGradeForm(data, state, "read");
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true));
// save user input
readGradeForm(data, state, "read");
} // doShow_submission_assignment_instruction
/**
* Action is to hide the preview assignment student view
*/
public void doHide_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true));
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false));
} // doShow_preview_assignment_student_view
/**
* Action is to hide the preview assignment assignment infos
*/
public void doHide_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true));
} // doHide_preview_assignment_assignment
/**
* Action is to show the preview assignment assignment info
*/
public void doShow_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false));
} // doShow_preview_assignment_assignment
/**
* Action is to hide the assignment option
*/
public void doHide_assignment_option(RunData data)
{
setNewAssignmentParameters(data, false);
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option");
} // doHide_assignment_option
/**
* Action is to show the assignment option
*/
public void doShow_assignment_option(RunData data)
{
setNewAssignmentParameters(data, false);
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
} // doShow_assignment_option
/**
* Action is to hide the assignment content in the view assignment page
*/
public void doHide_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true));
} // doHide_view_assignment
/**
* Action is to show the assignment content in the view assignment page
*/
public void doShow_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false));
} // doShow_view_assignment
/**
* Action is to hide the student view in the view assignment page
*/
public void doHide_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true));
} // doHide_view_student_view
/**
* Action is to show the student view in the view assignment page
*/
public void doShow_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false));
} // doShow_view_student_view
/**
* Action is to post assignment
*/
public void doPost_assignment(RunData data)
{
// post assignment
postOrSaveAssignment(data, "post");
} // doPost_assignment
/**
* Action is to tag items via an items tagging helper
*/
public void doHelp_items(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getItemsHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_items
/**
* Action is to tag an individual item via an item tagging helper
*/
public void doHelp_item(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String itemRef = params.getString(ITEM_REF);
TaggingHelperInfo helperInfo = provider
.getItemHelperInfo(itemRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_item
/**
* Action is to tag an activity via an activity tagging helper
*/
public void doHelp_activity(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getActivityHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (String key : helperParms.keySet()) {
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_activity
/**
* post or save assignment
*/
private void postOrSaveAssignment(RunData data, String postOrSave)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean post = (postOrSave != null) && postOrSave.equals("post");
// assignment old title
String aOldTitle = null;
// assignment old associated Gradebook entry if any
String oAssociateGradebookAssignment = null;
String mode = (String) state.getAttribute(STATE_MODE);
if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT))
{
// read input data if the mode is not preview mode
setNewAssignmentParameters(data, true);
}
String assignmentId = params.getString("assignmentId");
String assignmentContentId = params.getString("assignmentContentId");
if (state.getAttribute(STATE_MESSAGE) == null)
{
// AssignmentContent object
AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId);
// Assignment
AssignmentEdit a = getAssignmentEdit(state, assignmentId);
// put the names and values into vm file
String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE);
String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER);
// open time
Time openTime = getOpenTime(state);
// due time
Time dueTime = getDueTime(state);
// close time
Time closeTime = dueTime;
boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue();
if (enableCloseDate)
{
closeTime = getCloseTime(state);
}
// sections
String s = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION);
int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue();
int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue();
String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION);
String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null;
String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ;
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// the attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
List attachments1 = EntityManager.newReferenceList(attachments);
// set group property
String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE);
Collection groups = new Vector();
try
{
Site site = SiteService.getSite(siteId);
Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS);
if (range.equals(Assignment.AssignmentAccess.GROUPED) && (groupChoice == null || groupChoice.size() == 0))
{
// show alert if no group is selected for the group access assignment
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
else if (groupChoice != null)
{
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupId = (String) iGroups.next();
groups.add(site.getGroup(groupId));
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage());
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null))
{
aOldTitle = a.getTitle();
// old open time
Time oldOpenTime = a.getOpenTime();
// old due time
Time oldDueTime = a.getDueTime();
// commit the changes to AssignmentContent object
commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments1);
// set the Assignment Properties object
ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit();
oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit);
// the notification option
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// comment the changes to Assignment object
commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, s, range, groups);
// in case of non-electronic submission, create submissions for all students and mark it as submitted
if (ac.getTypeOfSubmission()== Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
try
{
Iterator sList = AssignmentService.getSubmissions(a).iterator();
if (sList == null || !sList.hasNext())
{
// add non-electronic submissions if there is none yet
addSubmissionsForNonElectronicAssignment(state, a);
}
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
resetAssignment(state);
}
if (post)
{
// only if user is posting the assignment
// add the due date to schedule if the schedule exists
integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit);
// the open date been announced
integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime);
// integrate with Gradebook
try
{
initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
}
} // if
} // if
} // if
} // doPost_assignment
/**
* Add submission objects if necessary for non-electronic type of assignment
* @param state
* @param a
*/
private void addSubmissionsForNonElectronicAssignment(SessionState state, Assignment a)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String authzGroupId = SiteService.siteReference(contextString);
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference());
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId);
Set grants = group.getUsers();
for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null && allowAddSubmissionUsers.contains(u))
{
if (AssignmentService.getSubmission(a.getReference(), u) == null)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit submission = AssignmentService.addSubmission(contextString, a.getId());
submission.removeSubmitter(UserDirectoryService.getCurrentUser());
submission.addSubmitter(u);
submission.setTimeSubmitted(TimeService.newTime());
submission.setSubmitted(true);
submission.setAssignment(a);
AssignmentService.commitEdit(submission);
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.toString() + " here userId = " + userId);
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage() + " authGroupId=" + authzGroupId);
}
}
private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) {
String aReference = a.getReference();
String addUpdateRemoveAssignment = "remove";
if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// if integrate with Gradebook
if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups")))
{
// if grouped assignment is not allowed to add into Gradebook
addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB"));
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
else
{
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD;
}
else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
addUpdateRemoveAssignment = "update";
}
if (!addUpdateRemoveAssignment.equals("remove") && gradeType == 3)
{
try
{
integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null);
// add all existing grades, if any, into Gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update");
// if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook
if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment))
{
integrateGradebook(state, aReference, oAssociateGradebookAssignment, null, null, null, -1, null, null, "remove");
// if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, oAssociateGradebookAssignment);
if (isExternalAssignmentDefined)
{
// iterate through all assignments currently in the site, see if any is associated with this GB entry
Iterator i = AssignmentService.getAssignmentsForContext(siteId);
boolean found = false;
while (!found && i.hasNext())
{
Assignment aI = (Assignment) i.next();
String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (gbEntry != null && gbEntry.equals(oAssociateGradebookAssignment))
{
found = true;
}
}
// so if none of the assignment in this site is associated with the entry, remove the entry
if (!found)
{
g.removeExternalAssessment(gradebookUid, oAssociateGradebookAssignment);
}
}
}
}
}
catch (NumberFormatException nE)
{
alertInvalidPoint(state, gradePoints);
}
}
else
{
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
}
}
else
{
// no need to do anything here, if the assignment is chosen to not hook up with GB.
// user can go to GB and delete the entry there manually
}
}
private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime)
{
if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString()))
{
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
String openDateAnnounced = a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
// announcement channel is in place
try
{
AnnouncementMessageEdit message = channel.addAnnouncementMessage();
AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit();
header.setDraft(/* draft */false);
header.replaceAttachments(/* attachment */EntityManager.newReferenceList());
if (openDateAnnounced == null)
{
// making new announcement
header.setSubject(/* subject */rb.getString("assig6") + " " + title);
message.setBody(/* body */rb.getString("opedat") + " "
+ FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " "
+ openTime.toStringLocalFull() + ". ");
}
else
{
// revised announcement
header.setSubject(/* subject */rb.getString("assig5") + " " + title);
message.setBody(/* body */rb.getString("newope") + " "
+ FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " "
+ openTime.toStringLocalFull() + ". ");
}
// group information
if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
try
{
// get the group ids selected
Collection groupRefs = a.getGroups();
// make a collection of Group objects
Collection groups = new Vector();
//make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
groups.add(site.getGroup(groupRef));
}
// set access
header.setGroupAccess(groups);
}
catch (Exception exception)
{
// log
Log.warn("chef", exception.getMessage());
}
}
else
{
// site announcement
header.clearGroupAccess();
}
channel.commitMessage(message, NotificationService.NOTI_NONE);
// commit related properties into Assignment object
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString());
if (message != null)
{
aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId());
}
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotmak"));
}
}
} // if
}
private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit)
{
if (state.getAttribute(CALENDAR) != null)
{
Calendar c = (Calendar) state.getAttribute(CALENDAR);
String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
CalendarEvent e = null;
if (dueDateScheduled != null || oldEventId != null)
{
// find the old event
boolean found = false;
if (oldEventId != null && c != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". ");
}
catch (PermissionException ee)
{
Log.warn("chef", "You do not have the permission to view the schedule event id= "
+ oldEventId + ".");
}
}
else
{
TimeBreakdown b = oldDueTime.breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null)
.iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException ignore)
{
// ignore PermissionException
}
}
if (found)
{
// remove the founded old event
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotrem") + " " + title + ". ");
}
catch (InUseException ee)
{
Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen"));
}
catch (IdUnusedException ee)
{
Log.warn("chef", rb.getString("cannotfin6") + e.getId());
}
}
}
if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString()))
{
if (c != null)
{
// commit related properties into Assignment object
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
try
{
e = null;
CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE;
Collection eGroups = new Vector();
if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
eAccess = CalendarEvent.EventAccess.GROUPED;
Collection groupRefs = aEdit.getGroups();
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
eGroups.add(site.getGroup(groupRef));
}
}
e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000),
/* title */rb.getString("due") + " " + title,
/* description */rb.getString("assig1") + " " + title + " " + "is due on "
+ dueTime.toStringLocalFull() + ". ",
/* type */rb.getString("deadl"),
/* location */"",
/* access */ eAccess,
/* groups */ eGroups,
/* attachments */EntityManager.newReferenceList());
aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString());
if (e != null)
{
aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId());
}
}
catch (IdUnusedException ee)
{
Log.warn("chef", ee.getMessage());
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotfin1"));
}
catch (Exception ee)
{
Log.warn("chef", ee.getMessage());
}
// try-catch
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
} // if
} // if
}
}
private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups)
{
a.setTitle(title);
a.setContent(ac);
a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING));
a.setSection(s);
a.setOpenTime(openTime);
a.setDueTime(dueTime);
// set the drop dead date as the due date
a.setDropDeadTime(dueTime);
if (enableCloseDate)
{
a.setCloseTime(closeTime);
}
else
{
// if editing an old assignment with close date
if (a.getCloseTime() != null)
{
a.setCloseTime(null);
}
}
// post the assignment
a.setDraft(!post);
try
{
if (range.equals("site"))
{
a.setAccess(Assignment.AssignmentAccess.SITE);
a.clearGroupAccess();
}
else if (range.equals("groups"))
{
a.setGroupAccess(groups);
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// commit assignment first
AssignmentService.commitEdit(a);
}
}
private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit)
{
if (aPropertiesEdit.getProperty("newAssignment") != null)
{
if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString()))
{
// not a newly created assignment, been added.
aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString());
}
}
else
{
// for newly created assignment
aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString());
}
if (checkAddDueTime != null)
{
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime);
}
else
{
aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce);
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment);
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
// if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference());
}
// allow resubmit number
if (allowResubmitNumber != null)
{
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
}
private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1)
{
ac.setTitle(title);
ac.setInstructions(description);
ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge));
ac.setTypeOfSubmission(submissionType);
ac.setAllowReviewService(useReviewService);
ac.setAllowStudentViewReport(allowStudentViewReport);
ac.setTypeOfGrade(gradeType);
if (gradeType == 3)
{
try
{
ac.setMaxGradePoint(Integer.parseInt(gradePoints));
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradePoints);
}
}
ac.setGroupProject(true);
ac.setIndividuallyGraded(false);
if (submissionType != 1)
{
ac.setAllowAttachments(true);
}
else
{
ac.setAllowAttachments(false);
}
// clear attachments
ac.clearAttachments();
// add each attachment
Iterator it = EntityManager.newReferenceList(attachments1).iterator();
while (it.hasNext())
{
Reference r = (Reference) it.next();
ac.addAttachment(r);
}
state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false));
// commit the changes
AssignmentService.commitEdit(ac);
}
/**
* reorderAssignments
*/
private void reorderAssignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List assignments = prepPage(state);
Iterator it = assignments.iterator();
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
while (it.hasNext()) // reads and writes the parameter for default ordering
{
Assignment a = (Assignment) it.next();
String assignmentid = a.getId();
String assignmentposition = params.getString("position_" + assignmentid);
AssignmentEdit ae = getAssignmentEdit(state, assignmentid);
ae.setPosition_order(new Long(assignmentposition).intValue());
AssignmentService.commitEdit(ae);
}
// clear the permission
SecurityService.clearAdvisors();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
//resetAssignment(state);
}
} // reorderAssignments
private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId)
{
AssignmentEdit a = null;
if (assignmentId.length() == 0)
{
// create a new assignment
try
{
a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
}
}
else
{
try
{
// edit assignment
a = AssignmentService.editAssignment(assignmentId);
}
catch (InUseException e)
{
addAlert(state, rb.getString("theassicon"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
} // try-catch
} // if-else
return a;
}
private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId)
{
AssignmentContentEdit ac = null;
if (assignmentContentId.length() == 0)
{
// new assignment
try
{
ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot3"));
}
}
else
{
try
{
// edit assignment
ac = AssignmentService.editAssignmentContent(assignmentContentId);
}
catch (InUseException e)
{
addAlert(state, rb.getString("theassicon"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin4"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot15"));
}
}
return ac;
}
private Time getOpenTime(SessionState state)
{
int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue();
int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue();
int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue();
int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue();
int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue();
String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM);
if ((openAMPM.equals("PM")) && (openHour != 12))
{
openHour = openHour + 12;
}
if ((openHour == 12) && (openAMPM.equals("AM")))
{
openHour = 0;
}
Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0);
return openTime;
}
private Time getCloseTime(SessionState state)
{
Time closeTime;
int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
return closeTime;
}
private Time getDueTime(SessionState state)
{
int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue();
int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue();
int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue();
int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue();
int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue();
String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
return dueTime;
}
private Time getAllowSubmitCloseTime(SessionState state)
{
int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
return closeTime;
}
/**
* Action is to post new assignment
*/
public void doSave_assignment(RunData data)
{
postOrSaveAssignment(data, "save");
} // doSave_assignment
/**
* Action is to reorder assignments
*/
public void doReorder_assignment(RunData data)
{
reorderAssignments(data);
} // doReorder_assignments
/**
* Action is to preview the selected assignment
*/
public void doPreview_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
setNewAssignmentParameters(data, false);
String assignmentId = data.getParameters().getString("assignmentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId);
String assignmentContentId = data.getParameters().getString("assignmentContentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId);
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false));
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT);
}
} // doPreview_assignment
/**
* Action is to view the selected assignment
*/
public void doView_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// show the assignment portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false));
// show the student view portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true));
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
EventTrackingService.post(EventTrackingService.newEvent(AssignmentService.SECURE_ACCESS_ASSIGNMENT, a.getReference(), false));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT);
}
} // doView_Assignment
/**
* Action is for student to view one assignment content
*/
public void doView_assignment_as_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT);
}
} // doView_assignment_as_student
/**
* Action is to show the edit assignment screen
*/
public void doEdit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
// whether the user can modify the assignment
state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId);
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
// for the non_electronice assignment, submissions are auto-generated by the time that assignment is created;
// don't need to go through the following checkings.
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
boolean anySubmitted = false;
for (;submissions.hasNext() && !anySubmitted;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted())
{
anySubmitted = true;
}
}
if (anySubmitted)
{
// if there is any submitted submission to this assignment, show alert
addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum"));
}
else
{
// otherwise, show alert about someone has started working on the assignment, not necessarily submitted
addAlert(state, rb.getString("hasDraftSum"));
}
}
}
// SECTION MOD
state.setAttribute(STATE_SECTION_STRING, a.getSection());
// put the names and values into vm file
state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle());
state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order());
TimeBreakdown openTime = a.getOpenTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear()));
int openHour = openTime.getHour();
if (openHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM");
}
if (openHour == 0)
{
// for midnight point, we mark it as 12AM
openHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin()));
TimeBreakdown dueTime = a.getDueTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear()));
int dueHour = dueTime.getHour();
if (dueHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM");
}
if (dueHour == 0)
{
// for midnight point, we mark it as 12AM
dueHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin()));
// generate alert when editing an assignment past due date
if (a.getDueTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot17"));
}
if (a.getCloseTime() != null)
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
TimeBreakdown closeTime = a.getCloseTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear()));
int closeHour = closeTime.getHour();
if (closeHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM");
}
if (closeHour == 0)
{
// for the midnight point, we mark it as 12 AM
closeHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin()));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
}
state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection());
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission()));
int typeOfGrade = a.getContent().getTypeOfGrade();
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade));
if (typeOfGrade == 3)
{
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay());
}
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions());
ResourceProperties properties = a.getProperties();
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge()));
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
state.setAttribute(ATTACHMENTS, a.getContent().getAttachments());
// notification option
if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// group setting
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups");
}
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):"0");
// set whether we use the review service or not
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, new Boolean(a.getContent().getAllowReviewService()).toString());
//set whether students can view the review service results
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, new Boolean(a.getContent().getAllowStudentViewReport()).toString());
state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doEdit_Assignment
/**
* Action is to show the delete assigment confirmation screen
*/
public void doDelete_confirm_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String[] assignmentIds = params.getStrings("selectedAssignments");
if (assignmentIds != null)
{
Vector ids = new Vector();
for (int i = 0; i < assignmentIds.length; i++)
{
String id = (String) assignmentIds[i];
if (!AssignmentService.allowRemoveAssignment(id))
{
addAlert(state, rb.getString("youarenot9") + " " + id + ". ");
}
ids.add(id);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// can remove all the selected assignments
state.setAttribute(DELETE_ASSIGNMENT_IDS, ids);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT);
}
}
else
{
addAlert(state, rb.getString("youmust6"));
}
} // doDelete_confirm_Assignment
/**
* Action is to delete the confirmed assignments
*/
public void doDelete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String assignmentId = (String) ids.get(i);
try
{
AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId);
ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit();
String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String title = aEdit.getTitle();
// remove releted event if there is one
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
removeCalendarEvent(state, aEdit, pEdit, title);
} // if-else
if (!AssignmentService.getSubmissions(aEdit).iterator().hasNext())
{
// there is no submission to this assignment yet, delete the assignment record completely
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(aEdit));
}
}
AssignmentService.removeAssignment(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". ");
}
}
else
{
// remove the assignment by marking the remove status property true
pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString());
AssignmentService.commitEdit(aEdit);
}
// remove from Gradebook
integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot6"));
}
} // for
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDelete_Assignment
private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException
{
// remove the associated calender event
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
// already has calendar object
// get the old event
CalendarEvent e = null;
boolean found = false;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
// no action needed for this condition
}
catch (PermissionException ee)
{
}
}
else
{
TimeBreakdown b = aEdit.getDueTime().breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1)
{
found = true;
}
}
}
// remove the founded old event
if (found)
{
// found the old event delete it
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotrem") + " " + title + ". ");
}
catch (InUseException ee)
{
Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen"));
}
catch (IdUnusedException ee)
{
Log.warn("chef", rb.getString("cannotfin6") + e.getId());
}
}
}
}
/**
* Action is to delete the assignment and also the related AssignmentSubmission
*/
public void doDeep_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String currentId = (String) ids.get(i);
try
{
AssignmentEdit a = AssignmentService.editAssignment(currentId);
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(a));
}
}
AssignmentService.removeAssignment(a);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". ");
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2"));
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDeep_delete_Assignment
/**
* Action is to show the duplicate assignment screen
*/
public void doDuplicate_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the view, so start with first page again.
resetPaging(state);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (assignmentId != null)
{
try
{
AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId);
// clean the duplicate's property
ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit();
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
AssignmentService.commitEdit(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot5"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee"));
}
catch (Exception e)
{
}
}
} // doDuplicate_Assignment
/**
* Action is to show the grade submission screen
*/
public void doGrade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
// reset the grade assignment id
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId"));
state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId"));
// allow resubmit number
String allowResubmitNumber = "0";
Assignment a = null;
try
{
a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
try
{
AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID));
if ((s.getFeedbackText() != null) && (s.getFeedbackText().length() == 0))
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText());
}
else
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment());
List v = EntityManager.newReferenceList();
Iterator attachments = s.getFeedbackAttachments().iterator();
while (attachments.hasNext())
{
v.add(attachments.next());
}
state.setAttribute(ATTACHMENTS, v);
state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade());
ResourceProperties p = s.getProperties();
if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null)
{
// if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property
allowResubmitNumber = "1";
}
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
}
} // doGrade_submission
/**
* Action is to release all the grades of the submission
*/
public void doRelease_grades(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
try
{
// get the assignment
Assignment a = AssignmentService.getAssignment(params.getString("assignmentId"));
String aReference = a.getReference();
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getGraded())
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
String grade = s.getGrade();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES))
.booleanValue() : false;
if (withGrade)
{
// for the assignment tool with grade option, a valide grade is needed
if (grade != null && !grade.equals(""))
{
sEdit.setGradeReleased(true);
}
}
else
{
// for the assignment tool without grade option, no grade is needed
sEdit.setGradeReleased(true);
}
// also set the return status
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
AssignmentService.commitEdit(sEdit);
}
} // while
// add grades into Gradebook
String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// integrate with Gradebook
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update");
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
} // doRelease_grades
/**
* Action is to show the assignment in grading page
*/
public void doExpand_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true));
} // doExpand_grade_assignment
/**
* Action is to hide the assignment in grading page
*/
public void doCollapse_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
} // doCollapse_grade_assignment
/**
* Action is to show the submissions in grading page
*/
public void doExpand_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true));
} // doExpand_grade_submission
/**
* Action is to hide the submissions in grading page
*/
public void doCollapse_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false));
} // doCollapse_grade_submission
/**
* Action is to show the grade assignment
*/
public void doGrade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// clean state attribute
state.removeAttribute(USER_SUBMISSIONS);
state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId"));
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
// we are changing the view, so start with first page again.
resetPaging(state);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
} // doGrade_assignment
/**
* Action is to show the View Students assignment screen
*/
public void doView_students_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT);
} // doView_students_Assignment
/**
* Action is to show the student submissions
*/
public void doShow_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// add the student id into the table
t.add(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doShow_student_submission
/**
* Action is to hide the student submissions
*/
public void doHide_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// remove the student id from the table
t.remove(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doHide_student_submission
/**
* Action is to show the graded assignment submission
*/
public void doView_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE);
} // doView_grade
/**
* Action is to show the student submissions
*/
public void doReport_submissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doReport_submissions
/**
*
*
*/
public void doAssignment_form(RunData data)
{
ParameterParser params = data.getParameters();
String option = (String) params.getString("option");
if (option != null)
{
if (option.equals("post"))
{
// post assignment
doPost_assignment(data);
}
else if (option.equals("save"))
{
// save assignment
doSave_assignment(data);
}
else if (option.equals("reorder"))
{
// reorder assignments
doReorder_assignment(data);
}
else if (option.equals("preview"))
{
// preview assignment
doPreview_assignment(data);
}
else if (option.equals("cancel"))
{
// cancel creating assignment
doCancel_new_assignment(data);
}
else if (option.equals("canceledit"))
{
// cancel editing assignment
doCancel_edit_assignment(data);
}
else if (option.equals("attach"))
{
// attachments
doAttachments(data);
}
else if (option.equals("view"))
{
// view
doView(data);
}
else if (option.equals("permissions"))
{
// permissions
doPermissions(data);
}
else if (option.equals("returngrade"))
{
// return grading
doReturn_grade_submission(data);
}
else if (option.equals("savegrade"))
{
// save grading
doSave_grade_submission(data);
}
else if (option.equals("previewgrade"))
{
// preview grading
doPreview_grade_submission(data);
}
else if (option.equals("cancelgrade"))
{
// cancel grading
doCancel_grade_submission(data);
}
else if (option.equals("cancelreorder"))
{
// cancel reordering
doCancel_reorder(data);
}
else if (option.equals("sortbygrouptitle"))
{
// read input data
setNewAssignmentParameters(data, true);
// sort by group title
doSortbygrouptitle(data);
}
else if (option.equals("sortbygroupdescription"))
{
// read input data
setNewAssignmentParameters(data, true);
// sort group by description
doSortbygroupdescription(data);
}
else if (option.equals("hide_instruction"))
{
// hide the assignment instruction
doHide_submission_assignment_instruction(data);
}
else if (option.equals("show_instruction"))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if (option.equals("sortbygroupdescription"))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
}
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String mode = (String) state.getAttribute(STATE_MODE);
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
setNewAssignmentParameters(data, false);
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
readGradeForm(data, state, "read");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.filepicker");
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig"));
state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr"));
// use the real attachment list
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
}
}
/**
* readGradeForm
*/
public void readGradeForm(RunData data, SessionState state, String gradeOption)
{
ParameterParser params = data.getParameters();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()
: false;
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT),
checkForFormattingErrors);
if (feedbackComment != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment);
}
String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT));
if (feedbackText != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText);
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS));
String g = params.getCleanString(GRADE_SUBMISSION_GRADE);
if (g != null)
{
state.setAttribute(GRADE_SUBMISSION_GRADE, g);
}
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
try
{
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
Assignment a = AssignmentService.getSubmission(sId).getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (withGrade)
{
// do grade validation only for Assignment with Grade tool
if (typeOfGrade == 3)
{
if ((grade.length() == 0))
{
if (gradeOption.equals("release") || gradeOption.equals("return"))
{
// in case of releasing grade, user must specify a grade
addAlert(state, rb.getString("plespethe2"));
}
}
else
{
// the preview grade process might already scaled up the grade by 10
if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getString("grad2"));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
}
// if ungraded and grade type is not "ungraded" type
if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != 1) && gradeOption.equals("release"))
{
addAlert(state, rb.getString("plespethe2"));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
// allow resubmit number and due time
if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (Integer.parseInt(allowResubmitNumberString) != 0)
{
int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth));
int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay));
int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear));
int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour));
int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin));
String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM);
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
// validate date
if (closeTime.before(TimeService.newTime()))
{
addAlert(state, rb.getString("assig4"));
}
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + ".");
}
}
else
{
// reset the state attributes
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
}
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
String siteId = ToolManager.getCurrentPlacement().getContext();
// show the list of assignment view first
if (state.getAttribute(STATE_SELECTED_VIEW) == null)
{
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_USER) == null)
{
state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser());
}
/** The content type image lookup service in the State. */
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
if (iService == null)
{
iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance();
state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService);
} // if
/** The calendar service in the State. */
CalendarService cService = (CalendarService) state.getAttribute(STATE_CALENDAR_SERVICE);
if (cService == null)
{
cService = org.sakaiproject.calendar.cover.CalendarService.getInstance();
state.setAttribute(STATE_CALENDAR_SERVICE, cService);
String calendarId = ServerConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(CALENDAR, cService.getCalendar(calendarId));
}
catch (IdUnusedException e)
{
Log.info("chef", "No calendar found for site " + siteId);
state.removeAttribute(CALENDAR);
}
catch (PermissionException e)
{
Log.info("chef", "No permission to get the calender. ");
state.removeAttribute(CALENDAR);
}
catch (Exception ex)
{
Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex);
state.removeAttribute(CALENDAR);
}
}
} // if
/** The announcement service in the State. */
AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE);
if (aService == null)
{
aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService);
String channelId = ServerConfigurationService.getString("channel", null);
if (channelId == null)
{
channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId));
}
catch (IdUnusedException e)
{
Log.warn("chef", "No announcement channel found. ");
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
catch (PermissionException e)
{
Log.warn("chef", "No permission to annoucement channel. ");
}
catch (Exception ex)
{
Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex);
}
}
} // if
if (state.getAttribute(STATE_CONTEXT_STRING) == null)
{
state.setAttribute(STATE_CONTEXT_STRING, siteId);
} // if context string is null
if (state.getAttribute(SORTED_BY) == null)
{
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
}
if (state.getAttribute(SORTED_ASC) == null)
{
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(SORTED_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null)
{
resetAssignment(state);
}
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null)
{
state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet());
}
if (state.getAttribute(ATTACHMENTS_MODIFIED) == null)
{
state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false));
}
// SECTION MOD
if (state.getAttribute(STATE_SECTION_STRING) == null)
{
state.setAttribute(STATE_SECTION_STRING, "001");
}
// // setup the observer to notify the Main panel
// if (state.getAttribute(STATE_OBSERVER) == null)
// {
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, portlet.getID());
//
// // the html element to update on delivery
// String elementId = mainPanelUpdateId(portlet.getID());
//
// // the event resource reference pattern to watch for
// String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), "");
//
// state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern));
// }
if (state.getAttribute(STATE_MODE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
if (state.getAttribute(WITH_GRADES) == null)
{
PortletConfig config = portlet.getPortletConfig();
String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades"));
if (withGrades == null)
{
withGrades = Boolean.FALSE.toString();
}
state.setAttribute(WITH_GRADES, new Boolean(withGrades));
}
// whether the choice of emails instructor submission notification is available in the installation
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null)
{
state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true)));
}
// whether or how the instructor receive submission notification emails, none(default)|each|digest
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null)
{
state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, new Integer(2002));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, new Integer(2012));
}
} // initState
/**
* reset the attributes for view submission
*/
private void resetViewSubmission(SessionState state)
{
state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.removeAttribute(VIEW_SUBMISSION_TEXT);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
} // resetViewSubmission
/**
* reset the attributes for view submission
*/
private void resetAssignment(SessionState state)
{
// put the input value into the state attributes
state.setAttribute(NEW_ASSIGNMENT_TITLE, "");
// get current time
Time t = TimeService.newTime();
TimeBreakdown tB = t.breakdownLocal();
int month = tB.getMonth();
int day = tB.getDay();
int year = tB.getYear();
// set the open time to be 12:00 PM
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
// due date is shifted forward by 7 days
t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000);
tB = t.breakdownLocal();
month = tB.getMonth();
day = tB.getDay();
year = tB.getYear();
// set the due time to be 5:00pm
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
// enable the close date by default
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
// set the close time to be 5:00 pm, same as the due time by default
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
state.setAttribute(NEW_ASSIGNMENT_SECTION, "001");
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, "");
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, "");
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
// make the honor pledge not include as the default
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString());
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
} // resetNewAssignment
/**
* construct a Hashtable using integer as the key and three character string of the month as the value
*/
private Hashtable monthTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(1), rb.getString("jan"));
n.put(new Integer(2), rb.getString("feb"));
n.put(new Integer(3), rb.getString("mar"));
n.put(new Integer(4), rb.getString("apr"));
n.put(new Integer(5), rb.getString("may"));
n.put(new Integer(6), rb.getString("jun"));
n.put(new Integer(7), rb.getString("jul"));
n.put(new Integer(8), rb.getString("aug"));
n.put(new Integer(9), rb.getString("sep"));
n.put(new Integer(10), rb.getString("oct"));
n.put(new Integer(11), rb.getString("nov"));
n.put(new Integer(12), rb.getString("dec"));
return n;
} // monthTable
/**
* construct a Hashtable using the integer as the key and grade type String as the value
*/
private Hashtable gradeTypeTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(2), rb.getString("letter"));
n.put(new Integer(3), rb.getString("points"));
n.put(new Integer(4), rb.getString("pass"));
n.put(new Integer(5), rb.getString("check"));
n.put(new Integer(1), rb.getString("ungra"));
return n;
} // gradeTypeTable
/**
* construct a Hashtable using the integer as the key and submission type String as the value
*/
private Hashtable submissionTypeTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(1), rb.getString("inlin"));
n.put(new Integer(2), rb.getString("attaonly"));
n.put(new Integer(3), rb.getString("inlinatt"));
n.put(new Integer(4), rb.getString("nonelec"));
return n;
} // submissionTypeTable
/**
* Sort based on the given property
*/
public void doSort(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
setupSort(data, data.getParameters().getString("criteria"));
}
/**
* setup sorting parameters
*
* @param criteria
* String for sortedBy
*/
private void setupSort(RunData data, String criteria)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_BY)))
{
state.setAttribute(SORTED_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort
/**
* Do sort by group title
*/
public void doSortbygrouptitle(RunData data)
{
setupSort(data, SORTED_BY_GROUP_TITLE);
} // doSortbygrouptitle
/**
* Do sort by group description
*/
public void doSortbygroupdescription(RunData data)
{
setupSort(data, SORTED_BY_GROUP_DESCRIPTION);
} // doSortbygroupdescription
/**
* Sort submission based on the given property
*/
public void doSort_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY)))
{
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
} // doSort_submission
/**
* Sort submission based on the given property in instructor grade view
*/
public void doSort_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY)))
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
} // doSort_grade_submission
public void doSort_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Sort sort = dtp.getSort();
if (sort.getSort().equals(criteria)) {
sort.setAscending(sort.isAscending() ? false : true);
} else {
sort.setSort(criteria);
sort.setAscending(true);
}
break;
}
}
}
public void doPage_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String page = params.getString("page");
String pageSize = params.getString("pageSize");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Pager pager = dtp.getPager();
pager.setPageSize(Integer.valueOf(pageSize));
if (Pager.FIRST.equals(page)) {
pager.setFirstItem(0);
} else if (Pager.PREVIOUS.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
- pager.getPageSize());
} else if (Pager.NEXT.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
+ pager.getPageSize());
} else if (Pager.LAST.equals(page)) {
pager.setFirstItem((pager.getTotalItems() / pager
.getPageSize())
* pager.getPageSize());
}
break;
}
}
}
/**
* the UserSubmission clas
*/
public class UserSubmission
{
/**
* the User object
*/
User m_user = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public UserSubmission(User u, AssignmentSubmission s)
{
m_user = u;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
/**
* Returns the User object
*/
public User getUser()
{
return m_user;
}
}
/**
* the AssignmentComparator clas
*/
private class AssignmentComparator implements Comparator
{
/**
* the SessionState object
*/
SessionState m_state = null;
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* the user
*/
User m_user = null;
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(SessionState state, String criteria, String asc)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
} // constructor
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
* @param user
* The user object
*/
public AssignmentComparator(SessionState state, String criteria, String asc, User user)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
m_user = user;
} // constructor
/**
* caculate the range string for an assignment
*/
private String getAssignmentRange(Assignment a)
{
String rv = "";
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
// site assignment
rv = rb.getString("range.allgroups");
}
else
{
try
{
// get current site
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for (Iterator k = a.getGroups().iterator(); k.hasNext();)
{
// announcement by group
rv = rv.concat(site.getGroup((String) k.next()).getTitle());
}
}
catch (Exception ignore)
{
}
}
return rv;
} // getAssignmentRange
/**
* implementing the compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2)
{
int result = -1;
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = status1.compareTo(status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = grade1.compareTo(grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = factor1.compareToIgnoreCase(factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = lName1.toLowerCase().compareTo(lName2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = status1.toLowerCase().compareTo(status2.toLowerCase());
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
- result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
+ result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = released1.compareTo(released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = status1.compareTo(status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = released1.compareTo(released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = title1.toLowerCase().compareTo(title2.toLowerCase());
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
} // compare
/**
* get the submissin status
*/
private String getSubmissionStatus(SessionState state, AssignmentSubmission s)
{
String status = "";
if (s.getReturned())
{
if (s.getTimeReturned() != null && s.getTimeSubmitted() != null && s.getTimeReturned().before(s.getTimeSubmitted()))
{
status = rb.getString("listsub.resubmi");
}
else
{
status = rb.getString("gen.returned");
}
}
else if (s.getGraded())
{
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
status = rb.getString("grad3");
}
else
{
status = rb.getString("gen.commented");
}
}
else
{
status = rb.getString("gen.ung1");
}
return status;
} // getSubmissionStatus
/**
* get the status string of assignment
*/
private String getAssignmentStatus(Assignment a)
{
String status = "";
Time currentTime = TimeService.newTime();
if (a.getDraft())
status = rb.getString("draft2");
else if (a.getOpenTime().after(currentTime))
status = rb.getString("notope");
else if (a.getDueTime().after(currentTime))
status = rb.getString("ope");
else if ((a.getCloseTime() != null) && (a.getCloseTime().before(currentTime)))
status = rb.getString("clos");
else
status = rb.getString("due2");
return status;
} // getAssignmentStatus
/**
* get submission status
*/
private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment)
{
String status = "";
if (submission != null)
if (submission.getSubmitted())
if (submission.getGraded() && submission.getGradeReleased())
status = rb.getString("grad3");
else if (submission.getReturned())
status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull();
else
{
status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull();
if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late");
}
else
status = rb.getString("inpro");
else
status = rb.getString("notsta");
return status;
} // getSubmissionStatus
/**
* get assignment maximun grade available based on the assignment grade type
*
* @param gradeType
* The int value of grade type
* @param a
* The assignment object
* @return The max grade String
*/
private String maxGrade(int gradeType, Assignment a)
{
String maxGrade = "";
if (gradeType == -1)
{
// Grade type not set
maxGrade = rb.getString("granotset");
}
else if (gradeType == 1)
{
// Ungraded grade type
maxGrade = rb.getString("nogra");
}
else if (gradeType == 2)
{
// Letter grade type
maxGrade = "A";
}
else if (gradeType == 3)
{
// Score based grade type
maxGrade = Integer.toString(a.getContent().getMaxGradePoint());
}
else if (gradeType == 4)
{
// Pass/fail grade type
maxGrade = rb.getString("pass2");
}
else if (gradeType == 5)
{
// Grade type that only requires a check
maxGrade = rb.getString("check2");
}
return maxGrade;
} // maxGrade
} // DiscussionComparator
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String siteRef = SiteService.siteReference(contextString);
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "asn.");
// disable auto-updates while leaving the list view
justDelivered(state);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
// switching back to assignment list view
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
doList_assignments(data);
}
} // doPermissions
/**
* transforms the Iterator to Vector
*/
private Vector iterator_to_vector(Iterator l)
{
Vector v = new Vector();
while (l.hasNext())
{
v.add(l.next());
}
return v;
} // iterator_to_vector
/**
* Implement this to return alist of all the resources that there are to page. Sort them as appropriate.
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS);
PagingPosition page = new PagingPosition(first, last);
page.validate(returnResources.size());
returnResources = returnResources.subList(page.getFirst() - 1, page.getLast());
return returnResources;
} // readAllResources
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState)
*/
protected int sizeResources(SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// all the resources for paging
List returnResources = new Vector();
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS))
{
String view = "";
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
view = (String) state.getAttribute(STATE_SELECTED_VIEW);
}
if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS))
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW)
|| !allowAddAssignment)
{
// in the student list view of assignments
Iterator assignments = AssignmentService
.getAssignmentsForContext(contextString);
Time currentTime = TimeService.newTime();
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
try
{
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || deleted.equals(""))
{
// show not deleted assignments
Time openTime = a.getOpenTime();
if (openTime != null && currentTime.after(openTime) && !a.getDraft())
{
returnResources.add(a);
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && AssignmentService.getSubmission(a.getReference(), (User) state
.getAttribute(STATE_USER)) != null)
{
// and those deleted assignments but the user has made submissions to them
returnResources.add(a);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
}
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
Vector submissions = new Vector();
Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING)));
if (assignments.size() > 0)
{
// users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ());
}
for (int j = 0; j < assignments.size(); j++)
{
Assignment a = (Assignment) assignments.get(j);
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if ((deleted == null || deleted.equals("")) && (!a.getDraft()))
{
try
{
List assignmentSubmissions = AssignmentService.getSubmissions(a);
for (int k = 0; k < assignmentSubmissions.size(); k++)
{
AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k);
if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s
.getTimeReturned())))))
{
// has been subitted or has been returned and not work on it yet
submissions.add(s);
} // if-else
}
}
catch (Exception e)
{
}
}
}
returnResources = submissions;
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT))
{
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
Iterator submissionsIterator = AssignmentService.getSubmissions(a).iterator();
List submissions = new Vector();
while (submissionsIterator.hasNext())
{
submissions.add(submissionsIterator.next());
}
// get all active site users
String authzGroupId = SiteService.siteReference(contextString);
// all users that can submit
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId);
Set grants = group.getUsers();
for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null && allowAddSubmissionUsers.contains(u))
{
boolean found = false;
for (int i = 0; !found && i<submissions.size();i++)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.get(i);
if (s.getSubmitterIds().contains(userId))
{
returnResources.add(new UserSubmission(u, s));
found = true;
}
}
// add those users who haven't made any submissions
if (!found)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId());
s.removeSubmitter(UserDirectoryService.getCurrentUser());
s.addSubmitter(u);
s.setSubmitted(true);
s.setAssignment(a);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference());
returnResources.add(new UserSubmission(u, sub));
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.toString() + " here userId = " + userId);
}
}
}
catch (Exception e)
{
Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
// sort them all
String ascending = "true";
String sort = "";
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && !sort.startsWith("sorted_grade_submission_by"))
{
ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY);
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && sort.startsWith("sorted_submission_by"))
{
ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_SUBMISSION_BY);
}
else
{
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
}
if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending));
}
// record the total item number
state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources);
return returnResources.size();
}
public void doView(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
String viewMode = data.getParameters().getString("view");
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
if (viewMode.equals(MODE_LIST_ASSIGNMENTS))
{
doList_assignments(data);
}
else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
doView_students_assignment(data);
}
else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
doReport_submissions(data);
}
else if (viewMode.equals(MODE_STUDENT_VIEW))
{
doView_student(data);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doView
/**
* put those variables related to 2ndToolbar into context
*/
private void add2ndToolbarFields(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("selectedView", state.getAttribute(STATE_MODE));
} // add2ndToolbarFields
/**
* valid grade?
*/
private void validPointGrade(SessionState state, String grade)
{
if (grade != null && !grade.equals(""))
{
if (grade.startsWith("-"))
{
// check for negative sign
addAlert(state, rb.getString("plesuse3"));
}
else
{
int index = grade.indexOf(".");
if (index != -1)
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
if (!grade.equals("."))
{
if (grade.length() > index + 2)
{
// if there are more than one decimal point
addAlert(state, rb.getString("plesuse2"));
}
else
{
// decimal points is the only allowed character inside grade
// replace it with '1', and try to parse the new String into int
String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0,
index).concat(grade.substring(index + 1));
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradeString);
}
}
}
else
{
// grade is "."
addAlert(state, rb.getString("plesuse1"));
}
}
else
{
// There is no decimal point; should be int number
String gradeString = grade + "0";
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradeString);
}
}
}
}
} // validPointGrade
private void alertInvalidPoint(SessionState state, String grade)
{
String VALID_CHARS_FOR_INT = "-01234567890";
boolean invalid = false;
// case 1: contains invalid char for int
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_INT.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse1"));
}
else
{
int maxInt = Integer.MAX_VALUE / 10;
int maxDec = Integer.MAX_VALUE - maxInt * 10;
// case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10
addAlert(state, rb.getString("plesuse4") + maxInt + "." + maxDec + ".");
}
}
/**
* display grade properly
*/
private String displayGrade(SessionState state, String grade)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (grade != null && (grade.length() >= 1))
{
if (grade.indexOf(".") != -1)
{
if (grade.startsWith("."))
{
grade = "0".concat(grade);
}
else if (grade.endsWith("."))
{
grade = grade.concat("0");
}
}
else
{
try
{
Integer.parseInt(grade);
grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
}
else
{
grade = "";
}
}
return grade;
} // displayGrade
/**
* scale the point value by 10 if there is a valid point grade
*/
private String scalePointGrade(SessionState state, String point)
{
validPointGrade(state, point);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (point != null && (point.length() >= 1))
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
int index = point.indexOf(".");
if (index != -1)
{
if (index == 0)
{
// if the point is the first char, add a 0 for the integer part
point = "0".concat(point.substring(1));
}
else if (index < point.length() - 1)
{
// use scale integer for gradePoint
point = point.substring(0, index) + point.substring(index + 1);
}
else
{
// decimal point is the last char
point = point.substring(0, index) + "0";
}
}
else
{
// if there is no decimal place, scale up the integer by 10
point = point + "0";
}
// filter out the "zero grade"
if (point.equals("00"))
{
point = "0";
}
}
}
return point;
} // scalePointGrade
/**
* Processes formatted text that is coming back from the browser (from the formatted text editing widget).
*
* @param state
* Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser
* The string from the browser
* @param checkForFormattingErrors
* Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors.
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors)
{
StringBuffer alertMsg = new StringBuffer();
try
{
boolean replaceWhitespaceTags = true;
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors,
replaceWhitespaceTags);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
Log.warn("chef", this + ": ", e);
return strFromBrowser;
}
}
/**
* Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced.
*/
private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser)
{
if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser;
StringBuffer buf = new StringBuffer(strFromBrowser);
int pos = -1;
int numopentags = 0;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<ins>");
numopentags++;
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</ins>");
numopentags--;
}
while (numopentags > 0)
{
buf.append("</ins>");
numopentags--;
}
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
buf = new StringBuffer(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors));
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
}
/**
* Called to deal with old Chef-style assignment feedback annotation, {{like this}}.
*
* @param value
* A formatted text string that may contain {{}} style markup
* @return HTML ready to for display on a browser
*/
public static String escapeAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
StringBuffer buf = new StringBuffer(value);
int pos = -1;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<span class='highlight'>");
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</span>");
}
return FormattedText.escapeHtmlFormattedText(buf.toString());
}
/**
* Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget)
*/
public static String escapeAssignmentFeedbackTextarea(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
return FormattedText.escapeHtmlFormattedTextarea(value);
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private static String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuffer buf = new StringBuffer(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("<br/>")) != -1)
{
buf.replace(pos, pos + "<br/>".length(), "\n");
}
// <span class='chefAlert'>( -> {{
while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1)
{
buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{");
}
// )</span> -> }}
while ((pos = buf.indexOf(")</span>")) != -1)
{
buf.replace(pos, pos + ")</span>".length(), "}}");
}
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
} // fixAssignmentFeedback
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
public static String showPrevFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuffer buf = new StringBuffer(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("\n")) != -1)
{
buf.replace(pos, pos + "\n".length(), "<br />");
}
return buf.toString();
} // showPrevFeedback
private boolean alertGlobalNavigation(SessionState state, RunData data)
{
String mode = (String) state.getAttribute(STATE_MODE);
ParameterParser params = data.getParameters();
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)
|| mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)
|| mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)
|| mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)
|| mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null)
{
addAlert(state, rb.getString("alert.globalNavi"));
state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE);
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt"));
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
setNewAssignmentParameters(data, false);
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
readGradeForm(data, state, "read");
}
return true;
}
}
return false;
} // alertGlobalNavigation
/**
* Dispatch function inside add submission page
*/
public void doRead_add_submission_form(RunData data)
{
String option = data.getParameters().getString("option");
if (option.equals("cancel"))
{
// cancel
doCancel_show_submission(data);
}
else if (option.equals("preview"))
{
// preview
doPreview_submission(data);
}
else if (option.equals("save"))
{
// save draft
doSave_submission(data);
}
else if (option.equals("post"))
{
// post
doPost_submission(data);
}
else if (option.equals("revise"))
{
// done preview
doDone_preview_submission(data);
}
else if (option.equals("attach"))
{
// attach
doAttachments(data);
}
}
/**
*
*/
public void doSet_defaultNoSubmissionScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
try
{
// record the default grade setting for no-submission
AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId);
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
Assignment a = AssignmentService.getAssignment(assignmentId);
if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getString("grad2"));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the user list
List userSubmissions = new Vector();
if (state.getAttribute(USER_SUBMISSIONS) != null)
{
userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS);
}
// constructor a new UserSubmissions list
List userSubmissionsNew = new Vector();
for (int i = 0; i<userSubmissions.size(); i++)
{
// get the UserSubmission object
UserSubmission us = (UserSubmission) userSubmissions.get(i);
User u = us.getUser();
AssignmentSubmission submission = us.getSubmission();
// check whether there is a submission associated
if (submission == null)
{
AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId);
s.removeSubmitter(UserDirectoryService.getCurrentUser());
s.addSubmitter(u);
// submitted by without submit time
s.setSubmitted(true);
s.setGrade(grade);
s.setGraded(true);
s.setAssignment(a);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference());
userSubmissionsNew.add(new UserSubmission(u, sub));
}
else if (submission.getTimeSubmitted() == null)
{
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference());
sEdit.setGrade(grade);
sEdit.setSubmitted(true);
sEdit.setGraded(true);
sEdit.setAssignment(a);
AssignmentService.commitEdit(sEdit);
userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference())));
}
else
{
// no change for this user
userSubmissionsNew.add(us);
}
}
state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew);
}
}
catch (Exception e)
{
Log.warn("chef", e.toString());
}
}
/**
*
* @return
*/
public void doUpload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String flow = params.getString("flow");
if (flow.equals("upload"))
{
// upload
doUpload_all_upload(data);
}
else if (flow.equals("cancel"))
{
// cancel
doCancel_upload_all(data);
}
}
public void doUpload_all_upload(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String contextString = ToolManager.getCurrentPlacement().getContext();
String toolTitle = ToolManager.getTool("sakai.assignment").getTitle();
boolean hasSubmissions = false;
boolean hasGradeFile = false;
boolean hasComments = false;
boolean releaseGrades = false;
// check against the content elements selection
if (params.getString("studentSubmission") != null)
{
// should contain student submission information
hasSubmissions = true;
}
if (params.getString("gradeFile") != null)
{
// should contain grade file
hasGradeFile = true;
}
if (params.getString("instructorComments") != null)
{
// comments.xml should be available
hasComments = true;
}
if (params.getString("release") != null)
{
// comments.xml should be available
releaseGrades = params.getBoolean("release");
}
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSIONS, Boolean.valueOf(hasSubmissions));
state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile));
state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComments));
state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades));
if (!hasSubmissions && !hasGradeFile && !hasComments)
{
// has to choose one upload feature
addAlert(state, rb.getString("uploadall.alert.choose.element"));
}
else
{
// constructor the hashtable for all submission objects
Hashtable submissionTable = new Hashtable();
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
String uName = users[0].getSortName();
submissionTable.put(uName, new UploadGradeWrapper("", "", "", new Vector()));
}
}
catch (Exception e)
{
Log.warn("chef", e.toString());
}
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = params.getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0)
{
// no file
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
else
{
byte[] fileData = fileFromUpload.get();
if(fileData.length >= max_bytes)
{
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if(fileData.length > 0)
{
ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData));
ZipEntry entry;
try
{
while ((entry=zin.getNextEntry()) != null)
{
if (!entry.isDirectory())
{
String entryName = entry.getName();
if (entryName.endsWith("grades.csv"))
{
if (hasGradeFile)
{
// read grades.cvs from zip
String result = StringUtil.trimToZero(readIntoString(zin));
String[] lines=null;
if (result.indexOf("\r") != -1)
lines = result.split("\r");
else if (result.indexOf("\n") != -1)
lines = result.split("\n");
for (int i = 3; i<lines.length; i++)
{
// escape the first three header lines
String[] items = lines[i].split(",");
if (items.length > 3)
{
// has grade information
try
{
User u = UserDirectoryService.getUserByEid(items[0]/*user id*/);
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getSortName());
if (w != null)
{
w.setGrade(assignment.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, items[3]):items[3]);
submissionTable.put(u.getSortName(), w);
}
}
catch (Exception e )
{
Log.warn("chef", e.toString());
}
}
}
}
}
else
{
// get user sort name
String userName = "";
if (entryName.indexOf("/") != -1)
{
userName = entryName.substring(0, entryName.lastIndexOf("/"));
if (userName.indexOf("/") != -1)
{
userName = userName.substring(userName.lastIndexOf("/")+1, userName.length());
}
}
if (hasComments && entryName.endsWith("comments.txt"))
{
// read the comments file
String comment = StringUtil.trimToNull(readIntoString(zin));
if (submissionTable.containsKey(userName) && comment != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setComment(comment);
submissionTable.put(userName, r);
}
}
else if (hasSubmissions)
{
if (entryName.endsWith("_submissionText.html"))
{
// upload the student submission text along with the feedback text
String text = StringUtil.trimToNull(readIntoString(zin));
if (submissionTable.containsKey(userName) && text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setText(text);
submissionTable.put(userName, r);
}
}
else
{
// upload all the files as instuctor attachments to the submission for grading purpose
String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length());
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
try
{
if (submissionTable.containsKey(userName))
{
// add the file as attachment
ResourceProperties properties = ContentHostingService.newResourceProperties();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName);
ContentResource attachment = ContentHostingService.addAttachmentResource(
fName,
contextString,
toolTitle,
iService.getContentType(fName.substring(fName.lastIndexOf(".") + 1)),
readIntoString(zin).getBytes(),
properties);
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
List attachments = r.getAttachments();
attachments.add(EntityManager.newReference(attachment.getReference()));
r.setAttachments(attachments);
}
}
catch (Exception ee)
{
Log.warn("chef", ee.toString());
}
}
}
}
}
}
}
catch (IOException e)
{
// uploaded file is not a valid archive
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// update related submissions
if (assignment != null)
{
Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
String uName = users[0].getSortName();
if (submissionTable.containsKey(uName))
{
// update the AssignmetnSubmission record
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName);
// add all attachment
if (hasSubmissions)
{
sEdit.clearFeedbackAttachments();
for (Iterator attachments = w.getAttachments().iterator(); attachments.hasNext();)
{
sEdit.addFeedbackAttachment((Reference) attachments.next());
}
sEdit.setFeedbackText(w.getText());
}
if (hasComments)
{
// add comment
sEdit.setFeedbackComment(w.getComment());
}
if (hasGradeFile)
{
// set grade
sEdit.setGrade(w.getGrade());
sEdit.setGraded(true);
}
// release or not
sEdit.setGradeReleased(releaseGrades);
sEdit.setReturned(releaseGrades);
// commit
AssignmentService.commitEdit(sEdit);
}
catch (Exception ee)
{
Log.debug("chef", ee.toString());
}
}
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// go back to the list of submissions view
cleanUploadAllContext(state);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
private String readIntoString(ZipInputStream zin) throws IOException {
byte[] buf = new byte[1024];
int len;
StringBuffer b = new StringBuffer();
while ((len = zin.read(buf)) > 0) {
b.append(new String(buf));
}
return b.toString();
}
/**
*
* @return
*/
public void doCancel_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
cleanUploadAllContext(state);
}
/**
* clean the state variabled used by upload all process
*/
private void cleanUploadAllContext(SessionState state)
{
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSIONS);
state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE);
state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS);
state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES);
}
/**
* Action is to preparing to go to the upload files
*/
public void doPrep_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL);
} // doPrep_upload_all
/**
* the UploadGradeWrapper class to be used for the "upload all" feature
*/
public class UploadGradeWrapper
{
/**
* the grade
*/
String m_grade = null;
/**
* the text
*/
String m_text = null;
/**
* the comment
*/
String m_comment = "";
/**
* the attachment list
*/
List m_attachments = EntityManager.newReferenceList();
public UploadGradeWrapper(String grade, String text, String comment, List attachments)
{
m_grade = grade;
m_text = text;
m_comment = comment;
m_attachments = attachments;
}
/**
* Returns grade string
*/
public String getGrade()
{
return m_grade;
}
/**
* Returns the text
*/
public String getText()
{
return m_text;
}
/**
* Returns the comment string
*/
public String getComment()
{
return m_comment;
}
/**
* Returns the attachment list
*/
public List getAttachments()
{
return m_attachments;
}
/**
* set the grade string
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* set the text
*/
public void setText(String text)
{
m_text = text;
}
/**
* set the comment string
*/
public void setComment(String comment)
{
m_comment = comment;
}
/**
* set the attachment list
*/
public void setAttachments(List attachments)
{
m_attachments = attachments;
}
}
private List<DecoratedTaggingProvider> initDecoratedProviders() {
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>();
for (TaggingProvider provider : taggingManager.getProviders())
{
providers.add(new DecoratedTaggingProvider(provider));
}
return providers;
}
private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
if (providers == null)
{
providers = initDecoratedProviders();
state.setAttribute(mode + PROVIDER_LIST, providers);
}
context.put("providers", providers);
return providers;
}
private void addActivity(Context context, Assignment assignment)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("activity", assignmentActivityProducer
.getActivity(assignment));
}
private void addItem(Context context, AssignmentSubmission submission, String userId)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("item", assignmentActivityProducer
.getItem(submission, userId));
}
private ContentReviewService contentReviewService;
public String getReportURL(Long score) {
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
return contentReviewService.getIconUrlforScore(score);
}
}
| true | true | public int compare(Object o1, Object o2)
{
int result = -1;
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = status1.compareTo(status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = grade1.compareTo(grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = factor1.compareToIgnoreCase(factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = lName1.toLowerCase().compareTo(lName2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = status1.toLowerCase().compareTo(status2.toLowerCase());
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = released1.compareTo(released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = status1.compareTo(status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = released1.compareTo(released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = title1.toLowerCase().compareTo(title2.toLowerCase());
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
} // compare
| public int compare(Object o1, Object o2)
{
int result = -1;
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = s1.compareToIgnoreCase(s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = status1.compareTo(status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = grade1.compareTo(grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = factor1.compareToIgnoreCase(factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = factor1.compareToIgnoreCase(factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = lName1.toLowerCase().compareTo(lName2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = status1.toLowerCase().compareTo(status2.toLowerCase());
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = released1.compareTo(released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase());
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = status1.compareTo(status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1;
}
}
else
{
result = grade1.compareTo(grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = released1.compareTo(released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = title1.toLowerCase().compareTo(title2.toLowerCase());
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
} // compare
|
diff --git a/open-tracking-tools-otp/src/test/java/org/opentrackingtools/VehicleStatePLFilterSimulationTest.java b/open-tracking-tools-otp/src/test/java/org/opentrackingtools/VehicleStatePLFilterSimulationTest.java
index 710f1cd..d144579 100644
--- a/open-tracking-tools-otp/src/test/java/org/opentrackingtools/VehicleStatePLFilterSimulationTest.java
+++ b/open-tracking-tools-otp/src/test/java/org/opentrackingtools/VehicleStatePLFilterSimulationTest.java
@@ -1,532 +1,532 @@
package org.opentrackingtools;
import gov.sandia.cognition.math.MutableDouble;
import gov.sandia.cognition.math.RingAccumulator;
import gov.sandia.cognition.math.matrix.Matrix;
import gov.sandia.cognition.math.matrix.MatrixFactory;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.VectorEntry;
import gov.sandia.cognition.math.matrix.VectorFactory;
import gov.sandia.cognition.statistics.DataDistribution;
import gov.sandia.cognition.statistics.bayesian.ParticleFilter;
import gov.sandia.cognition.statistics.distribution.MultivariateGaussian;
import gov.sandia.cognition.statistics.distribution.MultivariateGaussian.SufficientStatistic;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.geotools.factory.FactoryRegistryException;
import org.geotools.referencing.operation.projection.ProjectionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.operation.NoninvertibleTransformException;
import org.opengis.referencing.operation.TransformException;
import org.opentrackingtools.distributions.CountedDataDistribution;
import org.opentrackingtools.distributions.OnOffEdgeTransDistribution;
import org.opentrackingtools.distributions.TruncatedRoadGaussian;
import org.opentrackingtools.estimators.MotionStateEstimatorPredictor;
import org.opentrackingtools.graph.otp.OtpGraph;
import org.opentrackingtools.model.GpsObservation;
import org.opentrackingtools.model.VehicleStateDistribution;
import org.opentrackingtools.paths.PathState;
import org.opentrackingtools.util.Simulation;
import org.opentrackingtools.util.Simulation.SimulationParameters;
import org.opentrackingtools.util.TrueObservation;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.internal.junit.ArrayAsserts;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Ranges;
import com.vividsolutions.jts.geom.Coordinate;
public class VehicleStatePLFilterSimulationTest {
private static final double[] fourZeros =
new double[] { 0, 0, 0, 0 };
private static final double[] oneZero = new double[] { 0 };
private static final double[] sixteenZeros = VectorFactory
.getDefault().createVector(16).toArray();
private static final double[] twoZeros = new double[] { 0, 0 };
static {
BasicConfigurator.configure();
ToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);
TruncatedRoadGaussian.velocityRange = Ranges.closed(0d, 20d);
}
public static void assertVectorWithCovarianceError(Vector mean,
Matrix cov, double scale) {
for (int i = 0; i < mean.getDimensionality(); i++) {
final double error = mean.getElement(i);
final double stdDev = Math.sqrt(cov.getElement(i, i));
AssertJUnit.assertEquals(0d, error, scale * stdDev);
}
}
@DataProvider
private static final Object[][] initialStateData() {
return new Object[][] { {
/*
* Road only
*/
new VehicleStateInitialParameters(null, VectorFactory
.getDefault().createVector2D(70d, 70d),
Integer.MAX_VALUE, VectorFactory.getDefault()
.createVector1D(6.25e-4), Integer.MAX_VALUE,
VectorFactory.getDefault().createVector2D(6.25e-4,
6.25e-4), Integer.MAX_VALUE, VectorFactory
.getDefault().createVector2D(1d, Double.MAX_VALUE),
VectorFactory.getDefault().createVector2D(
Double.MAX_VALUE, 1d), 25, 30, 2159585l),
new VehicleStateInitialParameters(
null,
// VectorFactory.getDefault().createVector2D(70d, 70d), Integer.MAX_VALUE,
// VectorFactory.getDefault().createVector1D(6.25e-4), Integer.MAX_VALUE,
// VectorFactory.getDefault().createVector2D(6.25e-4, 6.25e-4), Integer.MAX_VALUE,
VectorFactory.getDefault().createVector2D(70d, 70d), 20,
VectorFactory.getDefault().createVector1D(6.25e-4), 20,
VectorFactory.getDefault().createVector2D(6.25e-4,
6.25e-4), 20, VectorFactory.getDefault()
.createVector2D(1d, Double.MAX_VALUE), VectorFactory
.getDefault().createVector2D(Double.MAX_VALUE, 1d),
25, 30, 2159585l), Boolean.FALSE, 36000 },
// {
// /*
// * Ground only
// */
// new VehicleStateInitialParameters(null, VectorFactory
// .getDefault().createVector2D(70d, 70d), 20,
// VectorFactory.getDefault().createVector1D(6.25e-4),
// 20, VectorFactory.getDefault().createVector2D(
// 6.25e-4, 6.25e-4), 20, VectorFactory.getDefault()
// .createVector2D(Double.MAX_VALUE, 1d),
// VectorFactory.getDefault().createVector2D(
// 1d, Double.MAX_VALUE), 25, 30, 2159585l),
// new VehicleStateInitialParameters(null, VectorFactory
// .getDefault().createVector2D(70d, 70d), 20,
// VectorFactory.getDefault().createVector1D(6.25e-4), 20,
// VectorFactory.getDefault().createVector2D(6.25e-4, 6.25e-4), 20,
// VectorFactory.getDefault().createVector2D(Double.MAX_VALUE, 1d),
// VectorFactory.getDefault().createVector2D(1d, Double.MAX_VALUE),
// 25, 30, 2159585l),
// Boolean.FALSE, 36000 },
// {
// /*
// * Mixed
// */
// new VehicleStateInitialParameters(null, VectorFactory
// .getDefault().createVector2D(70d, 70d), 20,
// VectorFactory.getDefault().createVector1D(6.25e-4),
// 20, VectorFactory.getDefault().createVector2D(
// 6.25e-4, 6.25e-4), 20, VectorFactory.getDefault()
// .createVector2D(0.5d, 0.5d), VectorFactory
// .getDefault().createVector2D(0.5d, 0.5d), 25, 30,
// 2159585l),
// new VehicleStateInitialParameters(null, VectorFactory
// .getDefault().createVector2D(70d, 70d), 20,
// VectorFactory.getDefault().createVector1D(6.25e-4),
// 20, VectorFactory.getDefault().createVector2D(
// 6.25e-4, 6.25e-4), 20, VectorFactory.getDefault()
// .createVector2D(70d, 30d), VectorFactory
// .getDefault().createVector2D(30d, 70d), 25, 30,
// 2159585l), Boolean.FALSE, 36000 }
};
}
private Matrix avgTransform;
private OtpGraph graph;
final Logger log = Logger
.getLogger(VehicleStatePLFilterSimulationTest.class);
private Simulation sim;
private Coordinate startCoord;
private Matrix createModelCovariance(
VehicleStateDistribution<GpsObservation> trueVehicleState,
SufficientStatistic stateErrorSS) {
final Matrix modelCovariance;
if (stateErrorSS.getMean().getDimensionality() == 4) {
final Matrix Qg =
trueVehicleState.getOffRoadModelCovarianceParam()
.getValue();
final Matrix factor =
MotionStateEstimatorPredictor.getCovarianceFactor(this.sim
.getSimParameters().getFrequency(), false);
modelCovariance = factor.times(Qg).times(factor.transpose());
} else {
final Matrix Qr =
trueVehicleState.getOnRoadModelCovarianceParam().getValue();
final Matrix factor =
MotionStateEstimatorPredictor.getCovarianceFactor(this.sim
.getSimParameters().getFrequency(), true);
modelCovariance = factor.times(Qr).times(factor.transpose());
}
return modelCovariance;
}
private VehicleStateDistribution<GpsObservation> resetState(
VehicleStateDistribution<GpsObservation> vehicleState) {
return this.sim.computeInitialState();
}
@Test(dataProvider = "initialStateData")
public void runSimulation(
VehicleStateInitialParameters simInitialParams,
VehicleStateInitialParameters filterInitialParams,
boolean generalizeMoveDiff, long duration)
throws NoninvertibleTransformException, TransformException {
final SimulationParameters simParams =
new SimulationParameters(this.startCoord, new Date(0l),
duration, simInitialParams.getInitialObsFreq(), false,
true, simInitialParams);
this.sim =
new Simulation("test-sim", this.graph, simParams,
simInitialParams);
long time = this.sim.getSimParameters().getStartTime().getTime();
VehicleStateDistribution<GpsObservation> trueVehicleState =
this.sim.computeInitialState();
Random rng;
if (filterInitialParams.getSeed() != 0) {
rng = new Random(filterInitialParams.getSeed());
} else {
rng = new Random();
}
final ParticleFilter<GpsObservation, VehicleStateDistribution<GpsObservation>> filter =
new VehicleStatePLPathSamplingFilter<GpsObservation, OtpGraph>(
new TrueObservation(trueVehicleState.getObservation(),
trueVehicleState),
this.graph,
new VehicleStateDistribution.VehicleStateDistributionFactory<GpsObservation, OtpGraph>(),
filterInitialParams, true, rng);
final DataDistribution<VehicleStateDistribution<GpsObservation>> vehicleStateDist =
filter.getUpdater().createInitialParticles(
filterInitialParams.getNumParticles());
final MultivariateGaussian.SufficientStatistic obsErrorSS =
new MultivariateGaussian.SufficientStatistic();
final MultivariateGaussian.SufficientStatistic stateErrorSS =
new MultivariateGaussian.SufficientStatistic();
final MultivariateGaussian.SufficientStatistic obsCovErrorSS =
new MultivariateGaussian.SufficientStatistic();
final MultivariateGaussian.SufficientStatistic onRoadCovErrorSS =
new MultivariateGaussian.SufficientStatistic();
final MultivariateGaussian.SufficientStatistic offRoadCovErrorSS =
new MultivariateGaussian.SufficientStatistic();
final MultivariateGaussian.SufficientStatistic transitionsSS =
new MultivariateGaussian.SufficientStatistic();
final RingAccumulator<MutableDouble> averager =
new RingAccumulator<MutableDouble>();
final Stopwatch watch = new Stopwatch();
final long approxRuns =
this.sim.getSimParameters().getDuration()
/ Math.round(this.sim.getSimParameters().getFrequency());
this.updateAndCheckStats(vehicleStateDist, trueVehicleState,
obsErrorSS, stateErrorSS, obsCovErrorSS, onRoadCovErrorSS,
offRoadCovErrorSS, transitionsSS, generalizeMoveDiff);
do {
try {
trueVehicleState = this.sim.stepSimulation(trueVehicleState);
if (trueVehicleState.getPathStateParam().getValue()
.isOnRoad()) {
for (final VectorEntry entry : trueVehicleState
.getMotionStateParam().getValue()) {
AssertJUnit.assertTrue(entry.getValue() >= 0d);
}
}
watch.reset();
watch.start();
filter.update(vehicleStateDist, new TrueObservation(
trueVehicleState.getObservation(), trueVehicleState));
watch.stop();
averager.accumulate(new MutableDouble(watch.elapsedMillis()));
if (averager.getCount() > 1 && averager.getCount() % 20 == 0) {
this.log.info("avg. records per sec = " + 1000d
/ averager.getMean().value);
}
this.updateAndCheckStats(vehicleStateDist, trueVehicleState,
obsErrorSS, stateErrorSS, obsCovErrorSS,
onRoadCovErrorSS, offRoadCovErrorSS, transitionsSS,
generalizeMoveDiff);
time =
trueVehicleState.getObservation().getTimestamp()
.getTime();
} catch (final ProjectionException ex) {
trueVehicleState = this.resetState(trueVehicleState);
// if (vehicleState.getParentState() != null)
// vehicleState.setParentState(resetState(vehicleState.getParentState()));
this.log
.warn("Outside of projection! Flipped state velocities");
}
} while (time < this.sim.getSimParameters().getEndTime()
.getTime());
AssertJUnit
.assertTrue(transitionsSS.getCount() > 0.95d * approxRuns);
}
@BeforeTest
public void setUp() throws NoSuchAuthorityCodeException,
FactoryRegistryException, FactoryException, IOException {
this.log.setLevel(Level.DEBUG);
this.graph = new OtpGraph("/tmp");
this.startCoord = new Coordinate(40.714192, -74.006291);//new Coordinate(40.7549, -73.97749);
this.avgTransform =
MatrixFactory
.getDefault()
.copyArray(
new double[][] { { 1, 0, 1, 0 }, { 0, 1, 0, 1 } })
.scale(1d / 2d);
}
private
void
updateAndCheckStats(
DataDistribution<VehicleStateDistribution<GpsObservation>> vehicleStateDist,
VehicleStateDistribution<GpsObservation> trueVehicleState,
SufficientStatistic obsErrorSS,
SufficientStatistic stateErrorSS,
SufficientStatistic obsCovErrorSS,
SufficientStatistic onRoadCovErrorSS,
SufficientStatistic offRoadCovErrorSS,
SufficientStatistic transitionsSS, boolean generalizeMoveDiff) {
final SufficientStatistic groundStateMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic obsCovMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic onRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic offRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic transitionStat =
new MultivariateGaussian.SufficientStatistic();
int truePathsFound = 0;
int numOnTrueEdge = 0;
final boolean hasPriorOnVariances = false;
Preconditions.checkState(vehicleStateDist.getDomainSize() > 0);
trueVehicleState.getObservation().getProjectedPoint()
.minus(trueVehicleState.getMeanLocation());
for (final VehicleStateDistribution<GpsObservation> state : vehicleStateDist
.getDomain()) {
AssertJUnit
.assertEquals(
new TrueObservation(trueVehicleState.getObservation(),
null), state.getObservation());
final int stateCount;
if (vehicleStateDist instanceof CountedDataDistribution<?>) {
stateCount =
((CountedDataDistribution<VehicleStateDistribution<GpsObservation>>) vehicleStateDist)
.getCount(state);
} else {
stateCount = 1;
}
final PathState pathState =
state.getPathStateParam().getValue();
final PathState truePathState =
state.getPathStateParam().getValue();
final VehicleStateDistribution<GpsObservation> parentState =
state.getParentState();
Vector transType = null;
if (parentState != null) {
final PathState parentPathState =
parentState.getPathStateParam().getValue();
transType =
OnOffEdgeTransDistribution.getTransitionType(
- parentPathState.getEdge().getInferenceGraphEdge(),
- pathState.getEdge().getInferenceGraphEdge());
+ parentPathState.getEdge().getInferenceGraphSegment(),
+ pathState.getEdge().getInferenceGraphSegment());
if (parentPathState.isOnRoad()) {
transType =
transType.stack(MotionStateEstimatorPredictor.zeros2D);
} else {
transType =
MotionStateEstimatorPredictor.zeros2D.stack(transType);
}
}
for (int i = 0; i < stateCount; i++) {
if ((pathState.isOnRoad() && truePathState.isOnRoad() && pathState
.getPath().getGeometry()
.covers(truePathState.getPath().getGeometry()))
|| (!pathState.isOnRoad() && !truePathState.isOnRoad())) {
truePathsFound++;
}
- if (pathState.getEdge().getInferenceGraphEdge()
- .equals(truePathState.getEdge().getInferenceGraphEdge())) {
+ if (pathState.getEdge().getInferenceGraphSegment()
+ .equals(truePathState.getEdge().getInferenceGraphSegment())) {
numOnTrueEdge++;
}
groundStateMeanStat.update(pathState.getGroundState());
final Matrix obsCovMean =
state.getObservationCovarianceParam().getParameterPrior()
.getMean();
obsCovMeanStat.update(obsCovMean.convertToVector());
final Matrix onRoadCovMean =
state.getOnRoadModelCovarianceParam().getParameterPrior()
.getMean();
onRoadCovStat.update(onRoadCovMean.convertToVector());
offRoadCovStat.update(state.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
if (transType != null) {
transitionStat.update(transType);
}
}
}
this.log.debug("truePathsFound=" + truePathsFound);
this.log.debug("numOnTrueEdges=" + numOnTrueEdge);
Preconditions.checkNotNull(groundStateMeanStat.getMean());
final Vector obsError =
trueVehicleState
.getObservation()
.getProjectedPoint()
.minus(
MotionStateEstimatorPredictor.getOg().times(
groundStateMeanStat.getMean()));
final PathState truePathState =
trueVehicleState.getPathStateParam().getValue();
final Vector stateError =
truePathState.getGroundState().minus(
groundStateMeanStat.getMean());
final Vector obsCovError;
final Vector onRoadCovError;
final Vector offRoadCovError;
obsCovError =
obsCovMeanStat.getMean().minus(
trueVehicleState.getObservationCovarianceParam()
.getValue().convertToVector());
onRoadCovError =
onRoadCovStat.getMean().minus(
trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().convertToVector());
offRoadCovError =
offRoadCovStat.getMean().minus(
trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
this.log
.info("trueMotionState=" + truePathState.getMotionState());
this.log.debug("obsError=" + obsError);
this.log.debug("stateError=" + stateError);
this.log.debug("obsCovMean=" + obsCovMeanStat.getMean());
this.log.debug("onRoadCovMean=" + onRoadCovStat.getMean());
this.log.debug("offRoadCovMean=" + offRoadCovStat.getMean());
if (transitionStat.getMean() != null) {
final Vector trueTransProbs =
trueVehicleState
.getEdgeTransitionParam()
.getParameterPrior()
.getEdgeMotionTransProbPrior()
.getMean()
.stack(
trueVehicleState.getEdgeTransitionParam()
.getParameterPrior()
.getFreeMotionTransProbPrior().getMean());
transitionsSS.update(transitionStat.getMean().minus(
trueTransProbs));
// log.debug("transitionMean=" + transitionStat.getMean());
}
obsErrorSS.update(obsError);
stateErrorSS.update(stateError);
obsCovErrorSS.update(obsCovError);
onRoadCovErrorSS.update(onRoadCovError);
offRoadCovErrorSS.update(offRoadCovError);
if (!hasPriorOnVariances) {
this.log.debug("obsErrorSS=" + obsErrorSS.getMean());
this.log.debug("stateErrorSS=" + stateErrorSS.getMean());
// log.debug("obsCovErrorSS=" + obsCovErrorSS.getMean());
// log.debug("onRoadCovErrorSS=" + onRoadCovErrorSS.getMean());
// log.debug("offRoadCovErrorSS=" + offRoadCovErrorSS.getMean());
// log.debug("transitionErrorSS=" + transitionsSS.getMean());
}
if (obsErrorSS.getCount() > 1) {//Math.min(approxRuns / 16, 155)) {
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(obsErrorSS.getMean(),
trueVehicleState.getObservationCovarianceParam()
.getValue(), 5d);
final Matrix stateModelCovariance =
this.createModelCovariance(trueVehicleState, stateErrorSS);
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(stateErrorSS.getMean(),
stateModelCovariance, 5d);
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros, obsCovErrorSS
.getMean().toArray(), 0.7d * trueVehicleState
.getObservationCovarianceParam().getValue()
.normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.oneZero,
onRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros,
offRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().normFrobenius());
}
}
}
| false | true | void
updateAndCheckStats(
DataDistribution<VehicleStateDistribution<GpsObservation>> vehicleStateDist,
VehicleStateDistribution<GpsObservation> trueVehicleState,
SufficientStatistic obsErrorSS,
SufficientStatistic stateErrorSS,
SufficientStatistic obsCovErrorSS,
SufficientStatistic onRoadCovErrorSS,
SufficientStatistic offRoadCovErrorSS,
SufficientStatistic transitionsSS, boolean generalizeMoveDiff) {
final SufficientStatistic groundStateMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic obsCovMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic onRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic offRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic transitionStat =
new MultivariateGaussian.SufficientStatistic();
int truePathsFound = 0;
int numOnTrueEdge = 0;
final boolean hasPriorOnVariances = false;
Preconditions.checkState(vehicleStateDist.getDomainSize() > 0);
trueVehicleState.getObservation().getProjectedPoint()
.minus(trueVehicleState.getMeanLocation());
for (final VehicleStateDistribution<GpsObservation> state : vehicleStateDist
.getDomain()) {
AssertJUnit
.assertEquals(
new TrueObservation(trueVehicleState.getObservation(),
null), state.getObservation());
final int stateCount;
if (vehicleStateDist instanceof CountedDataDistribution<?>) {
stateCount =
((CountedDataDistribution<VehicleStateDistribution<GpsObservation>>) vehicleStateDist)
.getCount(state);
} else {
stateCount = 1;
}
final PathState pathState =
state.getPathStateParam().getValue();
final PathState truePathState =
state.getPathStateParam().getValue();
final VehicleStateDistribution<GpsObservation> parentState =
state.getParentState();
Vector transType = null;
if (parentState != null) {
final PathState parentPathState =
parentState.getPathStateParam().getValue();
transType =
OnOffEdgeTransDistribution.getTransitionType(
parentPathState.getEdge().getInferenceGraphEdge(),
pathState.getEdge().getInferenceGraphEdge());
if (parentPathState.isOnRoad()) {
transType =
transType.stack(MotionStateEstimatorPredictor.zeros2D);
} else {
transType =
MotionStateEstimatorPredictor.zeros2D.stack(transType);
}
}
for (int i = 0; i < stateCount; i++) {
if ((pathState.isOnRoad() && truePathState.isOnRoad() && pathState
.getPath().getGeometry()
.covers(truePathState.getPath().getGeometry()))
|| (!pathState.isOnRoad() && !truePathState.isOnRoad())) {
truePathsFound++;
}
if (pathState.getEdge().getInferenceGraphEdge()
.equals(truePathState.getEdge().getInferenceGraphEdge())) {
numOnTrueEdge++;
}
groundStateMeanStat.update(pathState.getGroundState());
final Matrix obsCovMean =
state.getObservationCovarianceParam().getParameterPrior()
.getMean();
obsCovMeanStat.update(obsCovMean.convertToVector());
final Matrix onRoadCovMean =
state.getOnRoadModelCovarianceParam().getParameterPrior()
.getMean();
onRoadCovStat.update(onRoadCovMean.convertToVector());
offRoadCovStat.update(state.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
if (transType != null) {
transitionStat.update(transType);
}
}
}
this.log.debug("truePathsFound=" + truePathsFound);
this.log.debug("numOnTrueEdges=" + numOnTrueEdge);
Preconditions.checkNotNull(groundStateMeanStat.getMean());
final Vector obsError =
trueVehicleState
.getObservation()
.getProjectedPoint()
.minus(
MotionStateEstimatorPredictor.getOg().times(
groundStateMeanStat.getMean()));
final PathState truePathState =
trueVehicleState.getPathStateParam().getValue();
final Vector stateError =
truePathState.getGroundState().minus(
groundStateMeanStat.getMean());
final Vector obsCovError;
final Vector onRoadCovError;
final Vector offRoadCovError;
obsCovError =
obsCovMeanStat.getMean().minus(
trueVehicleState.getObservationCovarianceParam()
.getValue().convertToVector());
onRoadCovError =
onRoadCovStat.getMean().minus(
trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().convertToVector());
offRoadCovError =
offRoadCovStat.getMean().minus(
trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
this.log
.info("trueMotionState=" + truePathState.getMotionState());
this.log.debug("obsError=" + obsError);
this.log.debug("stateError=" + stateError);
this.log.debug("obsCovMean=" + obsCovMeanStat.getMean());
this.log.debug("onRoadCovMean=" + onRoadCovStat.getMean());
this.log.debug("offRoadCovMean=" + offRoadCovStat.getMean());
if (transitionStat.getMean() != null) {
final Vector trueTransProbs =
trueVehicleState
.getEdgeTransitionParam()
.getParameterPrior()
.getEdgeMotionTransProbPrior()
.getMean()
.stack(
trueVehicleState.getEdgeTransitionParam()
.getParameterPrior()
.getFreeMotionTransProbPrior().getMean());
transitionsSS.update(transitionStat.getMean().minus(
trueTransProbs));
// log.debug("transitionMean=" + transitionStat.getMean());
}
obsErrorSS.update(obsError);
stateErrorSS.update(stateError);
obsCovErrorSS.update(obsCovError);
onRoadCovErrorSS.update(onRoadCovError);
offRoadCovErrorSS.update(offRoadCovError);
if (!hasPriorOnVariances) {
this.log.debug("obsErrorSS=" + obsErrorSS.getMean());
this.log.debug("stateErrorSS=" + stateErrorSS.getMean());
// log.debug("obsCovErrorSS=" + obsCovErrorSS.getMean());
// log.debug("onRoadCovErrorSS=" + onRoadCovErrorSS.getMean());
// log.debug("offRoadCovErrorSS=" + offRoadCovErrorSS.getMean());
// log.debug("transitionErrorSS=" + transitionsSS.getMean());
}
if (obsErrorSS.getCount() > 1) {//Math.min(approxRuns / 16, 155)) {
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(obsErrorSS.getMean(),
trueVehicleState.getObservationCovarianceParam()
.getValue(), 5d);
final Matrix stateModelCovariance =
this.createModelCovariance(trueVehicleState, stateErrorSS);
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(stateErrorSS.getMean(),
stateModelCovariance, 5d);
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros, obsCovErrorSS
.getMean().toArray(), 0.7d * trueVehicleState
.getObservationCovarianceParam().getValue()
.normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.oneZero,
onRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros,
offRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().normFrobenius());
}
}
}
| void
updateAndCheckStats(
DataDistribution<VehicleStateDistribution<GpsObservation>> vehicleStateDist,
VehicleStateDistribution<GpsObservation> trueVehicleState,
SufficientStatistic obsErrorSS,
SufficientStatistic stateErrorSS,
SufficientStatistic obsCovErrorSS,
SufficientStatistic onRoadCovErrorSS,
SufficientStatistic offRoadCovErrorSS,
SufficientStatistic transitionsSS, boolean generalizeMoveDiff) {
final SufficientStatistic groundStateMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic obsCovMeanStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic onRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic offRoadCovStat =
new MultivariateGaussian.SufficientStatistic();
final SufficientStatistic transitionStat =
new MultivariateGaussian.SufficientStatistic();
int truePathsFound = 0;
int numOnTrueEdge = 0;
final boolean hasPriorOnVariances = false;
Preconditions.checkState(vehicleStateDist.getDomainSize() > 0);
trueVehicleState.getObservation().getProjectedPoint()
.minus(trueVehicleState.getMeanLocation());
for (final VehicleStateDistribution<GpsObservation> state : vehicleStateDist
.getDomain()) {
AssertJUnit
.assertEquals(
new TrueObservation(trueVehicleState.getObservation(),
null), state.getObservation());
final int stateCount;
if (vehicleStateDist instanceof CountedDataDistribution<?>) {
stateCount =
((CountedDataDistribution<VehicleStateDistribution<GpsObservation>>) vehicleStateDist)
.getCount(state);
} else {
stateCount = 1;
}
final PathState pathState =
state.getPathStateParam().getValue();
final PathState truePathState =
state.getPathStateParam().getValue();
final VehicleStateDistribution<GpsObservation> parentState =
state.getParentState();
Vector transType = null;
if (parentState != null) {
final PathState parentPathState =
parentState.getPathStateParam().getValue();
transType =
OnOffEdgeTransDistribution.getTransitionType(
parentPathState.getEdge().getInferenceGraphSegment(),
pathState.getEdge().getInferenceGraphSegment());
if (parentPathState.isOnRoad()) {
transType =
transType.stack(MotionStateEstimatorPredictor.zeros2D);
} else {
transType =
MotionStateEstimatorPredictor.zeros2D.stack(transType);
}
}
for (int i = 0; i < stateCount; i++) {
if ((pathState.isOnRoad() && truePathState.isOnRoad() && pathState
.getPath().getGeometry()
.covers(truePathState.getPath().getGeometry()))
|| (!pathState.isOnRoad() && !truePathState.isOnRoad())) {
truePathsFound++;
}
if (pathState.getEdge().getInferenceGraphSegment()
.equals(truePathState.getEdge().getInferenceGraphSegment())) {
numOnTrueEdge++;
}
groundStateMeanStat.update(pathState.getGroundState());
final Matrix obsCovMean =
state.getObservationCovarianceParam().getParameterPrior()
.getMean();
obsCovMeanStat.update(obsCovMean.convertToVector());
final Matrix onRoadCovMean =
state.getOnRoadModelCovarianceParam().getParameterPrior()
.getMean();
onRoadCovStat.update(onRoadCovMean.convertToVector());
offRoadCovStat.update(state.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
if (transType != null) {
transitionStat.update(transType);
}
}
}
this.log.debug("truePathsFound=" + truePathsFound);
this.log.debug("numOnTrueEdges=" + numOnTrueEdge);
Preconditions.checkNotNull(groundStateMeanStat.getMean());
final Vector obsError =
trueVehicleState
.getObservation()
.getProjectedPoint()
.minus(
MotionStateEstimatorPredictor.getOg().times(
groundStateMeanStat.getMean()));
final PathState truePathState =
trueVehicleState.getPathStateParam().getValue();
final Vector stateError =
truePathState.getGroundState().minus(
groundStateMeanStat.getMean());
final Vector obsCovError;
final Vector onRoadCovError;
final Vector offRoadCovError;
obsCovError =
obsCovMeanStat.getMean().minus(
trueVehicleState.getObservationCovarianceParam()
.getValue().convertToVector());
onRoadCovError =
onRoadCovStat.getMean().minus(
trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().convertToVector());
offRoadCovError =
offRoadCovStat.getMean().minus(
trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().convertToVector());
this.log
.info("trueMotionState=" + truePathState.getMotionState());
this.log.debug("obsError=" + obsError);
this.log.debug("stateError=" + stateError);
this.log.debug("obsCovMean=" + obsCovMeanStat.getMean());
this.log.debug("onRoadCovMean=" + onRoadCovStat.getMean());
this.log.debug("offRoadCovMean=" + offRoadCovStat.getMean());
if (transitionStat.getMean() != null) {
final Vector trueTransProbs =
trueVehicleState
.getEdgeTransitionParam()
.getParameterPrior()
.getEdgeMotionTransProbPrior()
.getMean()
.stack(
trueVehicleState.getEdgeTransitionParam()
.getParameterPrior()
.getFreeMotionTransProbPrior().getMean());
transitionsSS.update(transitionStat.getMean().minus(
trueTransProbs));
// log.debug("transitionMean=" + transitionStat.getMean());
}
obsErrorSS.update(obsError);
stateErrorSS.update(stateError);
obsCovErrorSS.update(obsCovError);
onRoadCovErrorSS.update(onRoadCovError);
offRoadCovErrorSS.update(offRoadCovError);
if (!hasPriorOnVariances) {
this.log.debug("obsErrorSS=" + obsErrorSS.getMean());
this.log.debug("stateErrorSS=" + stateErrorSS.getMean());
// log.debug("obsCovErrorSS=" + obsCovErrorSS.getMean());
// log.debug("onRoadCovErrorSS=" + onRoadCovErrorSS.getMean());
// log.debug("offRoadCovErrorSS=" + offRoadCovErrorSS.getMean());
// log.debug("transitionErrorSS=" + transitionsSS.getMean());
}
if (obsErrorSS.getCount() > 1) {//Math.min(approxRuns / 16, 155)) {
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(obsErrorSS.getMean(),
trueVehicleState.getObservationCovarianceParam()
.getValue(), 5d);
final Matrix stateModelCovariance =
this.createModelCovariance(trueVehicleState, stateErrorSS);
VehicleStatePLFilterSimulationTest
.assertVectorWithCovarianceError(stateErrorSS.getMean(),
stateModelCovariance, 5d);
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros, obsCovErrorSS
.getMean().toArray(), 0.7d * trueVehicleState
.getObservationCovarianceParam().getValue()
.normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.oneZero,
onRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOnRoadModelCovarianceParam()
.getValue().normFrobenius());
ArrayAsserts.assertArrayEquals(
VehicleStatePLFilterSimulationTest.fourZeros,
offRoadCovErrorSS.getMean().toArray(),
0.7d * trueVehicleState.getOffRoadModelCovarianceParam()
.getValue().normFrobenius());
}
}
}
|
diff --git a/src/minecraft/net/minecraft/src/GuiIngame.java b/src/minecraft/net/minecraft/src/GuiIngame.java
index 3ba710ce..da7d0e8e 100644
--- a/src/minecraft/net/minecraft/src/GuiIngame.java
+++ b/src/minecraft/net/minecraft/src/GuiIngame.java
@@ -1,473 +1,473 @@
package net.minecraft.src;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.src.Block;
import net.minecraft.src.ChatLine;
import net.minecraft.src.EntityClientPlayerMP;
import net.minecraft.src.FontRenderer;
import net.minecraft.src.FoodStats;
import net.minecraft.src.Gui;
import net.minecraft.src.GuiChat;
import net.minecraft.src.GuiSavingLevelString;
import net.minecraft.src.InventoryPlayer;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Material;
import net.minecraft.src.MathHelper;
import net.minecraft.src.NetClientHandler;
import net.minecraft.src.Potion;
import net.minecraft.src.RenderHelper;
import net.minecraft.src.RenderItem;
import net.minecraft.src.ScaledResolution;
import net.minecraft.src.StringTranslate;
import net.minecraft.src.Tessellator;
import org.lwjgl.opengl.GL11;
//Spout Start
import org.getspout.spout.chunkcache.ChunkCache;
import org.getspout.spout.client.SpoutClient;
import org.spoutcraft.spoutcraftapi.gui.*;
import org.getspout.spout.player.ChatManager;
//Spout End
public class GuiIngame extends Gui {
private static RenderItem itemRenderer = new RenderItem();
//Spout Improved Chat Start
//Increased default size, efficiency reasons
public List<ChatLine> chatMessageList = new ArrayList<ChatLine>(2500);
//Spout Improved Chat End
public static final Random rand = new Random(); //Spout private -> public static final
private Minecraft mc;
public String field_933_a = null;
private int updateCounter = 0;
private String recordPlaying = "";
private int recordPlayingUpFor = 0;
private boolean recordIsPlaying = false;
public float damageGuiPartialTime;
float prevVignetteBrightness = 1.0F;
public GuiIngame(Minecraft var1) {
this.mc = var1;
}
//Spout Start
//Most of function rewritten
public void renderGameOverlay(float var1, boolean var2, int var3, int var4) {
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.func_905_b();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getEntityBrightness(var1), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(!this.mc.gameSettings.thirdPersonView && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * var1;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /*GL_BLEND*/);
GuiIngame.rand.setSeed((long)(this.updateCounter * 312871));
int var15;
int var17;
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/gui/icons.png"));
if(this.mc.playerController.shouldDrawHUD()) {
//Armor Bar Begin
mainScreen.getArmorBar().render();
//Armor Bar End
//Health Bar Begin
mainScreen.getHealthBar().render();
//Health Bar End
//Bubble Bar Begin
mainScreen.getBubbleBar().render();
//Bubble Bar End
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for(var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, var1);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
}
if(this.mc.thePlayer.func_22060_M() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.func_22060_M();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
mainScreen.render();
String var23;
if(this.mc.playerController.shouldDrawHUD() && this.mc.gameSettings.showDebugInfo) {
GL11.glPushMatrix();
if(Minecraft.hasPaidCheckTime > 0L) {
GL11.glTranslatef(0.0F, 32.0F, 0.0F);
}
if (this.mc.gameSettings.fastDebugMode != 2) {
font.drawStringWithShadow("Minecraft Beta 1.7.3 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.func_6262_n(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.func_21002_o(), 2, 42, 16777215);
long maxMem = Runtime.getRuntime().maxMemory();
long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long usedMem = (maxMem - freeMem);
String os = System.getProperty("os.name");
if (os != null && os.toLowerCase().contains("win")) {
usedMem *= 2; //Windows underreports used memory
usedMem += 1024L * 100;
}
var23 = "Used memory: " + ((int)((usedMem / (float)maxMem) * 100f)) + "% (" + usedMem / 1024L / 1024L + "MB) of " + totalMem / 1024L / 1024L + "MB";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 2, 14737632);
var23 = "Allocated memory: " + totalMem * 100L / maxMem + "% (" + totalMem / 1024L / 1024L + "MB)";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 12, 14737632);
//No Cheating!
int offset = 0;
if (SpoutClient.getInstance().isCheatMode()) {
this.drawString(font, "x: " + this.mc.thePlayer.posX, 2, 64, 14737632);
this.drawString(font, "y: " + this.mc.thePlayer.posY, 2, 72, 14737632);
this.drawString(font, "z: " + this.mc.thePlayer.posZ, 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
offset = 40;
}
if (mc.isMultiplayerWorld() && SpoutClient.getInstance().isSpoutEnabled()) {
this.drawString(font, "Spout Map Data Cache Info:", 2, 64 + offset, 0xE0E000);
this.drawString(font, "Average packet size: " + ChunkCache.averageChunkSize.get() + " bytes", 2, 72 + offset, 14737632);
this.drawString(font, "Cache hit percent: " + ChunkCache.hitPercentage.get(), 2, 80 + offset, 14737632);
long currentTime = System.currentTimeMillis();
long downBandwidth = (8 * ChunkCache.totalPacketDown.get()) / (currentTime - ChunkCache.loggingStart.get());
long upBandwidth = (8 * ChunkCache.totalPacketUp.get()) / (currentTime - ChunkCache.loggingStart.get());
this.drawString(font, "Bandwidth (Up): " + Math.max(1, upBandwidth) + "kbps", 2, 88 + offset, 14737632);
this.drawString(font, "Bandwidth (Down): " + Math.max(1, downBandwidth) + "kbps", 2, 96 + offset, 14737632);
}
}
else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
GL11.glPopMatrix();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - var1;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
if (this.mc.playerController.shouldDrawHUD() && chatTextWidget.isVisible()) {
int viewedLine = 0;
for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size() - 1, (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
opacity *= 10D;
if(opacity < 0.0D) {
opacity = 0.0D;
}
if(opacity > 1.0D) {
opacity = 1.0D;
}
opacity *= opacity;
int color = chatOpen ? 255 : (int)(255D * opacity);
if (color > 0) {
int x = 2;
int y = -viewedLine * 9;
String chat = chatMessageList.get(line).message;
chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
chat = ChatManager.formatUrl(chat);
//TODO add support for opening URL in browser if clicked?
drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
GL11.glEnable(3042 /*GL_BLEND*/);
font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
}
viewedLine++;
}
}
}
GL11.glPopMatrix();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.field_35384_x.field_35965_e) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.field_35786_c;
int var40 = var41.field_35785_d;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
- int var18 = (var6 - var16 * var17) / 2;
+ int var18 = (screenWidth - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiSavingLevelString var50 = (GuiSavingLevelString)var44.get(var20);
font.drawStringWithShadow(var50.field_35624_a, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.field_35623_b < 0) {
var54 = 5;
} else if(var50.field_35623_b < 150) {
var54 = 0;
} else if(var50.field_35623_b < 300) {
var54 = 1;
} else if(var50.field_35623_b < 600) {
var54 = 2;
} else if(var50.field_35623_b < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
//Spout End
private void renderPumpkinBlur(int var1, int var2) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDepthMask(false);
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("%blur%/misc/pumpkinblur.png"));
Tessellator var3 = Tessellator.instance;
var3.startDrawingQuads();
var3.addVertexWithUV(0.0D, (double)var2, -90.0D, 0.0D, 1.0D);
var3.addVertexWithUV((double)var1, (double)var2, -90.0D, 1.0D, 1.0D);
var3.addVertexWithUV((double)var1, 0.0D, -90.0D, 1.0D, 0.0D);
var3.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
var3.draw();
GL11.glDepthMask(true);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private void renderVignette(float var1, int var2, int var3) {
var1 = 1.0F - var1;
if(var1 < 0.0F) {
var1 = 0.0F;
}
if(var1 > 1.0F) {
var1 = 1.0F;
}
this.prevVignetteBrightness = (float)((double)this.prevVignetteBrightness + (double)(var1 - this.prevVignetteBrightness) * 0.01D);
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDepthMask(false);
GL11.glBlendFunc(0, 769);
GL11.glColor4f(this.prevVignetteBrightness, this.prevVignetteBrightness, this.prevVignetteBrightness, 1.0F);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("%blur%/misc/vignette.png"));
Tessellator var4 = Tessellator.instance;
var4.startDrawingQuads();
var4.addVertexWithUV(0.0D, (double)var3, -90.0D, 0.0D, 1.0D);
var4.addVertexWithUV((double)var2, (double)var3, -90.0D, 1.0D, 1.0D);
var4.addVertexWithUV((double)var2, 0.0D, -90.0D, 1.0D, 0.0D);
var4.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
var4.draw();
GL11.glDepthMask(true);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBlendFunc(770, 771);
}
private void renderPortalOverlay(float var1, int var2, int var3) {
if(var1 < 1.0F) {
var1 *= var1;
var1 *= var1;
var1 = var1 * 0.8F + 0.2F;
}
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDepthMask(false);
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, var1);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/terrain.png"));
float var4 = (float)(Block.portal.blockIndexInTexture % 16) / 16.0F;
float var5 = (float)(Block.portal.blockIndexInTexture / 16) / 16.0F;
float var6 = (float)(Block.portal.blockIndexInTexture % 16 + 1) / 16.0F;
float var7 = (float)(Block.portal.blockIndexInTexture / 16 + 1) / 16.0F;
Tessellator var8 = Tessellator.instance;
var8.startDrawingQuads();
var8.addVertexWithUV(0.0D, (double)var3, -90.0D, (double)var4, (double)var7);
var8.addVertexWithUV((double)var2, (double)var3, -90.0D, (double)var6, (double)var7);
var8.addVertexWithUV((double)var2, 0.0D, -90.0D, (double)var6, (double)var5);
var8.addVertexWithUV(0.0D, 0.0D, -90.0D, (double)var4, (double)var5);
var8.draw();
GL11.glDepthMask(true);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private void renderInventorySlot(int var1, int var2, int var3, float var4) {
ItemStack var5 = this.mc.thePlayer.inventory.mainInventory[var1];
if(var5 != null) {
float var6 = (float)var5.animationsToGo - var4;
if(var6 > 0.0F) {
GL11.glPushMatrix();
float var7 = 1.0F + var6 / 5.0F;
GL11.glTranslatef((float)(var2 + 8), (float)(var3 + 12), 0.0F);
GL11.glScalef(1.0F / var7, (var7 + 1.0F) / 2.0F, 1.0F);
GL11.glTranslatef((float)(-(var2 + 8)), (float)(-(var3 + 12)), 0.0F);
}
itemRenderer.renderItemIntoGUI(this.mc.fontRenderer, this.mc.renderEngine, var5, var2, var3);
if(var6 > 0.0F) {
GL11.glPopMatrix();
}
itemRenderer.renderItemOverlayIntoGUI(this.mc.fontRenderer, this.mc.renderEngine, var5, var2, var3);
}
}
public void updateTick() {
if(this.recordPlayingUpFor > 0) {
--this.recordPlayingUpFor;
}
++this.updateCounter;
for(int var1 = 0; var1 < this.chatMessageList.size(); ++var1) {
++((ChatLine)this.chatMessageList.get(var1)).updateCounter;
}
}
public void clearChatMessages() {
this.chatMessageList.clear();
}
public void addChatMessage(String var1) {
while(this.mc.fontRenderer.getStringWidth(var1) > 320) {
int var2;
for(var2 = 1; var2 < var1.length() && this.mc.fontRenderer.getStringWidth(var1.substring(0, var2 + 1)) <= 320; ++var2) {
;
}
this.addChatMessage(var1.substring(0, var2));
var1 = var1.substring(var2);
}
this.chatMessageList.add(0, new ChatLine(var1));
//Spout Improved Chat Start
while(this.chatMessageList.size() > 3000) {
this.chatMessageList.remove(this.chatMessageList.size() - 1);
}
//Spout Improved Chat End
}
public void setRecordPlayingMessage(String var1) {
this.recordPlaying = "Now playing: " + var1;
this.recordPlayingUpFor = 60;
this.recordIsPlaying = true;
}
public void addChatMessageTranslate(String var1) {
StringTranslate var2 = StringTranslate.getInstance();
String var3 = var2.translateKey(var1);
this.addChatMessage(var3);
}
}
| true | true | public void renderGameOverlay(float var1, boolean var2, int var3, int var4) {
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.func_905_b();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getEntityBrightness(var1), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(!this.mc.gameSettings.thirdPersonView && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * var1;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /*GL_BLEND*/);
GuiIngame.rand.setSeed((long)(this.updateCounter * 312871));
int var15;
int var17;
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/gui/icons.png"));
if(this.mc.playerController.shouldDrawHUD()) {
//Armor Bar Begin
mainScreen.getArmorBar().render();
//Armor Bar End
//Health Bar Begin
mainScreen.getHealthBar().render();
//Health Bar End
//Bubble Bar Begin
mainScreen.getBubbleBar().render();
//Bubble Bar End
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for(var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, var1);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
}
if(this.mc.thePlayer.func_22060_M() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.func_22060_M();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
mainScreen.render();
String var23;
if(this.mc.playerController.shouldDrawHUD() && this.mc.gameSettings.showDebugInfo) {
GL11.glPushMatrix();
if(Minecraft.hasPaidCheckTime > 0L) {
GL11.glTranslatef(0.0F, 32.0F, 0.0F);
}
if (this.mc.gameSettings.fastDebugMode != 2) {
font.drawStringWithShadow("Minecraft Beta 1.7.3 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.func_6262_n(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.func_21002_o(), 2, 42, 16777215);
long maxMem = Runtime.getRuntime().maxMemory();
long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long usedMem = (maxMem - freeMem);
String os = System.getProperty("os.name");
if (os != null && os.toLowerCase().contains("win")) {
usedMem *= 2; //Windows underreports used memory
usedMem += 1024L * 100;
}
var23 = "Used memory: " + ((int)((usedMem / (float)maxMem) * 100f)) + "% (" + usedMem / 1024L / 1024L + "MB) of " + totalMem / 1024L / 1024L + "MB";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 2, 14737632);
var23 = "Allocated memory: " + totalMem * 100L / maxMem + "% (" + totalMem / 1024L / 1024L + "MB)";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 12, 14737632);
//No Cheating!
int offset = 0;
if (SpoutClient.getInstance().isCheatMode()) {
this.drawString(font, "x: " + this.mc.thePlayer.posX, 2, 64, 14737632);
this.drawString(font, "y: " + this.mc.thePlayer.posY, 2, 72, 14737632);
this.drawString(font, "z: " + this.mc.thePlayer.posZ, 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
offset = 40;
}
if (mc.isMultiplayerWorld() && SpoutClient.getInstance().isSpoutEnabled()) {
this.drawString(font, "Spout Map Data Cache Info:", 2, 64 + offset, 0xE0E000);
this.drawString(font, "Average packet size: " + ChunkCache.averageChunkSize.get() + " bytes", 2, 72 + offset, 14737632);
this.drawString(font, "Cache hit percent: " + ChunkCache.hitPercentage.get(), 2, 80 + offset, 14737632);
long currentTime = System.currentTimeMillis();
long downBandwidth = (8 * ChunkCache.totalPacketDown.get()) / (currentTime - ChunkCache.loggingStart.get());
long upBandwidth = (8 * ChunkCache.totalPacketUp.get()) / (currentTime - ChunkCache.loggingStart.get());
this.drawString(font, "Bandwidth (Up): " + Math.max(1, upBandwidth) + "kbps", 2, 88 + offset, 14737632);
this.drawString(font, "Bandwidth (Down): " + Math.max(1, downBandwidth) + "kbps", 2, 96 + offset, 14737632);
}
}
else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
GL11.glPopMatrix();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - var1;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
if (this.mc.playerController.shouldDrawHUD() && chatTextWidget.isVisible()) {
int viewedLine = 0;
for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size() - 1, (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
opacity *= 10D;
if(opacity < 0.0D) {
opacity = 0.0D;
}
if(opacity > 1.0D) {
opacity = 1.0D;
}
opacity *= opacity;
int color = chatOpen ? 255 : (int)(255D * opacity);
if (color > 0) {
int x = 2;
int y = -viewedLine * 9;
String chat = chatMessageList.get(line).message;
chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
chat = ChatManager.formatUrl(chat);
//TODO add support for opening URL in browser if clicked?
drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
GL11.glEnable(3042 /*GL_BLEND*/);
font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
}
viewedLine++;
}
}
}
GL11.glPopMatrix();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.field_35384_x.field_35965_e) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.field_35786_c;
int var40 = var41.field_35785_d;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
int var18 = (var6 - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiSavingLevelString var50 = (GuiSavingLevelString)var44.get(var20);
font.drawStringWithShadow(var50.field_35624_a, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.field_35623_b < 0) {
var54 = 5;
} else if(var50.field_35623_b < 150) {
var54 = 0;
} else if(var50.field_35623_b < 300) {
var54 = 1;
} else if(var50.field_35623_b < 600) {
var54 = 2;
} else if(var50.field_35623_b < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
| public void renderGameOverlay(float var1, boolean var2, int var3, int var4) {
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.func_905_b();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getEntityBrightness(var1), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(!this.mc.gameSettings.thirdPersonView && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * var1;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /*GL_BLEND*/);
GuiIngame.rand.setSeed((long)(this.updateCounter * 312871));
int var15;
int var17;
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/gui/icons.png"));
if(this.mc.playerController.shouldDrawHUD()) {
//Armor Bar Begin
mainScreen.getArmorBar().render();
//Armor Bar End
//Health Bar Begin
mainScreen.getHealthBar().render();
//Health Bar End
//Bubble Bar Begin
mainScreen.getBubbleBar().render();
//Bubble Bar End
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for(var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, var1);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
}
if(this.mc.thePlayer.func_22060_M() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.func_22060_M();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
mainScreen.render();
String var23;
if(this.mc.playerController.shouldDrawHUD() && this.mc.gameSettings.showDebugInfo) {
GL11.glPushMatrix();
if(Minecraft.hasPaidCheckTime > 0L) {
GL11.glTranslatef(0.0F, 32.0F, 0.0F);
}
if (this.mc.gameSettings.fastDebugMode != 2) {
font.drawStringWithShadow("Minecraft Beta 1.7.3 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.func_6262_n(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.func_21002_o(), 2, 42, 16777215);
long maxMem = Runtime.getRuntime().maxMemory();
long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long usedMem = (maxMem - freeMem);
String os = System.getProperty("os.name");
if (os != null && os.toLowerCase().contains("win")) {
usedMem *= 2; //Windows underreports used memory
usedMem += 1024L * 100;
}
var23 = "Used memory: " + ((int)((usedMem / (float)maxMem) * 100f)) + "% (" + usedMem / 1024L / 1024L + "MB) of " + totalMem / 1024L / 1024L + "MB";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 2, 14737632);
var23 = "Allocated memory: " + totalMem * 100L / maxMem + "% (" + totalMem / 1024L / 1024L + "MB)";
this.drawString(font, var23, screenWidth - font.getStringWidth(var23) - 2, 12, 14737632);
//No Cheating!
int offset = 0;
if (SpoutClient.getInstance().isCheatMode()) {
this.drawString(font, "x: " + this.mc.thePlayer.posX, 2, 64, 14737632);
this.drawString(font, "y: " + this.mc.thePlayer.posY, 2, 72, 14737632);
this.drawString(font, "z: " + this.mc.thePlayer.posZ, 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
offset = 40;
}
if (mc.isMultiplayerWorld() && SpoutClient.getInstance().isSpoutEnabled()) {
this.drawString(font, "Spout Map Data Cache Info:", 2, 64 + offset, 0xE0E000);
this.drawString(font, "Average packet size: " + ChunkCache.averageChunkSize.get() + " bytes", 2, 72 + offset, 14737632);
this.drawString(font, "Cache hit percent: " + ChunkCache.hitPercentage.get(), 2, 80 + offset, 14737632);
long currentTime = System.currentTimeMillis();
long downBandwidth = (8 * ChunkCache.totalPacketDown.get()) / (currentTime - ChunkCache.loggingStart.get());
long upBandwidth = (8 * ChunkCache.totalPacketUp.get()) / (currentTime - ChunkCache.loggingStart.get());
this.drawString(font, "Bandwidth (Up): " + Math.max(1, upBandwidth) + "kbps", 2, 88 + offset, 14737632);
this.drawString(font, "Bandwidth (Down): " + Math.max(1, downBandwidth) + "kbps", 2, 96 + offset, 14737632);
}
}
else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
GL11.glPopMatrix();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - var1;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
if (this.mc.playerController.shouldDrawHUD() && chatTextWidget.isVisible()) {
int viewedLine = 0;
for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size() - 1, (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
opacity *= 10D;
if(opacity < 0.0D) {
opacity = 0.0D;
}
if(opacity > 1.0D) {
opacity = 1.0D;
}
opacity *= opacity;
int color = chatOpen ? 255 : (int)(255D * opacity);
if (color > 0) {
int x = 2;
int y = -viewedLine * 9;
String chat = chatMessageList.get(line).message;
chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
chat = ChatManager.formatUrl(chat);
//TODO add support for opening URL in browser if clicked?
drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
GL11.glEnable(3042 /*GL_BLEND*/);
font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
}
viewedLine++;
}
}
}
GL11.glPopMatrix();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.field_35384_x.field_35965_e) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.field_35786_c;
int var40 = var41.field_35785_d;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
int var18 = (screenWidth - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiSavingLevelString var50 = (GuiSavingLevelString)var44.get(var20);
font.drawStringWithShadow(var50.field_35624_a, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.field_35623_b < 0) {
var54 = 5;
} else if(var50.field_35623_b < 150) {
var54 = 0;
} else if(var50.field_35623_b < 300) {
var54 = 1;
} else if(var50.field_35623_b < 600) {
var54 = 2;
} else if(var50.field_35623_b < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
|
diff --git a/okapi/filters/openxml/src/main/java/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java b/okapi/filters/openxml/src/main/java/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
index 0ed111d7e..aea06c12a 100644
--- a/okapi/filters/openxml/src/main/java/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
+++ b/okapi/filters/openxml/src/main/java/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
@@ -1,1989 +1,1995 @@
/*===========================================================================
Copyright (C) 2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.filters.openxml;
//import org.apache.log4j.BasicConfigurator;
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
import java.io.*;
import java.net.URL;
import java.util.Hashtable;
//import java.util.Iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
//import java.util.TreeMap; // DWH 10-10-08
import java.util.logging.Level;
import java.util.logging.Logger;
import net.htmlparser.jericho.EndTag;
//import net.htmlparser.jericho.EndTagType;
import net.htmlparser.jericho.Segment;
//import net.htmlparser.jericho.StartTagType;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.CharacterReference;
import net.htmlparser.jericho.StartTag;
import net.htmlparser.jericho.StartTagType;
import net.htmlparser.jericho.Tag;
//import net.sf.okapi.common.encoder.IEncoder;
import net.sf.okapi.common.encoder.EncoderManager;
import net.sf.okapi.common.exceptions.OkapiIOException;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.MimeTypeMapper;
import net.sf.okapi.common.filters.FilterConfiguration;
import net.sf.okapi.common.filters.PropertyTextUnitPlaceholder;
import net.sf.okapi.filters.abstractmarkup.AbstractMarkupFilter;
import net.sf.okapi.filters.yaml.TaggedFilterConfiguration;
import net.sf.okapi.filters.yaml.TaggedFilterConfiguration.RULE_TYPE;
import net.sf.okapi.common.resource.Code;
import net.sf.okapi.common.resource.DocumentPart;
import net.sf.okapi.common.resource.Property;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.TextFragment;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.common.resource.TextFragment.TagType;
import net.sf.okapi.common.skeleton.GenericSkeleton;
/**
* <p>Filters Microsoft Office Word, Excel, and Powerpoint Documents.
* OpenXML is the format of these documents.
*
* <p>Since OpenXML files are Zip files that contain XML documents,
* <b>OpenXMLFilter</b> handles opening and processing the zip file, and
* instantiates this filter to process the XML documents.
*
* <p>This filter extends AbstractBaseMarkupFilter, which extends
* AbstractBaseFilter. It uses the Jericho parser to analyze the
* XML files.
*
* <p>The filter exhibits slightly differnt behavior depending on whether
* the XML file is Word, Excel, Powerpoint, or a chart in Word. The
* tags in these files are configured in yaml configuration files that
* specify the behavior of the tags. These configuration files are
* <p><li>wordConfiguration.yml
* <li>excelConfiguration.yml
* <li>powerpointConfiguration.yml
* <li>wordChartConfiguration.yml
*
* In Word and Powerpoint, text is always surrounded by paragraph tags
* <w:p> or <a:p>, which signal the beginning and end of the text unit
* for this filter, and are marked as TEXT_UNIT_ELEMENTs in the configuration
* files. Inside these are one or more text runs surrounded by <w:r> or <a:r>
* tags and marked as TEXT_RUN_ELEMENTS by the configuration files. The text
* itself occurs between text marker tags <w:t> or <a:t> tags, which are
* designated TEXT_MARKER_ELEMENTS by the configuration files. Tags between
* and including <w:r> and <w:t> (which usually include a <w:rPr> tag sequence
* for character style) are consolidated into a single MARKER_OPENING code. Tags
* between and including </w:t> and </w:r>, which sometimes include graphics
* tags, are consolidated into a single MARKER_CLOSING code. If there is no
* text between <w:r> and </w:r>, a single MARKER_PLACEHOLDER code is created
* for the text run. If there is no character style information,
* <w:r><w:t>text</w:t></w:r> is not surrounded by MARKER_OPENING or
* MARKER_CLOSING codes, to simplify things for translators; these are supplied
* by OpenXMLContentSkeletonWriter during output. The same is true for text
* runs marked by <a:r> and <a:t> in Powerpoint files.
*
* Excel files are simpler, and only mark text by <v>, <t>, and <text> tags
* in worksheet, sharedString, and comment files respectively. These tags
* work like TEXT_UNIT, TEXT_RUN, and TEXT_MARKER elements combined.
*/
public class OpenXMLContentFilter extends AbstractMarkupFilter {
private Logger LOGGER=null;
public final static int MSWORD=1;
public final static int MSEXCEL=2;
public final static int MSPOWERPOINT=3;
public final static int MSWORDCHART=4; // DWH 4-16-09
public final static int MSEXCELCOMMENT=5; // DWH 5-13-09
public final static int MSWORDDOCPROPERTIES=6; // DWH 5-25-09
private int configurationType;
// private Package p=null;
private int filetype=MSWORD; // DWH 4-13-09
private String sConfigFileName; // DWH 10-15-08
private URL urlConfig; // DWH 3-9-09
private Hashtable<String,String> htXMLFileType=null;
private String sInsideTextBox = ""; // DWH 7-23-09 textbox
private boolean bInTextBox = false; // DWH 7-23-09 textbox
private boolean bInTextRun = false; // DWH 4-10-09
private boolean bInSubTextRun = false; // DWH 4-10-09
private boolean bInDeletion = false; // DWH 5-8-09 <w:del> deletion in tracking mode in Word
private boolean bInInsertion = false; // DWH 5-8-09 <w:ins> insertion in tracking mode in Word
private boolean bBetweenTextMarkers=false; // DWH 4-14-09
private boolean bAfterText = false; // DWH 4-10-09
private TextRun trTextRun = null; // DWH 4-10-09
private TextRun trNonTextRun = null; // DWH 5-5-09
private boolean bIgnoredPreRun = false; // DWH 4-10-09
private boolean bBeforeFirstTextRun = true; // DWH 4-15-09
private boolean bInMainFile = false; // DWH 4-15-09
private boolean bInSettingsFile = false; // DWH 4-12-10
private boolean bExcludeTextInRun = false; // DWH 5-27-09
private boolean bExcludeTextInUnit = false; // DWH 5-29-09
private String sCurrentCharacterStyle = ""; // DWH 5-27-09
private String sCurrentParagraphStyle = ""; // DWH 5-27-09
private boolean bPreferenceTranslateWordHidden = false; // DWH 6-29-09
private boolean bPreferenceTranslateExcelExcludeColors = false;
// DWH 6-12-09 don't translate text in Excel in some colors
private boolean bPreferenceTranslateExcelExcludeColumns = false;
// DWH 6-12-09 don't translate text in Excel in some specified columns
private TreeSet<String> tsExcludeWordStyles = null; // DWH 5-27-09 set of styles to exclude from translation
private TreeSet<String> tsExcelExcludedStyles; // DWH 6-12-09
private TreeSet<String> tsExcelExcludedColumns; // DWH 6-12-09
private TreeMap<Integer,ExcelSharedString> tmSharedStrings=null; // DWH 6-13-09
private boolean bInExcelSharedStringCell=false; // DWH 6-13-09
private boolean bExcludeTranslatingThisExcelCell=false; // DWH 6-13-09
private int nOriginalSharedStringCount=0; // DWH 6-13-09
private int nNextSharedStringCount=0; // DWH 6-13-09
private int nCurrentSharedString=-1; // DWH 6-13-09 if nonzero, text may be excluded from translation
private String sCurrentExcelSheet=""; // DWH 6-25-09 current sheet number
private YamlParameters params=null; // DWH 7-16-09
private TaggedFilterConfiguration config=null; // DWH 7-16-09
private RawDocument rdSource; // Textbox
private EncoderManager internalEncManager; // The encoderManager of the base class is not used
private String endpara=""; // DWH 8-17-09
private boolean bInPowerpointEndPara; // DWH 8-17-09
private String sEndTxbxContent=""; // DWH 10-23-09
public OpenXMLContentFilter() {
super(); // 1-6-09
setMimeType(MimeTypeMapper.XML_MIME_TYPE);
setFilterWriter(createFilterWriter());
tsExcludeWordStyles = new TreeSet<String>();
internalEncManager = new EncoderManager(); // DWH 5-14-09
internalEncManager.setMapping(MimeTypeMapper.XML_MIME_TYPE, "net.sf.okapi.common.encoder.XMLEncoder");
internalEncManager.setMapping(MimeTypeMapper.DOCX_MIME_TYPE, "net.sf.okapi.common.encoder.OpenXMLEncoder");
// internalEncManager.setAllKnownMappings();
internalEncManager.setDefaultOptions(null, "utf-8", "\n"); // DWH 5-14-09
internalEncManager.updateEncoder(MimeTypeMapper.DOCX_MIME_TYPE); // DWH 5-14-09
}
public List<FilterConfiguration> getConfigurations () {
List<FilterConfiguration> list = new ArrayList<FilterConfiguration>();
list.add(new FilterConfiguration(getName(),
getMimeType(),
getClass().getName(),
"Microsoft OpenXML Document",
"Microsoft OpenXML files (Used inside Office documents)."));
return list;
}
/**
* Logs information about the event fir the log level is FINEST.
* @param event event to log information about
*/
public void displayOneEvent(Event event) // DWH 4-22-09 LOGGER
{
Set<String> setter;
if (LOGGER.isLoggable(Level.FINEST))
{
String etyp=event.getEventType().toString();
if (event.getEventType() == EventType.TEXT_UNIT) {
// assertTrue(event.getResource() instanceof TextUnit);
} else if (event.getEventType() == EventType.DOCUMENT_PART) {
// assertTrue(event.getResource() instanceof DocumentPart);
} else if (event.getEventType() == EventType.START_GROUP
|| event.getEventType() == EventType.END_GROUP) {
// assertTrue(event.getResource() instanceof StartGroup || event.getResource() instanceof Ending);
}
if (etyp.equals("START"))
LOGGER.log(Level.FINEST,"\n");
LOGGER.log(Level.FINEST,etyp + ": ");
if (event.getResource() != null) {
LOGGER.log(Level.FINEST,"(" + event.getResource().getId()+")");
if (event.getResource() instanceof DocumentPart) {
setter = ((DocumentPart) event.getResource()).getSourcePropertyNames();
for(String seti : setter)
LOGGER.log(Level.FINEST,seti);
} else {
LOGGER.log(Level.FINEST,event.getResource().toString());
}
if (event.getResource().getSkeleton() != null) {
LOGGER.log(Level.FINEST,"*Skeleton: \n" + event.getResource().getSkeleton().toString());
}
}
}
}
/**
* Sets the name of the Yaml configuration file for the current file type, reads the file, and sets the parameters.
* @param filetype type of XML in the current file
*/
public void setUpConfig(int filetype)
{
this.filetype = filetype; // DWH 5-13-09
switch(filetype)
{
case MSWORDCHART:
sConfigFileName = "/net/sf/okapi/filters/openxml/wordChartConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSWORDCHART;
break;
case MSEXCEL:
sConfigFileName = "/net/sf/okapi/filters/openxml/excelConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSEXCEL;
break;
case MSPOWERPOINT:
sConfigFileName = "/net/sf/okapi/filters/openxml/powerpointConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSPOWERPOINT;
break;
case MSEXCELCOMMENT: // DWH 5-13-09
sConfigFileName = "/net/sf/okapi/filters/openxml/excelCommentConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSEXCEL;
break;
case MSWORDDOCPROPERTIES: // DWH 5-13-09
sConfigFileName = "/net/sf/okapi/filters/openxml/wordDocPropertiesConfiguration.yml"; // DWH 5-25-09
configurationType = MSWORDDOCPROPERTIES;
break;
case MSWORD:
default:
sConfigFileName = "/net/sf/okapi/filters/openxml/wordConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSWORD;
break;
}
urlConfig = OpenXMLContentFilter.class.getResource(sConfigFileName); // DWH 3-9-09
config = new TaggedFilterConfiguration(urlConfig);
// setDefaultConfig(urlConfig); // DWH 7-16-09 no longer needed; AbstractMarkup now calls getConfig everywhere
try
{
setParameters(new YamlParameters(urlConfig));
// DWH 3-9-09 it doesn't update automatically from setDefaultConfig 7-16-09 YamlParameters
}
catch(Exception e)
{
throw new OkapiIOException("Can't read MS Office Filter Configuration File.");
}
}
/**
* Combines contiguous compatible text runs, in order to simplify the inline tags presented
* to a user. Note that MSWord can have embedded <w:r> elements for ruby text. Note
* that Piped streams are used which use a separate thread for this processing.
* @param in input stream of the XML file
* @param in piped output stream for the "squished" output
* @return a PipedInputStream used for further processing of the file
*/
public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
final OutputStreamWriter osw;
final BufferedWriter bw;
final InputStreamReader isr;
final BufferedReader br;
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
osw = new OutputStreamWriter(pios,"UTF-8");
bw = new BufferedWriter(osw);
isr = new InputStreamReader(in,"UTF-8");
br = new BufferedReader(isr);
}
catch (IOException e)
{
throw new OkapiIOException("Can't read piped input stream.");
}
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
boolean bHaveACRInsideR=false; // DWH 11-09-09 don't collapse if have a carriage return in style
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
- bInsideNastyTextBox = true;
+ if (!isAStandaloneTug(tug))
+ bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp = ""; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (tugname.equals("w:cr"))
{
bHaveACRInsideR = true;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text) && !bHaveACRInsideR) // DWH 11-09-09 bHaveACRInsideR
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
- try
- {
- bw.write(s);
- LOGGER.log(Level.FINEST,s); //
- } catch (IOException e) {
- LOGGER.log(Level.WARNING,"Problem writing piped stream.");
-// throw new OkapiIOException("Can't read piped input.");
- s = s + " ";
- }
+ try
+ {
+ bw.write(s);
+ LOGGER.log(Level.FINEST,s); //
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING,"Problem writing piped stream.");
+ // throw new OkapiIOException("Can't read piped input.");
+ s = s + " ";
+ }
+ }
+ private boolean isAStandaloneTug(String tug)
+ {
+ int len=tug.length();
+ return(tug.substring(len-2, len).equals("/>") ? true : false);
}
});
readThread.start();
return piis;
}
/**
* Adds CDATA as a DocumentPart
* @param a tag containing the CDATA
*/
protected void handleCdataSection(Tag tag) { // 1-5-09
if (bInDeletion) // DWH 5-8-09
addToNonTextRun(tag.toString());
else
addToDocumentPart(tag.toString());
}
/**
* Handles text. If in a text run, it ends the text run and
* adds the tags that were in it as a single MARKER_OPENING code.
* This would correspond to <w:r>...<w:t> in MSWord. It will
* then start a new text run anticipating </w:t>...</w:r>. If
* text is found that was not in a text run, i.e. it was not between
* text markers, it is not text to be processed by a user, so it
* becomes part of a new text run which will become part of a
* code. If the text is not in a text unit, then it is added to a
* document part.
* @param text the text to be handled
*/
@Override
protected void handleText(Segment text) {
if (text==null) // DWH 4-14-09
return;
String txt=text.toString();
handleSomeText(txt,text.isWhiteSpace()); // DWH 5-14-09
}
private void handleSomeText(String tixt, boolean bWhiteSpace) // DWH 6-25-09 tixt was txt
{
String txt=tixt; // DWH 6-25-09 added this so txt can be changed for Excel index to shared strings
if (bInDeletion) // DWH 5-8-09
{
addToNonTextRun(txt);
return;
}
// if in excluded state everything is skeleton including text
if (getRuleState().isExludedState()) {
addToDocumentPart(txt);
return;
}
if (bInTextBox)
{
sInsideTextBox += txt;
return;
}
// check for need to modify index in Excel cell pointing to a shared string
if (bInExcelSharedStringCell)
// DWH 6-13-09 Excel options; true if in sheet cell pointing to a shared string
// only possible if (bPreferenceTranslateExcelExcludeColors || bPreferenceTranslateExcelExcludeColumns)
// and this cell is marked as containing a shared string
{
int nSharedStringNumber=-1;
try
{
nSharedStringNumber = new Integer(txt).intValue();
}
catch(Exception e) {};
if (nSharedStringNumber>=0 && nSharedStringNumber<nNextSharedStringCount)
{
ExcelSharedString ess = tmSharedStrings.get(nSharedStringNumber);
if (!ess.getBEncountered()) // first time this string seen in sheets
{
ess.setBEncountered(true);
ess.setBTranslatable(!bExcludeTranslatingThisExcelCell);
}
else if (ess.getBTranslatable() != !bExcludeTranslatingThisExcelCell)
// this shared string should be translated in some columns but not others
{
int oppnum = ess.getNIndex();
if (oppnum > -1) // this already has a shared string elsewhere
txt = (new Integer(oppnum)).toString();
else
{
ExcelSharedString newess = // create twin with opposite translatable status
new ExcelSharedString(true,!bExcludeTranslatingThisExcelCell,nSharedStringNumber,"");
tmSharedStrings.put(new Integer(nNextSharedStringCount),newess); // add twin to list
txt = (new Integer(nNextSharedStringCount)).toString(); // DWH 6-25-09 !!! replace index to shared string with new one pointing to a copy
ess.setNIndex(nNextSharedStringCount++); // point current one to new twin
}
}
}
}
// check for ignorable whitespace and add it to the skeleton
// The Jericho html parser always pulls out the largest stretch of text
// so standalone whitespace should always be ignorable if we are not
// already processing inline text
// if (text.isWhiteSpace() && !isInsideTextRun()) {
if (bWhiteSpace && !isInsideTextRun()) {
addToDocumentPart(txt);
return;
}
if (canStartNewTextUnit())
{
// if (bBetweenTextMarkers)
// startTextUnit(txt);
// else
addToDocumentPart(txt);
}
else
{
if (bInTextRun) // DWH 4-20-09 whole if revised
{
if (bBetweenTextMarkers)
{
if (filetype==MSEXCEL && txt!=null && txt.length()>0 && txt.charAt(0)=='=')
addToTextRun(txt); // DWH 5-13-09 don't treat Excel formula as text to be translated
else if (bExcludeTextInRun || bExcludeTextInUnit) // DWH 5-29-09 don't treat as text if excluding text
addToTextRun(internalEncManager.encode(txt,0)); // DWH 8-7-09 still have to encode text if not in text unit
else if (nCurrentSharedString>0 && nCurrentSharedString<nNextSharedStringCount)
// DWH 6-13-09 in Excel Shared Strings File, only if some shared strings excluded from translation
{
ExcelSharedString ess = tmSharedStrings.get(new Integer(nCurrentSharedString));
ess.setS(txt);
int oppEssNum = ess.getNIndex();
if (oppEssNum>-1 && oppEssNum<nNextSharedStringCount)
{
ExcelSharedString oppess = tmSharedStrings.get(new Integer(oppEssNum));
oppess.setS(txt);
}
if (ess.getBTranslatable()) // if this sharedString is translatable, add as text
{
addTextRunToCurrentTextUnit(false); // adds a code for the preceding text run
bAfterText = true;
addToTextUnit(txt); // adds the text
trTextRun = new TextRun(); // then starts a new text run for a code after the text
bInTextRun = true;
}
else
addToTextRun(internalEncManager.encode(txt,0)); // if not translatable, add as part of code
}
else
{
addTextRunToCurrentTextUnit(false); // adds a code for the preceding text run
bAfterText = true;
addToTextUnit(txt); // adds the text
trTextRun = new TextRun(); // then starts a new text run for a code after the text
bInTextRun = true;
}
}
else
addToTextRun(internalEncManager.encode(txt,0)); // for <w:delText>text</w:delText> don't translate deleted text (will be inside code)
}
else
{
if (bInPowerpointEndPara) // DWH 8-28-09 skip everything in a:endParaRpr
{
endpara += txt;
return;
}
else
{
trTextRun = new TextRun();
bInTextRun = true;
addToTextRun(internalEncManager.encode(txt,0)); // not inside text markers, so this text will become part of a code
}
}
}
}
/**
* Handles a tag that is anticipated to be a DocumentPart. Since everything
* between TEXTUNIT markers is treated as an inline code, if there is a
* current TextUnit, this is added as a code in the text unit.
* @param tag a tag
*/
@Override
protected void handleDocumentPart(Tag tag) {
if (canStartNewTextUnit()) // DWH ifline and whole else: is an inline code if inside a text unit
addToDocumentPart(tag.toString()); // 1-5-09
else if (bInDeletion) // DWH 5-8-09
addToNonTextRun(tag.toString());
else
addCodeToCurrentTextUnit(tag);
}
/**
* Handle all numeric entities. Default implementation converts entity to
* Unicode character.
*
* @param entity
* - the numeric entity
*/
protected void handleCharacterEntity(Segment entity) { // DWH 5-14-09
String decodedText = CharacterReference.decode(entity.toString(), false);
/*
if (!isCurrentTextUnit()) {
startTextUnit();
}
addToTextUnit(decodedText);
*/ if (decodedText!=null && !decodedText.equals("")) // DWH 5-14-09 treat CharacterEntities like other text
handleSomeText(decodedText,false);
}
/**
* Handles a start tag. TEXT_UNIT_ELEMENTs start a new TextUnit. TEXT_RUN_ELEMENTs
* start a new text run. TEXT_MARKER_ELEMENTS set a flag that any following
* text will be between text markers. ATTRIBUTES_ONLY tags have translatable text
* in the attributes, so within a text unit, it is added within a text run; otherwise it
* becomes a DocumentPart.
* @param startTagt the start tag to process
*/
@Override
protected void handleStartTag(StartTag startTag) {
String sTagName;
String sTagString;
String sPartName; // DWH 2-26-09 for PartName attribute in [Content_Types].xml
String sContentType; // DWH 2-26-09 for ContentType attribute in [Content_Types].xml
// if in excluded state everything is skeleton including text
String tempTagType; // DWH 5-7-09
String sTagElementType; // DWH 6-13-09
if (startTag==null) // DWH 4-14-09
return;
if (bInDeletion)
{
addToNonTextRun(startTag);
return;
}
sTagName = startTag.getName(); // DWH 2-26-09
sTagString = startTag.toString(); // DWH 2-26-09
sTagElementType = getConfig().getElementType(sTagName); // DWH 6-13-09
if (bInTextBox) // DWH 7-23-09 textbox
{
if (sTagName.equals("w:txbxcontent")) // DWH 10-22-09 so this won't be an inline code
appendToFirstSkeletonPart(sTagString); // DWH 10-23-09 adds to skeleton of Group element
else
sInsideTextBox += sTagString;
return;
}
if (bInPowerpointEndPara) // DWH 8-27-09 skip everything in a:endParaRpr
{
endpara += sTagString;
return;
}
if (getRuleState().isExludedState()) {
addToDocumentPart(sTagString);
// process these tag types to update parser state
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case EXCLUDED_ELEMENT:
getRuleState().pushExcludedRule(sTagName);
break;
case INCLUDED_ELEMENT:
getRuleState().pushIncludedRule(sTagName);
break;
case PRESERVE_WHITESPACE:
getRuleState().pushPreserverWhitespaceRule(sTagName);
break;
}
return;
}
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case INLINE_ELEMENT:
if (canStartNewTextUnit()) {
if (sTagElementType.equals("style")) // DWH 6-13-09
// DWH 5-27-09 to exclude hidden styles
sCurrentCharacterStyle = startTag.getAttributeValue("w:styleId");
else if (sTagElementType.equals("hidden")) // DWH 6-13-09
// DWH 5-27-09 to exclude hidden styles
{
if (!sCurrentCharacterStyle.equals(""))
excludeStyle(sCurrentCharacterStyle);
}
else if (sTagElementType.equals("excell")) // DWH 6-13-09 cell in Excel sheet
{
if (bPreferenceTranslateExcelExcludeColors || bPreferenceTranslateExcelExcludeColumns)
bExcludeTranslatingThisExcelCell = evaluateSharedString(startTag);
}
else if (sTagElementType.equals("sharedstring")) // DWH 6-13-09 shared string in Excel
nCurrentSharedString++;
else if (sTagElementType.equals("count")) // DWH 6-13-09 shared string count in Excel
{
sTagString = newSharedStringCount(sTagString);
}
addToDocumentPart(sTagString);
}
else
{
if (sTagElementType.equals("rstyle")) // DWH 6-13-09 text run style
// DWH 5-29-09 in a text unit, some styles shouldn't be translated
{
sCurrentCharacterStyle = startTag.getAttributeValue("w:val");
// if (tsExcludeWordStyles.contains(sCurrentCharacterStyle))
if (containsAString(tsExcludeWordStyles,sCurrentCharacterStyle))
bExcludeTextInRun = true;
}
else if (sTagElementType.equals("pstyle")) // DWH 6-13-09 text unit style
// DWH 5-29-09 in a text unit, some styles shouldn't be translated
{
sCurrentParagraphStyle = startTag.getAttributeValue("w:val");
// if (tsExcludeWordStyles.contains(sCurrentParagraphStyle))
if (containsAString(tsExcludeWordStyles,sCurrentParagraphStyle))
bExcludeTextInUnit = true;
}
else if (sTagElementType.equals("hidden") &&
!bPreferenceTranslateWordHidden)
// DWH 6-13-09 to exclude hidden styles
{
if (bInTextRun)
bExcludeTextInRun = true;
else
bExcludeTextInUnit = true;
}
if (bInTextRun) // DWH 4-9-09
addToTextRun(startTag);
else // DWH 5-7-09
{
if (sTagElementType.equals("delete")) // DWH 6-13-09
bInDeletion = true;
addToNonTextRun(startTag); // DWH 5-5-09
}
}
break;
case ATTRIBUTES_ONLY:
// we assume we have already ended any (non-complex) TextUnit in
// the main while loop above
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
if (canStartNewTextUnit()) // DWH 2-14-09 document part just created is part of inline codes
{
propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); // 1-29-09
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { // 1-29-09
startDocumentPart(sTagString, sTagName, propertyTextUnitPlaceholders);
// DWH 1-29-09
endDocumentPart();
} else {
// no attributes that need processing - just treat as skeleton
addToDocumentPart(sTagString);
}
}
else
{
propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); // 1-29-09
if (sTagElementType.equals("a:endpararpr")) // DWH 8-17-09 for Powerpoint a:endParaRpr
{
endpara += sTagString;
if (!startTag.isSyntacticalEmptyElementTag()) // if not standalone tag, ignore tags until end tag
bInPowerpointEndPara = true;
}
else if (bInTextRun) // DWH 4-10-09
addToTextRun(startTag,propertyTextUnitPlaceholders);
else
addToNonTextRun(startTag,propertyTextUnitPlaceholders);
}
break;
case GROUP_ELEMENT:
if (!bInSettingsFile) // DWH 4-12-10 else is for <v:textbox ...> in settings.xml file
{
if (!startTag.isSyntacticalEmptyElementTag()) // DWH 4-21-10 for <v:textbox .../>
{
if (!canStartNewTextUnit()) // DWH 6-29-09 for text box: embedded text unit
{
bInTextBox = true; // DWH 7-23-09 textbox
sInsideTextBox = ""; // DWH 7-23-09 textbox
addTextRunToCurrentTextUnit(true); // DWH 7-29-09 add text run stuff as a placeholder
}
getRuleState().pushGroupRule(sTagName);
startGroup(new GenericSkeleton(sTagString),"textbox");
}
else if (canStartNewTextUnit()) // DWH 6-29-09
addToDocumentPart(sTagString); // DWH 6-29-09
else if (bInTextRun) // DWH 6-29-09
addToTextRun(sTagString); // DWH 6-29-09
else // DWH 6-29-09
addToNonTextRun(sTagString); // DWH 6-29-09
}
else
addToDocumentPart(sTagString); // DWH 4-12-10 for <v:textbox ...> in settings.xml file
break;
case EXCLUDED_ELEMENT:
getRuleState().pushExcludedRule(sTagName);
addToDocumentPart(sTagString);
break;
case INCLUDED_ELEMENT:
getRuleState().pushIncludedRule(sTagName);
addToDocumentPart(sTagString);
break;
case TEXT_UNIT_ELEMENT:
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09 trNonTextRun should be null at this point
bBeforeFirstTextRun = true; // DWH 5-5-09 addNonTextRunToCurrentTextUnit sets it false
// if (startTag.isSyntacticalEmptyElementTag()) // means the tag ended with />
if (sTagString.endsWith("/>")) // DWH 3-18-09 in case text unit element is a standalone tag (weird, but Microsoft does it)
addToDocumentPart(sTagString); // 1-5-09
else
{
getRuleState().pushTextUnitRule(sTagName);
startTextUnit(new GenericSkeleton(sTagString)); // DWH 1-29-09
if (configurationType==MSEXCEL ||
configurationType==MSWORDCHART ||
configurationType==MSWORDDOCPROPERTIES)
// DWH 4-16-09 Excel and Word Charts don't have text runs or text markers
{
bInTextRun = true;
bBetweenTextMarkers = true;
}
else
{
bInTextRun = false;
bBetweenTextMarkers = false;
}
}
break;
case TEXT_RUN_ELEMENT: // DWH 4-10-09 smoosh text runs into single <x>text</x>
bExcludeTextInRun = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (canStartNewTextUnit()) // DWH 5-5-09 shouldn't happen
addToDocumentPart(sTagString);
else
{
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
bBeforeFirstTextRun = false; // DWH 5-5-09
if (getConfig().getElementType(sTagName).equals("insert")) // DWH 5-8-09 w:ins
bInInsertion = true;
else if (bInTextRun)
bInSubTextRun = true;
else
{
bInTextRun = true;
bAfterText = false;
bIgnoredPreRun = false;
bBetweenTextMarkers = false; // DWH 4-16-09
}
addToTextRun(startTag);
}
break;
case TEXT_MARKER_ELEMENT: // DWH 4-14-09 whole case
if (canStartNewTextUnit()) // DWH 5-5-09 shouldn't happen
addToDocumentPart(sTagString);
else
{
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
if (bInTextRun)
{
bBetweenTextMarkers = true;
addToTextRun(startTag);
}
else
addToNonTextRun(sTagString);
}
break;
case PRESERVE_WHITESPACE:
getRuleState().pushPreserverWhitespaceRule(sTagName);
addToDocumentPart(sTagString);
break;
default:
if (sTagName.equals("override")) // DWH 2-26-09 in [Content_Types].xml
{ // it could be slow to do this test every time; I wonder if there is a better way
sPartName = startTag.getAttributeValue("PartName");
sContentType = startTag.getAttributeValue("ContentType");
if (htXMLFileType!=null)
htXMLFileType.put(sPartName, sContentType);
}
if (canStartNewTextUnit()) // DWH 1-14-09 then not currently in text unit; added else
addToDocumentPart(sTagString); // 1-5-09
else if (bInTextRun) // DWH 4-10-09
addToTextRun(startTag);
else
addToNonTextRun(startTag); // DWH 5-5-09
}
}
/**
* Handles end tags. These either add to current text runs
* or end text runs or text units as appropriate.
* @param endTag the end tag to process
*/
@Override
protected void handleEndTag(EndTag endTag) {
// if in excluded state everything is skeleton including text
String sTagName; // DWH 2-26-09
String sTagString; // DWH 4-14-09
String tempTagType; // DWH 5-5-09
String sTagElementType; // DWH 6-13-09
String s; // temporary string
DocumentPart dippy; // DWH 7-28-09 textbox
GenericSkeleton skel; // DWH 7-28-09 textbox
TextUnit tu; // DWH 7-28-09 textbox
int dpid; // DWH 7-28-09 textbox
WordTextBox wtb = null; // DWH 7-23-09 textbox
ArrayList<Event> textBoxEventList=null; // DWH 7-23-09 textbox
Event event; // DWH 7-23-09 textbox
OpenXMLContentFilter tboxcf; // DWH 7-23-09
int nTextBoxLevel; // DWH 1-27-09
if (endTag==null) // DWH 4-14-09
return;
sTagName = endTag.getName(); // DWH 2-26-09
sTagElementType = getConfig().getElementType(sTagName); // DWH 6-13-09
if (bInDeletion)
{
addToNonTextRun(endTag);
if (sTagElementType.equals("delete")) // DWH 6-13-09
{
bInDeletion = false;
}
return;
}
sTagString = endTag.toString(); // DWH 2-26-09
if (getRuleState().isExludedState()) {
addToDocumentPart(sTagString); // DWH 7-16-09
// process these tag types to update parser state
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case EXCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
break;
case INCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
break;
case PRESERVE_WHITESPACE:
getRuleState().popPreserverWhitespaceRule();
break;
}
return;
}
if (bInTextBox && getConfig().getMainRuleType(sTagName)!=RULE_TYPE.GROUP_ELEMENT)
{
if (sTagName.equals("w:txbxcontent")) // DWH 10-22-09 so this won't be an inline code
sEndTxbxContent = sTagString;
else
sInsideTextBox += sTagString;
return;
}
if (bInPowerpointEndPara) // DWH 8-27-09 skip everything in a:endParaRpr
{
endpara += sTagString;
if (sTagElementType.equals("a:endpararpr")) // DWH 8-27-09 for Powerpoint a:endParaRpr
bInPowerpointEndPara = false;
return;
}
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case INLINE_ELEMENT:
if (canStartNewTextUnit())
{
addToDocumentPart(sTagString); // DWH 5-29-09
if (sTagElementType.equals("sharedstring")) // DWH 6-13-09 shared string in Excel
{
if (nCurrentSharedString==nOriginalSharedStringCount-1) // this is the last original shared string
{
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09 trNonTextRun should be null at this point
bBeforeFirstTextRun = true; // DWH 5-5-09 addNonTextRunToCurrentTextUnit sets it false
bInTextRun = false;
bBetweenTextMarkers = false;
for(int i=nCurrentSharedString+1;i<nNextSharedStringCount;i++)
{
ExcelSharedString ess = tmSharedStrings.get(new Integer(i));
String txt = ess.getS();
if (ess.getBTranslatable())
{
startTextUnit(new GenericSkeleton("<si><t>"));
addToTextUnit(txt);
endTextUnit(new GenericSkeleton("</t></si>"));
}
else
addToDocumentPart("<si><t>"+txt+"</t></si>");
}
nCurrentSharedString = -1; // reset so other text will translate; see handleText
}
}
}
else if (bInTextRun) // DWH 5-29-09
addToTextRun(endTag);
else if (sTagElementType.equals("delete")) // DWH 5-7-09 6-13-09
{
if (trNonTextRun!=null)
addNonTextRunToCurrentTextUnit();
addToTextUnitCode(TextFragment.TagType.CLOSING, sTagString, "delete"); // DWH 5-7-09 adds as opening d
}
else if (sTagElementType.equals("excell")) // DWH 6-13-09 cell in Excel sheet
{
bInExcelSharedStringCell = false;
addToDocumentPart(sTagString);
}
else
addToNonTextRun(endTag); // DWH 5-5-09
break;
case GROUP_ELEMENT:
if (!bInSettingsFile) // DWH 4-12-10 else is for <v:textbox in settings.xml
{
if (sInsideTextBox.length()>0)
{
wtb = new WordTextBox();
tboxcf = wtb.getTextBoxOpenXMLContentFilter();
wtb.open(sInsideTextBox, getSrcLoc());
tboxcf.setUpConfig(MSWORD);
tboxcf.setTextUnitId(getTextUnitId()); // set min textUnitId so no overlap
tboxcf.setDocumentPartId(getDocumentPartId()); // set min documentPartId so no overlap
textBoxEventList = wtb.doEvents();
for(Iterator<Event> it=textBoxEventList.iterator() ; it.hasNext();)
{
event = it.next();
if (event.getEventType()==EventType.TEXT_UNIT) // DWH 10-27-09 property for being in text box
{
TextUnit txu = (TextUnit) event.getResource();
Property prop = txu.getProperty("TextBoxLevel");
if (prop==null)
txu.setProperty(new Property("TextBoxLevel","1",false));
else
{
nTextBoxLevel = 0;
try
{
nTextBoxLevel = Integer.parseInt(prop.getValue());
}
catch(Exception e) {}
nTextBoxLevel++; // if it was already in a text box, increase the level by 1
prop.setValue((new Integer(nTextBoxLevel)).toString());
}
}
addFilterEvent(event); // add events from WordTextBox before EndGroup event
}
setTextUnitId(tboxcf.getTextUnitId());
// set current TextUnitId to next one not used inside textbox
setDocumentPartId(tboxcf.getDocumentPartId());
// set current DocumentPartId to next one not used inside textbox
// Note: if this class ever uses startGroupId, endGroupId, subDocumentId or documentId
// they will need to be set as textUnitId and documentPartId above and here
}
bInTextBox = false;
sInsideTextBox = "";
getRuleState().popGroupRule();
endGroup(new GenericSkeleton(sEndTxbxContent+sTagString)); // DWH 10-23-09 added sEndTxbxContent
sEndTxbxContent = ""; // DWH 10-23-09
}
else
{
addToDocumentPart(sTagString); // DWH 4-12-10 for <v:textbox in settings.xml
}
break;
case EXCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
addToDocumentPart(sTagString);
break;
case INCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
addToDocumentPart(sTagString);
break;
case TEXT_UNIT_ELEMENT:
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (bInTextRun)
{
addTextRunToCurrentTextUnit(true);
bInTextRun = false;
} // otherwise this is an illegal element, so just ignore it
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
bBetweenTextMarkers = true; // DWH 4-16-09 ???
getRuleState().popTextUnitRule();
endTextUnit(new GenericSkeleton(endpara+sTagString)); // DWH 8-17-09
endpara = ""; // DWH 8-17-09 for Powerpoint a:endParaRpr
break;
case TEXT_RUN_ELEMENT: // DWH 4-10-09 smoosh text runs into single <x>text</x>
bExcludeTextInRun = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (canStartNewTextUnit()) // DWH 5-5-09
addToDocumentPart(sTagString);
else
{
addToTextRun(endTag);
if (sTagElementType.equals("insert")) // DWH 6-13-09 end of insertion </w:ins>
{
bInInsertion = false;
addTextRunToCurrentTextUnit(true);
bInTextRun = false;
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
}
else if (bInSubTextRun)
bInSubTextRun = false;
else if (bInTextRun)
{
if (!bInInsertion) // DWH 5-5-09 if inserting, don't end TextRun till end of insertion
{
addTextRunToCurrentTextUnit(true);
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
}
bInTextRun = false;
} // otherwise this is an illegal element, so just ignore it
}
break;
case TEXT_MARKER_ELEMENT: // DWH 4-14-09 whole case
if (canStartNewTextUnit()) // DWH 5-5-09
addToDocumentPart(sTagString);
else if (bInTextRun) // DWH 5-5-09 lacked else
{
bBetweenTextMarkers = false;
addToTextRun(endTag);
}
else
addToNonTextRun(sTagString); // DWH 5-5-09
break;
case PRESERVE_WHITESPACE:
getRuleState().popPreserverWhitespaceRule();
addToDocumentPart(sTagString);
break;
default:
if (canStartNewTextUnit()) // DWH 1-14-09 then not currently in text unit; added else
addToDocumentPart(sTagString); // not in text unit, so add to skeleton
else if (bInTextRun) // DWH 4-9-09
addToTextRun(endTag);
else
addToNonTextRun(endTag); // DWH 5-5-09
break;
}
}
/**
* Treats XML comments as DocumentParts.
* @param tag comment tag
*/
@Override
protected void handleComment(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML doc type declaratons as DocumentParts.
* @param tag doc type declaration tag
*/
@Override
protected void handleDocTypeDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML markup declaratons as DocumentParts.
* @param tag markup declaration tag
*/
@Override
protected void handleMarkupDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML processing instructions as DocumentParts.
* @param tag processing instruction tag
*/
@Override
protected void handleProcessingInstruction(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML server common tags as DocumentParts.
* @param tag server common tag
*/
@Override
protected void handleServerCommon(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats server common escaped tags as DocumentParts.
* @param tag server common escaped tag
*/
@Override
protected void handleServerCommonEscaped(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML declaratons as DocumentParts.
* @param tag XML declaration tag
*/
@Override
protected void handleXmlDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Returns name of the filter.
* @return name of the filter
*/
public String getName() {
return "OpenXMLContentFilter";
}
/**
* Normalizes naming of attributes whose values are the
* encoding or a language name, so that they can be
* automatically changed to the output encoding and output.
* Unfortunately, this hard codes the tags to look for.
* @param attrName name of the attribute
* @param attrValue, value of the attribute
* @param tag tag that contains the attribute
* @return a normalized name for the attribute
*/
@Override
protected String normalizeAttributeName(String attrName, String attrValue, Tag tag) {
// normalize values for HTML
String normalizedName = attrName;
String tagName; // DWH 2-19-09 */
// Any attribute that encodes language should be renamed here to "language"
// Any attribute that encodes locale or charset should be normalized too
/*
// <meta http-equiv="Content-Type"
// content="text/html; charset=ISO-2022-JP">
if (isMetaCharset(attrName, attrValue, tag)) {
normalizedName = HtmlEncoder.NORMALIZED_ENCODING;
return normalizedName;
}
// <meta http-equiv="Content-Language" content="en"
if (tag.getName().equals("meta") && attrName.equals(HtmlEncoder.CONTENT)) {
StartTag st = (StartTag) tag;
if (st.getAttributeValue("http-equiv") != null) {
if (st.getAttributeValue("http-equiv").equals("Content-Language")) {
normalizedName = HtmlEncoder.NORMALIZED_LANGUAGE;
return normalizedName;
}
}
}
*/
// <w:lang w:val="en-US" ...>
tagName = tag.getName();
if (tagName.equals("w:lang") || tagName.equals("w:themefontlang")) // DWH 4-3-09 themeFontLang
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("w:val") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
else if (tagName.equals("c:lang")) // DWH 4-3-09
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("val") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
else if (tagName.equals("a:endpararpr") || tagName.equals("a:rpr"))
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("lang") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
return normalizedName;
}
protected void initFileTypes() // DWH $$$ needed?
{
htXMLFileType = new Hashtable();
}
protected String getContentType(String sPartName) // DWH $$$ needed?
{
String rslt="",tmp;
if (sPartName!=null)
{
tmp = (String)htXMLFileType.get(sPartName);
if (tmp!=null)
rslt = tmp;
}
return(rslt);
}
/**
* Adds a text string to a sequence of tags that are
* not in a text run, that will become a single code.
* @param s the text string to add
*/
private void addToNonTextRun(String s) // DWH 5-5-09
{
if (trNonTextRun==null)
trNonTextRun = new TextRun();
trNonTextRun.append(s);
}
/**
* Adds a tag to a sequence of tags that are
* not in a text run, that will become a single code.
* @param s the text string to add
*/
private void addToNonTextRun(Tag tag) // DWH 5-5-09
{
if (trNonTextRun==null)
trNonTextRun = new TextRun();
trNonTextRun.append(tag.toString());
}
/**
* Adds a tag and codes to a sequence of tags that are
* not in a text run, that will become a single code.
* @param tag the tag to add
* @param propertyTextUnitPlaceholders a list of codes of embedded text
*/
private void addToNonTextRun(Tag tag, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
String txt;
int offset;
if (trNonTextRun==null)
trNonTextRun = new TextRun();
txt=trNonTextRun.getText();
offset=txt.length();
trNonTextRun.appendWithPropertyTextUnitPlaceholders(tag.toString(),offset,propertyTextUnitPlaceholders);
}
/**
* Adds a text string to a text run that will become a single code.
* @param s the text string to add
*/
private void addToTextRun(String s)
{
if (trTextRun==null)
trTextRun = new TextRun();
trTextRun.append(s);
}
/**
* Adds a tag to a text run that will become a single code.
* @param tag the tag to add
*/
private void addToTextRun(Tag tag) // DWH 4-10-09 adds tag text to string that will be part of larger code later
{
// add something here to check if it was bold, italics, etc. to set a property
if (trTextRun==null)
trTextRun = new TextRun();
trTextRun.append(tag.toString());
}
/**
* Adds a tag and codes to a text run that will become a single code.
* @param tag the tag to add
* @param propertyTextUnitPlaceholders a list of codes of embedded text
*/
private void addToTextRun(Tag tag, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
String txt;
int offset;
if (trTextRun==null)
trTextRun = new TextRun();
txt=trTextRun.getText();
offset=txt.length();
trTextRun.appendWithPropertyTextUnitPlaceholders(tag.toString(),offset,propertyTextUnitPlaceholders);
}
/**
* Adds the text and codes in a text run as a single code in a text unit.
* If it is after text, it is added as a MARKER_CLOSING. If no text
* was encountered and this is being called by an ending TEXT_RUN_ELEMENT
* or ending TEXT_UNIT_ELEMENT, it is added as a MARKER_PLACEHOLDER.
* Otherwise, it is added as a MARKER_OPENING.
* compatible contiguous text runs if desired, and creates a
* START_SUBDOCUMENT event
* @param bEndRun true if called while processing an end TEXT_RUN_ELEMENT
* or end TEXT_UNIT_ELEMENT
*/
private void addTextRunToCurrentTextUnit(boolean bEndRun) {
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
TextFragment.TagType codeType;
String text,tempTagType;
int len;
if (trTextRun!=null && !(text=trTextRun.getText()).equals("")) // DWH 5-14-09 "" can occur with Character entities
{
if (bAfterText)
codeType = TextFragment.TagType.CLOSING;
else if (bEndRun) // if no text was encountered and this is the </w:r> or </w:p>, this is a standalone code
codeType = TextFragment.TagType.PLACEHOLDER;
else
codeType = TextFragment.TagType.OPENING;
// text = trTextRun.getText();
if (codeType==TextFragment.TagType.OPENING &&
!bBeforeFirstTextRun && // DWH 4-15-09 only do this if there wasn't stuff before <w:r>
bInMainFile && // DWH 4-15-08 only do this in MSWORD document and MSPOWERPOINT slides
((text.equals("<w:r><w:t>") || text.equals("<w:r><w:t xml:space=\"preserve\">")) ||
(text.equals("<a:r><a:t>") || text.equals("<a:r><a:t xml:space=\"preserve\">"))))
{
bIgnoredPreRun = true; // don't put codes around text that has no attributes
trTextRun = null;
return;
}
else if (codeType==TextFragment.TagType.CLOSING && bIgnoredPreRun)
{
bIgnoredPreRun = false;
if (text.endsWith("</w:t></w:r>") || text.endsWith("</a:t></a:r>"))
{
len = text.length();
if (len>12) // take off the end codes and leave the rest as a placeholder code, if any
{
text = text.substring(0,len-12);
codeType = TextFragment.TagType.CLOSING;
}
else
{
trTextRun = null;
return;
}
}
}
propertyTextUnitPlaceholders = trTextRun.getPropertyTextUnitPlaceholders();
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
// add code and process actionable attributes
addToTextUnitCode(codeType, text, "x", propertyTextUnitPlaceholders);
} else {
// no actionable attributes, just add the code as-is
addToTextUnitCode(codeType, text, "x");
}
trTextRun = null;
bBeforeFirstTextRun = false; // since the text run has now been added to the text unit
}
}
private void addNonTextRunToCurrentTextUnit() { // DWW 5-5-09
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
TextFragment.TagType codeType;
String text,tempTagType;
if (trNonTextRun!=null)
{
text = trNonTextRun.getText();
if (canStartNewTextUnit()) // DWH shouldn't happen
{
addToDocumentPart(text);
}
propertyTextUnitPlaceholders = trNonTextRun.getPropertyTextUnitPlaceholders();
if (bBeforeFirstTextRun &&
(propertyTextUnitPlaceholders==null || propertyTextUnitPlaceholders.size()==0))
// if a nonTextRun occurs before the first text run, and it doesn't have any
// embedded text, just add the tags to the skeleton after <w:r> or <a:r>.
// Since skeleton is not a TextFragment, it can't have embedded text, so if
// there is embedded text, do the else and make a PLACEHOLDER code
{
appendToFirstSkeletonPart(text);
}
else
{
codeType = TextFragment.TagType.PLACEHOLDER;
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
// add code and process actionable attributes
addToTextUnitCode(codeType, text, "x", propertyTextUnitPlaceholders);
} else {
// no actionable attributes, just add the code as-is
addToTextUnitCode(codeType, text, "x");
}
}
trNonTextRun = null;
}
}
public void excludeStyle(String sTyle) // DWH 5-27-09 to exclude selected styles or hidden text
{
if (sTyle!=null && !sTyle.equals(""))
tsExcludeWordStyles.add(sTyle);
}
private boolean evaluateSharedString(Tag tag) // DWH 6-13-09 Excel options
{
boolean bExcludeCell=false;
String sCell;
String sStyle;
for (Attribute attribute : tag.parseAttributes())
{
if (attribute.getName().equals("r"))
{
sCell = attribute.getValue();
Excell eggshell = new Excell(sCell);
if (bPreferenceTranslateExcelExcludeColumns &&
((tsExcelExcludedColumns.contains(sCurrentExcelSheet+eggshell.getColumn())) || // matches excluded sheet and column
((new Integer(sCurrentExcelSheet).intValue())>3 && tsExcelExcludedColumns.contains("3"+eggshell.getColumn()))))
// matches column on a sheet>3
bExcludeCell = true; // this cell has been specifically excluded
}
else if (attribute.getName().equals("s"))
{
sStyle = attribute.getValue();
if (bPreferenceTranslateExcelExcludeColors && tsExcelExcludedStyles.contains(sStyle))
bExcludeCell = true; // this style includes an excluded color
}
else if (attribute.getName().equals("t"))
{
bInExcelSharedStringCell = attribute.getValue().equals("s"); // global for handleText
// true if this string is in sharedStrings.xml
}
}
if (!bInExcelSharedStringCell)
bExcludeCell = false; // only exclude the cell if the string is in sharedStrings.xml
return bExcludeCell;
}
public int getConfigurationType()
{
return configurationType;
}
protected void setBInMainFile(boolean bInMainFile) // DWH 4-15-09
{
this.bInMainFile = bInMainFile;
}
protected boolean getBInMainFile() // DWH 4-15-09
{
return bInMainFile;
}
protected void setBInSettingsFile(boolean bInSettingsFile) // DWH 4-12-10 for <v:textbox
{
this.bInSettingsFile = bInSettingsFile;
}
protected boolean getBInSettingsFile() // DWH 4-12-10 for <v:textbox
{
return bInSettingsFile;
}
public void setLogger(Logger lgr)
{
LOGGER = lgr;
}
public void setTsExcludeWordStyles(TreeSet tsExcludeWordStyles)
{
this.tsExcludeWordStyles = tsExcludeWordStyles;
}
public TreeSet getTsExcludeWordStyles()
{
return tsExcludeWordStyles;
}
public void setBPreferenceTranslateWordHidden(boolean bPreferenceTranslateWordHidden)
{
this.bPreferenceTranslateWordHidden = bPreferenceTranslateWordHidden;
}
public boolean getBPreferenceTranslateWordHidden()
{
return bPreferenceTranslateWordHidden;
}
public void setBPreferenceTranslateExcelExcludeColors(boolean bPreferenceTranslateExcelExcludeColors) // DWH 6-13-09 Excel options
{
this.bPreferenceTranslateExcelExcludeColors = bPreferenceTranslateExcelExcludeColors;
}
public boolean getBPreferenceTranslateExcelExcludeColors() // DWH 6-13-09 Excel options
{
return bPreferenceTranslateExcelExcludeColors;
}
public void setBPreferenceTranslateExcelExcludeColumns(boolean bPreferenceTranslateExcelExcludeColumns) // DWH 6-13-09 Excel options
{
this.bPreferenceTranslateExcelExcludeColumns = bPreferenceTranslateExcelExcludeColumns;
}
public boolean getBPreferenceTranslateExcelExcludeColumns() // DWH 6-13-09 Excel options
{
return bPreferenceTranslateExcelExcludeColumns;
}
public void setSCurrentExcelSheet(String sCurrentExcelSheet) // DWH 6-13-09 Excel options
{
this.sCurrentExcelSheet = sCurrentExcelSheet;
}
public String getSCurrentExcelSheet() // DWH 6-13-09 Excel options
{
return sCurrentExcelSheet;
}
public void setTsExcelExcludedStyles(TreeSet<String> tsExcelExcludedStyles) // DWH 6-13-09 Excel options
{
this.tsExcelExcludedStyles = tsExcelExcludedStyles;
}
public TreeSet<String> getTsExcelExcludedStyles() // DWH 6-13-09 Excel options
{
return tsExcelExcludedStyles;
}
public void setTsExcelExcludedColumns(TreeSet<String> tsExcelExcludedColumns) // DWH 6-13-09 Excel options
{
this.tsExcelExcludedColumns = tsExcelExcludedColumns;
}
public TreeSet<String> gettsExcelExcludedColumns() // DWH 6-13-09 Excel options
{
return tsExcelExcludedColumns;
}
protected void initTmSharedStrings(int nExcelOriginalSharedStringCount) // DWH 6-13-09 Excel options
{
this.nOriginalSharedStringCount = nExcelOriginalSharedStringCount; // DWH 6-13-09
this.nNextSharedStringCount = nExcelOriginalSharedStringCount; // next count to modify
tmSharedStrings = new TreeMap<Integer,ExcelSharedString>();
for(int i=0;i<nExcelOriginalSharedStringCount;i++)
tmSharedStrings.put(new Integer(i), new ExcelSharedString(false,true,-1,""));
// DWH 6-25-09 leave nIndex -1 unless a copy of a shared string is needed
nCurrentSharedString = -1;
}
private String newSharedStringCount(String sTagString)
// DWH 6-13-09 replaces count of sharedStrings in sst element in sharedStrings.xml in Excel
// if some shared Strings are to be translated in some contexts but not others
{
String sNewTagString=sTagString,sOrigNum;
int nDx,nDx2;
nDx = sTagString.indexOf("uniqueCount");
if (nDx==-1)
nDx = sTagString.indexOf("count=");
if (nDx>-1)
{
nDx2 = sTagString.substring(nDx+7).indexOf('"');
if (nDx2>nDx)
{
sOrigNum = sTagString.substring(nDx+7,nDx2);
if (sOrigNum.equals(new Integer(nOriginalSharedStringCount).toString()))
sNewTagString = sTagString.substring(0,nDx+7) +
(new Integer(nNextSharedStringCount)).toString() +
sTagString.substring(nDx2); // replace old count with new one
}
}
return sNewTagString;
}
private boolean containsAString(TreeSet ts, String s)
{
boolean rslt = false;
String ss;
for(Iterator it=ts.iterator(); it.hasNext();)
{
ss = (String)it.next();
if (s.equals(ss))
{
rslt = true;
break;
}
}
return rslt;
}
@Override
protected TaggedFilterConfiguration getConfig() {
return config; // this may be bad if AbstractMarkup calls it too soon !!!!
}
public IParameters getParameters() { // DWH 7-16-09
// TODO Auto-generated method stub
return params;
}
public void setParameters(IParameters params) { // DWH 7-16-09
this.params = (YamlParameters)params;
}
private void addToTextUnitCode(TagType codeType, String data, String type)
{
addToTextUnit(new Code(codeType, type, data));
}
private void addToTextUnitCode(TagType codeType, String data, String type, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
addToTextUnit(new Code(codeType, type, data), propertyTextUnitPlaceholders);
}
private String getCommonTagType(Tag tag)
{
return getConfig().getElementType(tag); // DWH
}
/*
Textbox code
private void handleTextBox(List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders,
StartTag tag)
{
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
startDocumentPart(tag.toString(), tag.getName(), propertyTextUnitPlaceholders);
endDocumentPart()
} else {
// no attributes that needs processing - just treat as skeleton
addToDocumentPart(tag.toString());
}
if (propOrText.getType() == PlaceholderType.TRANSLATABLE) {
TextUnit tu = embeddedTextUnit(propOrText, tag);
currentSkeleton.addReference(tu);
referencableFilterEvents.add(new Event(EventType.TEXT_UNIT, tu));
}
private TextUnit embeddedTextUnit(PropertyTextUnitPlaceholder propOrText, String tag) {
TextUnit tu = new TextUnit(createId(TEXT_UNIT, ++textUnitId), propOrText.getValue());
tu.setPreserveWhitespaces(isPreserveWhitespace());
tu.setMimeType(propOrText.getMimeType());
tu.setIsReferent(true);
GenericSkeleton skel = new GenericSkeleton();
skel.add(tag.substring(propOrText.getMainStartPos(), propOrText.getValueStartPos()));
skel.addContentPlaceholder(tu);
skel.add(tag.substring(propOrText.getValueEndPos(), propOrText.getMainEndPos()));
tu.setSkeleton(skel);
return tu;
}
*/
}
| false | true | public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
final OutputStreamWriter osw;
final BufferedWriter bw;
final InputStreamReader isr;
final BufferedReader br;
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
osw = new OutputStreamWriter(pios,"UTF-8");
bw = new BufferedWriter(osw);
isr = new InputStreamReader(in,"UTF-8");
br = new BufferedReader(isr);
}
catch (IOException e)
{
throw new OkapiIOException("Can't read piped input stream.");
}
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
boolean bHaveACRInsideR=false; // DWH 11-09-09 don't collapse if have a carriage return in style
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp = ""; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (tugname.equals("w:cr"))
{
bHaveACRInsideR = true;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text) && !bHaveACRInsideR) // DWH 11-09-09 bHaveACRInsideR
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
try
{
bw.write(s);
LOGGER.log(Level.FINEST,s); //
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Problem writing piped stream.");
// throw new OkapiIOException("Can't read piped input.");
s = s + " ";
}
}
});
readThread.start();
return piis;
}
| public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
final OutputStreamWriter osw;
final BufferedWriter bw;
final InputStreamReader isr;
final BufferedReader br;
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
osw = new OutputStreamWriter(pios,"UTF-8");
bw = new BufferedWriter(osw);
isr = new InputStreamReader(in,"UTF-8");
br = new BufferedReader(isr);
}
catch (IOException e)
{
throw new OkapiIOException("Can't read piped input stream.");
}
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
boolean bHaveACRInsideR=false; // DWH 11-09-09 don't collapse if have a carriage return in style
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
if (!isAStandaloneTug(tug))
bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp = ""; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (tugname.equals("w:cr"))
{
bHaveACRInsideR = true;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
bHaveACRInsideR = false; // DWH 11-09-09
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text) && !bHaveACRInsideR) // DWH 11-09-09 bHaveACRInsideR
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
try
{
bw.write(s);
LOGGER.log(Level.FINEST,s); //
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Problem writing piped stream.");
// throw new OkapiIOException("Can't read piped input.");
s = s + " ";
}
}
private boolean isAStandaloneTug(String tug)
{
int len=tug.length();
return(tug.substring(len-2, len).equals("/>") ? true : false);
}
});
readThread.start();
return piis;
}
|
diff --git a/modules/topology-common/src/main/java/net/es/topology/common/visitors/sls/SLSTraverserImpl.java b/modules/topology-common/src/main/java/net/es/topology/common/visitors/sls/SLSTraverserImpl.java
index 5daed64..d47c3c6 100644
--- a/modules/topology-common/src/main/java/net/es/topology/common/visitors/sls/SLSTraverserImpl.java
+++ b/modules/topology-common/src/main/java/net/es/topology/common/visitors/sls/SLSTraverserImpl.java
@@ -1,309 +1,325 @@
package net.es.topology.common.visitors.sls;
import net.es.lookup.common.exception.LSClientException;
import net.es.lookup.common.exception.ParserException;
import net.es.topology.common.records.ts.*;
import net.es.topology.common.records.ts.utils.RecordsCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
/**
* @author <a href="mailto:[email protected]">Ahmed El-Hassany</a>
*/
public class SLSTraverserImpl implements Traverser {
private final Logger logger = LoggerFactory.getLogger(SLSTraverserImpl.class);
RecordsCache cache;
/**
* A Unique UUID to identify the log trace within each traverser instance.
*
* @see <a href="http://netlogger.lbl.gov/">Netlogger</a> best practices document.
*/
private String logGUID;
public SLSTraverserImpl(RecordsCache cache, String logGUID) {
this.cache = cache;
this.logGUID = logGUID;
}
public SLSTraverserImpl(RecordsCache cache) {
this(cache, UUID.randomUUID().toString());
}
public String getLogGUID() {
return logGUID;
}
public void setLogGUID(String logGUID) {
this.logGUID = logGUID;
}
public RecordsCache getCache() {
return this.cache;
}
public Logger getLogger() {
return this.logger;
}
@Override
public void traverse(NetworkObject record, Visitor visitor) {
}
@Override
public void traverse(BidirectionalLink record, Visitor visitor) {
}
@Override
public void traverse(BidirectionalPort record, Visitor visitor) {
}
@Override
public void traverse(Link record, Visitor visitor) {
}
@Override
public void traverse(LinkGroup record, Visitor visitor) {
}
@Override
public void traverse(Node record, Visitor visitor) {
}
@Override
public void traverse(NSA record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.NSA.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getTopologies() != null) {
for (String urn : record.getTopologies()) {
Topology sLSRecord = getCache().getTopology(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPeersWith() != null) {
for (String urn : record.getPeersWith()) {
NSA sLSRecord = getCache().getNSA(urn);
if (sLSRecord != null && sLSRecord.getId().equalsIgnoreCase(record.getId()) == false) {
sLSRecord.accept(visitor);
}
}
}
if (record.getManagedBy() != null) {
for (String urn : record.getManagedBy()) {
NSA sLSRecord = getCache().getNSA(urn);
if (sLSRecord != null && sLSRecord.getId().equalsIgnoreCase(record.getId()) == false) {
sLSRecord.accept(visitor);
}
}
}
if (record.getNSIServices() != null) {
for (String urn : record.getNSIServices()) {
NSIService sLSRecord = getCache().getNSIService(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
// TODO (AH) travers admin contact
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.NSA.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.NSA.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.NSA.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
@Override
public void traverse(NSIService record, Visitor visitor) {
}
@Override
public void traverse(Port record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.Port.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getIsSink() != null) {
for (String urn : record.getIsSink()) {
Link sLSRecord = getCache().getLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getIsSource() != null) {
for (String urn : record.getIsSource()) {
Link sLSRecord = getCache().getLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
// TODO (AH) travers hasService
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Port.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Port.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.Port.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
@Override
public void traverse(PortGroup record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.PortGroup.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getPorts() != null) {
for (String urn : record.getPorts()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPortGroups() != null) {
for (String urn : record.getPortGroups()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
// to stop cyclic dependencies
if (sLSRecord != null && !sLSRecord.getId().equalsIgnoreCase(record.getId())) {
sLSRecord.accept(visitor);
}
}
}
if (record.getIsSink() != null) {
for (String urn : record.getIsSink()) {
LinkGroup sLSRecord = getCache().getLinkGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getIsSource() != null) {
for (String urn : record.getIsSource()) {
LinkGroup sLSRecord = getCache().getLinkGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getIsAlias() != null) {
for (String urn : record.getIsAlias()) {
Port sLSRecord = getCache().getPort(urn);
// to stop cyclic dependencies
if (sLSRecord != null && !sLSRecord.getId().equalsIgnoreCase(record.getId())) {
sLSRecord.accept(visitor);
}
}
}
// TODO (AH) travers labelGroup
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.PortGroup.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.PortGroup.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.PortGroup.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
@Override
public void traverse(Topology record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getTopologies() != null) {
for (String urn : record.getTopologies()) {
Topology sLSRecord = getCache().getTopology(urn);
if (sLSRecord != null && sLSRecord.getId().equalsIgnoreCase(record.getId()) == false) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPorts() != null) {
for (String urn : record.getPorts()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getNodes() != null) {
for (String urn : record.getNodes()) {
Node sLSRecord = getCache().getNode(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinks() != null) {
for (String urn : record.getLinks()) {
Link sLSRecord = getCache().getLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalLinks() != null) {
for (String urn : record.getBidirectionalLinks()) {
BidirectionalLink sLSRecord = getCache().getBidirectionalLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalPorts() != null) {
for (String urn : record.getBidirectionalPorts()) {
BidirectionalPort sLSRecord = getCache().getBidirectionalPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinkGroups() != null) {
for (String urn : record.getLinkGroups()) {
LinkGroup sLSRecord = getCache().getLinkGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPortGroups() != null) {
for (String urn : record.getPortGroups()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasInboundPort() != null) {
for (String urn : record.getHasInboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasOutboundPort() != null) {
- for (String urn : record.getHasInboundPort()) {
+ for (String urn : record.getHasOutboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
+ if (record.getHasInboundPortGroup() != null) {
+ for (String urn : record.getHasInboundPortGroup()) {
+ PortGroup sLSRecord = getCache().getPortGroup(urn);
+ if (sLSRecord != null) {
+ sLSRecord.accept(visitor);
+ }
+ }
+ }
+ if (record.getHasOutboundPortGroup() != null) {
+ for (String urn : record.getHasOutboundPortGroup()) {
+ PortGroup sLSRecord = getCache().getPortGroup(urn);
+ if (sLSRecord != null) {
+ sLSRecord.accept(visitor);
+ }
+ }
+ }
// TODO (AH): travers services and hasService
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
}
| false | true | public void traverse(Topology record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getTopologies() != null) {
for (String urn : record.getTopologies()) {
Topology sLSRecord = getCache().getTopology(urn);
if (sLSRecord != null && sLSRecord.getId().equalsIgnoreCase(record.getId()) == false) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPorts() != null) {
for (String urn : record.getPorts()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getNodes() != null) {
for (String urn : record.getNodes()) {
Node sLSRecord = getCache().getNode(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinks() != null) {
for (String urn : record.getLinks()) {
Link sLSRecord = getCache().getLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalLinks() != null) {
for (String urn : record.getBidirectionalLinks()) {
BidirectionalLink sLSRecord = getCache().getBidirectionalLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalPorts() != null) {
for (String urn : record.getBidirectionalPorts()) {
BidirectionalPort sLSRecord = getCache().getBidirectionalPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinkGroups() != null) {
for (String urn : record.getLinkGroups()) {
LinkGroup sLSRecord = getCache().getLinkGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPortGroups() != null) {
for (String urn : record.getPortGroups()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasInboundPort() != null) {
for (String urn : record.getHasInboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasOutboundPort() != null) {
for (String urn : record.getHasInboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
// TODO (AH): travers services and hasService
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
| public void traverse(Topology record, Visitor visitor) {
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.start recordURN=" + record.getId() + " guid=" + getLogGUID());
try {
if (record.getTopologies() != null) {
for (String urn : record.getTopologies()) {
Topology sLSRecord = getCache().getTopology(urn);
if (sLSRecord != null && sLSRecord.getId().equalsIgnoreCase(record.getId()) == false) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPorts() != null) {
for (String urn : record.getPorts()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getNodes() != null) {
for (String urn : record.getNodes()) {
Node sLSRecord = getCache().getNode(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinks() != null) {
for (String urn : record.getLinks()) {
Link sLSRecord = getCache().getLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalLinks() != null) {
for (String urn : record.getBidirectionalLinks()) {
BidirectionalLink sLSRecord = getCache().getBidirectionalLink(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getBidirectionalPorts() != null) {
for (String urn : record.getBidirectionalPorts()) {
BidirectionalPort sLSRecord = getCache().getBidirectionalPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getLinkGroups() != null) {
for (String urn : record.getLinkGroups()) {
LinkGroup sLSRecord = getCache().getLinkGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getPortGroups() != null) {
for (String urn : record.getPortGroups()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasInboundPort() != null) {
for (String urn : record.getHasInboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasOutboundPort() != null) {
for (String urn : record.getHasOutboundPort()) {
Port sLSRecord = getCache().getPort(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasInboundPortGroup() != null) {
for (String urn : record.getHasInboundPortGroup()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
if (record.getHasOutboundPortGroup() != null) {
for (String urn : record.getHasOutboundPortGroup()) {
PortGroup sLSRecord = getCache().getPortGroup(urn);
if (sLSRecord != null) {
sLSRecord.accept(visitor);
}
}
}
// TODO (AH): travers services and hasService
} catch (LSClientException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=LSClientException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
} catch (ParserException ex) {
getLogger().warn("event=SLSTraverserImpl.traverse.Topology.warning reason=ParserException message=\"" + ex.getMessage() + "\" recordURN=" + record.getId() + " guid=" + getLogGUID());
}
getLogger().trace("event=SLSTraverserImpl.traverse.Topology.end status=0 recordURN=" + record.getId() + " guid=" + getLogGUID());
}
|
diff --git a/src/Main4.java b/src/Main4.java
index 61f5f73..404ce6b 100644
--- a/src/Main4.java
+++ b/src/Main4.java
@@ -1,6 +1,6 @@
public class Main4 {
public static void main(String[] args) {
- System.out.println("Hello World testing 004 !");
+ System.out.println("Hello World testing 0004 !");
}
}
| true | true | public static void main(String[] args) {
System.out.println("Hello World testing 004 !");
}
| public static void main(String[] args) {
System.out.println("Hello World testing 0004 !");
}
|
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_baulastEditorPanel.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_baulastEditorPanel.java
index 6beeaff9..b858a820 100644
--- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_baulastEditorPanel.java
+++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Alb_baulastEditorPanel.java
@@ -1,1321 +1,1322 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Alb_baulastEditorPanel.java
*
* Created on 27.11.2009, 14:20:31
*/
package de.cismet.cids.custom.objecteditors.wunda_blau;
import Sirius.navigator.ui.ComponentRegistry;
import Sirius.server.middleware.types.AbstractAttributeRepresentationFormater;
import Sirius.server.middleware.types.LightweightMetaObject;
import Sirius.server.middleware.types.MetaObject;
import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport;
import de.cismet.cids.custom.objectrenderer.utils.FlurstueckFinder;
import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.editors.DefaultBindableDateChooser;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.collections.TypeSafeCollections;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
/**
*
* @author srichter
*/
public class Alb_baulastEditorPanel extends javax.swing.JPanel {
static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Alb_baulastEditorPanel.class);
private CidsBean cidsBean;
private final DefaultComboBoxModel NO_SELECTION_MODEL = new DefaultComboBoxModel(new Object[]{});
private final boolean editable;
private final Collection<JComponent> editableComponents;
private Collection<CidsBean> currentListToAdd;
// private boolean landParcelListInitialized = false;
private boolean baulastArtenListInitialized = false;
/** Creates new form Alb_baulastEditorPanel */
public Alb_baulastEditorPanel(boolean editable) {
this.editable = editable;
this.editableComponents = TypeSafeCollections.newArrayList();
initComponents();
initEditableComponents();
currentListToAdd = null;
dlgAddLandParcelDiv.pack();
dlgAddLandParcelDiv.setLocationRelativeTo(this);
dlgAddBaulastArt.pack();
dlgAddBaulastArt.setLocationRelativeTo(this);
AutoCompleteDecorator.decorate(cbBaulastArt);
CismetThreadPool.execute(new AbstractFlurstueckComboModelWorker(cbParcels1, true) {
@Override
protected ComboBoxModel doInBackground() throws Exception {
return new DefaultComboBoxModel(FlurstueckFinder.getLWGemarkungen());
}
});
}
private final void initEditableComponents() {
editableComponents.add(txtLageplan);
editableComponents.add(txtLaufendeNr);
editableComponents.add(txtTextblatt);
editableComponents.add(defaultBindableDateChooser1);
editableComponents.add(defaultBindableDateChooser2);
editableComponents.add(defaultBindableDateChooser3);
editableComponents.add(defaultBindableDateChooser4);
// editableComponents.add(lstFlurstueckeBeguenstigt);
// editableComponents.add(lstFlurstueckeBelastet);
for (final JComponent editableComponent : editableComponents) {
editableComponent.setOpaque(editable);
if (!editable) {
editableComponent.setBorder(null);
if (editableComponent instanceof JTextField) {
((JTextField) editableComponent).setEditable(false);
} else if (editableComponent instanceof DefaultBindableDateChooser) {
final DefaultBindableDateChooser dateChooser = (DefaultBindableDateChooser) editableComponent;
dateChooser.setEditable(false);
dateChooser.getEditor().setOpaque(false);
dateChooser.getEditor().setBorder(null);
}
// else if (editableComponent instanceof JList) {
// JList listEC = ((JList) editableComponent);
// listEC.setEnabled(false);
// }
panControlsFSBeg.setVisible(false);
panControlsFSBel.setVisible(false);
panArtControls.setVisible(false);
}
}
}
/** Creates new form Alb_baulastEditorPanel */
public Alb_baulastEditorPanel() {
this(true);
}
/** 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;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter();
dlgAddBaulastArt = new javax.swing.JDialog();
panAddBaulastArt = new javax.swing.JPanel();
lblSuchwortEingeben1 = new javax.swing.JLabel();
cbBaulastArt = new javax.swing.JComboBox();
panMenButtons1 = new javax.swing.JPanel();
btnMenAbort1 = new javax.swing.JButton();
btnMenOk1 = new javax.swing.JButton();
dlgAddLandParcelDiv = new javax.swing.JDialog();
panAddLandParcel1 = new javax.swing.JPanel();
lblFlurstueckAuswaehlen = new javax.swing.JLabel();
cbParcels1 = new javax.swing.JComboBox();
panMenButtons2 = new javax.swing.JPanel();
btnFlurstueckAddMenCancel = new javax.swing.JButton();
btnFlurstueckAddMenOk = new javax.swing.JButton();
cbParcels2 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
cbParcels3 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
lblGemarkung = new javax.swing.JLabel();
lblFlur = new javax.swing.JLabel();
lblFlurstueck = new javax.swing.JLabel();
lblGemarkungsname = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
panMain = new javax.swing.JPanel();
rpFSBeguenstigt = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBeguenstigt = new ColorJScrollpane(new Color(255, 255, 0));
lstFlurstueckeBeguenstigt = new javax.swing.JList();
semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBegFlurstuecke = new javax.swing.JLabel();
panControlsFSBeg = new javax.swing.JPanel();
btnAddBeguenstigt = new javax.swing.JButton();
btnRemoveBeguenstigt = new javax.swing.JButton();
rpFSBelastet = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBelastet = new ColorJScrollpane(new Color(0, 255, 0));
lstFlurstueckeBelastet = new javax.swing.JList();
semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBelFlurstuecke = new javax.swing.JLabel();
panControlsFSBel = new javax.swing.JPanel();
btnAddBelastet = new javax.swing.JButton();
btnRemoveBelastet = new javax.swing.JButton();
rpInfo = new de.cismet.tools.gui.RoundedPanel();
lblDescLaufendeNr = new javax.swing.JLabel();
lblDescEintragungsdatum = new javax.swing.JLabel();
lblDescBefristungsdatum = new javax.swing.JLabel();
lblDescGeschlossenAm = new javax.swing.JLabel();
lblDescLoeschungsdatum = new javax.swing.JLabel();
lblDescTextblatt = new javax.swing.JLabel();
txtTextblatt = new javax.swing.JTextField();
txtLaufendeNr = new javax.swing.JTextField();
lblDescLageplan = new javax.swing.JLabel();
txtLageplan = new javax.swing.JTextField();
defaultBindableDateChooser4 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser1 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser2 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser3 = new de.cismet.cids.editors.DefaultBindableDateChooser();
rpHeadInfo = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadInfo = new javax.swing.JLabel();
lblDescBaulastart = new javax.swing.JLabel();
scpBaulastart = new javax.swing.JScrollPane();
lstBaulastArt = new javax.swing.JList();
panArtControls = new javax.swing.JPanel();
btnAddArt = new javax.swing.JButton();
btnRemoveArt = new javax.swing.JButton();
dlgAddBaulastArt.setTitle("Art hinzufügen");
dlgAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
dlgAddBaulastArt.setModal(true);
panAddBaulastArt.setMaximumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setPreferredSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setLayout(new java.awt.GridBagLayout());
lblSuchwortEingeben1.setFont(new java.awt.Font("Tahoma", 1, 11));
lblSuchwortEingeben1.setText("Bitte Art auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
panAddBaulastArt.add(lblSuchwortEingeben1, gridBagConstraints);
cbBaulastArt.setMaximumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setMinimumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setPreferredSize(new java.awt.Dimension(250, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(cbBaulastArt, gridBagConstraints);
panMenButtons1.setLayout(new java.awt.GridBagLayout());
btnMenAbort1.setText("Abbrechen");
btnMenAbort1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenAbort1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenAbort1, gridBagConstraints);
btnMenOk1.setText("Ok");
btnMenOk1.setMaximumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setMinimumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setPreferredSize(new java.awt.Dimension(85, 23));
btnMenOk1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenOk1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenOk1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(panMenButtons1, gridBagConstraints);
dlgAddBaulastArt.getContentPane().add(panAddBaulastArt, java.awt.BorderLayout.CENTER);
dlgAddLandParcelDiv.setTitle("Flurstück hinzufügen");
dlgAddLandParcelDiv.setMinimumSize(new java.awt.Dimension(380, 120));
dlgAddLandParcelDiv.setModal(true);
panAddLandParcel1.setMaximumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setMinimumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setPreferredSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setLayout(new java.awt.GridBagLayout());
lblFlurstueckAuswaehlen.setFont(new java.awt.Font("Tahoma", 1, 11));
lblFlurstueckAuswaehlen.setText("Bitte Flurstück auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(15, 10, 20, 10);
panAddLandParcel1.add(lblFlurstueckAuswaehlen, gridBagConstraints);
cbParcels1.setEditable(true);
cbParcels1.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels1.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels1.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels1, gridBagConstraints);
panMenButtons2.setLayout(new java.awt.GridBagLayout());
btnFlurstueckAddMenCancel.setText("Abbrechen");
btnFlurstueckAddMenCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenCancelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenCancel, gridBagConstraints);
btnFlurstueckAddMenOk.setText("Ok");
btnFlurstueckAddMenOk.setMaximumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setMinimumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setPreferredSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenOkActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenOk, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(panMenButtons2, gridBagConstraints);
cbParcels2.setEditable(true);
cbParcels2.setEnabled(false);
cbParcels2.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels2.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels2.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels2ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels2, gridBagConstraints);
cbParcels3.setEditable(true);
cbParcels3.setEnabled(false);
cbParcels3.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels3.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels3.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels3ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels3, gridBagConstraints);
lblGemarkung.setText("Gemarkung");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkung, gridBagConstraints);
lblFlur.setText("Flur");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlur, gridBagConstraints);
lblFlurstueck.setText("Flurstück");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlurstueck, gridBagConstraints);
lblGemarkungsname.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkungsname, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
panAddLandParcel1.add(jSeparator1, gridBagConstraints);
dlgAddLandParcelDiv.getContentPane().add(panAddLandParcel1, java.awt.BorderLayout.CENTER);
setOpaque(false);
setLayout(new java.awt.BorderLayout());
panMain.setOpaque(false);
panMain.setLayout(new java.awt.GridBagLayout());
rpFSBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBeguenstigt.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setOpaque(false);
lstFlurstueckeBeguenstigt.setFixedCellWidth(270);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_beguenstigt}");
org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBeguenstigt);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBeguenstigt.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBeguenstigtMouseClicked(evt);
}
});
scpFlurstueckeBeguenstigt.setViewportView(lstFlurstueckeBeguenstigt);
rpFSBeguenstigt.add(scpFlurstueckeBeguenstigt, java.awt.BorderLayout.CENTER);
semiRoundedPanel1.setBackground(java.awt.Color.darkGray);
semiRoundedPanel1.setLayout(new java.awt.GridBagLayout());
lblHeadBegFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBegFlurstuecke.setText("Begünstigte Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel1.add(lblHeadBegFlurstuecke, gridBagConstraints);
rpFSBeguenstigt.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH);
panControlsFSBeg.setOpaque(false);
panControlsFSBeg.setLayout(new java.awt.GridBagLayout());
btnAddBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnAddBeguenstigt, gridBagConstraints);
btnRemoveBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnRemoveBeguenstigt, gridBagConstraints);
rpFSBeguenstigt.add(panControlsFSBeg, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
panMain.add(rpFSBeguenstigt, gridBagConstraints);
rpFSBelastet.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBelastet.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBelastet.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setOpaque(false);
lstFlurstueckeBelastet.setFixedCellWidth(270);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_belastet}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBelastet);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBelastet.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBelastetMouseClicked(evt);
}
});
scpFlurstueckeBelastet.setViewportView(lstFlurstueckeBelastet);
rpFSBelastet.add(scpFlurstueckeBelastet, java.awt.BorderLayout.CENTER);
semiRoundedPanel2.setBackground(java.awt.Color.darkGray);
semiRoundedPanel2.setLayout(new java.awt.GridBagLayout());
lblHeadBelFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBelFlurstuecke.setText("Belastete Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel2.add(lblHeadBelFlurstuecke, gridBagConstraints);
rpFSBelastet.add(semiRoundedPanel2, java.awt.BorderLayout.NORTH);
panControlsFSBel.setOpaque(false);
panControlsFSBel.setLayout(new java.awt.GridBagLayout());
btnAddBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnAddBelastet, gridBagConstraints);
btnRemoveBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnRemoveBelastet, gridBagConstraints);
rpFSBelastet.add(panControlsFSBel, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
panMain.add(rpFSBelastet, gridBagConstraints);
rpInfo.setLayout(new java.awt.GridBagLayout());
lblDescLaufendeNr.setText("Laufende Nummer:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLaufendeNr, gridBagConstraints);
lblDescEintragungsdatum.setText("Eintragungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescEintragungsdatum, gridBagConstraints);
lblDescBefristungsdatum.setText("Befristungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBefristungsdatum, gridBagConstraints);
lblDescGeschlossenAm.setText("Geschlossen am:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescGeschlossenAm, gridBagConstraints);
lblDescLoeschungsdatum.setText("Löschungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLoeschungsdatum, gridBagConstraints);
lblDescTextblatt.setText("Textblatt:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescTextblatt, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.textblatt}"), txtTextblatt, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtTextblatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"), txtLaufendeNr, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtLaufendeNr, gridBagConstraints);
lblDescLageplan.setText("Lageplan:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lageplan}"), txtLageplan, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(txtLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.loeschungsdatum}"), defaultBindableDateChooser4, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
+ binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser4, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eintragungsdatum}"), defaultBindableDateChooser1, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser1, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.befristungsdatum}"), defaultBindableDateChooser2, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser2, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geschlossen_am}"), defaultBindableDateChooser3, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser3, gridBagConstraints);
rpHeadInfo.setBackground(java.awt.Color.darkGray);
rpHeadInfo.setLayout(new java.awt.GridBagLayout());
lblHeadInfo.setForeground(new java.awt.Color(255, 255, 255));
lblHeadInfo.setText("Info");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpHeadInfo.add(lblHeadInfo, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
rpInfo.add(rpHeadInfo, gridBagConstraints);
lblDescBaulastart.setText("Arten:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBaulastart, gridBagConstraints);
scpBaulastart.setMaximumSize(new java.awt.Dimension(1500, 500));
scpBaulastart.setMinimumSize(new java.awt.Dimension(150, 75));
scpBaulastart.setPreferredSize(new java.awt.Dimension(150, 75));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBaulastArt);
bindingGroup.addBinding(jListBinding);
scpBaulastart.setViewportView(lstBaulastArt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(scpBaulastart, gridBagConstraints);
panArtControls.setOpaque(false);
panArtControls.setLayout(new java.awt.GridBagLayout());
btnAddArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnAddArt, gridBagConstraints);
btnRemoveArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnRemoveArt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(panArtControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
panMain.add(rpInfo, gridBagConstraints);
add(panMain, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
}// </editor-fold>//GEN-END:initComponents
private final MetaObject[] getLWBaulastarten() {
return ObjectRendererUtils.getLightweightMetaObjectsForQuery("alb_baulast_art", "select id,baulast_art from alb_baulast_art order by baulast_art", new String[]{"baulast_art"}, new AbstractAttributeRepresentationFormater() {
@Override
public String getRepresentation() {
return String.valueOf(getAttribute("baulast_art"));
}
});
}
private void btnAddBelastetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddBelastetActionPerformed
currentListToAdd = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "flurstuecke_belastet");
handleAddFlurstueck();
}//GEN-LAST:event_btnAddBelastetActionPerformed
private void btnAddBeguenstigtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddBeguenstigtActionPerformed
currentListToAdd = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "flurstuecke_beguenstigt");
handleAddFlurstueck();
}//GEN-LAST:event_btnAddBeguenstigtActionPerformed
private final void handleAddFlurstueck() {
btnFlurstueckAddMenOk.setEnabled(false);
dlgAddLandParcelDiv.setVisible(true);
}
private void btnRemoveBeguenstigtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveBeguenstigtActionPerformed
final Object[] selection = lstFlurstueckeBeguenstigt.getSelectedValues();
if (selection != null && selection.length > 0) {
final int answer = JOptionPane.showConfirmDialog(this, "Soll das Flurstück wirklich gelöscht werden?", "Begünstigtes Flurstück entfernen", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
final Collection flurstueckCol = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "flurstuecke_beguenstigt");
if (flurstueckCol != null) {
for (Object cur : selection) {
try {
flurstueckCol.remove(cur);
} catch (Exception e) {
ObjectRendererUtils.showExceptionWindowToUser("Fehler beim Löschen", e, this);
}
}
}
}
}
}//GEN-LAST:event_btnRemoveBeguenstigtActionPerformed
private void btnRemoveBelastetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveBelastetActionPerformed
final Object[] selection = lstFlurstueckeBelastet.getSelectedValues();
if (selection != null && selection.length > 0) {
final int answer = JOptionPane.showConfirmDialog(this, "Soll das Flurstück wirklich gelöscht werden?", "Belastetes Flurstück entfernen", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
final Collection flurstueckCol = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "flurstuecke_belastet");
if (flurstueckCol != null) {
for (Object cur : selection) {
try {
flurstueckCol.remove(cur);
} catch (Exception e) {
ObjectRendererUtils.showExceptionWindowToUser("Fehler beim Löschen", e, this);
}
}
}
}
}
}//GEN-LAST:event_btnRemoveBelastetActionPerformed
private void btnAddArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddArtActionPerformed
if (!baulastArtenListInitialized) {
CismetThreadPool.execute(new BaulastArtenComboModelWorker());
}
dlgAddBaulastArt.setVisible(true);
}//GEN-LAST:event_btnAddArtActionPerformed
private void btnRemoveArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveArtActionPerformed
final Object[] selection = lstBaulastArt.getSelectedValues();
if (selection != null && selection.length > 0) {
final int answer = JOptionPane.showConfirmDialog(this, "Soll die Art wirklich gelöscht werden?", "Art entfernen", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
final Collection artCol = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "art");
if (artCol != null) {
for (Object cur : selection) {
try {
artCol.remove(cur);
} catch (Exception e) {
ObjectRendererUtils.showExceptionWindowToUser("Fehler beim Löschen", e, this);
}
}
}
}
}
}//GEN-LAST:event_btnRemoveArtActionPerformed
private void btnMenAbort1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMenAbort1ActionPerformed
dlgAddBaulastArt.setVisible(false);
}//GEN-LAST:event_btnMenAbort1ActionPerformed
private void btnMenOk1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMenOk1ActionPerformed
final Object selection = cbBaulastArt.getSelectedItem();
if (selection instanceof LightweightMetaObject) {
final CidsBean selectedBean = ((LightweightMetaObject) selection).getBean();
final Collection<CidsBean> colToAdd = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "art");
if (colToAdd != null) {
if (!colToAdd.contains(selectedBean)) {
colToAdd.add(selectedBean);
}
}
}
dlgAddBaulastArt.setVisible(false);
}//GEN-LAST:event_btnMenOk1ActionPerformed
private void lstFlurstueckeBelastetMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstFlurstueckeBelastetMouseClicked
if (evt.getClickCount() > 1) {
handleJumpToListeSelectionBean(lstFlurstueckeBelastet);
}
}//GEN-LAST:event_lstFlurstueckeBelastetMouseClicked
private void btnFlurstueckAddMenCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFlurstueckAddMenCancelActionPerformed
dlgAddLandParcelDiv.setVisible(false);
}//GEN-LAST:event_btnFlurstueckAddMenCancelActionPerformed
private void btnFlurstueckAddMenOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFlurstueckAddMenOkActionPerformed
final Object selection = cbParcels3.getSelectedItem();
if (selection instanceof LightweightMetaObject) {
final CidsBean selectedBean = ((LightweightMetaObject) selection).getBean();
if (currentListToAdd != null) {
if (!currentListToAdd.contains(selectedBean)) {
currentListToAdd.add(selectedBean);
}
}
} else if (selection instanceof String) {
int result = JOptionPane.showConfirmDialog(this, "Das Flurstück befindet sich nicht im Datenbestand der aktuellen Flurstücke. Soll es als historisch angelegt werden?", "Historisches Flurstück anlegen", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
CidsBean beanToAdd = landParcelBeanFromComboBoxes(selection.toString());
if (beanToAdd != null) {
boolean alreadyContained = false;
for (CidsBean currentChk : currentListToAdd) {
//use toString equals because unsaved Bean != saved Bean with same data
if (String.valueOf(currentChk).equals(String.valueOf(beanToAdd))) {
alreadyContained = true;
break;
}
}
if (!alreadyContained) {
try {
if (MetaObject.NEW == beanToAdd.getMetaObject().getStatus()) {
beanToAdd = beanToAdd.persist();
}
currentListToAdd.add(beanToAdd);
} catch (Exception ex) {
log.error(ex, ex);
}
}
}
}
currentListToAdd = null;
}
dlgAddLandParcelDiv.setVisible(false);
}//GEN-LAST:event_btnFlurstueckAddMenOkActionPerformed
// private final Map<String, CidsBean> unpersistedHistoricLandparcels = TypeSafeCollections.newHashMap();
private CidsBean landParcelBeanFromComboBoxes(String zaehlerNenner) {
int result = JOptionPane.YES_OPTION;
try {
final Map<String, Object> newLandParcelProperties = TypeSafeCollections.newHashMap();
final String gemarkung = String.valueOf(cbParcels1.getSelectedItem());
final String flur = String.valueOf(cbParcels2.getSelectedItem());
if (flur.length() != 3) {
result = JOptionPane.showConfirmDialog(this, "Das neue Flurstück entspricht nicht der Namenskonvention: Flur sollte dreistellig sein (mit führenden Nullen, z.B. 007). Datensatz trotzdem abspeichern?", "Warnung: Format", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
}
if (result == JOptionPane.YES_OPTION) {
final String[] zaehlerNennerTiles = zaehlerNenner.split("/");
final String zaehler = zaehlerNennerTiles[0];
newLandParcelProperties.put(FlurstueckFinder.FLURSTUECK_GEMARKUNG, Integer.valueOf(gemarkung));
newLandParcelProperties.put(FlurstueckFinder.FLURSTUECK_FLUR, flur);
newLandParcelProperties.put(FlurstueckFinder.FLURSTUECK_ZAEHLER, zaehler);
String nenner = "0";
if (zaehlerNennerTiles.length == 2) {
nenner = zaehlerNennerTiles[1];
}
newLandParcelProperties.put(FlurstueckFinder.FLURSTUECK_NENNER, nenner);
//the following code tries to avoid the creation of multiple entries for the same landparcel.
//however, there *might* be a chance that a historic landparcel is created multiple times when more then
//one client creates the same parcel at the "same time".
MetaObject[] searchResult = FlurstueckFinder.getLWLandparcel(gemarkung, flur, zaehler, nenner);
if (searchResult != null && searchResult.length > 0) {
return searchResult[0].getBean();
} else {
// final String compountParcelData = gemarkung + "-" + flur + "-" + zaehler + "/" + nenner;
// CidsBean newBean = unpersistedHistoricLandparcels.get(compountParcelData);
// if (newBean == null) {
CidsBean newBean = CidsBeanSupport.createNewCidsBeanFromTableName(FlurstueckFinder.FLURSTUECK_TABLE_NAME, newLandParcelProperties);
// unpersistedHistoricLandparcels.put(compountParcelData, newBean);
// }
return newBean;
}
}
} catch (Exception ex) {
log.error(ex, ex);
}
return null;
}
private static final String CB_EDITED_ACTION_COMMAND = "comboBoxEdited";
private void cbParcels1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbParcels1ActionPerformed
Object selection = cbParcels1.getSelectedItem();
cbParcels3.setEnabled(false);
btnFlurstueckAddMenOk.setEnabled(false);
if (selection instanceof LightweightMetaObject) {
final LightweightMetaObject lwmo = (LightweightMetaObject) selection;
final String selGemarkungsNr = String.valueOf(selection);
CismetThreadPool.execute(new AbstractFlurstueckComboModelWorker(cbParcels2, CB_EDITED_ACTION_COMMAND.equals(evt.getActionCommand())) {
@Override
protected ComboBoxModel doInBackground() throws Exception {
return new DefaultComboBoxModel(FlurstueckFinder.getLWFlure(selGemarkungsNr));
}
});
String gemarkungsname = String.valueOf(lwmo.getLWAttribute(FlurstueckFinder.GEMARKUNG_NAME));
lblGemarkungsname.setText("(" + gemarkungsname + ")");
cbParcels1.getEditor().getEditorComponent().setBackground(Color.WHITE);
} else {
final int foundBeanIndex = ObjectRendererUtils.findComboBoxItemForString(cbParcels1, String.valueOf(selection));
if (foundBeanIndex < 0) {
cbParcels2.setModel(new DefaultComboBoxModel());
try {
Integer.parseInt(String.valueOf(selection));
cbParcels1.getEditor().getEditorComponent().setBackground(Color.YELLOW);
cbParcels2.setEnabled(true);
if (CB_EDITED_ACTION_COMMAND.equals(evt.getActionCommand())) {
cbParcels2.requestFocusInWindow();
}
} catch (Exception notANumberEx) {
log.debug(selection + " is not a number!", notANumberEx);
cbParcels2.setEnabled(false);
cbParcels1.getEditor().getEditorComponent().setBackground(Color.RED);
lblGemarkungsname.setText("(Ist keine Zahl)");
}
lblGemarkungsname.setText(" ");
} else {
cbParcels1.setSelectedIndex(foundBeanIndex);
cbParcels2.getEditor().getEditorComponent().setBackground(Color.WHITE);
cbParcels3.getEditor().getEditorComponent().setBackground(Color.WHITE);
}
}
}//GEN-LAST:event_cbParcels1ActionPerformed
private void cbParcels2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbParcels2ActionPerformed
Object selection = cbParcels2.getSelectedItem();
if (selection instanceof MetaObject) {
final String selGem = String.valueOf(cbParcels1.getSelectedItem());
final StringBuffer selFlurNr = new StringBuffer(String.valueOf(cbParcels2.getSelectedItem()));
btnFlurstueckAddMenOk.setEnabled(false);
CismetThreadPool.execute(new AbstractFlurstueckComboModelWorker(cbParcels3, CB_EDITED_ACTION_COMMAND.equals(evt.getActionCommand())) {
@Override
protected ComboBoxModel doInBackground() throws Exception {
return new DefaultComboBoxModel(FlurstueckFinder.getLWFurstuecksZaehlerNenner(selGem, selFlurNr.toString()));
}
});
cbParcels2.getEditor().getEditorComponent().setBackground(Color.WHITE);
} else {
final int foundBeanIndex = ObjectRendererUtils.findComboBoxItemForString(cbParcels2, String.valueOf(selection));
if (foundBeanIndex < 0) {
cbParcels2.getEditor().getEditorComponent().setBackground(Color.YELLOW);
cbParcels3.setModel(new DefaultComboBoxModel());
cbParcels3.setEnabled(true);
if (CB_EDITED_ACTION_COMMAND.equals(evt.getActionCommand())) {
cbParcels3.requestFocusInWindow();
}
} else {
cbParcels2.setSelectedIndex(foundBeanIndex);
cbParcels3.getEditor().getEditorComponent().setBackground(Color.WHITE);
}
}
}//GEN-LAST:event_cbParcels2ActionPerformed
private boolean checkFlurstueckSelectionComplete() {
if (cbParcels2.isEnabled() && cbParcels3.isEnabled()) {
Object sel2 = cbParcels2.getSelectedItem();
Object sel3 = cbParcels3.getSelectedItem();
if (sel2 != null && sel3 != null) {
if (sel2.toString().length() > 0 && sel3.toString().length() > 0) {
return true;
}
}
}
return false;
}
private void cbParcels3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbParcels3ActionPerformed
btnFlurstueckAddMenOk.setEnabled(checkFlurstueckSelectionComplete());
if (CB_EDITED_ACTION_COMMAND.equals(evt.getActionCommand())) {
btnFlurstueckAddMenOk.requestFocusInWindow();
}
if (cbParcels3.getSelectedItem() instanceof MetaObject) {
cbParcels3.getEditor().getEditorComponent().setBackground(Color.WHITE);
} else {
final int foundBeanIndex = ObjectRendererUtils.findComboBoxItemForString(cbParcels3, String.valueOf(cbParcels3.getSelectedItem()));
if (foundBeanIndex < 0) {
cbParcels3.getEditor().getEditorComponent().setBackground(Color.YELLOW);
} else {
cbParcels3.setSelectedIndex(foundBeanIndex);
}
}
}//GEN-LAST:event_cbParcels3ActionPerformed
private void lstFlurstueckeBeguenstigtMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstFlurstueckeBeguenstigtMouseClicked
if (evt.getClickCount() > 1) {
handleJumpToListeSelectionBean(lstFlurstueckeBeguenstigt);
}
}//GEN-LAST:event_lstFlurstueckeBeguenstigtMouseClicked
private final void handleJumpToListeSelectionBean(JList list) {
final Object selectedObj = list.getSelectedValue();
if (selectedObj instanceof CidsBean) {
Object realFSBean = ((CidsBean) selectedObj).getProperty("fs_referenz");
if (realFSBean instanceof CidsBean) {
final MetaObject selMO = ((CidsBean) realFSBean).getMetaObject();
ComponentRegistry.getRegistry().getDescriptionPane().gotoMetaObject(selMO, "");
}
}
}
public CidsBean getCidsBean() {
return cidsBean;
}
public void setCidsBean(CidsBean cidsBean) {
if (cidsBean != null) {
this.cidsBean = cidsBean;
bindingGroup.unbind();
bindingGroup.bind();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAddArt;
private javax.swing.JButton btnAddBeguenstigt;
private javax.swing.JButton btnAddBelastet;
private javax.swing.JButton btnFlurstueckAddMenCancel;
private javax.swing.JButton btnFlurstueckAddMenOk;
private javax.swing.JButton btnMenAbort1;
private javax.swing.JButton btnMenOk1;
private javax.swing.JButton btnRemoveArt;
private javax.swing.JButton btnRemoveBeguenstigt;
private javax.swing.JButton btnRemoveBelastet;
private javax.swing.JComboBox cbBaulastArt;
private javax.swing.JComboBox cbParcels1;
private javax.swing.JComboBox cbParcels2;
private javax.swing.JComboBox cbParcels3;
private de.cismet.cids.editors.DefaultBindableDateChooser defaultBindableDateChooser1;
private de.cismet.cids.editors.DefaultBindableDateChooser defaultBindableDateChooser2;
private de.cismet.cids.editors.DefaultBindableDateChooser defaultBindableDateChooser3;
private de.cismet.cids.editors.DefaultBindableDateChooser defaultBindableDateChooser4;
private javax.swing.JDialog dlgAddBaulastArt;
private javax.swing.JDialog dlgAddLandParcelDiv;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lblDescBaulastart;
private javax.swing.JLabel lblDescBefristungsdatum;
private javax.swing.JLabel lblDescEintragungsdatum;
private javax.swing.JLabel lblDescGeschlossenAm;
private javax.swing.JLabel lblDescLageplan;
private javax.swing.JLabel lblDescLaufendeNr;
private javax.swing.JLabel lblDescLoeschungsdatum;
private javax.swing.JLabel lblDescTextblatt;
private javax.swing.JLabel lblFlur;
private javax.swing.JLabel lblFlurstueck;
private javax.swing.JLabel lblFlurstueckAuswaehlen;
private javax.swing.JLabel lblGemarkung;
private javax.swing.JLabel lblGemarkungsname;
private javax.swing.JLabel lblHeadBegFlurstuecke;
private javax.swing.JLabel lblHeadBelFlurstuecke;
private javax.swing.JLabel lblHeadInfo;
private javax.swing.JLabel lblSuchwortEingeben1;
private javax.swing.JList lstBaulastArt;
private javax.swing.JList lstFlurstueckeBeguenstigt;
private javax.swing.JList lstFlurstueckeBelastet;
private javax.swing.JPanel panAddBaulastArt;
private javax.swing.JPanel panAddLandParcel1;
private javax.swing.JPanel panArtControls;
private javax.swing.JPanel panControlsFSBeg;
private javax.swing.JPanel panControlsFSBel;
private javax.swing.JPanel panMain;
private javax.swing.JPanel panMenButtons1;
private javax.swing.JPanel panMenButtons2;
private de.cismet.tools.gui.RoundedPanel rpFSBeguenstigt;
private de.cismet.tools.gui.RoundedPanel rpFSBelastet;
private de.cismet.tools.gui.SemiRoundedPanel rpHeadInfo;
private de.cismet.tools.gui.RoundedPanel rpInfo;
private javax.swing.JScrollPane scpBaulastart;
private javax.swing.JScrollPane scpFlurstueckeBeguenstigt;
private javax.swing.JScrollPane scpFlurstueckeBelastet;
private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel1;
private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel2;
private de.cismet.cids.editors.converters.SqlDateToUtilDateConverter sqlDateToUtilDateConverter;
private javax.swing.JTextField txtLageplan;
private javax.swing.JTextField txtLaufendeNr;
private javax.swing.JTextField txtTextblatt;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
private static final ComboBoxModel waitModel = new DefaultComboBoxModel(new String[]{"Wird geladen..."});
// class FlurstueckComboModelWorker extends SwingWorker<ComboBoxModel, Void> {
//
// public FlurstueckComboModelWorker() {
// cbLandParcels.setModel(waitModel);
// cbLandParcels.setEnabled(false);
// btnMenOk.setEnabled(false);
// }
//
// @Override
// protected ComboBoxModel doInBackground() throws Exception {
// return new DefaultComboBoxModel(getLWLandparcels());
// }
//
// @Override
// protected void done() {
// try {
// cbLandParcels.setModel(get());
//// landParcelListInitialized = true;
// } catch (InterruptedException ex) {
// log.debug(ex, ex);
// } catch (ExecutionException ex) {
// log.error(ex, ex);
// } finally {
// cbLandParcels.setEnabled(true);
// btnMenOk.setEnabled(true);
// }
// }
// }
class BaulastArtenComboModelWorker extends SwingWorker<ComboBoxModel, Void> {
public BaulastArtenComboModelWorker() {
cbBaulastArt.setModel(waitModel);
cbBaulastArt.setEnabled(false);
btnMenOk1.setEnabled(false);
}
@Override
protected ComboBoxModel doInBackground() throws Exception {
return new DefaultComboBoxModel(getLWBaulastarten());
}
@Override
protected void done() {
try {
cbBaulastArt.setModel(get());
baulastArtenListInitialized = true;
} catch (InterruptedException ex) {
log.debug(ex, ex);
} catch (ExecutionException ex) {
log.error(ex, ex);
} finally {
cbBaulastArt.setEnabled(true);
btnMenOk1.setEnabled(true);
}
}
}
abstract class AbstractFlurstueckComboModelWorker extends SwingWorker<ComboBoxModel, Void> {
private final JComboBox box;
private final boolean switchToBox;
public AbstractFlurstueckComboModelWorker(JComboBox box, boolean switchToBox) {
this.box = box;
this.switchToBox = switchToBox;
box.setVisible(true);
box.setEnabled(false);
box.setModel(waitModel);
}
@Override
protected void done() {
try {
box.setModel(get());
if (switchToBox) {
box.requestFocus();
}
} catch (InterruptedException ex) {
log.debug(ex, ex);
} catch (ExecutionException ex) {
log.error(ex, ex);
} finally {
box.setEnabled(true);
}
}
}
static final class ColorJScrollpane extends JScrollPane {
private static final int STRIPE_THICKNESS = 5;
public ColorJScrollpane() {
this.stripeColor = Color.LIGHT_GRAY;
}
public ColorJScrollpane(Color stripeColor) {
this.stripeColor = stripeColor;
}
private final Color stripeColor;
@Override
public void paint(Graphics g) {
final Graphics2D g2d = (Graphics2D) g;
final Color backupCol = g2d.getColor();
g2d.setColor(stripeColor);
g2d.fillRect(0, STRIPE_THICKNESS, STRIPE_THICKNESS, getHeight() - 2 * STRIPE_THICKNESS);
g2d.setColor(backupCol);
super.paint(g);
}
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter();
dlgAddBaulastArt = new javax.swing.JDialog();
panAddBaulastArt = new javax.swing.JPanel();
lblSuchwortEingeben1 = new javax.swing.JLabel();
cbBaulastArt = new javax.swing.JComboBox();
panMenButtons1 = new javax.swing.JPanel();
btnMenAbort1 = new javax.swing.JButton();
btnMenOk1 = new javax.swing.JButton();
dlgAddLandParcelDiv = new javax.swing.JDialog();
panAddLandParcel1 = new javax.swing.JPanel();
lblFlurstueckAuswaehlen = new javax.swing.JLabel();
cbParcels1 = new javax.swing.JComboBox();
panMenButtons2 = new javax.swing.JPanel();
btnFlurstueckAddMenCancel = new javax.swing.JButton();
btnFlurstueckAddMenOk = new javax.swing.JButton();
cbParcels2 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
cbParcels3 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
lblGemarkung = new javax.swing.JLabel();
lblFlur = new javax.swing.JLabel();
lblFlurstueck = new javax.swing.JLabel();
lblGemarkungsname = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
panMain = new javax.swing.JPanel();
rpFSBeguenstigt = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBeguenstigt = new ColorJScrollpane(new Color(255, 255, 0));
lstFlurstueckeBeguenstigt = new javax.swing.JList();
semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBegFlurstuecke = new javax.swing.JLabel();
panControlsFSBeg = new javax.swing.JPanel();
btnAddBeguenstigt = new javax.swing.JButton();
btnRemoveBeguenstigt = new javax.swing.JButton();
rpFSBelastet = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBelastet = new ColorJScrollpane(new Color(0, 255, 0));
lstFlurstueckeBelastet = new javax.swing.JList();
semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBelFlurstuecke = new javax.swing.JLabel();
panControlsFSBel = new javax.swing.JPanel();
btnAddBelastet = new javax.swing.JButton();
btnRemoveBelastet = new javax.swing.JButton();
rpInfo = new de.cismet.tools.gui.RoundedPanel();
lblDescLaufendeNr = new javax.swing.JLabel();
lblDescEintragungsdatum = new javax.swing.JLabel();
lblDescBefristungsdatum = new javax.swing.JLabel();
lblDescGeschlossenAm = new javax.swing.JLabel();
lblDescLoeschungsdatum = new javax.swing.JLabel();
lblDescTextblatt = new javax.swing.JLabel();
txtTextblatt = new javax.swing.JTextField();
txtLaufendeNr = new javax.swing.JTextField();
lblDescLageplan = new javax.swing.JLabel();
txtLageplan = new javax.swing.JTextField();
defaultBindableDateChooser4 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser1 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser2 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser3 = new de.cismet.cids.editors.DefaultBindableDateChooser();
rpHeadInfo = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadInfo = new javax.swing.JLabel();
lblDescBaulastart = new javax.swing.JLabel();
scpBaulastart = new javax.swing.JScrollPane();
lstBaulastArt = new javax.swing.JList();
panArtControls = new javax.swing.JPanel();
btnAddArt = new javax.swing.JButton();
btnRemoveArt = new javax.swing.JButton();
dlgAddBaulastArt.setTitle("Art hinzufügen");
dlgAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
dlgAddBaulastArt.setModal(true);
panAddBaulastArt.setMaximumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setPreferredSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setLayout(new java.awt.GridBagLayout());
lblSuchwortEingeben1.setFont(new java.awt.Font("Tahoma", 1, 11));
lblSuchwortEingeben1.setText("Bitte Art auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
panAddBaulastArt.add(lblSuchwortEingeben1, gridBagConstraints);
cbBaulastArt.setMaximumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setMinimumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setPreferredSize(new java.awt.Dimension(250, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(cbBaulastArt, gridBagConstraints);
panMenButtons1.setLayout(new java.awt.GridBagLayout());
btnMenAbort1.setText("Abbrechen");
btnMenAbort1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenAbort1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenAbort1, gridBagConstraints);
btnMenOk1.setText("Ok");
btnMenOk1.setMaximumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setMinimumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setPreferredSize(new java.awt.Dimension(85, 23));
btnMenOk1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenOk1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenOk1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(panMenButtons1, gridBagConstraints);
dlgAddBaulastArt.getContentPane().add(panAddBaulastArt, java.awt.BorderLayout.CENTER);
dlgAddLandParcelDiv.setTitle("Flurstück hinzufügen");
dlgAddLandParcelDiv.setMinimumSize(new java.awt.Dimension(380, 120));
dlgAddLandParcelDiv.setModal(true);
panAddLandParcel1.setMaximumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setMinimumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setPreferredSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setLayout(new java.awt.GridBagLayout());
lblFlurstueckAuswaehlen.setFont(new java.awt.Font("Tahoma", 1, 11));
lblFlurstueckAuswaehlen.setText("Bitte Flurstück auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(15, 10, 20, 10);
panAddLandParcel1.add(lblFlurstueckAuswaehlen, gridBagConstraints);
cbParcels1.setEditable(true);
cbParcels1.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels1.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels1.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels1, gridBagConstraints);
panMenButtons2.setLayout(new java.awt.GridBagLayout());
btnFlurstueckAddMenCancel.setText("Abbrechen");
btnFlurstueckAddMenCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenCancelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenCancel, gridBagConstraints);
btnFlurstueckAddMenOk.setText("Ok");
btnFlurstueckAddMenOk.setMaximumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setMinimumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setPreferredSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenOkActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenOk, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(panMenButtons2, gridBagConstraints);
cbParcels2.setEditable(true);
cbParcels2.setEnabled(false);
cbParcels2.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels2.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels2.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels2ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels2, gridBagConstraints);
cbParcels3.setEditable(true);
cbParcels3.setEnabled(false);
cbParcels3.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels3.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels3.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels3ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels3, gridBagConstraints);
lblGemarkung.setText("Gemarkung");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkung, gridBagConstraints);
lblFlur.setText("Flur");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlur, gridBagConstraints);
lblFlurstueck.setText("Flurstück");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlurstueck, gridBagConstraints);
lblGemarkungsname.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkungsname, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
panAddLandParcel1.add(jSeparator1, gridBagConstraints);
dlgAddLandParcelDiv.getContentPane().add(panAddLandParcel1, java.awt.BorderLayout.CENTER);
setOpaque(false);
setLayout(new java.awt.BorderLayout());
panMain.setOpaque(false);
panMain.setLayout(new java.awt.GridBagLayout());
rpFSBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBeguenstigt.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setOpaque(false);
lstFlurstueckeBeguenstigt.setFixedCellWidth(270);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_beguenstigt}");
org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBeguenstigt);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBeguenstigt.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBeguenstigtMouseClicked(evt);
}
});
scpFlurstueckeBeguenstigt.setViewportView(lstFlurstueckeBeguenstigt);
rpFSBeguenstigt.add(scpFlurstueckeBeguenstigt, java.awt.BorderLayout.CENTER);
semiRoundedPanel1.setBackground(java.awt.Color.darkGray);
semiRoundedPanel1.setLayout(new java.awt.GridBagLayout());
lblHeadBegFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBegFlurstuecke.setText("Begünstigte Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel1.add(lblHeadBegFlurstuecke, gridBagConstraints);
rpFSBeguenstigt.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH);
panControlsFSBeg.setOpaque(false);
panControlsFSBeg.setLayout(new java.awt.GridBagLayout());
btnAddBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnAddBeguenstigt, gridBagConstraints);
btnRemoveBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnRemoveBeguenstigt, gridBagConstraints);
rpFSBeguenstigt.add(panControlsFSBeg, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
panMain.add(rpFSBeguenstigt, gridBagConstraints);
rpFSBelastet.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBelastet.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBelastet.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setOpaque(false);
lstFlurstueckeBelastet.setFixedCellWidth(270);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_belastet}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBelastet);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBelastet.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBelastetMouseClicked(evt);
}
});
scpFlurstueckeBelastet.setViewportView(lstFlurstueckeBelastet);
rpFSBelastet.add(scpFlurstueckeBelastet, java.awt.BorderLayout.CENTER);
semiRoundedPanel2.setBackground(java.awt.Color.darkGray);
semiRoundedPanel2.setLayout(new java.awt.GridBagLayout());
lblHeadBelFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBelFlurstuecke.setText("Belastete Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel2.add(lblHeadBelFlurstuecke, gridBagConstraints);
rpFSBelastet.add(semiRoundedPanel2, java.awt.BorderLayout.NORTH);
panControlsFSBel.setOpaque(false);
panControlsFSBel.setLayout(new java.awt.GridBagLayout());
btnAddBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnAddBelastet, gridBagConstraints);
btnRemoveBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnRemoveBelastet, gridBagConstraints);
rpFSBelastet.add(panControlsFSBel, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
panMain.add(rpFSBelastet, gridBagConstraints);
rpInfo.setLayout(new java.awt.GridBagLayout());
lblDescLaufendeNr.setText("Laufende Nummer:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLaufendeNr, gridBagConstraints);
lblDescEintragungsdatum.setText("Eintragungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescEintragungsdatum, gridBagConstraints);
lblDescBefristungsdatum.setText("Befristungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBefristungsdatum, gridBagConstraints);
lblDescGeschlossenAm.setText("Geschlossen am:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescGeschlossenAm, gridBagConstraints);
lblDescLoeschungsdatum.setText("Löschungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLoeschungsdatum, gridBagConstraints);
lblDescTextblatt.setText("Textblatt:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescTextblatt, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.textblatt}"), txtTextblatt, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtTextblatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"), txtLaufendeNr, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtLaufendeNr, gridBagConstraints);
lblDescLageplan.setText("Lageplan:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lageplan}"), txtLageplan, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(txtLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.loeschungsdatum}"), defaultBindableDateChooser4, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser4, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eintragungsdatum}"), defaultBindableDateChooser1, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser1, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.befristungsdatum}"), defaultBindableDateChooser2, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser2, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geschlossen_am}"), defaultBindableDateChooser3, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser3, gridBagConstraints);
rpHeadInfo.setBackground(java.awt.Color.darkGray);
rpHeadInfo.setLayout(new java.awt.GridBagLayout());
lblHeadInfo.setForeground(new java.awt.Color(255, 255, 255));
lblHeadInfo.setText("Info");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpHeadInfo.add(lblHeadInfo, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
rpInfo.add(rpHeadInfo, gridBagConstraints);
lblDescBaulastart.setText("Arten:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBaulastart, gridBagConstraints);
scpBaulastart.setMaximumSize(new java.awt.Dimension(1500, 500));
scpBaulastart.setMinimumSize(new java.awt.Dimension(150, 75));
scpBaulastart.setPreferredSize(new java.awt.Dimension(150, 75));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBaulastArt);
bindingGroup.addBinding(jListBinding);
scpBaulastart.setViewportView(lstBaulastArt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(scpBaulastart, gridBagConstraints);
panArtControls.setOpaque(false);
panArtControls.setLayout(new java.awt.GridBagLayout());
btnAddArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnAddArt, gridBagConstraints);
btnRemoveArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnRemoveArt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(panArtControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
panMain.add(rpInfo, gridBagConstraints);
add(panMain, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter();
dlgAddBaulastArt = new javax.swing.JDialog();
panAddBaulastArt = new javax.swing.JPanel();
lblSuchwortEingeben1 = new javax.swing.JLabel();
cbBaulastArt = new javax.swing.JComboBox();
panMenButtons1 = new javax.swing.JPanel();
btnMenAbort1 = new javax.swing.JButton();
btnMenOk1 = new javax.swing.JButton();
dlgAddLandParcelDiv = new javax.swing.JDialog();
panAddLandParcel1 = new javax.swing.JPanel();
lblFlurstueckAuswaehlen = new javax.swing.JLabel();
cbParcels1 = new javax.swing.JComboBox();
panMenButtons2 = new javax.swing.JPanel();
btnFlurstueckAddMenCancel = new javax.swing.JButton();
btnFlurstueckAddMenOk = new javax.swing.JButton();
cbParcels2 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
cbParcels3 = new javax.swing.JComboBox(NO_SELECTION_MODEL);
lblGemarkung = new javax.swing.JLabel();
lblFlur = new javax.swing.JLabel();
lblFlurstueck = new javax.swing.JLabel();
lblGemarkungsname = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
panMain = new javax.swing.JPanel();
rpFSBeguenstigt = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBeguenstigt = new ColorJScrollpane(new Color(255, 255, 0));
lstFlurstueckeBeguenstigt = new javax.swing.JList();
semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBegFlurstuecke = new javax.swing.JLabel();
panControlsFSBeg = new javax.swing.JPanel();
btnAddBeguenstigt = new javax.swing.JButton();
btnRemoveBeguenstigt = new javax.swing.JButton();
rpFSBelastet = new de.cismet.tools.gui.RoundedPanel();
scpFlurstueckeBelastet = new ColorJScrollpane(new Color(0, 255, 0));
lstFlurstueckeBelastet = new javax.swing.JList();
semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadBelFlurstuecke = new javax.swing.JLabel();
panControlsFSBel = new javax.swing.JPanel();
btnAddBelastet = new javax.swing.JButton();
btnRemoveBelastet = new javax.swing.JButton();
rpInfo = new de.cismet.tools.gui.RoundedPanel();
lblDescLaufendeNr = new javax.swing.JLabel();
lblDescEintragungsdatum = new javax.swing.JLabel();
lblDescBefristungsdatum = new javax.swing.JLabel();
lblDescGeschlossenAm = new javax.swing.JLabel();
lblDescLoeschungsdatum = new javax.swing.JLabel();
lblDescTextblatt = new javax.swing.JLabel();
txtTextblatt = new javax.swing.JTextField();
txtLaufendeNr = new javax.swing.JTextField();
lblDescLageplan = new javax.swing.JLabel();
txtLageplan = new javax.swing.JTextField();
defaultBindableDateChooser4 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser1 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser2 = new de.cismet.cids.editors.DefaultBindableDateChooser();
defaultBindableDateChooser3 = new de.cismet.cids.editors.DefaultBindableDateChooser();
rpHeadInfo = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeadInfo = new javax.swing.JLabel();
lblDescBaulastart = new javax.swing.JLabel();
scpBaulastart = new javax.swing.JScrollPane();
lstBaulastArt = new javax.swing.JList();
panArtControls = new javax.swing.JPanel();
btnAddArt = new javax.swing.JButton();
btnRemoveArt = new javax.swing.JButton();
dlgAddBaulastArt.setTitle("Art hinzufügen");
dlgAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
dlgAddBaulastArt.setModal(true);
panAddBaulastArt.setMaximumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setMinimumSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setPreferredSize(new java.awt.Dimension(300, 120));
panAddBaulastArt.setLayout(new java.awt.GridBagLayout());
lblSuchwortEingeben1.setFont(new java.awt.Font("Tahoma", 1, 11));
lblSuchwortEingeben1.setText("Bitte Art auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
panAddBaulastArt.add(lblSuchwortEingeben1, gridBagConstraints);
cbBaulastArt.setMaximumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setMinimumSize(new java.awt.Dimension(250, 20));
cbBaulastArt.setPreferredSize(new java.awt.Dimension(250, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(cbBaulastArt, gridBagConstraints);
panMenButtons1.setLayout(new java.awt.GridBagLayout());
btnMenAbort1.setText("Abbrechen");
btnMenAbort1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenAbort1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenAbort1, gridBagConstraints);
btnMenOk1.setText("Ok");
btnMenOk1.setMaximumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setMinimumSize(new java.awt.Dimension(85, 23));
btnMenOk1.setPreferredSize(new java.awt.Dimension(85, 23));
btnMenOk1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMenOk1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons1.add(btnMenOk1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddBaulastArt.add(panMenButtons1, gridBagConstraints);
dlgAddBaulastArt.getContentPane().add(panAddBaulastArt, java.awt.BorderLayout.CENTER);
dlgAddLandParcelDiv.setTitle("Flurstück hinzufügen");
dlgAddLandParcelDiv.setMinimumSize(new java.awt.Dimension(380, 120));
dlgAddLandParcelDiv.setModal(true);
panAddLandParcel1.setMaximumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setMinimumSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setPreferredSize(new java.awt.Dimension(180, 180));
panAddLandParcel1.setLayout(new java.awt.GridBagLayout());
lblFlurstueckAuswaehlen.setFont(new java.awt.Font("Tahoma", 1, 11));
lblFlurstueckAuswaehlen.setText("Bitte Flurstück auswählen:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(15, 10, 20, 10);
panAddLandParcel1.add(lblFlurstueckAuswaehlen, gridBagConstraints);
cbParcels1.setEditable(true);
cbParcels1.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels1.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels1.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels1, gridBagConstraints);
panMenButtons2.setLayout(new java.awt.GridBagLayout());
btnFlurstueckAddMenCancel.setText("Abbrechen");
btnFlurstueckAddMenCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenCancelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenCancel, gridBagConstraints);
btnFlurstueckAddMenOk.setText("Ok");
btnFlurstueckAddMenOk.setMaximumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setMinimumSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.setPreferredSize(new java.awt.Dimension(85, 23));
btnFlurstueckAddMenOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFlurstueckAddMenOkActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panMenButtons2.add(btnFlurstueckAddMenOk, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(panMenButtons2, gridBagConstraints);
cbParcels2.setEditable(true);
cbParcels2.setEnabled(false);
cbParcels2.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels2.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels2.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels2ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels2, gridBagConstraints);
cbParcels3.setEditable(true);
cbParcels3.setEnabled(false);
cbParcels3.setMaximumSize(new java.awt.Dimension(100, 18));
cbParcels3.setMinimumSize(new java.awt.Dimension(100, 18));
cbParcels3.setPreferredSize(new java.awt.Dimension(100, 18));
cbParcels3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbParcels3ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 0.33;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(cbParcels3, gridBagConstraints);
lblGemarkung.setText("Gemarkung");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkung, gridBagConstraints);
lblFlur.setText("Flur");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlur, gridBagConstraints);
lblFlurstueck.setText("Flurstück");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblFlurstueck, gridBagConstraints);
lblGemarkungsname.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panAddLandParcel1.add(lblGemarkungsname, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
panAddLandParcel1.add(jSeparator1, gridBagConstraints);
dlgAddLandParcelDiv.getContentPane().add(panAddLandParcel1, java.awt.BorderLayout.CENTER);
setOpaque(false);
setLayout(new java.awt.BorderLayout());
panMain.setOpaque(false);
panMain.setLayout(new java.awt.GridBagLayout());
rpFSBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBeguenstigt.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBeguenstigt.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBeguenstigt.setOpaque(false);
lstFlurstueckeBeguenstigt.setFixedCellWidth(270);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_beguenstigt}");
org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBeguenstigt);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBeguenstigt.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBeguenstigtMouseClicked(evt);
}
});
scpFlurstueckeBeguenstigt.setViewportView(lstFlurstueckeBeguenstigt);
rpFSBeguenstigt.add(scpFlurstueckeBeguenstigt, java.awt.BorderLayout.CENTER);
semiRoundedPanel1.setBackground(java.awt.Color.darkGray);
semiRoundedPanel1.setLayout(new java.awt.GridBagLayout());
lblHeadBegFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBegFlurstuecke.setText("Begünstigte Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel1.add(lblHeadBegFlurstuecke, gridBagConstraints);
rpFSBeguenstigt.add(semiRoundedPanel1, java.awt.BorderLayout.NORTH);
panControlsFSBeg.setOpaque(false);
panControlsFSBeg.setLayout(new java.awt.GridBagLayout());
btnAddBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnAddBeguenstigt, gridBagConstraints);
btnRemoveBeguenstigt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBeguenstigt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBeguenstigt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBeguenstigtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBeg.add(btnRemoveBeguenstigt, gridBagConstraints);
rpFSBeguenstigt.add(panControlsFSBeg, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
panMain.add(rpFSBeguenstigt, gridBagConstraints);
rpFSBelastet.setMaximumSize(new java.awt.Dimension(270, 195));
scpFlurstueckeBelastet.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5), javax.swing.BorderFactory.createEtchedBorder()));
scpFlurstueckeBelastet.setMaximumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setMinimumSize(new java.awt.Dimension(270, 142));
scpFlurstueckeBelastet.setOpaque(false);
lstFlurstueckeBelastet.setFixedCellWidth(270);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flurstuecke_belastet}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFlurstueckeBelastet);
bindingGroup.addBinding(jListBinding);
lstFlurstueckeBelastet.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lstFlurstueckeBelastetMouseClicked(evt);
}
});
scpFlurstueckeBelastet.setViewportView(lstFlurstueckeBelastet);
rpFSBelastet.add(scpFlurstueckeBelastet, java.awt.BorderLayout.CENTER);
semiRoundedPanel2.setBackground(java.awt.Color.darkGray);
semiRoundedPanel2.setLayout(new java.awt.GridBagLayout());
lblHeadBelFlurstuecke.setForeground(new java.awt.Color(255, 255, 255));
lblHeadBelFlurstuecke.setText("Belastete Flurstücke");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
semiRoundedPanel2.add(lblHeadBelFlurstuecke, gridBagConstraints);
rpFSBelastet.add(semiRoundedPanel2, java.awt.BorderLayout.NORTH);
panControlsFSBel.setOpaque(false);
panControlsFSBel.setLayout(new java.awt.GridBagLayout());
btnAddBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnAddBelastet, gridBagConstraints);
btnRemoveBelastet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveBelastet.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveBelastet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveBelastetActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panControlsFSBel.add(btnRemoveBelastet, gridBagConstraints);
rpFSBelastet.add(panControlsFSBel, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
panMain.add(rpFSBelastet, gridBagConstraints);
rpInfo.setLayout(new java.awt.GridBagLayout());
lblDescLaufendeNr.setText("Laufende Nummer:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLaufendeNr, gridBagConstraints);
lblDescEintragungsdatum.setText("Eintragungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescEintragungsdatum, gridBagConstraints);
lblDescBefristungsdatum.setText("Befristungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBefristungsdatum, gridBagConstraints);
lblDescGeschlossenAm.setText("Geschlossen am:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescGeschlossenAm, gridBagConstraints);
lblDescLoeschungsdatum.setText("Löschungsdatum:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLoeschungsdatum, gridBagConstraints);
lblDescTextblatt.setText("Textblatt:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescTextblatt, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.textblatt}"), txtTextblatt, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtTextblatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"), txtLaufendeNr, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
rpInfo.add(txtLaufendeNr, gridBagConstraints);
lblDescLageplan.setText("Lageplan:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lageplan}"), txtLageplan, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("nicht verfügbar");
binding.setSourceUnreadableValue("");
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(txtLageplan, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.loeschungsdatum}"), defaultBindableDateChooser4, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser4, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eintragungsdatum}"), defaultBindableDateChooser1, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser1, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.befristungsdatum}"), defaultBindableDateChooser2, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser2, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geschlossen_am}"), defaultBindableDateChooser3, org.jdesktop.beansbinding.BeanProperty.create("date"));
binding.setSourceNullValue(null);
binding.setSourceUnreadableValue(null);
binding.setConverter(sqlDateToUtilDateConverter);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(defaultBindableDateChooser3, gridBagConstraints);
rpHeadInfo.setBackground(java.awt.Color.darkGray);
rpHeadInfo.setLayout(new java.awt.GridBagLayout());
lblHeadInfo.setForeground(new java.awt.Color(255, 255, 255));
lblHeadInfo.setText("Info");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpHeadInfo.add(lblHeadInfo, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
rpInfo.add(rpHeadInfo, gridBagConstraints);
lblDescBaulastart.setText("Arten:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(lblDescBaulastart, gridBagConstraints);
scpBaulastart.setMaximumSize(new java.awt.Dimension(1500, 500));
scpBaulastart.setMinimumSize(new java.awt.Dimension(150, 75));
scpBaulastart.setPreferredSize(new java.awt.Dimension(150, 75));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art}");
jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBaulastArt);
bindingGroup.addBinding(jListBinding);
scpBaulastart.setViewportView(lstBaulastArt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(scpBaulastart, gridBagConstraints);
panArtControls.setOpaque(false);
panArtControls.setLayout(new java.awt.GridBagLayout());
btnAddArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnAddArt, gridBagConstraints);
btnRemoveArt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveArt.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveArt.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveArt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveArtActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panArtControls.add(btnRemoveArt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
rpInfo.add(panArtControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
panMain.add(rpInfo, gridBagConstraints);
add(panMain, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/com/voxbone/kelpie/Session.java b/src/main/java/com/voxbone/kelpie/Session.java
index 5e741e8..deb11d8 100755
--- a/src/main/java/com/voxbone/kelpie/Session.java
+++ b/src/main/java/com/voxbone/kelpie/Session.java
@@ -1,1517 +1,1527 @@
/**
* Copyright 2012 Voxbone SA/NV
*
* 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.voxbone.kelpie;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import javax.sip.address.SipURI;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.jabberstudio.jso.JID;
import org.jabberstudio.jso.JSOImplementation;
import org.jabberstudio.jso.NSI;
import org.jabberstudio.jso.Packet;
import org.jabberstudio.jso.Stream;
import org.jabberstudio.jso.StreamContext;
import org.jabberstudio.jso.StreamElement;
import org.jabberstudio.jso.StreamError;
import org.jabberstudio.jso.StreamException;
import org.jabberstudio.jso.event.PacketEvent;
import org.jabberstudio.jso.event.PacketListener;
import org.jabberstudio.jso.event.StreamStatusEvent;
import org.jabberstudio.jso.event.StreamStatusListener;
import org.jabberstudio.jso.io.src.ChannelStreamSource;
import org.jabberstudio.jso.util.Utilities;
/**
* Represents an authenticated Server to Server java connection
*
* This class can also manage inbound Dialback challenge requests,
* (for chalanges we initate the DialbackSession is used instead)
*
* There is one connection for to each server keplie is federated with (in each direction)
*/
class Session extends Thread implements StreamStatusListener, PacketListener
{
enum StreamType { RTP, RTCP, VRTP, VRTCP }
private Stream conn;
private String host;
private SocketChannel socketChannel;
private String sessionKey;
private boolean confirmed;
private List<Packet> queue = new LinkedList<Packet>();
private static String clientName = null;
private static String clientVersion = null;
private static String fakeId = null;
private static boolean mapJID = false;
private static String iconHash;
private static byte [] iconData;
private static int iconSize;
static Logger logger = Logger.getLogger(Session.class);
public String internalCallId;
private static String convertToHex(byte [] data)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++)
{
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do
{
if ((0 <= halfbyte) && (halfbyte <= 9))
{
buf.append((char) ('0' + halfbyte));
}
else
{
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
static
{
MessageDigest md;
try
{
md = MessageDigest.getInstance("SHA-1");
byte [] sha1hash = new byte[40];
byte [] data = new byte[20000];
InputStream is = Session.class.getResourceAsStream("/icon.jpg");
iconSize = is.read(data, 0, data.length);
iconData = new byte[iconSize];
System.arraycopy(data, 0, iconData, 0, iconSize);
md.update(iconData);
sha1hash = md.digest();
iconHash = convertToHex(sha1hash);
}
catch (NoSuchAlgorithmException e)
{
}
catch (IOException e)
{
logger.error("Error reading icon", e);
}
catch (Exception e)
{
logger.error("Error reading icon", e);
}
}
public static void configure(Properties properties)
{
clientName = "http://" + properties.getProperty("com.voxbone.kelpie.hostname", "kelpie.voxbone.com") + "/caps";
clientVersion = "0.2";
fakeId = properties.getProperty("com.voxbone.kelpie.service_name", "kelpie");
mapJID = Boolean.parseBoolean(properties.getProperty("com.voxbone.kelpie.map.strict", "false"));
}
private long idNum = 0;
public Session(String internalCallId, String host, SocketChannel sc) throws StreamException
{
this.internalCallId = internalCallId;
JSOImplementation jso = JSOImplementation.getInstance();
this.socketChannel = sc;
this.host = host;
conn = jso.createStream(Utilities.SERVER_NAMESPACE);
conn.getOutboundContext().addNamespace("db", "jabber:server:dialback");
conn.getOutboundContext().setID(Integer.toHexString((int) (Math.random() * 1000000000)));
conn.addStreamStatusListener(new StatusMonitor(this.internalCallId));
conn.addStreamStatusListener(this);
conn.addPacketListener(PacketEvent.RECEIVED, this);
conn.connect(new ChannelStreamSource(sc));
start();
}
public synchronized void sendPacket(Packet p) throws StreamException
{
if (!confirmed)
{
queue.add(p);
}
else
{
try
{
conn.send(p);
}
catch (StreamException e)
{
// ignore ...
}
}
}
public void sendDBResult(String to) throws StreamException
{
JID local = new JID(host);
JID remote = new JID(to);
conn.getOutboundContext().setTo(remote);
SessionManager.addSession(this);
conn.open();
Packet p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
sessionKey = UUID.randomUUID().toString();
p.addText(sessionKey);
conn.send(p);
}
public Stream getConnection()
{
return conn;
}
public String getSessionKey()
{
return sessionKey;
}
public void confirm()
{
confirmed = true;
}
public boolean isConfirmed()
{
return confirmed;
}
public boolean execute() throws Exception
{
boolean running = true;
try
{
if (conn.getCurrentStatus().isConnected())
{
conn.process();
}
else
{
conn.close();
conn.disconnect();
}
}
catch (StreamException e)
{
// ignore ...
conn.close();
conn.disconnect();
}
if (conn.getCurrentStatus().isDisconnected())
{
running = false;
SessionManager.removeSession(this);
}
return running;
}
public void packetTransferred(PacketEvent evt)
{
try
{
JID local = evt.getData().getTo();
JID remote = evt.getData().getFrom();
logger.debug("[[" + internalCallId + "]] got message of " + evt.getData().getQualifiedName());
if (evt.getData().getQualifiedName().equals("db:result"))
{
String type = evt.getData().getAttributeValue("type");
if (type != null && type.length() > 0)
{
synchronized (this)
{
confirm();
while (!queue.isEmpty())
{
conn.send(queue.remove(0));
}
}
return;
}
String result = evt.getData().normalizeText();
evt.setHandled(true);
// this isn't a dialback connection - add it to the list of connections
// we don't save this because it can only be used for inbound stuff
//SessionManager.addSession(this);
logger.debug("[[" + internalCallId + "]] Got a result response: " + evt.getData().normalizeText());
logger.debug("[[" + internalCallId + "]] Packet is of type: " + evt.getData().getClass().getName());
DialbackSession dbs = new DialbackSession(internalCallId, local, remote, conn.getOutboundContext().getID(), result);
boolean valid = dbs.doDialback();
Packet p = null;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "valid");
confirm();
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Error sending packet!", e);
}
if (!valid)
{
// close the stream if invalid
conn.close();
}
}
else if (evt.getData().getQualifiedName().equals("db:verify"))
{
String key = evt.getData().normalizeText();
// if we get a db:verify here and n
logger.debug("[[" + internalCallId + "]] Got a verification token " + key);
Session sess = SessionManager.getSession(evt.getData().getFrom());
boolean valid = false;
if (sess != null)
{
logger.debug("[[" + internalCallId + "]] Found matching session");
if (key.equals(sess.getSessionKey()))
{
logger.debug("[[" + internalCallId + "]] Keys Match! Sending the ok");
valid = true;
}
}
Packet p;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setID(evt.getData().getID());
p.setAttributeValue("type", "valid");
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Steam error in session", e);
}
}
else if ( evt.getData().getQualifiedName().equals(":message")
&& evt.getData().getAttributeValue("type") != null
&& evt.getData().getAttributeValue("type").equals("chat"))
{
logger.debug("[[" + internalCallId + "]] Got an IM");
StreamElement body = evt.getData().getFirstElement("body");
if (body != null)
{
String msg = body.normalizeText();
logger.debug("[[" + internalCallId + "]] Body=" + msg);
MessageMessage mm = new MessageMessage(evt.getData());
if (msg.equals("callback"))
{
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.offerPayloads.add(CallSession.PAYLOAD_PCMU);
cs.offerPayloads.add(CallSession.PAYLOAD_PCMA);
Session sess = SessionManager.findCreateSession(cs.jabberLocal.getDomain(), cs.jabberRemote);
sess.startCall(cs, evt.getData().getTo().getNode(), UriMappings.toSipId(evt.getData().getFrom()));
}
else if (msg.startsWith("/dial:"))
{
logger.debug("[[" + internalCallId + "]] DIAL command detected");
CallSession cs = CallManager.getSession(evt.getData().getFrom(), evt.getData().getTo());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found, sending dtmfs");
for (int i = "/dial:".length(); i < msg.length(); i++)
{
cs.relay.sendSipDTMF(msg.charAt(i));
}
}
}
else
{
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
if (sub != null)
{
domain = ((SipURI)sub.remoteParty.getURI()).getHost();
}
SipService.sendMessageMessage(mm, domain);
}
}
}
else if (evt.getData().getQualifiedName().equals(":presence"))
{
logger.debug("[[" + internalCallId + "]] Got presence stanza");
String type = evt.getData().getAttributeValue("type");
if (type == null || type.equals("unavailable"))
{
logger.debug("[[" + internalCallId + "]] Got a presence message");
StreamElement caps = evt.getData().getFirstElement(new NSI("c", "http://jabber.org/protocol/caps"));
if (caps != null && caps.getAttributeValue("ext") != null)
{
logger.debug("[[" + internalCallId + "]] Caps found");
if (caps.getAttributeValue("ext").contains("voice-v1"))
{
logger.debug("[[" + internalCallId + "]] Voice support detected, taking note");
UriMappings.addVoiceResource(evt.getData().getFrom());
}
}
Presence pres = new Presence(evt.getData());
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found matching subscription!");
sub.sendNotify(false, pres);
}
}
else
{
if (type.equals("subscribe"))
{
logger.debug("[[" + internalCallId + "]] New subscription received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub == null)
{
logger.debug("[[" + internalCallId + "]] No existing subscription, sending one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
else if (sub.remoteTag != null)
{
logger.debug("[[" + internalCallId + "]] Subscription exists, sending refresh");
sub.sendSubscribe(false);
}
}
else
{
logger.debug("[[" + internalCallId + "]] Subscription to " + fakeId + ", sending dummy accept");
Session sess = SessionManager.findCreateSession(host, evt.getData().getFrom());
sess.sendSubscribeRequest(new JID(fakeId + "@" + host), evt.getData().getFrom(), "subscribed");
}
}
else if (type.equals("unsubscribe"))
{
logger.debug("[[" + internalCallId + "]] Unsubscribe request");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.removeSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing subscription");
sub.sendSubscribe(true);
}
sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing watcher");
SipSubscriptionManager.removeWatcher(from, sub);
sub.sendNotify(true, null);
}
}
}
else if (type.equals("subscribed"))
{
logger.debug("[[" + internalCallId + "]] Jabber client accepted subscription, sending notify");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
sub.sendNotify(false, null);
}
}
else if (type.equals("probe"))
{
logger.debug("[[" + internalCallId + "]] Probe received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found a subscription, sending re-subscribe");
sub.sendSubscribe(false);
}
else
{
logger.debug("[[" + internalCallId + "]] No Subscription for this person, sending 0 length one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
}
}
}
}
else if (evt.getData().getQualifiedName().equals(":iq"))
{
Packet packet = evt.getData();
logger.debug("[[" + internalCallId + "]] got disco packet");
if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("query", "http://jabber.org/protocol/disco#info")))
{
logger.debug("[[" + internalCallId + "]] Got a feature query");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("query", "http://jabber.org/protocol/disco#info"));
query.setAttributeValue("node", clientName + "#" + clientVersion);
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/voice/v1");
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/video/v1");
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
else if ( packet.getAttributeValue("type").equals("error"))
{
logger.debug("[[" + internalCallId + "]] Got error stanza");
StreamElement error = packet.getFirstElement("error");
if ( error != null )
{
logger.debug("[[" + internalCallId + "]] Error code: " + error.getAttributeValue("code") + " type: " + error.getAttributeValue("type") );
if (error.getAttributeValue("type") == "cancel") {
- logger.debug("[[" + internalCallId + "]] Sending cancel..." );
- // mapJID = true;
+ String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
+ CallSession cs = CallManager.getSession(sessionId);
+ if (cs != null) {
+ logger.debug("[[" + internalCallId + "]] Sending reject..." );
+ SipService.sendReject(cs);
+ logger.debug("[[" + internalCallId + "]] Removing session... " );
+ CallManager.removeSession(cs);
+ }
+ } else {
+ logger.debug("[[" + internalCallId + "]] Proceeding... ");
}
}
+ /*
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null && mapJID)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
+ */
}
else if ( packet.getAttributeValue("type").equals("set")
&& packet.getFirstElement(new NSI("session", "http://www.google.com/session")) != null)
{
if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("initiate"))
{
logger.debug("[[" + internalCallId + "]] Got a request to start a call");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.parseInitiate(packet);
CallManager.addSession(cs);
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(UriMappings.toSipId(cs.jabberRemote), cs.jabberLocal.getNode());
if (sub != null)
{
domain = ((SipURI) sub.remoteParty.getURI()).getHost();
}
SipService.sendInvite(cs, domain);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-info"))
{
logger.debug("[[" + internalCallId + "]] Got transport info");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
StreamElement origTransport = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
if (origTransport.getNamespaceURI().equals("http://www.google.com/transport/p2p"))
{
StreamElement candidate = origTransport.getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (!cs.sentTransport)
{
sess.sendTransportInfo(cs);
cs.sentTransport = true;
}
sess.acceptTransport(packet);
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("candidates"))
{
logger.debug("[[" + internalCallId + "]] Got candidate");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
/*StreamElement origTransport = */packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
StreamElement candidate = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (candidate.getAttributeValue("name").equals("video_rtp")/* || candidate.getAttributeValue("name").equals("video_rtcp")*/)
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("video_rtcp"))
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTCP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
else if (candidate.getAttributeValue("name").equals("rtp")/* || candidate.getAttributeValue("name").equals("rtcp")*/)
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("rtcp"))
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTCP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = CallManager.getSession(packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found sending 200 OK");
cs.parseAccept(packet);
SipService.acceptCall(cs);
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("terminate"))
{
logger.debug("[[" + internalCallId + "]] Got a terminate");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding bye");
SipService.sendBye(cs);
CallManager.removeSession(cs);
}
}
else if ( packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("reject"))
{
logger.debug("[[" + internalCallId + "]] Got a reject");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
}
}
else if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("vCard", "vcard-temp")))
{
logger.debug("[[" + internalCallId + "]] Got an ICON request!");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("vCard", "vcard-temp"));
StreamElement fullName = query.addElement("FN");
//if a telephone number add a + to be pretty
if(packet.getTo().getNode().toString().matches("[0-9]+"))
{
fullName.addText("+" + packet.getTo().getNode().toString());
}
else
{
fullName.addText(packet.getTo().getNode().toString());
}
StreamElement photo = query.addElement("PHOTO");
StreamElement type = photo.addElement("TYPE");
type.addText("image/jpeg");
StreamElement binval = photo.addElement("BINVAL");
byte [] encoded = Base64.encodeBase64Chunked(iconData);
binval.addText(new String(encoded));
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
}
}
catch (Exception e)
{
logger.error("Exception in packetTransferred", e);
}
}
private void ackIQ(Packet packet) throws StreamException
{
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
sendPacket(p);
}
public void acceptTransport(Packet origPacket) throws StreamException
{
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
logger.debug("[[" + internalCallId + "]] Accepting a transport");
p.setFrom(origPacket.getTo());
p.setTo(origPacket.getFrom());
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
StreamElement origSession = origPacket.getFirstElement();
StreamElement session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "transport-accept");
session.setID(origSession.getID());
session.setAttributeValue("initiator", origSession.getAttributeValue("initiator"));
session.addElement(new NSI("transport", "http://www.google.com/transport/p2p"));
sendPacket(p);
}
public boolean sendSubscribeRequest(JID from, JID to, String type)
{
Packet p = conn.getDataFactory().createPacketNode(new NSI("presence", Utilities.SERVER_NAMESPACE), Packet.class);
p.setFrom(from);
p.setTo(to);
p.setAttributeValue("type", type);
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Stream Error sending Subscribe!", e);
return false;
}
return true;
}
public boolean startCall(CallSession callSession, String from, String to)
{
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", Utilities.SERVER_NAMESPACE), Packet.class);
callSession.jabberLocal = new JID(from + "@" + host + "/kelpie");
callSession.jabberRemote = new JID(UriMappings.toJID(to).toString() + "/" + UriMappings.getVoiceResource(UriMappings.toJID(to)));
callSession.jabberInitiator = callSession.jabberLocal.toString();
callSession.jabberSessionId = Integer.toString((int) (Math.random() * 1000000000));
CallManager.addSession(callSession);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
StreamElement session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "initiate");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
StreamElement description = null;
if (callSession.vRelay != null)
{
description = session.addElement(new NSI("description", "http://www.google.com/session/video"));
for (CallSession.VPayload payload : callSession.offerVPayloads)
{
StreamElement payload_type = description.addElement("payload-type");
payload_type.setAttributeValue("id", Integer.toString(payload.id));
payload_type.setAttributeValue("name", payload.name);
payload_type.setAttributeValue("width", Integer.toString(payload.width));
payload_type.setAttributeValue("height", Integer.toString(payload.height));
payload_type.setAttributeValue("framerate", Integer.toString(payload.framerate));
}
}
else
{
description = session.addElement(new NSI("description", "http://www.google.com/session/phone"));
}
for (CallSession.Payload payload : callSession.offerPayloads)
{
StreamElement payload_type = description.addElement("payload-type", "http://www.google.com/session/phone");
payload_type.setAttributeValue("id", Integer.toString(payload.id));
payload_type.setAttributeValue("clockrate", Integer.toString(payload.clockRate));
payload_type.setAttributeValue("bitrate", Integer.toString(payload.bitRate));
payload_type.setAttributeValue("name", payload.name);
}
/*StreamElement transport = */session.addElement(new NSI("transport", "http://www.google.com/transport/p2p"));
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Stream error in startCall", e);
return false;
}
if (callSession.vRelay != null)
{
callSession.sentTransport = true;
callSession.sentVTransport = true;
sendTransportCandidates(callSession, StreamType.RTCP);
sendTransportCandidates(callSession, StreamType.RTP);
sendTransportCandidates(callSession, StreamType.VRTCP);
sendTransportCandidates(callSession, StreamType.VRTP);
}
else
{
callSession.sentTransport = true;
sendTransportInfo(callSession);
}
return true;
}
private boolean sendTransportInfo(CallSession callSession)
{
Packet p;
StreamElement session;
StreamElement transport;
p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
Random r = new Random();
byte [] bytes = new byte[4];
r.nextBytes(bytes);
callSession.candidateUser = String.format("%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3]);
session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "transport-info");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
transport = session.addElement(new NSI("transport", "http://www.google.com/transport/p2p"));
StreamElement candidate = transport.addElement("candidate");
candidate.setAttributeValue("name", "rtp");
candidate.setAttributeValue("address", SipService.getLocalIP());
candidate.setAttributeValue("port", Integer.toString(callSession.relay.getJabberPort()));
candidate.setAttributeValue("preference", "1");
candidate.setAttributeValue("username", callSession.candidateUser);
candidate.setAttributeValue("password", callSession.candidateUser);
candidate.setAttributeValue("protocol", "udp");
candidate.setAttributeValue("generation", "0");
candidate.setAttributeValue("type", "local");
candidate.setAttributeValue("network", "0");
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error while sending TransportInfo", e);
return false;
}
return true;
}
private boolean sendTransportCandidates(CallSession callSession, StreamType type)
{
Packet p;
StreamElement session;
Random r = new Random();
byte [] bytes = new byte[4];
r.nextBytes(bytes);
if (type == StreamType.RTP || type == StreamType.RTCP)
{
if (callSession.candidateUser == null)
{
callSession.candidateUser = String.format("%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3]);
}
p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "candidates");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
StreamElement candidate = session.addElement("candidate");
if (type == StreamType.RTP)
{
candidate.setAttributeValue("name", "rtp");
candidate.setAttributeValue("address", SipService.getLocalIP());
candidate.setAttributeValue("port", Integer.toString(callSession.relay.getJabberPort()));
}
else
{
candidate.setAttributeValue("name", "rtcp");
candidate.setAttributeValue("address", SipService.getLocalIP());
candidate.setAttributeValue("port", Integer.toString(callSession.relay.getJabberRtcpPort()));
}
candidate.setAttributeValue("preference", "1");
candidate.setAttributeValue("username", callSession.candidateUser);
candidate.setAttributeValue("password", callSession.candidateUser);
candidate.setAttributeValue("protocol", "udp");
candidate.setAttributeValue("generation", "0");
candidate.setAttributeValue("type", "local");
candidate.setAttributeValue("network", "0");
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error while sending audio TransportCandidates", e);
return false;
}
}
else if (type == StreamType.VRTP || type == StreamType.VRTCP)
{
if (callSession.candidateVUser == null)
{
callSession.candidateVUser = String.format("%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3]);
}
p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "candidates");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
StreamElement candidate = session.addElement("candidate");
if (type == StreamType.VRTP)
{
candidate.setAttributeValue("name", "video_rtp");
candidate.setAttributeValue("address", SipService.getLocalIP());
candidate.setAttributeValue("port", Integer.toString(callSession.vRelay.getJabberPort()));
}
else
{
candidate.setAttributeValue("name", "video_rtcp");
candidate.setAttributeValue("address", SipService.getLocalIP());
candidate.setAttributeValue("port", Integer.toString(callSession.vRelay.getJabberRtcpPort()));
}
candidate.setAttributeValue("preference", "1");
candidate.setAttributeValue("username", callSession.candidateVUser);
candidate.setAttributeValue("password", callSession.candidateVUser);
candidate.setAttributeValue("protocol", "udp");
candidate.setAttributeValue("generation", "0");
candidate.setAttributeValue("type", "local");
candidate.setAttributeValue("network", "0");
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error while sending video TransportCandidates", e);
return false;
}
}
return true;
}
public boolean sendAccept(CallSession callSession)
{
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", Utilities.SERVER_NAMESPACE), Packet.class);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
StreamElement session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "accept");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
StreamElement description = null;
if (callSession.vRelay != null)
{
description = session.addElement(new NSI("description", "http://www.google.com/session/video"));
for (CallSession.VPayload payload : callSession.answerVPayloads)
{
StreamElement payload_type = description.addElement("payload-type");
payload_type.setAttributeValue("id", Integer.toString(payload.id));
payload_type.setAttributeValue("name", payload.name);
payload_type.setAttributeValue("width", Integer.toString(payload.width));
payload_type.setAttributeValue("height", Integer.toString(payload.height));
payload_type.setAttributeValue("framerate", Integer.toString(payload.framerate));
payload_type.setAttributeValue("clockrate", Integer.toString(payload.clockRate));
}
}
else
{
description = session.addElement(new NSI("description", "http://www.google.com/session/phone"));
}
for (CallSession.Payload payload : callSession.answerPayloads)
{
StreamElement payload_type = description.addElement("payload-type", "http://www.google.com/session/phone");
payload_type.setAttributeValue("id", Integer.toString(payload.id));
payload_type.setAttributeValue("clockrate", Integer.toString(payload.clockRate));
payload_type.setAttributeValue("bitrate", Integer.toString(payload.bitRate));
payload_type.setAttributeValue("name", payload.name);
}
/*StreamElement transport = */session.addElement(new NSI("transport", "http://www.google.com/transport/p2p"));
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error sending accept", e);
return false;
}
return true;
}
public boolean sendBye(CallSession callSession)
{
CallManager.removeSession(callSession);
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", Utilities.SERVER_NAMESPACE), Packet.class);
p.setFrom(callSession.jabberLocal);
p.setTo(callSession.jabberRemote);
p.setID(Long.toString(++this.idNum));
p.setAttributeValue("type", "set");
StreamElement session = p.addElement(new NSI("session", "http://www.google.com/session"));
session.setAttributeValue("type", "terminate");
session.setID(callSession.jabberSessionId);
session.setAttributeValue("initiator", callSession.jabberInitiator);
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error sending BYE", e);
return false;
}
return true;
}
public boolean sendPresence(Presence pres)
{
if (pres == null)
{
return false;
}
Packet p = conn.getDataFactory().createPacketNode(new NSI("presence", Utilities.SERVER_NAMESPACE), Packet.class);
if (pres.type != null && pres.type.equals("closed"))
{
p.setAttributeValue("type", "unavailable");
}
JID from;
if (pres.resource != null)
{
from = new JID(pres.from + "@" + host + "/" + pres.resource);
}
else
{
from = new JID(pres.from + "@" + host);
}
JID to = UriMappings.toJID(pres.to);
p.setFrom(from);
p.setTo(to);
StreamElement caps = conn.getDataFactory().createElementNode(new NSI("c", "http://jabber.org/protocol/caps"));
caps.setAttributeValue("ext", "voice-v1 video-v1 camera-v1");
caps.setAttributeValue("node", clientName);
caps.setAttributeValue("ver", clientVersion);
p.add(caps);
if (pres.show != null)
{
StreamElement show = conn.getDataFactory().createElementNode(new NSI("show", Utilities.SERVER_NAMESPACE));
show.addText(pres.show);
p.add(show);
}
if (pres.note != null)
{
StreamElement status = conn.getDataFactory().createElementNode(new NSI("status", Utilities.SERVER_NAMESPACE));
status.addText(pres.note);
p.add(status);
}
if (pres.resource != null && pres.resource.equals("KelpiePhone"))
{
StreamElement priority = conn.getDataFactory().createElementNode(new NSI("priority", Utilities.SERVER_NAMESPACE));
priority.addText("0.1");
p.add(priority);
}
else
{
StreamElement priority = conn.getDataFactory().createElementNode(new NSI("priority", Utilities.SERVER_NAMESPACE));
priority.addText("1");
p.add(priority);
}
StreamElement vCard = conn.getDataFactory().createElementNode(new NSI("x", "vcard-temp:x:update"));
StreamElement photo = vCard.addElement("photo");
photo.addText(iconHash);
p.add(vCard);
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error sending presence", e);
return false;
}
if (pres.resource != null && !pres.resource.equals("KelpiePhone"))
{
p = conn.getDataFactory().createPacketNode(new NSI("presence", Utilities.SERVER_NAMESPACE), Packet.class);
p.setAttributeValue("type", "unavailable");
from = new JID(pres.from + "@" +host + "/KelpiePhone");
p.setFrom(from);
p.setTo(to);
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error sending presence", e);
return false;
}
}
return true;
}
public boolean sendMessageMessage(MessageMessage mm)
{
JID from = new JID(mm.from + "@" + host);
JID to = UriMappings.toJID(mm.to);
if (to == null)
{
logger.error("[[" + internalCallId + "]] No mapping for to destination : " + mm.to);
return false;
}
Packet p = conn.getDataFactory().createPacketNode(new NSI("message", Utilities.SERVER_NAMESPACE), Packet.class);
p.setFrom(from);
p.setTo(to);
p.addElement("body");
p.getFirstElement("body").addText(mm.body);
p.setAttributeValue("type", "chat");
if (mm.subject != null)
{
p.addElement("subject");
p.getFirstElement("subject").addText(mm.subject);
}
if (mm.thread != null)
{
p.addElement("thread");
p.getFirstElement("thread").addText(mm.thread);
}
try
{
sendPacket(p);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error sending IM", e);
return false;
}
return true;
}
public void statusChanged(StreamStatusEvent evt)
{
Stream conn = evt.getStream();
StreamContext ctx = evt.getContext();
try
{
if (ctx.isInbound())
{
if (evt.getNextStatus() == Stream.OPENED)
{
// Finish opening
String ns = conn.getDefaultNamespace();
conn.getOutboundContext().setFrom(new JID(host));
conn.open();
// Validate name
if (logger.isDebugEnabled())
{
logger.debug("[[" + internalCallId + "]] namespace == " + ns);
}
if (ctx.getNamespaceByURI(ns) == null)
{
StreamError err = ctx.getDataFactory().createStreamError(StreamError.INVALID_NAMESPACE_CONDITION);
conn.close(new StreamException(err));
}
}
else if (evt.getNextStatus() == Stream.CLOSED || evt.getNextStatus() == Stream.DISCONNECTED)
{
// Finish disconnecting
conn.close();
}
}
else if (ctx.isOutbound())
{
if (evt.getPreviousStatus() == Stream.OPENED && evt.getNextStatus() == Stream.CLOSED)
{
conn.disconnect();
}
}
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error changing status", e);
}
}
public void run()
{
Selector sel = null;
logger.info("[[" + internalCallId + "]] Session thread started: " + this.socketChannel.socket().toString());
try
{
sel = SelectorProvider.provider().openSelector();
socketChannel.register(sel, SelectionKey.OP_READ, this);
while (true)
{
if (sel.select() >= 0)
{
Iterator<SelectionKey> itr = sel.selectedKeys().iterator();
while (itr.hasNext())
{
SelectionKey key = itr.next();
itr.remove();
if (key.isReadable())
{
this.execute();
}
}
}
else
{
logger.error("[[" + internalCallId + "]] Select returned error");
}
if (conn.getCurrentStatus().isDisconnected())
{
break;
}
}
logger.info("[[" + internalCallId + "]] Session Connection finished: " + this.socketChannel.socket().toString());
sel.close();
}
catch (IOException e)
{
logger.error("[[" + internalCallId + "]] Error in xmpp session thread", e);
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Error in xmpp session thread", e);
}
catch (Exception e)
{
logger.error("[[" + internalCallId + "]] Error in xmpp session thread", e);
}
finally
{
try
{
if (sel != null)
{
sel.close();
}
}
catch (IOException e)
{
// we are dead already, RIP
}
}
// make sure the connection is closed
try
{
conn.close();
conn.disconnect();
try
{
socketChannel.socket().shutdownInput();
}
catch (IOException e)
{
// ignore
}
try
{
socketChannel.socket().shutdownOutput();
}
catch (IOException e)
{
// ignore
}
try
{
socketChannel.close();
}
catch (IOException e)
{
// ignore
}
}
catch (StreamException e)
{
logger.error("[[" + internalCallId + "]] Problem closing stream", e);
}
}
}
| false | true | public void packetTransferred(PacketEvent evt)
{
try
{
JID local = evt.getData().getTo();
JID remote = evt.getData().getFrom();
logger.debug("[[" + internalCallId + "]] got message of " + evt.getData().getQualifiedName());
if (evt.getData().getQualifiedName().equals("db:result"))
{
String type = evt.getData().getAttributeValue("type");
if (type != null && type.length() > 0)
{
synchronized (this)
{
confirm();
while (!queue.isEmpty())
{
conn.send(queue.remove(0));
}
}
return;
}
String result = evt.getData().normalizeText();
evt.setHandled(true);
// this isn't a dialback connection - add it to the list of connections
// we don't save this because it can only be used for inbound stuff
//SessionManager.addSession(this);
logger.debug("[[" + internalCallId + "]] Got a result response: " + evt.getData().normalizeText());
logger.debug("[[" + internalCallId + "]] Packet is of type: " + evt.getData().getClass().getName());
DialbackSession dbs = new DialbackSession(internalCallId, local, remote, conn.getOutboundContext().getID(), result);
boolean valid = dbs.doDialback();
Packet p = null;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "valid");
confirm();
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Error sending packet!", e);
}
if (!valid)
{
// close the stream if invalid
conn.close();
}
}
else if (evt.getData().getQualifiedName().equals("db:verify"))
{
String key = evt.getData().normalizeText();
// if we get a db:verify here and n
logger.debug("[[" + internalCallId + "]] Got a verification token " + key);
Session sess = SessionManager.getSession(evt.getData().getFrom());
boolean valid = false;
if (sess != null)
{
logger.debug("[[" + internalCallId + "]] Found matching session");
if (key.equals(sess.getSessionKey()))
{
logger.debug("[[" + internalCallId + "]] Keys Match! Sending the ok");
valid = true;
}
}
Packet p;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setID(evt.getData().getID());
p.setAttributeValue("type", "valid");
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Steam error in session", e);
}
}
else if ( evt.getData().getQualifiedName().equals(":message")
&& evt.getData().getAttributeValue("type") != null
&& evt.getData().getAttributeValue("type").equals("chat"))
{
logger.debug("[[" + internalCallId + "]] Got an IM");
StreamElement body = evt.getData().getFirstElement("body");
if (body != null)
{
String msg = body.normalizeText();
logger.debug("[[" + internalCallId + "]] Body=" + msg);
MessageMessage mm = new MessageMessage(evt.getData());
if (msg.equals("callback"))
{
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.offerPayloads.add(CallSession.PAYLOAD_PCMU);
cs.offerPayloads.add(CallSession.PAYLOAD_PCMA);
Session sess = SessionManager.findCreateSession(cs.jabberLocal.getDomain(), cs.jabberRemote);
sess.startCall(cs, evt.getData().getTo().getNode(), UriMappings.toSipId(evt.getData().getFrom()));
}
else if (msg.startsWith("/dial:"))
{
logger.debug("[[" + internalCallId + "]] DIAL command detected");
CallSession cs = CallManager.getSession(evt.getData().getFrom(), evt.getData().getTo());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found, sending dtmfs");
for (int i = "/dial:".length(); i < msg.length(); i++)
{
cs.relay.sendSipDTMF(msg.charAt(i));
}
}
}
else
{
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
if (sub != null)
{
domain = ((SipURI)sub.remoteParty.getURI()).getHost();
}
SipService.sendMessageMessage(mm, domain);
}
}
}
else if (evt.getData().getQualifiedName().equals(":presence"))
{
logger.debug("[[" + internalCallId + "]] Got presence stanza");
String type = evt.getData().getAttributeValue("type");
if (type == null || type.equals("unavailable"))
{
logger.debug("[[" + internalCallId + "]] Got a presence message");
StreamElement caps = evt.getData().getFirstElement(new NSI("c", "http://jabber.org/protocol/caps"));
if (caps != null && caps.getAttributeValue("ext") != null)
{
logger.debug("[[" + internalCallId + "]] Caps found");
if (caps.getAttributeValue("ext").contains("voice-v1"))
{
logger.debug("[[" + internalCallId + "]] Voice support detected, taking note");
UriMappings.addVoiceResource(evt.getData().getFrom());
}
}
Presence pres = new Presence(evt.getData());
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found matching subscription!");
sub.sendNotify(false, pres);
}
}
else
{
if (type.equals("subscribe"))
{
logger.debug("[[" + internalCallId + "]] New subscription received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub == null)
{
logger.debug("[[" + internalCallId + "]] No existing subscription, sending one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
else if (sub.remoteTag != null)
{
logger.debug("[[" + internalCallId + "]] Subscription exists, sending refresh");
sub.sendSubscribe(false);
}
}
else
{
logger.debug("[[" + internalCallId + "]] Subscription to " + fakeId + ", sending dummy accept");
Session sess = SessionManager.findCreateSession(host, evt.getData().getFrom());
sess.sendSubscribeRequest(new JID(fakeId + "@" + host), evt.getData().getFrom(), "subscribed");
}
}
else if (type.equals("unsubscribe"))
{
logger.debug("[[" + internalCallId + "]] Unsubscribe request");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.removeSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing subscription");
sub.sendSubscribe(true);
}
sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing watcher");
SipSubscriptionManager.removeWatcher(from, sub);
sub.sendNotify(true, null);
}
}
}
else if (type.equals("subscribed"))
{
logger.debug("[[" + internalCallId + "]] Jabber client accepted subscription, sending notify");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
sub.sendNotify(false, null);
}
}
else if (type.equals("probe"))
{
logger.debug("[[" + internalCallId + "]] Probe received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found a subscription, sending re-subscribe");
sub.sendSubscribe(false);
}
else
{
logger.debug("[[" + internalCallId + "]] No Subscription for this person, sending 0 length one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
}
}
}
}
else if (evt.getData().getQualifiedName().equals(":iq"))
{
Packet packet = evt.getData();
logger.debug("[[" + internalCallId + "]] got disco packet");
if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("query", "http://jabber.org/protocol/disco#info")))
{
logger.debug("[[" + internalCallId + "]] Got a feature query");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("query", "http://jabber.org/protocol/disco#info"));
query.setAttributeValue("node", clientName + "#" + clientVersion);
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/voice/v1");
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/video/v1");
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
else if ( packet.getAttributeValue("type").equals("error"))
{
logger.debug("[[" + internalCallId + "]] Got error stanza");
StreamElement error = packet.getFirstElement("error");
if ( error != null )
{
logger.debug("[[" + internalCallId + "]] Error code: " + error.getAttributeValue("code") + " type: " + error.getAttributeValue("type") );
if (error.getAttributeValue("type") == "cancel") {
logger.debug("[[" + internalCallId + "]] Sending cancel..." );
// mapJID = true;
}
}
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null && mapJID)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
}
else if ( packet.getAttributeValue("type").equals("set")
&& packet.getFirstElement(new NSI("session", "http://www.google.com/session")) != null)
{
if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("initiate"))
{
logger.debug("[[" + internalCallId + "]] Got a request to start a call");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.parseInitiate(packet);
CallManager.addSession(cs);
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(UriMappings.toSipId(cs.jabberRemote), cs.jabberLocal.getNode());
if (sub != null)
{
domain = ((SipURI) sub.remoteParty.getURI()).getHost();
}
SipService.sendInvite(cs, domain);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-info"))
{
logger.debug("[[" + internalCallId + "]] Got transport info");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
StreamElement origTransport = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
if (origTransport.getNamespaceURI().equals("http://www.google.com/transport/p2p"))
{
StreamElement candidate = origTransport.getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (!cs.sentTransport)
{
sess.sendTransportInfo(cs);
cs.sentTransport = true;
}
sess.acceptTransport(packet);
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("candidates"))
{
logger.debug("[[" + internalCallId + "]] Got candidate");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
/*StreamElement origTransport = */packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
StreamElement candidate = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (candidate.getAttributeValue("name").equals("video_rtp")/* || candidate.getAttributeValue("name").equals("video_rtcp")*/)
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("video_rtcp"))
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTCP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
else if (candidate.getAttributeValue("name").equals("rtp")/* || candidate.getAttributeValue("name").equals("rtcp")*/)
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("rtcp"))
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTCP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = CallManager.getSession(packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found sending 200 OK");
cs.parseAccept(packet);
SipService.acceptCall(cs);
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("terminate"))
{
logger.debug("[[" + internalCallId + "]] Got a terminate");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding bye");
SipService.sendBye(cs);
CallManager.removeSession(cs);
}
}
else if ( packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("reject"))
{
logger.debug("[[" + internalCallId + "]] Got a reject");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
}
}
else if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("vCard", "vcard-temp")))
{
logger.debug("[[" + internalCallId + "]] Got an ICON request!");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("vCard", "vcard-temp"));
StreamElement fullName = query.addElement("FN");
//if a telephone number add a + to be pretty
if(packet.getTo().getNode().toString().matches("[0-9]+"))
{
fullName.addText("+" + packet.getTo().getNode().toString());
}
else
{
fullName.addText(packet.getTo().getNode().toString());
}
StreamElement photo = query.addElement("PHOTO");
StreamElement type = photo.addElement("TYPE");
type.addText("image/jpeg");
StreamElement binval = photo.addElement("BINVAL");
byte [] encoded = Base64.encodeBase64Chunked(iconData);
binval.addText(new String(encoded));
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
}
}
catch (Exception e)
{
logger.error("Exception in packetTransferred", e);
}
}
| public void packetTransferred(PacketEvent evt)
{
try
{
JID local = evt.getData().getTo();
JID remote = evt.getData().getFrom();
logger.debug("[[" + internalCallId + "]] got message of " + evt.getData().getQualifiedName());
if (evt.getData().getQualifiedName().equals("db:result"))
{
String type = evt.getData().getAttributeValue("type");
if (type != null && type.length() > 0)
{
synchronized (this)
{
confirm();
while (!queue.isEmpty())
{
conn.send(queue.remove(0));
}
}
return;
}
String result = evt.getData().normalizeText();
evt.setHandled(true);
// this isn't a dialback connection - add it to the list of connections
// we don't save this because it can only be used for inbound stuff
//SessionManager.addSession(this);
logger.debug("[[" + internalCallId + "]] Got a result response: " + evt.getData().normalizeText());
logger.debug("[[" + internalCallId + "]] Packet is of type: " + evt.getData().getClass().getName());
DialbackSession dbs = new DialbackSession(internalCallId, local, remote, conn.getOutboundContext().getID(), result);
boolean valid = dbs.doDialback();
Packet p = null;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "valid");
confirm();
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Error sending packet!", e);
}
if (!valid)
{
// close the stream if invalid
conn.close();
}
}
else if (evt.getData().getQualifiedName().equals("db:verify"))
{
String key = evt.getData().normalizeText();
// if we get a db:verify here and n
logger.debug("[[" + internalCallId + "]] Got a verification token " + key);
Session sess = SessionManager.getSession(evt.getData().getFrom());
boolean valid = false;
if (sess != null)
{
logger.debug("[[" + internalCallId + "]] Found matching session");
if (key.equals(sess.getSessionKey()))
{
logger.debug("[[" + internalCallId + "]] Keys Match! Sending the ok");
valid = true;
}
}
Packet p;
if (valid)
{
logger.debug("[[" + internalCallId + "]] Session is valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setID(evt.getData().getID());
p.setAttributeValue("type", "valid");
}
else
{
logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"), Packet.class);
p.setFrom(local);
p.setTo(remote);
p.setAttributeValue("type", "invalid");
}
try
{
conn.send(p);
}
catch (StreamException e)
{
logger.error("Steam error in session", e);
}
}
else if ( evt.getData().getQualifiedName().equals(":message")
&& evt.getData().getAttributeValue("type") != null
&& evt.getData().getAttributeValue("type").equals("chat"))
{
logger.debug("[[" + internalCallId + "]] Got an IM");
StreamElement body = evt.getData().getFirstElement("body");
if (body != null)
{
String msg = body.normalizeText();
logger.debug("[[" + internalCallId + "]] Body=" + msg);
MessageMessage mm = new MessageMessage(evt.getData());
if (msg.equals("callback"))
{
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.offerPayloads.add(CallSession.PAYLOAD_PCMU);
cs.offerPayloads.add(CallSession.PAYLOAD_PCMA);
Session sess = SessionManager.findCreateSession(cs.jabberLocal.getDomain(), cs.jabberRemote);
sess.startCall(cs, evt.getData().getTo().getNode(), UriMappings.toSipId(evt.getData().getFrom()));
}
else if (msg.startsWith("/dial:"))
{
logger.debug("[[" + internalCallId + "]] DIAL command detected");
CallSession cs = CallManager.getSession(evt.getData().getFrom(), evt.getData().getTo());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found, sending dtmfs");
for (int i = "/dial:".length(); i < msg.length(); i++)
{
cs.relay.sendSipDTMF(msg.charAt(i));
}
}
}
else
{
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
if (sub != null)
{
domain = ((SipURI)sub.remoteParty.getURI()).getHost();
}
SipService.sendMessageMessage(mm, domain);
}
}
}
else if (evt.getData().getQualifiedName().equals(":presence"))
{
logger.debug("[[" + internalCallId + "]] Got presence stanza");
String type = evt.getData().getAttributeValue("type");
if (type == null || type.equals("unavailable"))
{
logger.debug("[[" + internalCallId + "]] Got a presence message");
StreamElement caps = evt.getData().getFirstElement(new NSI("c", "http://jabber.org/protocol/caps"));
if (caps != null && caps.getAttributeValue("ext") != null)
{
logger.debug("[[" + internalCallId + "]] Caps found");
if (caps.getAttributeValue("ext").contains("voice-v1"))
{
logger.debug("[[" + internalCallId + "]] Voice support detected, taking note");
UriMappings.addVoiceResource(evt.getData().getFrom());
}
}
Presence pres = new Presence(evt.getData());
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found matching subscription!");
sub.sendNotify(false, pres);
}
}
else
{
if (type.equals("subscribe"))
{
logger.debug("[[" + internalCallId + "]] New subscription received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub == null)
{
logger.debug("[[" + internalCallId + "]] No existing subscription, sending one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
else if (sub.remoteTag != null)
{
logger.debug("[[" + internalCallId + "]] Subscription exists, sending refresh");
sub.sendSubscribe(false);
}
}
else
{
logger.debug("[[" + internalCallId + "]] Subscription to " + fakeId + ", sending dummy accept");
Session sess = SessionManager.findCreateSession(host, evt.getData().getFrom());
sess.sendSubscribeRequest(new JID(fakeId + "@" + host), evt.getData().getFrom(), "subscribed");
}
}
else if (type.equals("unsubscribe"))
{
logger.debug("[[" + internalCallId + "]] Unsubscribe request");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.removeSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing subscription");
sub.sendSubscribe(true);
}
sub = SipSubscriptionManager.getWatcher(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Removing watcher");
SipSubscriptionManager.removeWatcher(from, sub);
sub.sendNotify(true, null);
}
}
}
else if (type.equals("subscribed"))
{
logger.debug("[[" + internalCallId + "]] Jabber client accepted subscription, sending notify");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
sub.sendNotify(false, null);
}
}
else if (type.equals("probe"))
{
logger.debug("[[" + internalCallId + "]] Probe received");
String from = UriMappings.toSipId(evt.getData().getFrom());
String to = evt.getData().getTo().getNode();
if (!to.equals(fakeId))
{
SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
if (sub != null)
{
logger.debug("[[" + internalCallId + "]] Found a subscription, sending re-subscribe");
sub.sendSubscribe(false);
}
else
{
logger.debug("[[" + internalCallId + "]] No Subscription for this person, sending 0 length one");
sub = new SipSubscription(from, to);
SipSubscriptionManager.addSubscriber(from, sub);
sub.sendSubscribe(false);
}
}
}
}
}
else if (evt.getData().getQualifiedName().equals(":iq"))
{
Packet packet = evt.getData();
logger.debug("[[" + internalCallId + "]] got disco packet");
if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("query", "http://jabber.org/protocol/disco#info")))
{
logger.debug("[[" + internalCallId + "]] Got a feature query");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("query", "http://jabber.org/protocol/disco#info"));
query.setAttributeValue("node", clientName + "#" + clientVersion);
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/voice/v1");
query.addElement("feature").setAttributeValue("var", "http://www.google.com/xmpp/protocol/video/v1");
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
else if ( packet.getAttributeValue("type").equals("error"))
{
logger.debug("[[" + internalCallId + "]] Got error stanza");
StreamElement error = packet.getFirstElement("error");
if ( error != null )
{
logger.debug("[[" + internalCallId + "]] Error code: " + error.getAttributeValue("code") + " type: " + error.getAttributeValue("type") );
if (error.getAttributeValue("type") == "cancel") {
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null) {
logger.debug("[[" + internalCallId + "]] Sending reject..." );
SipService.sendReject(cs);
logger.debug("[[" + internalCallId + "]] Removing session... " );
CallManager.removeSession(cs);
}
} else {
logger.debug("[[" + internalCallId + "]] Proceeding... ");
}
}
/*
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null && mapJID)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
*/
}
else if ( packet.getAttributeValue("type").equals("set")
&& packet.getFirstElement(new NSI("session", "http://www.google.com/session")) != null)
{
if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("initiate"))
{
logger.debug("[[" + internalCallId + "]] Got a request to start a call");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = new CallSession();
logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId + "]]");
cs.parseInitiate(packet);
CallManager.addSession(cs);
/* For coherence, we try to use the domain he has used in his subscription */
String domain = host;
SipSubscription sub = SipSubscriptionManager.getWatcher(UriMappings.toSipId(cs.jabberRemote), cs.jabberLocal.getNode());
if (sub != null)
{
domain = ((SipURI) sub.remoteParty.getURI()).getHost();
}
SipService.sendInvite(cs, domain);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-info"))
{
logger.debug("[[" + internalCallId + "]] Got transport info");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
StreamElement origTransport = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
if (origTransport.getNamespaceURI().equals("http://www.google.com/transport/p2p"))
{
StreamElement candidate = origTransport.getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (!cs.sentTransport)
{
sess.sendTransportInfo(cs);
cs.sentTransport = true;
}
sess.acceptTransport(packet);
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("candidates"))
{
logger.debug("[[" + internalCallId + "]] Got candidate");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
/*StreamElement origTransport = */packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("transport");
StreamElement candidate = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getFirstElement("candidate");
if ( candidate != null
&& candidate.getAttributeValue("protocol").equals("udp"))
{
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
if (candidate.getAttributeValue("name").equals("video_rtp")/* || candidate.getAttributeValue("name").equals("video_rtcp")*/)
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("video_rtcp"))
{
if (!cs.sentVTransport)
{
sess.sendTransportCandidates(cs, StreamType.VRTCP);
}
cs.vRelay.sendBind(candidate.getAttributeValue("username"), cs.candidateVUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
else if (candidate.getAttributeValue("name").equals("rtp")/* || candidate.getAttributeValue("name").equals("rtcp")*/)
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, false);
}
else if (candidate.getAttributeValue("name").equals("rtcp"))
{
if (!cs.sentTransport)
{
sess.sendTransportCandidates(cs, StreamType.RTCP);
}
cs.relay.sendBind(candidate.getAttributeValue("username"), cs.candidateUser, candidate.getAttributeValue("address"), Integer.parseInt(candidate.getAttributeValue("port")), packet, true);
}
}
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("transport-accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("accept"))
{
logger.debug("[[" + internalCallId + "]] Got transport accept");
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.ackIQ(packet);
CallSession cs = CallManager.getSession(packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID());
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] Call found sending 200 OK");
cs.parseAccept(packet);
SipService.acceptCall(cs);
}
}
else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("terminate"))
{
logger.debug("[[" + internalCallId + "]] Got a terminate");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding bye");
SipService.sendBye(cs);
CallManager.removeSession(cs);
}
}
else if ( packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getAttributeValue("type").equals("reject"))
{
logger.debug("[[" + internalCallId + "]] Got a reject");
String sessionId = packet.getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
CallSession cs = CallManager.getSession(sessionId);
if (cs != null)
{
logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
SipService.sendReject(cs);
CallManager.removeSession(cs);
}
}
}
else if ( packet.getAttributeValue("type").equals("get")
&& packet.getFirstElement().getNSI().equals(new NSI("vCard", "vcard-temp")))
{
logger.debug("[[" + internalCallId + "]] Got an ICON request!");
Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
p.setFrom(packet.getTo());
p.setTo(packet.getFrom());
p.setID(packet.getID());
p.setAttributeValue("type", "result");
StreamElement query = conn.getDataFactory().createElementNode(new NSI("vCard", "vcard-temp"));
StreamElement fullName = query.addElement("FN");
//if a telephone number add a + to be pretty
if(packet.getTo().getNode().toString().matches("[0-9]+"))
{
fullName.addText("+" + packet.getTo().getNode().toString());
}
else
{
fullName.addText(packet.getTo().getNode().toString());
}
StreamElement photo = query.addElement("PHOTO");
StreamElement type = photo.addElement("TYPE");
type.addText("image/jpeg");
StreamElement binval = photo.addElement("BINVAL");
byte [] encoded = Base64.encodeBase64Chunked(iconData);
binval.addText(new String(encoded));
p.add(query);
Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
sess.sendPacket(p);
}
}
}
catch (Exception e)
{
logger.error("Exception in packetTransferred", e);
}
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java b/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
index d495aed1..6f43e1b9 100644
--- a/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
+++ b/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
@@ -1,176 +1,176 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 14-Jan-2007
*/
package uk.me.parabola.imgfmt.app.labelenc;
import uk.me.parabola.log.Logger;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Locale;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Useful routines for the other encoders.
* Provides some default behaviour when a conversion is not possible for
* example.
*
* @author Steve Ratcliffe
*/
public class BaseEncoder {
private static final Logger log = Logger.getLogger(BaseEncoder.class);
protected static final EncodedText NO_TEXT = new EncodedText(null, 0);
private boolean charsetSupported = true;
// Whether to uppercase the labels or not. Default is true because many
// GPS devices do not display labels in lower case.
private boolean upperCase;
private String charset = "ascii";
private static final String[][] rows = new String[256][];
protected boolean isCharsetSupported() {
return charsetSupported;
}
protected void prepareForCharacterSet(String name) {
if (Charset.isSupported(name)) {
charsetSupported = true;
} else {
charsetSupported = false;
log.warn("requested character set not found " + name);
}
}
protected EncodedText simpleEncode(String text) {
if (text == null)
return NO_TEXT;
char[] in = text.toCharArray();
byte[] out = new byte[in.length + 1];
int off = 0;
for (char c : in)
out[off++] = (byte) (c & 0xff);
return new EncodedText(out, out.length);
}
protected boolean isUpperCase() {
return upperCase;
}
public void setUpperCase(boolean upperCase) {
this.upperCase = upperCase;
}
/**
* Convert a string into a string that uses only ascii characters.
*
* @param s The original string. It can use any unicode character.
* @return A string that uses only ascii characters that is a transcription
* or transliteration of the original string.
*/
protected char[] transliterate(String s) {
StringBuilder sb = new StringBuilder(s.length() + 5);
for (char c : s.toCharArray()) {
if (c < 0x80) {
sb.append(c);
} else {
int row = c >>> 8;
String[] rowmap = rows[row];
if (rowmap == null)
rowmap = loadRow(row);
//log.debug("char", Integer.toHexString(c), rowmap[c & 0xff]);
sb.append(rowmap[c & 0xff]);
}
}
return sb.toString().toCharArray();
}
/**
* Load one row of characters. This means unicode characters that are
* of the form U+RRXX where RR is the row.
* @param row Row number 0-255.
* @return An array of strings, one for each character in the row. If there
* is no ascii representation then a '?' character will fill that
* position.
*/
private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
- fmt.format("/chars/%s/row/%02d.trans", charset, row);
+ fmt.format("/chars/%s/row%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
/**
* Read in a character translit file. Not all code points need to
* be defined inside the file. Anything that is left out will become
* a question mark.
*
* @param is The open file to be read.
* @param newRow The row that we fill in with strings.
*/
private void readCharFile(InputStream is, String[] newRow) throws IOException {
if (is == null)
return;
BufferedReader br = new BufferedReader(new InputStreamReader(is, "ascii"));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() == 0 || line.charAt(0) == '#')
continue;
String[] fields = line.split("\\s+");
String upoint = fields[0];
String translation = fields[1];
if (upoint.length() != 6 || upoint.charAt(0) != 'U') continue;
// The first field must look like 'U+RRXX', we extract the XX part
int index = Integer.parseInt(upoint.substring(4), 16);
newRow[index] = translation.toUpperCase(Locale.ENGLISH);
}
}
}
| true | true | private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
fmt.format("/chars/%s/row/%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
| private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
fmt.format("/chars/%s/row%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
|
diff --git a/src/com/orange/groupbuy/api/service/UpdateUserService.java b/src/com/orange/groupbuy/api/service/UpdateUserService.java
index 67bba67..bcc882b 100644
--- a/src/com/orange/groupbuy/api/service/UpdateUserService.java
+++ b/src/com/orange/groupbuy/api/service/UpdateUserService.java
@@ -1,90 +1,85 @@
package com.orange.groupbuy.api.service;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import com.mongodb.BasicDBObject;
import com.orange.common.mongodb.MongoDBClient;
import com.orange.common.utils.StringUtil;
import com.orange.groupbuy.constant.DBConstants;
import com.orange.groupbuy.constant.ErrorCode;
import com.orange.groupbuy.constant.ServiceConstant;
import com.orange.groupbuy.manager.UserManager;
public class UpdateUserService extends CommonGroupBuyService {
String email;
String new_email;
String password;
String new_password;
@Override
public boolean setDataFromRequest(HttpServletRequest request) {
email = request.getParameter(ServiceConstant.PARA_EMAIL);
password = request.getParameter(ServiceConstant.PARA_PASSWORD);
new_email = request.getParameter(ServiceConstant.PARA_NEW_EMAIL);
new_password = request.getParameter(ServiceConstant.PARA_NEW_PASSWORD);
if (!StringUtil.isValidMail(email)){
log.info("<LoginUser> user email("+email+") not valid");
resultCode = ErrorCode.ERROR_EMAIL_NOT_VALID;
return false;
}
if (!check(email, ErrorCode.ERROR_PARAMETER_EMAIL_EMPTY, ErrorCode.ERROR_PARAMETER_EMAIL_NULL))
return false;
if (!check(password, ErrorCode.ERROR_PARAMETER_PASSWORD_EMPTY, ErrorCode.ERROR_PARAMETER_PASSWORD_NULL))
return false;
return true;
}
@Override
public boolean needSecurityCheck() {
return false;
}
@Override
public void handleData() {
BasicDBObject user = (BasicDBObject) UserManager.findUserByEmail(mongoClient, email);
if (user == null){
resultCode = ErrorCode.ERROR_USERID_NOT_FOUND;
log.info("<updateUser> user not found");
return;
}
else if(user.getString(DBConstants.F_PASSWORD).equals(password)){
log.info("<updateUsere> user="+user.toString());
}
else{
log.info("<updateUser> user password("+password+") not match");
resultCode = ErrorCode.ERROR_PASSWORD_NOT_MATCH;
return;
}
if(new_password != null && new_password.length() >= 0){
UserManager.updatePassword(mongoClient, email, new_password);
}
if(new_email != null && StringUtil.isValidMail(new_email)){
UserManager.updateEmail(mongoClient, email, new_email);
}
- else if (!StringUtil.isValidMail(new_email)){
- log.info("<UpdateUser> user email("+new_email+") not valid");
- resultCode = ErrorCode.ERROR_EMAIL_NOT_VALID;
- return;
- }
String userId = user.getString(MongoDBClient.ID);
// set result data, return userId
JSONObject obj = new JSONObject();
obj.put(ServiceConstant.PARA_USERID, userId);
resultData = obj;
}
}
| true | true | public void handleData() {
BasicDBObject user = (BasicDBObject) UserManager.findUserByEmail(mongoClient, email);
if (user == null){
resultCode = ErrorCode.ERROR_USERID_NOT_FOUND;
log.info("<updateUser> user not found");
return;
}
else if(user.getString(DBConstants.F_PASSWORD).equals(password)){
log.info("<updateUsere> user="+user.toString());
}
else{
log.info("<updateUser> user password("+password+") not match");
resultCode = ErrorCode.ERROR_PASSWORD_NOT_MATCH;
return;
}
if(new_password != null && new_password.length() >= 0){
UserManager.updatePassword(mongoClient, email, new_password);
}
if(new_email != null && StringUtil.isValidMail(new_email)){
UserManager.updateEmail(mongoClient, email, new_email);
}
else if (!StringUtil.isValidMail(new_email)){
log.info("<UpdateUser> user email("+new_email+") not valid");
resultCode = ErrorCode.ERROR_EMAIL_NOT_VALID;
return;
}
String userId = user.getString(MongoDBClient.ID);
// set result data, return userId
JSONObject obj = new JSONObject();
obj.put(ServiceConstant.PARA_USERID, userId);
resultData = obj;
}
| public void handleData() {
BasicDBObject user = (BasicDBObject) UserManager.findUserByEmail(mongoClient, email);
if (user == null){
resultCode = ErrorCode.ERROR_USERID_NOT_FOUND;
log.info("<updateUser> user not found");
return;
}
else if(user.getString(DBConstants.F_PASSWORD).equals(password)){
log.info("<updateUsere> user="+user.toString());
}
else{
log.info("<updateUser> user password("+password+") not match");
resultCode = ErrorCode.ERROR_PASSWORD_NOT_MATCH;
return;
}
if(new_password != null && new_password.length() >= 0){
UserManager.updatePassword(mongoClient, email, new_password);
}
if(new_email != null && StringUtil.isValidMail(new_email)){
UserManager.updateEmail(mongoClient, email, new_email);
}
String userId = user.getString(MongoDBClient.ID);
// set result data, return userId
JSONObject obj = new JSONObject();
obj.put(ServiceConstant.PARA_USERID, userId);
resultData = obj;
}
|
diff --git a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/editors/scanners/rules/BalancedParenthesisRule.java b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/editors/scanners/rules/BalancedParenthesisRule.java
index b53ad8c..b7fd8dd 100644
--- a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/editors/scanners/rules/BalancedParenthesisRule.java
+++ b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/editors/scanners/rules/BalancedParenthesisRule.java
@@ -1,85 +1,93 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.eclipse.ui.editors.scanners.rules;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IPredicateRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
/**
* @author fmancinelli, venkatesh, malaka
*/
public class BalancedParenthesisRule implements IPredicateRule
{
private IToken token;
private char startingChar;
public BalancedParenthesisRule(char startingChar, IToken token)
{
this.startingChar = startingChar;
this.token = token;
}
public IToken evaluate(ICharacterScanner scanner, boolean resume)
{
/*
* Here the logic is the following: isolate the partition between # and a white space provided that all
* parenthesis are balanced. If there are open parenthesis, keep scanning until the last parenthesis is closed.
*/
int parenthesis = 0;
int c = scanner.read();
if (c == startingChar) {
while ((c = scanner.read()) != ICharacterScanner.EOF) {
if (Character.isWhitespace(c) && parenthesis == 0) {
scanner.unread();
return token;
} else if (c == '(') {
parenthesis++;
} else if (c == ')') {
parenthesis--;
/* If this is the last parenthesis, then end scanning */
if (parenthesis == 0) {
return token;
}
+ /*
+ * If we find some closing parenthesis that leads to an unbalanced situation, then this parenthesis
+ * is part of the enclosing #directive. Unread it
+ */
+ else if (parenthesis < 0) {
+ scanner.unread();
+ return token;
+ }
}
}
return token;
}
scanner.unread();
return Token.UNDEFINED;
}
public IToken getSuccessToken()
{
return token;
}
public IToken evaluate(ICharacterScanner scanner)
{
return evaluate(scanner, false);
}
}
| true | true | public IToken evaluate(ICharacterScanner scanner, boolean resume)
{
/*
* Here the logic is the following: isolate the partition between # and a white space provided that all
* parenthesis are balanced. If there are open parenthesis, keep scanning until the last parenthesis is closed.
*/
int parenthesis = 0;
int c = scanner.read();
if (c == startingChar) {
while ((c = scanner.read()) != ICharacterScanner.EOF) {
if (Character.isWhitespace(c) && parenthesis == 0) {
scanner.unread();
return token;
} else if (c == '(') {
parenthesis++;
} else if (c == ')') {
parenthesis--;
/* If this is the last parenthesis, then end scanning */
if (parenthesis == 0) {
return token;
}
}
}
return token;
}
scanner.unread();
return Token.UNDEFINED;
}
| public IToken evaluate(ICharacterScanner scanner, boolean resume)
{
/*
* Here the logic is the following: isolate the partition between # and a white space provided that all
* parenthesis are balanced. If there are open parenthesis, keep scanning until the last parenthesis is closed.
*/
int parenthesis = 0;
int c = scanner.read();
if (c == startingChar) {
while ((c = scanner.read()) != ICharacterScanner.EOF) {
if (Character.isWhitespace(c) && parenthesis == 0) {
scanner.unread();
return token;
} else if (c == '(') {
parenthesis++;
} else if (c == ')') {
parenthesis--;
/* If this is the last parenthesis, then end scanning */
if (parenthesis == 0) {
return token;
}
/*
* If we find some closing parenthesis that leads to an unbalanced situation, then this parenthesis
* is part of the enclosing #directive. Unread it
*/
else if (parenthesis < 0) {
scanner.unread();
return token;
}
}
}
return token;
}
scanner.unread();
return Token.UNDEFINED;
}
|
diff --git a/src/v2/Count.java b/src/v2/Count.java
index 0d9a448..bf51117 100644
--- a/src/v2/Count.java
+++ b/src/v2/Count.java
@@ -1,100 +1,100 @@
package v2;
import java.io.IOException;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.util.GenericOptionsParser;
public class Count extends Configured implements Tool{
public Count(){
}
public static class Map extends Mapper<IntWritable, ProjectWritable, Text, IntWritable> {
Text text = new Text("count");
IntWritable one = new IntWritable(1);
@Override
public void map(IntWritable key, ProjectWritable value, Context context) throws IOException, InterruptedException {
context.write(text, one);
}
@Override
public void run (Context context) throws IOException, InterruptedException {
setup(context);
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
cleanup(context);
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int count = 0;
for(IntWritable c: values){
count+=c.get();
}
context.write(key, new IntWritable(count));
}
}
@Override
public int run(String[] args) throws Exception {
Job job = new Job();
Configuration conf = job.getConfiguration();
FileSystem fs = FileSystem.get(conf);
FileStatus[] jarFiles = fs.listStatus(new Path("/libs"));
for (FileStatus status : jarFiles) {
Path disqualified = new Path(status.getPath().toUri().getPath());
DistributedCache.addFileToClassPath(disqualified, conf, fs);
}
- job.setOutputKeyClass(IntWritable.class);
+ job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setCombinerClass(Reduce.class);
job.setNumReduceTasks(1);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(Count.class);
job.waitForCompletion(true);
return 0;
}
}
| true | true | public int run(String[] args) throws Exception {
Job job = new Job();
Configuration conf = job.getConfiguration();
FileSystem fs = FileSystem.get(conf);
FileStatus[] jarFiles = fs.listStatus(new Path("/libs"));
for (FileStatus status : jarFiles) {
Path disqualified = new Path(status.getPath().toUri().getPath());
DistributedCache.addFileToClassPath(disqualified, conf, fs);
}
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setCombinerClass(Reduce.class);
job.setNumReduceTasks(1);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(Count.class);
job.waitForCompletion(true);
return 0;
}
| public int run(String[] args) throws Exception {
Job job = new Job();
Configuration conf = job.getConfiguration();
FileSystem fs = FileSystem.get(conf);
FileStatus[] jarFiles = fs.listStatus(new Path("/libs"));
for (FileStatus status : jarFiles) {
Path disqualified = new Path(status.getPath().toUri().getPath());
DistributedCache.addFileToClassPath(disqualified, conf, fs);
}
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setCombinerClass(Reduce.class);
job.setNumReduceTasks(1);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(Count.class);
job.waitForCompletion(true);
return 0;
}
|
diff --git a/src/main/java/org/basex/gui/view/editor/EditorView.java b/src/main/java/org/basex/gui/view/editor/EditorView.java
index 299bdc7c9..37d2acb28 100644
--- a/src/main/java/org/basex/gui/view/editor/EditorView.java
+++ b/src/main/java/org/basex/gui/view/editor/EditorView.java
@@ -1,776 +1,776 @@
package org.basex.gui.view.editor;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import static org.basex.util.Token.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.GUIConstants.Msg;
import org.basex.gui.dialog.*;
import org.basex.gui.editor.Editor.Action;
import org.basex.gui.editor.*;
import org.basex.gui.layout.*;
import org.basex.gui.layout.BaseXFileChooser.Mode;
import org.basex.gui.layout.BaseXLayout.DropHandler;
import org.basex.gui.view.*;
import org.basex.io.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* This view allows the input and evaluation of queries and documents.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class EditorView extends View {
/** Number of files in the history. */
private static final int HISTORY = 18;
/** Number of files in the compact history. */
private static final int HISTCOMP = 7;
/** XQuery error pattern. */
private static final Pattern XQERROR = Pattern.compile(
"(.*?), ([0-9]+)/([0-9]+)" + COL);
/** XML error pattern. */
private static final Pattern XMLERROR = Pattern.compile(
LINE_X.replaceAll("%", "(.*?)") + COL + ".*");
/** Error information pattern. */
private static final Pattern ERRORINFO = Pattern.compile(
"^.*\r?\n\\[.*?\\] |" + LINE_X.replaceAll("%", ".*?") + COLS + "|\r?\n.*",
Pattern.DOTALL);
/** Error tooltip pattern. */
private static final Pattern ERRORTT = Pattern.compile(
"^.*\r?\n" + STOPPED_AT + "|\r?\n" + STACK_TRACE_C + ".*", Pattern.DOTALL);
/** Search bar. */
final SearchBar search;
/** History Button. */
final BaseXButton hist;
/** Execute Button. */
final BaseXButton stop;
/** Info label. */
final BaseXLabel info;
/** Position label. */
final BaseXLabel pos;
/** Query area. */
final BaseXTabs tabs;
/** Execute button. */
final BaseXButton go;
/** Thread counter. */
int threadID;
/** File in which the most recent error occurred. */
IO errFile;
/** Last error message. */
private String errMsg;
/** Most recent error position; used for clicking on error message. */
private int errPos;
/** Header string. */
private final BaseXLabel label;
/** Filter button. */
private final BaseXButton filter;
/**
* Default constructor.
* @param man view manager
*/
public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
- BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.EXEC.toString()));
+ BaseXLayout.addShortcut(H_EXECUTE_QUERY, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
@Override
public void refreshInit() { }
@Override
public void refreshFocus() { }
@Override
public void refreshMark() {
final EditorArea edit = getEditor();
go.setEnabled(edit.script || !gui.gprop.is(GUIProp.EXECRT));
final Nodes mrk = gui.context.marked;
filter.setEnabled(!gui.gprop.is(GUIProp.FILTERRT) && mrk != null && mrk.size() != 0);
}
@Override
public void refreshContext(final boolean more, final boolean quick) { }
@Override
public void refreshLayout() {
label.border(-6, 0, 0, 2).setFont(GUIConstants.lfont);
for(final EditorArea edit : editors()) edit.setFont(GUIConstants.mfont);
search.refreshLayout();
final Font ef = GUIConstants.font.deriveFont(7f + (GUIConstants.fontSize >> 1));
info.setFont(ef);
pos.setFont(ef);
}
@Override
public void refreshUpdate() { }
@Override
public boolean visible() {
return gui.gprop.is(GUIProp.SHOWEDITOR);
}
@Override
public void visible(final boolean v) {
gui.gprop.set(GUIProp.SHOWEDITOR, v);
}
@Override
protected boolean db() {
return false;
}
/**
* Opens a new file.
*/
public void open() {
// open file chooser for XML creation
final BaseXFileChooser fc = new BaseXFileChooser(OPEN,
gui.gprop.get(GUIProp.WORKPATH), gui);
fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
fc.filter(BXS_FILES, IO.BXSSUFFIX);
fc.textFilters();
final IOFile[] files = fc.multi().selectAll(Mode.FOPEN);
for(final IOFile f : files) open(f, true);
}
/**
* Reverts the contents of the currently opened editor.
*/
public void reopen() {
getEditor().reopen(true);
}
/**
* Saves the contents of the currently opened editor.
* @return {@code false} if operation was canceled
*/
public boolean save() {
final EditorArea edit = getEditor();
return edit.opened() ? save(edit.file) : saveAs();
}
/**
* Saves the contents of the currently opened editor under a new name.
* @return {@code false} if operation was canceled
*/
public boolean saveAs() {
// open file chooser for XML creation
final EditorArea edit = getEditor();
final String path = edit.opened() ? edit.file.path() :
gui.gprop.get(GUIProp.WORKPATH);
final BaseXFileChooser fc = new BaseXFileChooser(SAVE_AS, path, gui);
fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
fc.filter(BXS_FILES, IO.BXSSUFFIX);
fc.textFilters();
fc.suffix(IO.XQSUFFIX);
final IOFile file = fc.select(Mode.FSAVE);
return file != null && save(file);
}
/**
* Creates a new file.
*/
public void newFile() {
addTab();
refreshControls(true);
}
/**
* Opens the specified query file.
* @param file query file
* @param parse parse contents
* @return opened editor, or {@code null} if file could not be opened
*/
public EditorArea open(final IO file, final boolean parse) {
if(!visible()) GUICommands.C_SHOWEDITOR.execute(gui);
EditorArea edit = find(file, true);
if(edit != null) {
// display open file
tabs.setSelectedComponent(edit);
edit.reopen(true);
} else {
try {
final byte[] text = file.read();
// get current editor
edit = getEditor();
// create new tab if current text is stored on disk or has been modified
if(edit.opened() || edit.modified) edit = addTab();
edit.initText(text);
edit.file(file);
if(parse) edit.release(Action.PARSE);
} catch(final IOException ex) {
refreshHistory(null);
BaseXDialog.error(gui, FILE_NOT_OPENED);
return null;
}
}
return edit;
}
/**
* Refreshes the list of recent query files and updates the query path.
* @param file new file
*/
void refreshHistory(final IO file) {
final StringList paths = new StringList();
String path = null;
if(file != null) {
path = file.path();
gui.gprop.set(GUIProp.WORKPATH, file.dirPath());
paths.add(path);
tabs.setToolTipTextAt(tabs.getSelectedIndex(), path);
}
final String[] old = gui.gprop.strings(GUIProp.EDITOR);
for(int p = 0; paths.size() < HISTORY && p < old.length; p++) {
final IO fl = IO.get(old[p]);
if(fl.exists() && !fl.eq(file)) paths.add(fl.path());
}
// store sorted history
gui.gprop.set(GUIProp.EDITOR, paths.toArray());
hist.setEnabled(!paths.isEmpty());
}
/**
* Closes an editor.
* @param edit editor to be closed. {@code null} closes the currently
* opened editor.
* @return {@code true} if editor was closed
*/
public boolean close(final EditorArea edit) {
final EditorArea ea = edit != null ? edit : getEditor();
if(!confirm(ea)) return false;
tabs.remove(ea);
final int t = tabs.getTabCount();
final int i = tabs.getSelectedIndex();
if(t == 1) {
// reopen single tab
addTab();
} else if(i + 1 == t) {
// if necessary, activate last editor tab
tabs.setSelectedIndex(i - 1);
}
return true;
}
/**
* Jumps to a specific line.
*/
public void gotoLine() {
final EditorArea edit = getEditor();
final int ll = edit.last.length;
final int cr = edit.getCaret();
int l = 1;
for(int e = 0; e < ll && e < cr; e += cl(edit.last, e)) {
if(edit.last[e] == '\n') ++l;
}
final DialogLine dl = new DialogLine(gui, l);
if(!dl.ok()) return;
final int el = dl.line();
int p = 0;
l = 1;
for(int e = 0; e < ll && l < el; e += cl(edit.last, e)) {
if(edit.last[e] != '\n') continue;
p = e + 1;
++l;
}
edit.setCaret(p);
posCode.invokeLater();
}
/**
* Starts a thread, which shows a waiting info after a short timeout.
*/
public void start() {
final int thread = threadID;
new Thread() {
@Override
public void run() {
Performance.sleep(200);
if(thread == threadID) {
info.setText(PLEASE_WAIT_D, Msg.SUCCESS).setToolTipText(null);
stop.setEnabled(true);
}
}
}.start();
}
/**
* Evaluates the info message resulting from a parsed or executed query.
* @param msg info message
* @param ok {@code true} if evaluation was successful
* @param refresh refresh buttons
*/
public void info(final String msg, final boolean ok, final boolean refresh) {
// do not refresh view when query is running
if(!refresh && stop.isEnabled()) return;
++threadID;
errPos = -1;
errFile = null;
errMsg = null;
getEditor().resetError();
if(refresh) {
stop.setEnabled(false);
refreshMark();
}
if(ok) {
info.setCursor(GUIConstants.CURSORARROW);
info.setText(msg, Msg.SUCCESS).setToolTipText(null);
} else {
error(msg, false);
info.setCursor(GUIConstants.CURSORHAND);
info.setText(ERRORINFO.matcher(msg).replaceAll(""), Msg.ERROR);
final String tt = ERRORTT.matcher(msg).replaceAll("").
replace("<", "<").replace(">", ">").
replaceAll("\r?\n", "<br/>").replaceAll("(<br/>.*?)<br/>.*", "$1");
info.setToolTipText("<html>" + tt + "</html>");
}
}
/**
* Jumps to the current error.
*/
void jumpToError() {
if(errMsg != null) error(true);
}
/**
* Handles info messages resulting from a query execution.
* @param jump jump to error position
* @param msg info message
*/
public void error(final String msg, final boolean jump) {
errMsg = msg;
for(final String s : msg.split("\r?\n")) {
if(XQERROR.matcher(s).matches()) {
errMsg = s.replace(STOPPED_AT, "");
break;
}
}
error(jump);
}
/**
* Handles info messages resulting from a query execution.
* @param jump jump to error position
*/
private void error(final boolean jump) {
Matcher m = XQERROR.matcher(errMsg);
int el, ec = 2;
if(m.matches()) {
errFile = new IOFile(m.group(1));
el = Token.toInt(m.group(2));
ec = Token.toInt(m.group(3));
} else {
m = XMLERROR.matcher(errMsg);
if(!m.matches()) return;
el = Token.toInt(m.group(1));
errFile = getEditor().file;
}
EditorArea edit = find(errFile, false);
if(jump) {
if(edit == null) edit = open(errFile, false);
if(edit != null) tabs.setSelectedComponent(edit);
}
if(edit == null) return;
// find approximate error position
final int ll = edit.last.length;
int ep = ll;
for(int p = 0, l = 1, c = 1; p < ll; ++c, p += cl(edit.last, p)) {
if(l > el || l == el && c == ec) {
ep = p;
break;
}
if(edit.last[p] == '\n') {
++l;
c = 0;
}
}
if(ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
while(ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
}
edit.error(ep);
errPos = ep;
if(jump) {
edit.jumpError(errPos);
posCode.invokeLater();
}
}
/**
* Shows a quit dialog for all modified query files.
* @return {@code false} if confirmation was canceled
*/
public boolean confirm() {
for(final EditorArea edit : editors()) {
tabs.setSelectedComponent(edit);
if(!close(edit)) return false;
}
return true;
}
/**
* Checks if the current text can be saved or reverted.
* @return result of check
*/
public boolean modified() {
final EditorArea edit = getEditor();
return edit.modified || !edit.opened();
}
/**
* Returns the current editor.
* @return editor
*/
public EditorArea getEditor() {
final Component c = tabs.getSelectedComponent();
return c instanceof EditorArea ? (EditorArea) c : null;
}
/**
* Refreshes the query modification flag.
* @param force action
*/
void refreshControls(final boolean force) {
// update modification flag
final EditorArea edit = getEditor();
final boolean oe = edit.modified;
edit.modified = edit.hist != null && edit.hist.modified();
if(edit.modified == oe && !force) return;
// update tab title
String title = edit.file.name();
if(edit.modified) title += '*';
edit.label.setText(title);
// update components
gui.refreshControls();
posCode.invokeLater();
}
/** Code for setting cursor position. */
final GUICode posCode = new GUICode() {
@Override
public void eval(final Object arg) {
final int[] lc = getEditor().pos();
pos.setText(lc[0] + " : " + lc[1]);
}
};
/**
* Finds the editor that contains the specified file.
* @param file file to be found
* @param opened considers only opened files
* @return editor
*/
EditorArea find(final IO file, final boolean opened) {
for(final EditorArea edit : editors()) {
if(edit.file.eq(file) && (!opened || edit.opened())) return edit;
}
return null;
}
/**
* Saves the specified editor contents.
* @param file file to write
* @return {@code false} if confirmation was canceled
*/
private boolean save(final IO file) {
try {
final EditorArea edit = getEditor();
((IOFile) file).write(edit.getText());
edit.file(file);
return true;
} catch(final Exception ex) {
BaseXDialog.error(gui, FILE_NOT_SAVED);
return false;
}
}
/**
* Choose a unique tab file.
* @return io reference
*/
private IOFile newTabFile() {
// collect numbers of existing files
final BoolList bl = new BoolList();
for(final EditorArea edit : editors()) {
if(edit.opened()) continue;
final String n = edit.file.name().substring(FILE.length());
bl.set(n.isEmpty() ? 1 : Integer.parseInt(n), true);
}
// find first free file number
int c = 0;
while(++c < bl.size() && bl.get(c));
// create io reference
return new IOFile(gui.gprop.get(GUIProp.WORKPATH), FILE + (c == 1 ? "" : c));
}
/**
* Adds a new editor tab.
* @return editor reference
*/
EditorArea addTab() {
final EditorArea edit = new EditorArea(this, newTabFile());
edit.setFont(GUIConstants.mfont);
final BaseXBack tab = new BaseXBack(new BorderLayout(10, 0)).mode(Fill.NONE);
tab.add(edit.label, BorderLayout.CENTER);
final BaseXButton close = tabButton("e_close");
close.setRolloverIcon(BaseXLayout.icon("e_close2"));
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
close(edit);
}
});
tab.add(close, BorderLayout.EAST);
tabs.add(edit, tab, tabs.getComponentCount() - 2);
return edit;
}
/**
* Adds a tab for creating new tabs.
*/
private void addCreateTab() {
final BaseXButton add = tabButton("e_new");
add.setRolloverIcon(BaseXLayout.icon("e_new2"));
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
addTab();
refreshControls(true);
}
});
tabs.add(new BaseXBack(), add, 0);
tabs.setEnabledAt(0, false);
}
/**
* Adds a new tab button.
* @param icon button icon
* @return button
*/
private BaseXButton tabButton(final String icon) {
final BaseXButton b = new BaseXButton(gui, icon, null);
b.border(2, 2, 2, 2).setContentAreaFilled(false);
b.setFocusable(false);
return b;
}
/**
* Shows a quit dialog for the specified editor.
* @param edit editor to be saved
* @return {@code false} if confirmation was canceled
*/
private boolean confirm(final EditorArea edit) {
if(edit.modified && (edit.opened() || edit.getText().length != 0)) {
final Boolean ok = BaseXDialog.yesNoCancel(gui,
Util.info(CLOSE_FILE_X, edit.file.name()));
if(ok == null || ok && !save()) return false;
}
return true;
}
/**
* Returns all editors.
* @return editors
*/
EditorArea[] editors() {
final ArrayList<EditorArea> edits = new ArrayList<EditorArea>();
for(final Component c : tabs.getComponents()) {
if(c instanceof EditorArea) edits.add((EditorArea) c);
}
return edits.toArray(new EditorArea[edits.size()]);
}
}
| true | true | public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
| public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
BaseXLayout.addShortcut(H_EXECUTE_QUERY, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
|
diff --git a/TDI/test/model/ServerTest.java b/TDI/test/model/ServerTest.java
index edec8a2..4f54c9e 100644
--- a/TDI/test/model/ServerTest.java
+++ b/TDI/test/model/ServerTest.java
@@ -1,37 +1,36 @@
package model;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import junit.framework.Assert;
import org.junit.Test;
public class ServerTest implements Runnable{
private ServerSocket server;
@Test
public void test() {
try {
server = new ServerSocket(2345);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server s = new Server();
- s.sendCommand("lol");
}
@Override
public void run() {
// TODO Auto-generated method stub
assertTrue(true);
}
}
| true | true | public void test() {
try {
server = new ServerSocket(2345);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server s = new Server();
s.sendCommand("lol");
}
| public void test() {
try {
server = new ServerSocket(2345);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server s = new Server();
}
|
diff --git a/src/main/java/com/dumptruckman/chunky/config/CommentedConfiguration.java b/src/main/java/com/dumptruckman/chunky/config/CommentedConfiguration.java
index 88ec6e4..e3c6bb2 100644
--- a/src/main/java/com/dumptruckman/chunky/config/CommentedConfiguration.java
+++ b/src/main/java/com/dumptruckman/chunky/config/CommentedConfiguration.java
@@ -1,221 +1,221 @@
package com.dumptruckman.chunky.config;
import org.bukkit.util.config.Configuration;
import java.io.*;
import java.util.HashMap;
/**
* @author dumptruckman
*/
public class CommentedConfiguration extends Configuration {
private HashMap<String, String> comments;
private File file;
public CommentedConfiguration(File file) {
super(file);
comments = new HashMap<String, String>();
this.file = file;
}
@Override
public boolean save() {
// Save the config just like normal
boolean saved = super.save();
// if there's comments to add and it saved fine, we need to add comments
if (!comments.isEmpty() && saved) {
// String array of each line in the config file
String[] yamlContents =
convertFileToString(file).split("[" + System.getProperty("line.separator") + "]");
// This will hold the newly formatted line
String newContents = "";
// This holds the current path the lines are at in the config
String currentPath = "";
// This tells if the specified path has already been commented
boolean commentedPath = false;
// The depth of the path. (number of words separated by periods - 1)
int depth = 0;
// Loop through the config lines
for (String line : yamlContents) {
// If the line is a node (and not something like a list value)
if (line.contains(": ") || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Grab the index of the end of the node name
int index = 0;
index = line.indexOf(": ");
if (index < 0) {
index = line.length() - 1;
}
// If currentPath is empty, store the node name as the currentPath. (this is only on the first iteration, i think)
if (currentPath.isEmpty()) {
currentPath = line.substring(0, index);
} else {
// Calculate the whitespace preceding the node name
int whiteSpace = 0;
for (int n = 0; n < line.length(); n++) {
if (line.charAt(n) == ' ') {
whiteSpace++;
} else {
break;
}
}
// Find out if the current depth (whitespace * 4) is greater/lesser/equal to the previous depth
if (whiteSpace / 4 > depth) {
// Path is deeper. Add a . and the node name
currentPath += "." + line.substring(whiteSpace, index);
depth++;
} else if (whiteSpace / 4 < depth) {
// Path is shallower, calculate current depth from whitespace (whitespace / 4) and subtract that many levels from the currentPath
int newDepth = whiteSpace / 4;
for (int i = 0; i < depth - newDepth; i++) {
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
}
// Grab the index of the final period
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
// Add the new node name to the path
currentPath += line.substring(whiteSpace, index);
// Reset the depth
depth = newDepth;
} else {
// Path is same depth, replace the last path node name to the current node name
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
//currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += line.substring(whiteSpace, index);
}
// This is a new node so we need to mark it for commenting (if there are comments)
commentedPath = false;
}
}
String comment = "";
if (!commentedPath) {
// If there's a comment for the current path, retrieve it and flag that path as already commented
comment = comments.get(currentPath);
commentedPath = true;
}
if (comment != null) {
// Add the comment to the beginning of the current line
- if (!comment.isEmpty() && !comment.equals(System.getProperty("line.separator"))) {
+ if (!comment.trim().matches("^\\s*$")) {
line = comment + System.getProperty("line.separator") + line;
}
}
if (comment != null || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Add the (modified) line to the total config String
// This modified version will not write the config if a comment is not present
newContents += line + System.getProperty("line.separator");
}
}
try {
// Write the string to the config file
stringToFile(newContents, file);
} catch (IOException e) {
saved = false;
}
}
return saved;
}
/**
* Adds a comment just before the specified path. The comment can be multiple lines. An empty string will indicate a blank line.
* @param path Configuration path to add comment.
* @param commentLines Comments to add. One String per line.
*/
public void addComment(String path, String...commentLines) {
StringBuilder commentstring = new StringBuilder();
String leadingSpaces = "";
for (int n = 0; n < path.length(); n++) {
if (path.charAt(n) == '.') {
leadingSpaces += " ";
}
}
for (String line : commentLines) {
if (!line.isEmpty()) {
line = leadingSpaces + line;
} else {
line = " ";
}
if (commentstring.length() > 0) {
commentstring.append("\r\n");
}
commentstring.append(line);
}
comments.put(path, commentstring.toString());
}
/**
* Pass a file and it will return it's contents as a string.
* @param file File to read.
* @return Contents of file. String will be empty in case of any errors.
*/
private String convertFileToString(File file) {
if (file != null && file.exists() && file.canRead() && !file.isDirectory()) {
Writer writer = new StringWriter();
InputStream is = null;
char[] buffer = new char[1024];
try {
is = new FileInputStream(file);
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (IOException e) {
System.out.println("Exception ");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {}
}
}
return writer.toString();
} else {
return "";
}
}
/**
* Writes the contents of a string to a file.
* @param source String to write.
* @param file File to write to.
* @return True on success.
* @throws IOException
*/
private boolean stringToFile(String source, File file) throws IOException {
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
source.replaceAll("\n", System.getProperty("line.separator"));
out.write(source);
out.close();
return true;
} catch (IOException e) {
System.out.println("Exception ");
return false;
}
}
}
| true | true | public boolean save() {
// Save the config just like normal
boolean saved = super.save();
// if there's comments to add and it saved fine, we need to add comments
if (!comments.isEmpty() && saved) {
// String array of each line in the config file
String[] yamlContents =
convertFileToString(file).split("[" + System.getProperty("line.separator") + "]");
// This will hold the newly formatted line
String newContents = "";
// This holds the current path the lines are at in the config
String currentPath = "";
// This tells if the specified path has already been commented
boolean commentedPath = false;
// The depth of the path. (number of words separated by periods - 1)
int depth = 0;
// Loop through the config lines
for (String line : yamlContents) {
// If the line is a node (and not something like a list value)
if (line.contains(": ") || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Grab the index of the end of the node name
int index = 0;
index = line.indexOf(": ");
if (index < 0) {
index = line.length() - 1;
}
// If currentPath is empty, store the node name as the currentPath. (this is only on the first iteration, i think)
if (currentPath.isEmpty()) {
currentPath = line.substring(0, index);
} else {
// Calculate the whitespace preceding the node name
int whiteSpace = 0;
for (int n = 0; n < line.length(); n++) {
if (line.charAt(n) == ' ') {
whiteSpace++;
} else {
break;
}
}
// Find out if the current depth (whitespace * 4) is greater/lesser/equal to the previous depth
if (whiteSpace / 4 > depth) {
// Path is deeper. Add a . and the node name
currentPath += "." + line.substring(whiteSpace, index);
depth++;
} else if (whiteSpace / 4 < depth) {
// Path is shallower, calculate current depth from whitespace (whitespace / 4) and subtract that many levels from the currentPath
int newDepth = whiteSpace / 4;
for (int i = 0; i < depth - newDepth; i++) {
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
}
// Grab the index of the final period
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
// Add the new node name to the path
currentPath += line.substring(whiteSpace, index);
// Reset the depth
depth = newDepth;
} else {
// Path is same depth, replace the last path node name to the current node name
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
//currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += line.substring(whiteSpace, index);
}
// This is a new node so we need to mark it for commenting (if there are comments)
commentedPath = false;
}
}
String comment = "";
if (!commentedPath) {
// If there's a comment for the current path, retrieve it and flag that path as already commented
comment = comments.get(currentPath);
commentedPath = true;
}
if (comment != null) {
// Add the comment to the beginning of the current line
if (!comment.isEmpty() && !comment.equals(System.getProperty("line.separator"))) {
line = comment + System.getProperty("line.separator") + line;
}
}
if (comment != null || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Add the (modified) line to the total config String
// This modified version will not write the config if a comment is not present
newContents += line + System.getProperty("line.separator");
}
}
try {
// Write the string to the config file
stringToFile(newContents, file);
} catch (IOException e) {
saved = false;
}
}
return saved;
}
| public boolean save() {
// Save the config just like normal
boolean saved = super.save();
// if there's comments to add and it saved fine, we need to add comments
if (!comments.isEmpty() && saved) {
// String array of each line in the config file
String[] yamlContents =
convertFileToString(file).split("[" + System.getProperty("line.separator") + "]");
// This will hold the newly formatted line
String newContents = "";
// This holds the current path the lines are at in the config
String currentPath = "";
// This tells if the specified path has already been commented
boolean commentedPath = false;
// The depth of the path. (number of words separated by periods - 1)
int depth = 0;
// Loop through the config lines
for (String line : yamlContents) {
// If the line is a node (and not something like a list value)
if (line.contains(": ") || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Grab the index of the end of the node name
int index = 0;
index = line.indexOf(": ");
if (index < 0) {
index = line.length() - 1;
}
// If currentPath is empty, store the node name as the currentPath. (this is only on the first iteration, i think)
if (currentPath.isEmpty()) {
currentPath = line.substring(0, index);
} else {
// Calculate the whitespace preceding the node name
int whiteSpace = 0;
for (int n = 0; n < line.length(); n++) {
if (line.charAt(n) == ' ') {
whiteSpace++;
} else {
break;
}
}
// Find out if the current depth (whitespace * 4) is greater/lesser/equal to the previous depth
if (whiteSpace / 4 > depth) {
// Path is deeper. Add a . and the node name
currentPath += "." + line.substring(whiteSpace, index);
depth++;
} else if (whiteSpace / 4 < depth) {
// Path is shallower, calculate current depth from whitespace (whitespace / 4) and subtract that many levels from the currentPath
int newDepth = whiteSpace / 4;
for (int i = 0; i < depth - newDepth; i++) {
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
}
// Grab the index of the final period
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
// Add the new node name to the path
currentPath += line.substring(whiteSpace, index);
// Reset the depth
depth = newDepth;
} else {
// Path is same depth, replace the last path node name to the current node name
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
//currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += line.substring(whiteSpace, index);
}
// This is a new node so we need to mark it for commenting (if there are comments)
commentedPath = false;
}
}
String comment = "";
if (!commentedPath) {
// If there's a comment for the current path, retrieve it and flag that path as already commented
comment = comments.get(currentPath);
commentedPath = true;
}
if (comment != null) {
// Add the comment to the beginning of the current line
if (!comment.trim().matches("^\\s*$")) {
line = comment + System.getProperty("line.separator") + line;
}
}
if (comment != null || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// Add the (modified) line to the total config String
// This modified version will not write the config if a comment is not present
newContents += line + System.getProperty("line.separator");
}
}
try {
// Write the string to the config file
stringToFile(newContents, file);
} catch (IOException e) {
saved = false;
}
}
return saved;
}
|
diff --git a/src/main/java/org/apache/maven/plugin/pmd/PmdReport.java b/src/main/java/org/apache/maven/plugin/pmd/PmdReport.java
index 49250c1..c666960 100644
--- a/src/main/java/org/apache/maven/plugin/pmd/PmdReport.java
+++ b/src/main/java/org/apache/maven/plugin/pmd/PmdReport.java
@@ -1,486 +1,487 @@
package org.apache.maven.plugin.pmd;
/*
* 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 java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import net.sourceforge.pmd.IRuleViolation;
import net.sourceforge.pmd.PMD;
import net.sourceforge.pmd.PMDException;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetFactory;
import net.sourceforge.pmd.SourceType;
import net.sourceforge.pmd.renderers.CSVRenderer;
import net.sourceforge.pmd.renderers.HTMLRenderer;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.TextRenderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
import org.apache.maven.reporting.MavenReportException;
import org.codehaus.doxia.sink.Sink;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.FileResourceCreationException;
import org.codehaus.plexus.resource.loader.FileResourceLoader;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
/**
* Creates a PMD report.
*
* @author Brett Porter
* @version $Id: PmdReport.java,v 1.3 2005/02/23 00:08:53 brett Exp $
* @goal pmd
* @todo needs to support the multiple source roots
*/
public class PmdReport
extends AbstractPmdReport
{
/**
* The target JDK to analyse based on. Should match the target used in the compiler plugin. Valid values are
* currently <code>1.3</code>, <code>1.4</code>, <code>1.5</code> and <code>1.6</code>.
* <p>
* <b>Note:</b> support for <code>1.6</code> was added in version 2.3 of this plugin.
* </p>
*
* @parameter expression="${targetJdk}"
*/
private String targetJdk;
/**
* The rule priority threshold; rules with lower priority
* than this will not be evaluated.
*
* @parameter expression="${minimumPriority}" default-value="5"
*/
private int minimumPriority = 5;
/**
* Skip the PMD report generation. Most useful on the command line
* via "-Dpmd.skip=true".
*
* @parameter expression="${pmd.skip}" default-value="false"
*/
private boolean skip;
/**
* The PMD rulesets to use. See the <a href="http://pmd.sourceforge.net/rules/index.html">Stock Rulesets</a> for a
* list of some included. Defaults to the basic, imports and unusedcode rulesets.
*
* @parameter
*/
private String[] rulesets = new String[]{"rulesets/basic.xml", "rulesets/unusedcode.xml", "rulesets/imports.xml", };
/**
* The file encoding to use when reading the java source.
*
* @parameter
*/
private String sourceEncoding;
/**
* @component
* @required
* @readonly
*/
private ResourceManager locator;
/** @see org.apache.maven.reporting.MavenReport#getName(java.util.Locale) */
public String getName( Locale locale )
{
return getBundle( locale ).getString( "report.pmd.name" );
}
/** @see org.apache.maven.reporting.MavenReport#getDescription(java.util.Locale) */
public String getDescription( Locale locale )
{
return getBundle( locale ).getString( "report.pmd.description" );
}
public void setRulesets( String[] rules )
{
rulesets = rules;
}
/** @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale) */
public void executeReport( Locale locale )
throws MavenReportException
{
//configure ResourceManager
locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() );
locator.addSearchPath( "url", "" );
locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) );
if ( !skip && canGenerateReport() )
{
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
Sink sink = getSink();
PMD pmd = getPMD();
RuleContext ruleContext = new RuleContext();
Report report = new Report();
PmdReportListener reportSink = new PmdReportListener( sink, getBundle( locale ), aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
RuleSetFactory ruleSetFactory = new RuleSetFactory();
ruleSetFactory.setMinimumPriority( this.minimumPriority );
RuleSet[] sets = new RuleSet[rulesets.length];
try
{
for ( int idx = 0; idx < rulesets.length; idx++ )
{
String set = rulesets[idx];
getLog().debug( "Preparing ruleset: " + set );
File ruleset = null;
ruleset = locator.getResourceAsFile( set, getLocationTemp( set ) );
if ( null == ruleset )
{
throw new MavenReportException( "Could not resolve " + set );
}
InputStream rulesInput = new FileInputStream( ruleset );
sets[idx] = ruleSetFactory.createRuleSet( rulesInput );
}
}
catch ( IOException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( ResourceNotFoundException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( FileResourceCreationException e )
{
throw new MavenReportException( e.getMessage(), e );
}
boolean hasEncoding = sourceEncoding != null;
Map files;
try
{
files = getFilesToProcess( );
}
catch ( IOException e )
{
throw new MavenReportException( "Can't get file list", e );
}
for ( Iterator i = files.entrySet().iterator(); i.hasNext(); )
{
Map.Entry entry = (Map.Entry) i.next();
File file = (File) entry.getKey();
PmdFileInfo fileInfo = (PmdFileInfo) entry.getValue();
// TODO: lazily call beginFile in case there are no rules
reportSink.beginFile( file , fileInfo );
ruleContext.setSourceCodeFilename( file.getAbsolutePath() );
for ( int idx = 0; idx < rulesets.length; idx++ )
{
try
{
// PMD closes this Reader even though it did not open it so we have
// to open a new one with every call to processFile().
Reader reader = hasEncoding
? new InputStreamReader( new FileInputStream( file ), sourceEncoding )
: new FileReader( file );
pmd.processFile( reader, sets[idx], ruleContext );
}
catch ( UnsupportedEncodingException e1 )
{
throw new MavenReportException( "Encoding '" + sourceEncoding + "' is not supported.", e1 );
}
catch ( PMDException pe )
{
String msg = pe.getLocalizedMessage();
Exception r = pe.getReason();
- if (r != null) {
+ if ( r != null )
+ {
msg = msg + ": " + r.getLocalizedMessage();
}
getLog().warn( msg );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, msg ) );
}
catch ( FileNotFoundException e2 )
{
getLog().warn( "Error opening source file: " + file );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e2.getLocalizedMessage() ) );
}
catch ( Exception e3 )
{
getLog().warn( "Failure executing PMD for: " + file, e3 );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e3.getLocalizedMessage() ) );
}
}
reportSink.endFile( file );
}
reportSink.endDocument();
if ( !isHtml() )
{
// Use the PMD renderers to render in any format aside from HTML.
Renderer r = createRenderer();
StringWriter stringwriter = new StringWriter();
try
{
r.setWriter( stringwriter );
r.start();
r.renderFileReport( report );
r.end();
String buffer = stringwriter.toString();
Writer writer = new FileWriter( new File( targetDirectory, "pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
File siteDir = new File( targetDirectory, "site" );
siteDir.mkdirs();
writer = new FileWriter( new File( siteDir,
"pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
}
catch ( IOException ioe )
{
throw new MavenReportException( ioe.getMessage(), ioe );
}
}
}
finally
{
Thread.currentThread().setContextClassLoader( origLoader );
}
}
}
/**
* Convenience method to get the location of the specified file name.
*
* @param name the name of the file whose location is to be resolved
* @return a String that contains the absolute file name of the file
*/
private String getLocationTemp( String name )
{
String loc = name;
if ( loc.indexOf( '/' ) != -1 )
{
loc = loc.substring( loc.lastIndexOf( '/' ) + 1 );
}
if ( loc.indexOf( '\\' ) != -1 )
{
loc = loc.substring( loc.lastIndexOf( '\\' ) + 1 );
}
getLog().debug( "Before: " + name + " After: " + loc );
return loc;
}
/**
* Constructs the PMD class, passing it an argument
* that configures the target JDK.
*
* @return the resulting PMD
* @throws org.apache.maven.reporting.MavenReportException
* if targetJdk is not supported
*/
public PMD getPMD()
throws MavenReportException
{
PMD pmd = new PMD();
if ( null != targetJdk )
{
SourceType sourceType = SourceType.getSourceTypeForId( "java " + targetJdk );
if ( sourceType == null )
{
throw new MavenReportException( "Unsupported targetJdk value '" + targetJdk + "'." );
}
pmd.setJavaVersion( sourceType );
}
return pmd;
}
/** @see org.apache.maven.reporting.MavenReport#getOutputName() */
public String getOutputName()
{
return "pmd";
}
private static ResourceBundle getBundle( Locale locale )
{
return ResourceBundle.getBundle( "pmd-report", locale, PmdReport.class.getClassLoader() );
}
/**
* Create and return the correct renderer for the output type.
*
* @return the renderer based on the configured output
* @throws org.apache.maven.reporting.MavenReportException
* if no renderer found for the output type
*/
public final Renderer createRenderer()
throws MavenReportException
{
Renderer renderer = null;
if ( "xml".equals( format ) )
{
renderer = new XMLRenderer();
}
else if ( "txt".equals( format ) )
{
renderer = new TextRenderer();
}
else if ( "csv".equals( format ) )
{
renderer = new CSVRenderer();
}
else if ( "html".equals( format ) )
{
renderer = new HTMLRenderer();
}
else if ( !"".equals( format ) && !"none".equals( format ) )
{
try
{
renderer = (Renderer) Class.forName( format ).newInstance();
}
catch ( Exception e )
{
throw new MavenReportException(
"Can't find the custom format " + format + ": " + e.getClass().getName() );
}
}
if ( renderer == null )
{
throw new MavenReportException( "Can't create report with format of " + format );
}
return renderer;
}
/** @author <a href="mailto:[email protected]">Doug Douglass</a> */
private static class ProcessingErrorRuleViolation
implements IRuleViolation
{
private String filename;
private String description;
public ProcessingErrorRuleViolation( File file,
String description )
{
filename = file.getPath();
this.description = description;
}
public String getFilename()
{
return this.filename;
}
public int getBeginLine()
{
return 0;
}
public int getBeginColumn()
{
return 0;
}
public int getEndLine()
{
return 0;
}
public int getEndColumn()
{
return 0;
}
public Rule getRule()
{
return null;
}
public String getDescription()
{
return this.description;
}
public String getPackageName()
{
return null;
}
public String getMethodName()
{
return null;
}
public String getClassName()
{
return null;
}
public boolean isSuppressed()
{
return false;
}
public String getVariableName()
{
return null;
}
}
}
| true | true | public void executeReport( Locale locale )
throws MavenReportException
{
//configure ResourceManager
locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() );
locator.addSearchPath( "url", "" );
locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) );
if ( !skip && canGenerateReport() )
{
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
Sink sink = getSink();
PMD pmd = getPMD();
RuleContext ruleContext = new RuleContext();
Report report = new Report();
PmdReportListener reportSink = new PmdReportListener( sink, getBundle( locale ), aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
RuleSetFactory ruleSetFactory = new RuleSetFactory();
ruleSetFactory.setMinimumPriority( this.minimumPriority );
RuleSet[] sets = new RuleSet[rulesets.length];
try
{
for ( int idx = 0; idx < rulesets.length; idx++ )
{
String set = rulesets[idx];
getLog().debug( "Preparing ruleset: " + set );
File ruleset = null;
ruleset = locator.getResourceAsFile( set, getLocationTemp( set ) );
if ( null == ruleset )
{
throw new MavenReportException( "Could not resolve " + set );
}
InputStream rulesInput = new FileInputStream( ruleset );
sets[idx] = ruleSetFactory.createRuleSet( rulesInput );
}
}
catch ( IOException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( ResourceNotFoundException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( FileResourceCreationException e )
{
throw new MavenReportException( e.getMessage(), e );
}
boolean hasEncoding = sourceEncoding != null;
Map files;
try
{
files = getFilesToProcess( );
}
catch ( IOException e )
{
throw new MavenReportException( "Can't get file list", e );
}
for ( Iterator i = files.entrySet().iterator(); i.hasNext(); )
{
Map.Entry entry = (Map.Entry) i.next();
File file = (File) entry.getKey();
PmdFileInfo fileInfo = (PmdFileInfo) entry.getValue();
// TODO: lazily call beginFile in case there are no rules
reportSink.beginFile( file , fileInfo );
ruleContext.setSourceCodeFilename( file.getAbsolutePath() );
for ( int idx = 0; idx < rulesets.length; idx++ )
{
try
{
// PMD closes this Reader even though it did not open it so we have
// to open a new one with every call to processFile().
Reader reader = hasEncoding
? new InputStreamReader( new FileInputStream( file ), sourceEncoding )
: new FileReader( file );
pmd.processFile( reader, sets[idx], ruleContext );
}
catch ( UnsupportedEncodingException e1 )
{
throw new MavenReportException( "Encoding '" + sourceEncoding + "' is not supported.", e1 );
}
catch ( PMDException pe )
{
String msg = pe.getLocalizedMessage();
Exception r = pe.getReason();
if (r != null) {
msg = msg + ": " + r.getLocalizedMessage();
}
getLog().warn( msg );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, msg ) );
}
catch ( FileNotFoundException e2 )
{
getLog().warn( "Error opening source file: " + file );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e2.getLocalizedMessage() ) );
}
catch ( Exception e3 )
{
getLog().warn( "Failure executing PMD for: " + file, e3 );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e3.getLocalizedMessage() ) );
}
}
reportSink.endFile( file );
}
reportSink.endDocument();
if ( !isHtml() )
{
// Use the PMD renderers to render in any format aside from HTML.
Renderer r = createRenderer();
StringWriter stringwriter = new StringWriter();
try
{
r.setWriter( stringwriter );
r.start();
r.renderFileReport( report );
r.end();
String buffer = stringwriter.toString();
Writer writer = new FileWriter( new File( targetDirectory, "pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
File siteDir = new File( targetDirectory, "site" );
siteDir.mkdirs();
writer = new FileWriter( new File( siteDir,
"pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
}
catch ( IOException ioe )
{
throw new MavenReportException( ioe.getMessage(), ioe );
}
}
}
finally
{
Thread.currentThread().setContextClassLoader( origLoader );
}
}
}
| public void executeReport( Locale locale )
throws MavenReportException
{
//configure ResourceManager
locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() );
locator.addSearchPath( "url", "" );
locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) );
if ( !skip && canGenerateReport() )
{
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
Sink sink = getSink();
PMD pmd = getPMD();
RuleContext ruleContext = new RuleContext();
Report report = new Report();
PmdReportListener reportSink = new PmdReportListener( sink, getBundle( locale ), aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
RuleSetFactory ruleSetFactory = new RuleSetFactory();
ruleSetFactory.setMinimumPriority( this.minimumPriority );
RuleSet[] sets = new RuleSet[rulesets.length];
try
{
for ( int idx = 0; idx < rulesets.length; idx++ )
{
String set = rulesets[idx];
getLog().debug( "Preparing ruleset: " + set );
File ruleset = null;
ruleset = locator.getResourceAsFile( set, getLocationTemp( set ) );
if ( null == ruleset )
{
throw new MavenReportException( "Could not resolve " + set );
}
InputStream rulesInput = new FileInputStream( ruleset );
sets[idx] = ruleSetFactory.createRuleSet( rulesInput );
}
}
catch ( IOException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( ResourceNotFoundException e )
{
throw new MavenReportException( e.getMessage(), e );
}
catch ( FileResourceCreationException e )
{
throw new MavenReportException( e.getMessage(), e );
}
boolean hasEncoding = sourceEncoding != null;
Map files;
try
{
files = getFilesToProcess( );
}
catch ( IOException e )
{
throw new MavenReportException( "Can't get file list", e );
}
for ( Iterator i = files.entrySet().iterator(); i.hasNext(); )
{
Map.Entry entry = (Map.Entry) i.next();
File file = (File) entry.getKey();
PmdFileInfo fileInfo = (PmdFileInfo) entry.getValue();
// TODO: lazily call beginFile in case there are no rules
reportSink.beginFile( file , fileInfo );
ruleContext.setSourceCodeFilename( file.getAbsolutePath() );
for ( int idx = 0; idx < rulesets.length; idx++ )
{
try
{
// PMD closes this Reader even though it did not open it so we have
// to open a new one with every call to processFile().
Reader reader = hasEncoding
? new InputStreamReader( new FileInputStream( file ), sourceEncoding )
: new FileReader( file );
pmd.processFile( reader, sets[idx], ruleContext );
}
catch ( UnsupportedEncodingException e1 )
{
throw new MavenReportException( "Encoding '" + sourceEncoding + "' is not supported.", e1 );
}
catch ( PMDException pe )
{
String msg = pe.getLocalizedMessage();
Exception r = pe.getReason();
if ( r != null )
{
msg = msg + ": " + r.getLocalizedMessage();
}
getLog().warn( msg );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, msg ) );
}
catch ( FileNotFoundException e2 )
{
getLog().warn( "Error opening source file: " + file );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e2.getLocalizedMessage() ) );
}
catch ( Exception e3 )
{
getLog().warn( "Failure executing PMD for: " + file, e3 );
reportSink.ruleViolationAdded(
new ProcessingErrorRuleViolation( file, e3.getLocalizedMessage() ) );
}
}
reportSink.endFile( file );
}
reportSink.endDocument();
if ( !isHtml() )
{
// Use the PMD renderers to render in any format aside from HTML.
Renderer r = createRenderer();
StringWriter stringwriter = new StringWriter();
try
{
r.setWriter( stringwriter );
r.start();
r.renderFileReport( report );
r.end();
String buffer = stringwriter.toString();
Writer writer = new FileWriter( new File( targetDirectory, "pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
File siteDir = new File( targetDirectory, "site" );
siteDir.mkdirs();
writer = new FileWriter( new File( siteDir,
"pmd." + format ) );
writer.write( buffer, 0, buffer.length() );
writer.close();
}
catch ( IOException ioe )
{
throw new MavenReportException( ioe.getMessage(), ioe );
}
}
}
finally
{
Thread.currentThread().setContextClassLoader( origLoader );
}
}
}
|
diff --git a/app/jobs/FetchEmails.java b/app/jobs/FetchEmails.java
index ca40344..7c6139f 100644
--- a/app/jobs/FetchEmails.java
+++ b/app/jobs/FetchEmails.java
@@ -1,141 +1,141 @@
package jobs;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;
import javax.mail.search.*;
import models.Attachment;
import models.JobApplication;
import controllers.Mails;
import play.*;
import play.db.jpa.Blob;
import play.jobs.*;
import play.libs.IO;
@Every("10min")
public class FetchEmails extends Job {
public void doJob() throws Exception {
if(Play.configuration.getProperty("mailbox.username") == null || Play.configuration.getProperty("mailbox.password") == null) {
Logger.error("Please configure mailbox credentials in conf/credentials.conf");
return;
}
// Connect to gmail mailbox
Properties props = new Properties();
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.port", "993");
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", Play.configuration.getProperty("mailbox.username"), Play.configuration.getProperty("mailbox.password"));
// Open jobs mailbox
Folder folder = store.getFolder("jobs");
folder.open(Folder.READ_WRITE);
// Search unstarred messages
SearchTerm unstarred = new FlagTerm(new Flags(Flags.Flag.FLAGGED), false);
Message[] messages = folder.search(unstarred);
// Loop over messages
for (Message message : messages) {
String contentString = "";
List<Attachment> attachments = new ArrayList<Attachment>();
// Decode content
if (message.getContent() instanceof String) {
contentString = (String) message.getContent();
} else if (message.getContent() instanceof Multipart) {
Multipart mp = (Multipart) message.getContent();
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null
|| ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition
.equalsIgnoreCase(Part.INLINE)))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
contentString += (String) mbp.getContent();
} else {
attachments.add(saveAttachment(part));
}
}
}
}
String name = ((InternetAddress) message.getFrom()[0]).getPersonal();
String email = ((InternetAddress) message.getFrom()[0]).getAddress();
String to = ((InternetAddress) message.getAllRecipients()[0]).getAddress();
if("[email protected]".equals(to)) {
// Create Application
JobApplication application = new JobApplication(name, email, contentString, attachments);
application.create();
for(Attachment attachment : attachments) {
attachment.jobApplication = application;
attachment.create();
}
Mails.applied(application);
} else {
Pattern regexp = Pattern.compile("^jobs[+][^@]{5}-([0-9]+)@.*$");
Matcher matcher = regexp.matcher(to);
if(matcher.matches()) {
Long id = Long.parseLong(matcher.group(1));
JobApplication application = JobApplication.findById(id);
if(application == null) {
Logger.warn("Job application not found %s, for %s", id, to);
} else {
application.addMessage(name, email, contentString);
application.save();
}
} else {
Logger.warn("Unknow address --> %s", to);
}
}
- if (Play.mode == Play.Mode.PROD) {
+ if (Play.mode == Play.Mode.PROD || true) {
message.setFlag(Flag.FLAGGED, true);
}
}
// Close connection
folder.close(false);
store.close();
}
private Attachment saveAttachment(Part part) throws Exception, MessagingException, IOException {
Attachment attachment = new Attachment();
attachment.name = decodeName(part.getFileName());
attachment.content.set(part.getInputStream(), part.getContentType());
return attachment;
}
protected String decodeName(String name) throws Exception {
if (name == null || name.length() == 0) {
return "unknown";
}
String ret = java.net.URLDecoder.decode(name, "UTF-8");
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
}
| true | true | public void doJob() throws Exception {
if(Play.configuration.getProperty("mailbox.username") == null || Play.configuration.getProperty("mailbox.password") == null) {
Logger.error("Please configure mailbox credentials in conf/credentials.conf");
return;
}
// Connect to gmail mailbox
Properties props = new Properties();
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.port", "993");
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", Play.configuration.getProperty("mailbox.username"), Play.configuration.getProperty("mailbox.password"));
// Open jobs mailbox
Folder folder = store.getFolder("jobs");
folder.open(Folder.READ_WRITE);
// Search unstarred messages
SearchTerm unstarred = new FlagTerm(new Flags(Flags.Flag.FLAGGED), false);
Message[] messages = folder.search(unstarred);
// Loop over messages
for (Message message : messages) {
String contentString = "";
List<Attachment> attachments = new ArrayList<Attachment>();
// Decode content
if (message.getContent() instanceof String) {
contentString = (String) message.getContent();
} else if (message.getContent() instanceof Multipart) {
Multipart mp = (Multipart) message.getContent();
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null
|| ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition
.equalsIgnoreCase(Part.INLINE)))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
contentString += (String) mbp.getContent();
} else {
attachments.add(saveAttachment(part));
}
}
}
}
String name = ((InternetAddress) message.getFrom()[0]).getPersonal();
String email = ((InternetAddress) message.getFrom()[0]).getAddress();
String to = ((InternetAddress) message.getAllRecipients()[0]).getAddress();
if("[email protected]".equals(to)) {
// Create Application
JobApplication application = new JobApplication(name, email, contentString, attachments);
application.create();
for(Attachment attachment : attachments) {
attachment.jobApplication = application;
attachment.create();
}
Mails.applied(application);
} else {
Pattern regexp = Pattern.compile("^jobs[+][^@]{5}-([0-9]+)@.*$");
Matcher matcher = regexp.matcher(to);
if(matcher.matches()) {
Long id = Long.parseLong(matcher.group(1));
JobApplication application = JobApplication.findById(id);
if(application == null) {
Logger.warn("Job application not found %s, for %s", id, to);
} else {
application.addMessage(name, email, contentString);
application.save();
}
} else {
Logger.warn("Unknow address --> %s", to);
}
}
if (Play.mode == Play.Mode.PROD) {
message.setFlag(Flag.FLAGGED, true);
}
}
// Close connection
folder.close(false);
store.close();
}
| public void doJob() throws Exception {
if(Play.configuration.getProperty("mailbox.username") == null || Play.configuration.getProperty("mailbox.password") == null) {
Logger.error("Please configure mailbox credentials in conf/credentials.conf");
return;
}
// Connect to gmail mailbox
Properties props = new Properties();
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.port", "993");
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", Play.configuration.getProperty("mailbox.username"), Play.configuration.getProperty("mailbox.password"));
// Open jobs mailbox
Folder folder = store.getFolder("jobs");
folder.open(Folder.READ_WRITE);
// Search unstarred messages
SearchTerm unstarred = new FlagTerm(new Flags(Flags.Flag.FLAGGED), false);
Message[] messages = folder.search(unstarred);
// Loop over messages
for (Message message : messages) {
String contentString = "";
List<Attachment> attachments = new ArrayList<Attachment>();
// Decode content
if (message.getContent() instanceof String) {
contentString = (String) message.getContent();
} else if (message.getContent() instanceof Multipart) {
Multipart mp = (Multipart) message.getContent();
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null
|| ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition
.equalsIgnoreCase(Part.INLINE)))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
contentString += (String) mbp.getContent();
} else {
attachments.add(saveAttachment(part));
}
}
}
}
String name = ((InternetAddress) message.getFrom()[0]).getPersonal();
String email = ((InternetAddress) message.getFrom()[0]).getAddress();
String to = ((InternetAddress) message.getAllRecipients()[0]).getAddress();
if("[email protected]".equals(to)) {
// Create Application
JobApplication application = new JobApplication(name, email, contentString, attachments);
application.create();
for(Attachment attachment : attachments) {
attachment.jobApplication = application;
attachment.create();
}
Mails.applied(application);
} else {
Pattern regexp = Pattern.compile("^jobs[+][^@]{5}-([0-9]+)@.*$");
Matcher matcher = regexp.matcher(to);
if(matcher.matches()) {
Long id = Long.parseLong(matcher.group(1));
JobApplication application = JobApplication.findById(id);
if(application == null) {
Logger.warn("Job application not found %s, for %s", id, to);
} else {
application.addMessage(name, email, contentString);
application.save();
}
} else {
Logger.warn("Unknow address --> %s", to);
}
}
if (Play.mode == Play.Mode.PROD || true) {
message.setFlag(Flag.FLAGGED, true);
}
}
// Close connection
folder.close(false);
store.close();
}
|
diff --git a/openjdk/sun/nio/ch/DotNetSelectorImpl.java b/openjdk/sun/nio/ch/DotNetSelectorImpl.java
index ab6c1bb9..47ae5d3d 100644
--- a/openjdk/sun/nio/ch/DotNetSelectorImpl.java
+++ b/openjdk/sun/nio/ch/DotNetSelectorImpl.java
@@ -1,300 +1,301 @@
/*
* Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
// Parts Copyright (C) 2002-2007 Jeroen Frijters
package sun.nio.ch;
import cli.System.Net.Sockets.Socket;
import cli.System.Net.Sockets.SocketException;
import cli.System.Net.Sockets.AddressFamily;
import cli.System.Net.Sockets.SocketType;
import cli.System.Net.Sockets.ProtocolType;
import cli.System.Net.Sockets.SelectMode;
import cli.System.Collections.ArrayList;
import java.io.IOException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
final class DotNetSelectorImpl extends SelectorImpl
{
private Socket wakeupSourceFd;
private ArrayList channelArray = new ArrayList();
private long updateCount = 0;
// Lock for interrupt triggering and clearing
private final Object interruptLock = new Object();
private volatile boolean interruptTriggered = false;
// class for fdMap entries
private final static class MapEntry
{
SelectionKeyImpl ski;
long updateCount = 0;
long clearedCount = 0;
MapEntry(SelectionKeyImpl ski)
{
this.ski = ski;
}
}
private final HashMap<Socket, MapEntry> fdMap = new HashMap<Socket, MapEntry>();
DotNetSelectorImpl(SelectorProvider sp)
{
super(sp);
createWakeupSocket();
}
protected int doSelect(long timeout) throws IOException
{
if (channelArray == null)
throw new ClosedSelectorException();
processDeregisterQueue();
if (interruptTriggered)
{
resetWakeupSocket();
return 0;
}
ArrayList read = new ArrayList();
ArrayList write = new ArrayList();
ArrayList error = new ArrayList();
for (int i = 0; i < channelArray.get_Count(); i++)
{
SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i);
int ops = ski.interestOps();
if (ski.channel() instanceof SocketChannelImpl)
{
// TODO there's a race condition here...
if (((SocketChannelImpl)ski.channel()).isConnected())
{
ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE;
}
else
{
ops &= SelectionKey.OP_CONNECT;
}
}
if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0)
{
read.Add(ski.getSocket());
}
if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0)
{
write.Add(ski.getSocket());
}
if ((ops & SelectionKey.OP_CONNECT) != 0)
{
error.Add(ski.getSocket());
}
}
read.Add(wakeupSourceFd);
try
{
begin();
int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout);
try
{
if (false) throw new SocketException();
- Socket.Select(read, write, error, microSeconds);
+ // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work
+ Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds);
}
catch (SocketException _)
{
read.Clear();
write.Clear();
error.Clear();
}
}
finally
{
end();
}
processDeregisterQueue();
int updated = updateSelectedKeys(read, write, error);
// Done with poll(). Set wakeupSocket to nonsignaled for the next run.
resetWakeupSocket();
return updated;
}
private int updateSelectedKeys(ArrayList read, ArrayList write, ArrayList error)
{
updateCount++;
int keys = processFDSet(updateCount, read, PollArrayWrapper.POLLIN);
keys += processFDSet(updateCount, write, PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT);
keys += processFDSet(updateCount, error, PollArrayWrapper.POLLIN | PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT);
return keys;
}
private int processFDSet(long updateCount, ArrayList sockets, int rOps)
{
int numKeysUpdated = 0;
for (int i = 0; i < sockets.get_Count(); i++)
{
Socket desc = (Socket)sockets.get_Item(i);
if (desc == wakeupSourceFd)
{
synchronized (interruptLock)
{
interruptTriggered = true;
}
continue;
}
MapEntry me = fdMap.get(desc);
// If me is null, the key was deregistered in the previous
// processDeregisterQueue.
if (me == null)
continue;
SelectionKeyImpl sk = me.ski;
if (selectedKeys.contains(sk))
{ // Key in selected set
if (me.clearedCount != updateCount)
{
if (sk.channel.translateAndSetReadyOps(rOps, sk) &&
(me.updateCount != updateCount))
{
me.updateCount = updateCount;
numKeysUpdated++;
}
}
else
{ // The readyOps have been set; now add
if (sk.channel.translateAndUpdateReadyOps(rOps, sk) &&
(me.updateCount != updateCount))
{
me.updateCount = updateCount;
numKeysUpdated++;
}
}
me.clearedCount = updateCount;
}
else
{ // Key is not in selected set yet
if (me.clearedCount != updateCount)
{
sk.channel.translateAndSetReadyOps(rOps, sk);
if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0)
{
selectedKeys.add(sk);
me.updateCount = updateCount;
numKeysUpdated++;
}
}
else
{ // The readyOps have been set; now add
sk.channel.translateAndUpdateReadyOps(rOps, sk);
if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0)
{
selectedKeys.add(sk);
me.updateCount = updateCount;
numKeysUpdated++;
}
}
me.clearedCount = updateCount;
}
}
return numKeysUpdated;
}
protected void implClose() throws IOException
{
if (channelArray != null)
{
// prevent further wakeup
wakeup();
for (int i = 0; i < channelArray.get_Count(); i++)
{ // Deregister channels
SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i);
deregister(ski);
SelectableChannel selch = ski.channel();
if (!selch.isOpen() && !selch.isRegistered())
((SelChImpl)selch).kill();
}
selectedKeys = null;
channelArray = null;
}
}
protected void implRegister(SelectionKeyImpl ski)
{
channelArray.Add(ski);
fdMap.put(ski.getSocket(), new MapEntry(ski));
keys.add(ski);
}
protected void implDereg(SelectionKeyImpl ski) throws IOException
{
channelArray.Remove(ski);
fdMap.remove(ski.getSocket());
keys.remove(ski);
selectedKeys.remove(ski);
deregister(ski);
SelectableChannel selch = ski.channel();
if (!selch.isOpen() && !selch.isRegistered())
{
((SelChImpl)selch).kill();
}
}
public Selector wakeup()
{
synchronized (interruptLock)
{
if (!interruptTriggered)
{
wakeupSourceFd.Close();
interruptTriggered = true;
}
}
return this;
}
// Sets Windows wakeup socket to a non-signaled state.
private void resetWakeupSocket()
{
synchronized (interruptLock)
{
if (interruptTriggered == false)
return;
createWakeupSocket();
interruptTriggered = false;
}
}
private void createWakeupSocket()
{
wakeupSourceFd = new Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Dgram), ProtocolType.wrap(ProtocolType.Udp));
}
}
| true | true | protected int doSelect(long timeout) throws IOException
{
if (channelArray == null)
throw new ClosedSelectorException();
processDeregisterQueue();
if (interruptTriggered)
{
resetWakeupSocket();
return 0;
}
ArrayList read = new ArrayList();
ArrayList write = new ArrayList();
ArrayList error = new ArrayList();
for (int i = 0; i < channelArray.get_Count(); i++)
{
SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i);
int ops = ski.interestOps();
if (ski.channel() instanceof SocketChannelImpl)
{
// TODO there's a race condition here...
if (((SocketChannelImpl)ski.channel()).isConnected())
{
ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE;
}
else
{
ops &= SelectionKey.OP_CONNECT;
}
}
if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0)
{
read.Add(ski.getSocket());
}
if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0)
{
write.Add(ski.getSocket());
}
if ((ops & SelectionKey.OP_CONNECT) != 0)
{
error.Add(ski.getSocket());
}
}
read.Add(wakeupSourceFd);
try
{
begin();
int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout);
try
{
if (false) throw new SocketException();
Socket.Select(read, write, error, microSeconds);
}
catch (SocketException _)
{
read.Clear();
write.Clear();
error.Clear();
}
}
finally
{
end();
}
processDeregisterQueue();
int updated = updateSelectedKeys(read, write, error);
// Done with poll(). Set wakeupSocket to nonsignaled for the next run.
resetWakeupSocket();
return updated;
}
| protected int doSelect(long timeout) throws IOException
{
if (channelArray == null)
throw new ClosedSelectorException();
processDeregisterQueue();
if (interruptTriggered)
{
resetWakeupSocket();
return 0;
}
ArrayList read = new ArrayList();
ArrayList write = new ArrayList();
ArrayList error = new ArrayList();
for (int i = 0; i < channelArray.get_Count(); i++)
{
SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i);
int ops = ski.interestOps();
if (ski.channel() instanceof SocketChannelImpl)
{
// TODO there's a race condition here...
if (((SocketChannelImpl)ski.channel()).isConnected())
{
ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE;
}
else
{
ops &= SelectionKey.OP_CONNECT;
}
}
if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0)
{
read.Add(ski.getSocket());
}
if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0)
{
write.Add(ski.getSocket());
}
if ((ops & SelectionKey.OP_CONNECT) != 0)
{
error.Add(ski.getSocket());
}
}
read.Add(wakeupSourceFd);
try
{
begin();
int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout);
try
{
if (false) throw new SocketException();
// FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work
Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds);
}
catch (SocketException _)
{
read.Clear();
write.Clear();
error.Clear();
}
}
finally
{
end();
}
processDeregisterQueue();
int updated = updateSelectedKeys(read, write, error);
// Done with poll(). Set wakeupSocket to nonsignaled for the next run.
resetWakeupSocket();
return updated;
}
|
diff --git a/Paco-Server/src/com/google/sampling/experiential/server/EventServlet.java b/Paco-Server/src/com/google/sampling/experiential/server/EventServlet.java
index f31309d48..7c8c353ad 100755
--- a/Paco-Server/src/com/google/sampling/experiential/server/EventServlet.java
+++ b/Paco-Server/src/com/google/sampling/experiential/server/EventServlet.java
@@ -1,434 +1,444 @@
/*
* Copyright 2011 Google 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.google.sampling.experiential.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringEscapeUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.sampling.experiential.model.Event;
import com.google.sampling.experiential.model.PhotoBlob;
import com.google.sampling.experiential.shared.EventDAO;
import com.google.sampling.experiential.shared.TimeUtil;
/**
* Servlet that answers queries for Events.
*
* @author Bob Evans
*
*/
public class EventServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(EventServlet.class.getName());
private DateTimeFormatter jodaFormatter = DateTimeFormat.forPattern(TimeUtil.DATETIME_FORMAT);
private String defaultAdmin = "[email protected]";
private List<String> adminUsers = Lists.newArrayList(defaultAdmin);
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user == null) {
resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
} else {
String anonStr = req.getParameter("anon");
boolean anon = false;
if (anonStr != null) {
anon = Boolean.parseBoolean(anonStr);
}
if (req.getParameter("mapping") != null) {
dumpUserIdMapping(req, resp);
} else if (req.getParameter("json") != null) {
resp.setContentType("application/json;charset=UTF-8");
dumpEventsJson(resp, req, anon);
} else if (req.getParameter("csv") != null) {
resp.setContentType("text/csv;charset=UTF-8");
dumpEventsCSV(resp, req, anon);
} else {
resp.setContentType("text/html;charset=UTF-8");
showEvents(req, resp, anon);
}
}
}
private void dumpUserIdMapping(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<com.google.sampling.experiential.server.Query> query = new QueryParser().parse(stripQuotes(getParam(req, "q")));
List<Event> events = getEventsWithQuery(req, query);
sortEvents(events);
Set<String> whos = new HashSet<String>();
for (Event event : events) {
whos.add(event.getWho());
}
StringBuilder mappingOutput = new StringBuilder();
for (String who : whos) {
mappingOutput.append(who);
mappingOutput.append(",");
mappingOutput.append(Event.getAnonymousId(who));
mappingOutput.append("\n");
}
resp.setContentType("text/csv;charset=UTF-8");
resp.getWriter().println(mappingOutput.toString());
}
public static DateTimeZone getTimeZoneForClient(HttpServletRequest req) {
String tzStr = getParam(req, "tz");
if (tzStr != null && !tzStr.isEmpty()) {
DateTimeZone jodaTimeZone = DateTimeZone.forID(tzStr);
return jodaTimeZone;
} else {
Locale clientLocale = req.getLocale();
Calendar calendar = Calendar.getInstance(clientLocale);
TimeZone clientTimeZone = calendar.getTimeZone();
DateTimeZone jodaTimeZone = DateTimeZone.forTimeZone(clientTimeZone);
return jodaTimeZone;
}
}
private boolean isDevInstance(HttpServletRequest req) {
return ExperimentServlet.isDevInstance(req);
}
private User getWhoFromLogin() {
UserService userService = UserServiceFactory.getUserService();
return userService.getCurrentUser();
}
private static String getParam(HttpServletRequest req, String paramName) {
try {
String parameter = req.getParameter(paramName);
if (parameter == null || parameter.isEmpty()) {
return null;
}
return URLDecoder.decode(parameter, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new IllegalArgumentException("Unspported encoding");
}
}
private void dumpEventsJson(HttpServletResponse resp, HttpServletRequest req, boolean anon) throws IOException {
List<com.google.sampling.experiential.server.Query> query = new QueryParser().parse(stripQuotes(getParam(req, "q")));
List<Event> events = getEventsWithQuery(req, query);
sortEvents(events);
String jsonOutput = jsonifyEvents(events, anon);
resp.getWriter().println(jsonOutput);
}
private String jsonifyEvents(List<Event> events, boolean anon) {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
try {
List<EventDAO> eventDAOs = Lists.newArrayList();
for (Event event : events) {
String userId = event.getWho();
if (anon) {
userId = Event.getAnonymousId(userId);
}
eventDAOs.add(new EventDAO(userId, event.getWhen(), event.getExperimentName(), event.getLat(), event.getLon(),
event.getAppId(), event.getPacoVersion(), event.getWhatMap(), event.isShared(),
event.getResponseTime(), event.getScheduledTime(), null, Long.parseLong(event.getExperimentId())));
}
return mapper.writeValueAsString(eventDAOs);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Error could not retrieve events as json";
}
private void dumpEventsCSV(HttpServletResponse resp, HttpServletRequest req, boolean anon) throws IOException {
List<com.google.sampling.experiential.server.Query> query = new QueryParser().parse(stripQuotes(getParam(req, "q")));
String loggedInuser = getWhoFromLogin().getEmail();
if (loggedInuser != null && adminUsers.contains(loggedInuser)) {
loggedInuser = defaultAdmin;
}
List<Event> events = EventRetriever.getInstance().getEvents(query, loggedInuser, getTimeZoneForClient(req));
sortEvents(events);
List<String[]> eventsCSV = Lists.newArrayList();
Set<String> foundColumnNames = Sets.newHashSet();
for (Event event : events) {
Map<String, String> whatMap = event.getWhatMap();
foundColumnNames.addAll(whatMap.keySet());
}
List<String> columns = Lists.newArrayList();
columns.addAll(foundColumnNames);
Collections.sort(columns);
for (Event event : events) {
eventsCSV.add(event.toCSV(columns, anon));
}
// add back in the standard pacot event columns
columns.add(0, "who");
columns.add(1, "when");
columns.add(2, "lat");
columns.add(3, "lon");
columns.add(4, "appId");
columns.add(5, "pacoVersion");
columns.add(6, "experimentId");
columns.add(7, "experimentName");
columns.add(8, "responseTime");
columns.add(9, "scheduledTime");
resp.setContentType("text/csv;charset=UTF-8");
CSVWriter csvWriter = null;
try {
csvWriter = new CSVWriter(resp.getWriter());
String[] columnsArray = columns.toArray(new String[0]);
csvWriter.writeNext(columnsArray);
for (String[] eventCSV : eventsCSV) {
csvWriter.writeNext(eventCSV);
}
csvWriter.flush();
} finally {
if (csvWriter != null) {
csvWriter.close();
}
}
}
private void showEvents(HttpServletRequest req, HttpServletResponse resp, boolean anon) throws IOException {
List<com.google.sampling.experiential.server.Query> query = new QueryParser().parse(stripQuotes(getParam(req, "q")));
List<Event> greetings = getEventsWithQuery(req, query);
sortEvents(greetings);
printEvents(resp, greetings, anon);
}
private String stripQuotes(String parameter) {
if (parameter == null) {
return null;
}
if (parameter.startsWith("'") || parameter.startsWith("\"")) {
parameter = parameter.substring(1);
}
if (parameter.endsWith("'") || parameter.endsWith("\"")) {
parameter = parameter.substring(0, parameter.length() - 1);
}
return parameter;
}
private List<Event> getEventsWithQuery(HttpServletRequest req,
List<com.google.sampling.experiential.server.Query> queries) {
User whoFromLogin = getWhoFromLogin();
if (!isDevInstance(req) && whoFromLogin == null) {
throw new IllegalArgumentException("Must be logged in to retrieve data.");
}
String who = null;
if (whoFromLogin != null) {
who = whoFromLogin.getEmail();
}
return EventRetriever.getInstance().getEvents(queries, who, getTimeZoneForClient(req));
}
private void printEvents(HttpServletResponse resp, List<Event> greetings, boolean anon) throws IOException {
long t1 = System.currentTimeMillis();
long eventTime = 0;
long whatTime = 0;
if (greetings.isEmpty()) {
resp.getWriter().println("Nothing to see here.");
} else {
StringBuilder out = new StringBuilder();
out.append("<html><head><title>Current Ratings</title></head><body>");
out.append("<h1>Results</h1>");
out.append("<table border=1>");
out.append("<tr><th>Experiment Name</th><th>Scheduled Time</th><th>Response Time</th><th>Who</th><th>Responses</th></tr>");
for (Event eventRating : greetings) {
long e1 = System.currentTimeMillis();
out.append("<tr>");
out.append("<td>").append(eventRating.getExperimentName()).append("</td>");
- out.append("<td>").append(jodaFormatter.print(new DateTime(eventRating.getScheduledTime()))).append("</td>");
- out.append("<td>").append(jodaFormatter.print(new DateTime(eventRating.getResponseTime()))).append("</td>");
+ Date scheduledTime = eventRating.getScheduledTime();
+ String scheduledTimeString = "";
+ if (scheduledTime != null) {
+ scheduledTimeString = jodaFormatter.print(new DateTime(scheduledTime));
+ }
+ out.append("<td>").append(scheduledTimeString).append("</td>");
+ Date responseTime = eventRating.getResponseTime();
+ String responseTimeString = "";
+ if (responseTime != null) {
+ responseTimeString = jodaFormatter.print(new DateTime(responseTime));
+ }
+ out.append("<td>").append(responseTimeString).append("</td>");
String who = eventRating.getWho();
if (anon) {
who = Event.getAnonymousId(who);
}
out.append("<td>").append(who).append("</td>");
eventTime += System.currentTimeMillis() - e1;
long what1 = System.currentTimeMillis();
// we want to render photos as photos not as strings.
// It would be better to do this by getting the experiment for
// the event and going through the inputs.
// That was not done because there may be multiple experiments
// in the data returned for this interface and
// that is work that is otherwise necessary for now. Go
// pretotyping!
// TODO clean all the accesses of what could be tainted data.
List<PhotoBlob> photos = eventRating.getBlobs();
Map<String, PhotoBlob> photoByNames = Maps.newConcurrentMap();
for (PhotoBlob photoBlob : photos) {
photoByNames.put(photoBlob.getName(), photoBlob);
}
Map<String, String> whatMap = eventRating.getWhatMap();
Set<String> keys = whatMap.keySet();
if (keys != null) {
ArrayList<String> keysAsList = Lists.newArrayList(keys);
Collections.sort(keysAsList);
Collections.reverse(keysAsList);
for (String key : keysAsList) {
String value = whatMap.get(key);
if (value == null) {
value = "";
} else if (photoByNames.containsKey(key)) {
byte[] photoData = photoByNames.get(key).getValue();
if (photoData != null && photoData.length > 0) {
String photoString = new String(Base64.encodeBase64(photoData));
if (!photoString.equals("==")) {
value = "<img height=\"375\" src=\"data:image/jpg;base64," + photoString + "\">";
} else {
value = "";
}
} else {
value = "";
}
} else if (value.indexOf(" ") != -1) {
value = "\"" + StringEscapeUtils.escapeHtml4(value) + "\"";
} else {
value = StringEscapeUtils.escapeHtml4(value);
}
out.append("<td>");
out.append(key).append(" = ").append(value);
out.append("</td>");
}
}
whatTime += System.currentTimeMillis() - what1;
out.append("<tr>");
}
long t2 = System.currentTimeMillis();
log.info("EventServlet printEvents total: " + (t2 - t1));
log.info("Event time: " + eventTime);
log.info("what time: " + whatTime);
out.append("</table></body></html>");
resp.getWriter().println(out.toString());
}
}
private void sortEvents(List<Event> greetings) {
Comparator<Event> dateComparator = new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
Date when1 = o1.getWhen();
Date when2 = o2.getWhen();
if (when1 == null || when2 == null) {
return 0;
} else if (when1.after(when2)) {
return -1;
} else if (when2.after(when1)) {
return 1;
}
return 0;
}
};
Collections.sort(greetings, dateComparator);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
setCharacterEncoding(req, resp);
User who = getWhoFromLogin();
if (who == null) {
throw new IllegalArgumentException("Must be logged in!");
}
// TODO(bobevans): Add security check, and length check for DoS
if (ServletFileUpload.isMultipartContent(req)) {
processCsvUpload(req, resp);
} else {
processJsonUpload(req, resp);
}
}
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletFileUpload fileUploadTool = new ServletFileUpload();
fileUploadTool.setSizeMax(50000);
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter(); // TODO move all req/resp writing to here.
try {
new EventCsvUploadProcessor().processCsvUpload(getWhoFromLogin(), fileUploadTool.getItemIterator(req), out);
} catch (FileUploadException e) {
log.severe("FileUploadException: " + e.getMessage());
out.println("Error in receiving file.");
}
}
private void processJsonUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String postBodyString;
try {
postBodyString = org.apache.commons.io.IOUtils.toString(req.getInputStream());
} catch (IOException e) {
log.info("IO Exception reading post data stream: " + e.getMessage());
throw e;
}
// log.info(postBodyString);
if (postBodyString.equals("")) {
throw new IllegalArgumentException("Empty Post body");
}
String results = EventJsonUploadProcessor.create().processJsonEvents(postBodyString, getWhoFromLogin().getEmail());
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write(results);
}
private void setCharacterEncoding(HttpServletRequest req, HttpServletResponse resp)
throws UnsupportedEncodingException {
req.setCharacterEncoding(Charsets.UTF_8.name());
resp.setCharacterEncoding(Charsets.UTF_8.name());
}
}
| true | true | private void printEvents(HttpServletResponse resp, List<Event> greetings, boolean anon) throws IOException {
long t1 = System.currentTimeMillis();
long eventTime = 0;
long whatTime = 0;
if (greetings.isEmpty()) {
resp.getWriter().println("Nothing to see here.");
} else {
StringBuilder out = new StringBuilder();
out.append("<html><head><title>Current Ratings</title></head><body>");
out.append("<h1>Results</h1>");
out.append("<table border=1>");
out.append("<tr><th>Experiment Name</th><th>Scheduled Time</th><th>Response Time</th><th>Who</th><th>Responses</th></tr>");
for (Event eventRating : greetings) {
long e1 = System.currentTimeMillis();
out.append("<tr>");
out.append("<td>").append(eventRating.getExperimentName()).append("</td>");
out.append("<td>").append(jodaFormatter.print(new DateTime(eventRating.getScheduledTime()))).append("</td>");
out.append("<td>").append(jodaFormatter.print(new DateTime(eventRating.getResponseTime()))).append("</td>");
String who = eventRating.getWho();
if (anon) {
who = Event.getAnonymousId(who);
}
out.append("<td>").append(who).append("</td>");
eventTime += System.currentTimeMillis() - e1;
long what1 = System.currentTimeMillis();
// we want to render photos as photos not as strings.
// It would be better to do this by getting the experiment for
// the event and going through the inputs.
// That was not done because there may be multiple experiments
// in the data returned for this interface and
// that is work that is otherwise necessary for now. Go
// pretotyping!
// TODO clean all the accesses of what could be tainted data.
List<PhotoBlob> photos = eventRating.getBlobs();
Map<String, PhotoBlob> photoByNames = Maps.newConcurrentMap();
for (PhotoBlob photoBlob : photos) {
photoByNames.put(photoBlob.getName(), photoBlob);
}
Map<String, String> whatMap = eventRating.getWhatMap();
Set<String> keys = whatMap.keySet();
if (keys != null) {
ArrayList<String> keysAsList = Lists.newArrayList(keys);
Collections.sort(keysAsList);
Collections.reverse(keysAsList);
for (String key : keysAsList) {
String value = whatMap.get(key);
if (value == null) {
value = "";
} else if (photoByNames.containsKey(key)) {
byte[] photoData = photoByNames.get(key).getValue();
if (photoData != null && photoData.length > 0) {
String photoString = new String(Base64.encodeBase64(photoData));
if (!photoString.equals("==")) {
value = "<img height=\"375\" src=\"data:image/jpg;base64," + photoString + "\">";
} else {
value = "";
}
} else {
value = "";
}
} else if (value.indexOf(" ") != -1) {
value = "\"" + StringEscapeUtils.escapeHtml4(value) + "\"";
} else {
value = StringEscapeUtils.escapeHtml4(value);
}
out.append("<td>");
out.append(key).append(" = ").append(value);
out.append("</td>");
}
}
whatTime += System.currentTimeMillis() - what1;
out.append("<tr>");
}
long t2 = System.currentTimeMillis();
log.info("EventServlet printEvents total: " + (t2 - t1));
log.info("Event time: " + eventTime);
log.info("what time: " + whatTime);
out.append("</table></body></html>");
resp.getWriter().println(out.toString());
}
}
| private void printEvents(HttpServletResponse resp, List<Event> greetings, boolean anon) throws IOException {
long t1 = System.currentTimeMillis();
long eventTime = 0;
long whatTime = 0;
if (greetings.isEmpty()) {
resp.getWriter().println("Nothing to see here.");
} else {
StringBuilder out = new StringBuilder();
out.append("<html><head><title>Current Ratings</title></head><body>");
out.append("<h1>Results</h1>");
out.append("<table border=1>");
out.append("<tr><th>Experiment Name</th><th>Scheduled Time</th><th>Response Time</th><th>Who</th><th>Responses</th></tr>");
for (Event eventRating : greetings) {
long e1 = System.currentTimeMillis();
out.append("<tr>");
out.append("<td>").append(eventRating.getExperimentName()).append("</td>");
Date scheduledTime = eventRating.getScheduledTime();
String scheduledTimeString = "";
if (scheduledTime != null) {
scheduledTimeString = jodaFormatter.print(new DateTime(scheduledTime));
}
out.append("<td>").append(scheduledTimeString).append("</td>");
Date responseTime = eventRating.getResponseTime();
String responseTimeString = "";
if (responseTime != null) {
responseTimeString = jodaFormatter.print(new DateTime(responseTime));
}
out.append("<td>").append(responseTimeString).append("</td>");
String who = eventRating.getWho();
if (anon) {
who = Event.getAnonymousId(who);
}
out.append("<td>").append(who).append("</td>");
eventTime += System.currentTimeMillis() - e1;
long what1 = System.currentTimeMillis();
// we want to render photos as photos not as strings.
// It would be better to do this by getting the experiment for
// the event and going through the inputs.
// That was not done because there may be multiple experiments
// in the data returned for this interface and
// that is work that is otherwise necessary for now. Go
// pretotyping!
// TODO clean all the accesses of what could be tainted data.
List<PhotoBlob> photos = eventRating.getBlobs();
Map<String, PhotoBlob> photoByNames = Maps.newConcurrentMap();
for (PhotoBlob photoBlob : photos) {
photoByNames.put(photoBlob.getName(), photoBlob);
}
Map<String, String> whatMap = eventRating.getWhatMap();
Set<String> keys = whatMap.keySet();
if (keys != null) {
ArrayList<String> keysAsList = Lists.newArrayList(keys);
Collections.sort(keysAsList);
Collections.reverse(keysAsList);
for (String key : keysAsList) {
String value = whatMap.get(key);
if (value == null) {
value = "";
} else if (photoByNames.containsKey(key)) {
byte[] photoData = photoByNames.get(key).getValue();
if (photoData != null && photoData.length > 0) {
String photoString = new String(Base64.encodeBase64(photoData));
if (!photoString.equals("==")) {
value = "<img height=\"375\" src=\"data:image/jpg;base64," + photoString + "\">";
} else {
value = "";
}
} else {
value = "";
}
} else if (value.indexOf(" ") != -1) {
value = "\"" + StringEscapeUtils.escapeHtml4(value) + "\"";
} else {
value = StringEscapeUtils.escapeHtml4(value);
}
out.append("<td>");
out.append(key).append(" = ").append(value);
out.append("</td>");
}
}
whatTime += System.currentTimeMillis() - what1;
out.append("<tr>");
}
long t2 = System.currentTimeMillis();
log.info("EventServlet printEvents total: " + (t2 - t1));
log.info("Event time: " + eventTime);
log.info("what time: " + whatTime);
out.append("</table></body></html>");
resp.getWriter().println(out.toString());
}
}
|
diff --git a/src/main/java/org/glassfish/scripting/gem/GlassFishConsoleHandler.java b/src/main/java/org/glassfish/scripting/gem/GlassFishConsoleHandler.java
index 259b301..4b6c30e 100644
--- a/src/main/java/org/glassfish/scripting/gem/GlassFishConsoleHandler.java
+++ b/src/main/java/org/glassfish/scripting/gem/GlassFishConsoleHandler.java
@@ -1,53 +1,55 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.scripting.gem;
import java.util.logging.ConsoleHandler;
import java.util.logging.LogRecord;
/**
* @author Vivek Pandey
*/
public class GlassFishConsoleHandler extends ConsoleHandler {
@Override
public void publish(LogRecord record) {
if(record != null && record.getLoggerName() != null){
- if(record.getLoggerName().equals("org.glassfish.scripting.jruby.JRubyContainer")){
+ //log all the warning and error messages to console
+ if((record.getLevel().intValue() > 800 && record.getLevel().intValue() <= 1000) ||
+ record.getLoggerName().equals("org.glassfish.scripting.jruby.JRubyContainer")){
super.publish(record);
}
}
}
}
| true | true | public void publish(LogRecord record) {
if(record != null && record.getLoggerName() != null){
if(record.getLoggerName().equals("org.glassfish.scripting.jruby.JRubyContainer")){
super.publish(record);
}
}
}
| public void publish(LogRecord record) {
if(record != null && record.getLoggerName() != null){
//log all the warning and error messages to console
if((record.getLevel().intValue() > 800 && record.getLevel().intValue() <= 1000) ||
record.getLoggerName().equals("org.glassfish.scripting.jruby.JRubyContainer")){
super.publish(record);
}
}
}
|
diff --git a/src/main/java/org/mvel/ast/NewObjectNode.java b/src/main/java/org/mvel/ast/NewObjectNode.java
index bd6740c1..54e0b56a 100644
--- a/src/main/java/org/mvel/ast/NewObjectNode.java
+++ b/src/main/java/org/mvel/ast/NewObjectNode.java
@@ -1,75 +1,72 @@
package org.mvel.ast;
import org.mvel.*;
import org.mvel.integration.VariableResolverFactory;
import static org.mvel.optimizers.OptimizerFactory.getThreadAccessorOptimizer;
import org.mvel.util.ArrayTools;
/**
* @author Christopher Brock
*/
public class NewObjectNode extends ASTNode {
private Accessor newObjectOptimizer;
private String FQCN;
public NewObjectNode(char[] expr, int fields) {
super(expr, fields);
if ((fields & COMPILE_IMMEDIATE) != 0) {
int endRange = ArrayTools.findFirst('(', expr);
String name;
if (endRange == -1) {
name = new String(expr);
}
else {
name = new String(expr, 0, ArrayTools.findFirst('(', expr));
}
ParserContext pCtx = AbstractParser.getCurrentThreadParserContext();
if (pCtx != null && pCtx.hasImport(name)) {
egressType = pCtx.getImport(name);
}
- else if (AbstractParser.LITERALS.containsKey(name)) {
- egressType = (Class) AbstractParser.LITERALS.get(name);
- }
else {
try {
egressType = Class.forName(name);
}
catch (ClassNotFoundException e) {
throw new CompileException("class not found: " + name, e);
}
}
FQCN = egressType.getName();
if (!name.equals(FQCN)) {
int idx = FQCN.lastIndexOf('$');
if (idx != -1 && name.lastIndexOf('$') == -1) {
this.name = (FQCN.substring(0, idx + 1) + new String(this.name)).toCharArray();
}
else {
this.name = (FQCN.substring(0, FQCN.lastIndexOf('.') + 1) + new String(this.name)).toCharArray();
}
}
}
}
public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
if (newObjectOptimizer == null) {
newObjectOptimizer = getThreadAccessorOptimizer().optimizeObjectCreation(name, ctx, thisValue, factory);
}
return newObjectOptimizer.getValue(ctx, thisValue, factory);
}
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
return getReducedValueAccelerated(ctx, thisValue, factory);
}
public Accessor getNewObjectOptimizer() {
return newObjectOptimizer;
}
}
| true | true | public NewObjectNode(char[] expr, int fields) {
super(expr, fields);
if ((fields & COMPILE_IMMEDIATE) != 0) {
int endRange = ArrayTools.findFirst('(', expr);
String name;
if (endRange == -1) {
name = new String(expr);
}
else {
name = new String(expr, 0, ArrayTools.findFirst('(', expr));
}
ParserContext pCtx = AbstractParser.getCurrentThreadParserContext();
if (pCtx != null && pCtx.hasImport(name)) {
egressType = pCtx.getImport(name);
}
else if (AbstractParser.LITERALS.containsKey(name)) {
egressType = (Class) AbstractParser.LITERALS.get(name);
}
else {
try {
egressType = Class.forName(name);
}
catch (ClassNotFoundException e) {
throw new CompileException("class not found: " + name, e);
}
}
FQCN = egressType.getName();
if (!name.equals(FQCN)) {
int idx = FQCN.lastIndexOf('$');
if (idx != -1 && name.lastIndexOf('$') == -1) {
this.name = (FQCN.substring(0, idx + 1) + new String(this.name)).toCharArray();
}
else {
this.name = (FQCN.substring(0, FQCN.lastIndexOf('.') + 1) + new String(this.name)).toCharArray();
}
}
}
}
| public NewObjectNode(char[] expr, int fields) {
super(expr, fields);
if ((fields & COMPILE_IMMEDIATE) != 0) {
int endRange = ArrayTools.findFirst('(', expr);
String name;
if (endRange == -1) {
name = new String(expr);
}
else {
name = new String(expr, 0, ArrayTools.findFirst('(', expr));
}
ParserContext pCtx = AbstractParser.getCurrentThreadParserContext();
if (pCtx != null && pCtx.hasImport(name)) {
egressType = pCtx.getImport(name);
}
else {
try {
egressType = Class.forName(name);
}
catch (ClassNotFoundException e) {
throw new CompileException("class not found: " + name, e);
}
}
FQCN = egressType.getName();
if (!name.equals(FQCN)) {
int idx = FQCN.lastIndexOf('$');
if (idx != -1 && name.lastIndexOf('$') == -1) {
this.name = (FQCN.substring(0, idx + 1) + new String(this.name)).toCharArray();
}
else {
this.name = (FQCN.substring(0, FQCN.lastIndexOf('.') + 1) + new String(this.name)).toCharArray();
}
}
}
}
|
diff --git a/src/edgruberman/bukkit/simpledeathnotices/Main.java b/src/edgruberman/bukkit/simpledeathnotices/Main.java
index b229481..25c63d3 100644
--- a/src/edgruberman/bukkit/simpledeathnotices/Main.java
+++ b/src/edgruberman/bukkit/simpledeathnotices/Main.java
@@ -1,139 +1,139 @@
package edgruberman.bukkit.simpledeathnotices;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityEvent;
import edgruberman.bukkit.simpledeathnotices.MessageManager.MessageLevel;
public class Main extends org.bukkit.plugin.java.JavaPlugin {
private final String DEFAULT_LOG_LEVEL = "CONFIG";
private final String DEFAULT_BROADCAST_LEVEL = "EVENT";
public static MessageManager messageManager = null;
public void onEnable() {
Main.messageManager = new MessageManager(this);
Main.messageManager.log("Version " + this.getDescription().getVersion());
Configuration.load(this);
Main.messageManager.setLogLevel(MessageLevel.parse( this.getConfiguration().getString("logLevel", this.DEFAULT_LOG_LEVEL)));
Main.messageManager.setBroadcastLevel(MessageLevel.parse(this.getConfiguration().getString("broadcastLevel", this.DEFAULT_BROADCAST_LEVEL)));
Main.messageManager.log(MessageLevel.CONFIG,
"timestamp: " + this.getConfiguration().getString("timestamp")
+ "; format: " + this.getConfiguration().getString("format")
);
this.registerEvents();
Main.messageManager.log("Plugin Enabled");
}
public void onDisable() {
//TODO Unregister listeners when Bukkit supports it.
Main.messageManager.log("Plugin Disabled");
Main.messageManager = null;
}
private void registerEvents() {
EntityListener entityListener = new EntityListener(this);
org.bukkit.plugin.PluginManager pluginManager = this.getServer().getPluginManager();
pluginManager.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Event.Priority.Monitor, this);
pluginManager.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Event.Priority.Monitor, this);
}
public void describeEvent(EntityEvent event) {
Entity damager = null;
String damagerName = "";
if (event instanceof EntityDamageByEntityEvent){
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
- damagerName = " " + this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
+ damagerName += " " + this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
} else if (event instanceof EntityDamageByBlockEvent) {
damagerName = " " + ((EntityDamageByBlockEvent) event).getDamager().getType().toString().toLowerCase();
} else if (event instanceof EntityDamageByProjectileEvent) {
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
- damagerName = this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
+ damagerName += this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
damagerName += "'s " + this.getEntityName(((EntityDamageByProjectileEvent) event).getProjectile());
}
String deathCause;
if (event instanceof EntityDeathEvent) {
// We don't know what the last damage this player received was, but they are dead now.
deathCause = this.getCause(null);
} else {
deathCause = this.getCause(((EntityDamageEvent) event).getCause());
}
String deathNotice = this.getConfiguration().getString("format")
.replace(
"%TIMESTAMP%"
, (new SimpleDateFormat(this.getConfiguration().getString("timestamp")).format(new Date()))
)
.replace(
"%VICTIM%"
, ((Player) event.getEntity()).getDisplayName()
)
.replace(
"%CAUSE%"
, deathCause
)
.replace(
"%KILLER%"
, damagerName
)
;
Main.messageManager.broadcast(MessageLevel.EVENT, deathNotice);
}
public String getCause(DamageCause damageCause) {
String deathCause;
switch (damageCause) {
case ENTITY_ATTACK: deathCause = "being hit by"; break;
case ENTITY_EXPLOSION: deathCause = "an explosion from"; break;
case CONTACT: deathCause = "contact with"; break;
case SUFFOCATION: deathCause = "suffocation"; break;
case FALL: deathCause = "falling"; break;
case FIRE: deathCause = "fire"; break;
case FIRE_TICK: deathCause = "burning"; break;
case LAVA: deathCause = "lava"; break;
case DROWNING: deathCause = "drowning"; break;
case BLOCK_EXPLOSION: deathCause = "an explosion"; break;
case VOID: deathCause = "falling in to the void"; break;
case CUSTOM: deathCause = "something custom"; break;
default: deathCause = "something"; break;
}
return deathCause;
}
private String getEntityName(Entity entity) {
Main.messageManager.log(MessageLevel.FINEST, "Entity Class: " + entity.getClass().getName());
// For players, use their current display name.
if (entity instanceof Player)
return ((Player) entity).getDisplayName();
// For entities, use their class name stripping Craft from the front.
String[] damagerClass = entity.getClass().getName().split("\\.");
String name = damagerClass[damagerClass.length - 1].substring("Craft".length());
if (name.equals("TNTPrimed")) name = "TNT";
return name;
}
}
| false | true | public void describeEvent(EntityEvent event) {
Entity damager = null;
String damagerName = "";
if (event instanceof EntityDamageByEntityEvent){
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
damagerName = " " + this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
} else if (event instanceof EntityDamageByBlockEvent) {
damagerName = " " + ((EntityDamageByBlockEvent) event).getDamager().getType().toString().toLowerCase();
} else if (event instanceof EntityDamageByProjectileEvent) {
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
damagerName = this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
damagerName += "'s " + this.getEntityName(((EntityDamageByProjectileEvent) event).getProjectile());
}
String deathCause;
if (event instanceof EntityDeathEvent) {
// We don't know what the last damage this player received was, but they are dead now.
deathCause = this.getCause(null);
} else {
deathCause = this.getCause(((EntityDamageEvent) event).getCause());
}
String deathNotice = this.getConfiguration().getString("format")
.replace(
"%TIMESTAMP%"
, (new SimpleDateFormat(this.getConfiguration().getString("timestamp")).format(new Date()))
)
.replace(
"%VICTIM%"
, ((Player) event.getEntity()).getDisplayName()
)
.replace(
"%CAUSE%"
, deathCause
)
.replace(
"%KILLER%"
, damagerName
)
;
Main.messageManager.broadcast(MessageLevel.EVENT, deathNotice);
}
| public void describeEvent(EntityEvent event) {
Entity damager = null;
String damagerName = "";
if (event instanceof EntityDamageByEntityEvent){
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
damagerName += " " + this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
} else if (event instanceof EntityDamageByBlockEvent) {
damagerName = " " + ((EntityDamageByBlockEvent) event).getDamager().getType().toString().toLowerCase();
} else if (event instanceof EntityDamageByProjectileEvent) {
damager = ((EntityDamageByEntityEvent) event).getDamager();
if (!(damager instanceof Player)) damagerName = " a ";
damagerName += this.getEntityName(((EntityDamageByEntityEvent) event).getDamager());
damagerName += "'s " + this.getEntityName(((EntityDamageByProjectileEvent) event).getProjectile());
}
String deathCause;
if (event instanceof EntityDeathEvent) {
// We don't know what the last damage this player received was, but they are dead now.
deathCause = this.getCause(null);
} else {
deathCause = this.getCause(((EntityDamageEvent) event).getCause());
}
String deathNotice = this.getConfiguration().getString("format")
.replace(
"%TIMESTAMP%"
, (new SimpleDateFormat(this.getConfiguration().getString("timestamp")).format(new Date()))
)
.replace(
"%VICTIM%"
, ((Player) event.getEntity()).getDisplayName()
)
.replace(
"%CAUSE%"
, deathCause
)
.replace(
"%KILLER%"
, damagerName
)
;
Main.messageManager.broadcast(MessageLevel.EVENT, deathNotice);
}
|
diff --git a/database/src/main/java/no/bekk/bekkopen/cde/database/Main.java b/database/src/main/java/no/bekk/bekkopen/cde/database/Main.java
index e3786db..c235178 100644
--- a/database/src/main/java/no/bekk/bekkopen/cde/database/Main.java
+++ b/database/src/main/java/no/bekk/bekkopen/cde/database/Main.java
@@ -1,28 +1,28 @@
package no.bekk.bekkopen.cde.database;
import liquibase.exception.CommandLineParsingException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws CommandLineParsingException, IOException, NoSuchFieldException, IllegalAccessException {
List<String> defaultArgs = Arrays.asList(
"--driver=com.mysql.jdbc.Driver",
- "--url=jdbc:mysql://mysql.bekkopen.no/bekkopen",
+ "--url=jdbc:mysql://node1.morisbak.net/bekkopen",
"--username=bekkopen",
"--password=secret",
"--changeLogFile=bekkopen/database/db.changelog-master.xml"
);
List<String> suppliedArgs = Arrays.asList(args);
List<String> liquibaseArgs = new ArrayList<String>();
liquibaseArgs.addAll(defaultArgs);
liquibaseArgs.addAll(suppliedArgs);
liquibase.integration.commandline.Main.main(liquibaseArgs.toArray(new String[liquibaseArgs.size()]));
}
}
| true | true | public static void main(String[] args) throws CommandLineParsingException, IOException, NoSuchFieldException, IllegalAccessException {
List<String> defaultArgs = Arrays.asList(
"--driver=com.mysql.jdbc.Driver",
"--url=jdbc:mysql://mysql.bekkopen.no/bekkopen",
"--username=bekkopen",
"--password=secret",
"--changeLogFile=bekkopen/database/db.changelog-master.xml"
);
List<String> suppliedArgs = Arrays.asList(args);
List<String> liquibaseArgs = new ArrayList<String>();
liquibaseArgs.addAll(defaultArgs);
liquibaseArgs.addAll(suppliedArgs);
liquibase.integration.commandline.Main.main(liquibaseArgs.toArray(new String[liquibaseArgs.size()]));
}
| public static void main(String[] args) throws CommandLineParsingException, IOException, NoSuchFieldException, IllegalAccessException {
List<String> defaultArgs = Arrays.asList(
"--driver=com.mysql.jdbc.Driver",
"--url=jdbc:mysql://node1.morisbak.net/bekkopen",
"--username=bekkopen",
"--password=secret",
"--changeLogFile=bekkopen/database/db.changelog-master.xml"
);
List<String> suppliedArgs = Arrays.asList(args);
List<String> liquibaseArgs = new ArrayList<String>();
liquibaseArgs.addAll(defaultArgs);
liquibaseArgs.addAll(suppliedArgs);
liquibase.integration.commandline.Main.main(liquibaseArgs.toArray(new String[liquibaseArgs.size()]));
}
|
diff --git a/src/com/android/calendar/alerts/SnoozeAlarmsService.java b/src/com/android/calendar/alerts/SnoozeAlarmsService.java
index 2eac1a71..6ef983d5 100644
--- a/src/com/android/calendar/alerts/SnoozeAlarmsService.java
+++ b/src/com/android/calendar/alerts/SnoozeAlarmsService.java
@@ -1,88 +1,89 @@
/*
* Copyright (C) 2012 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.calendar.alerts;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.CalendarContract.CalendarAlerts;
/**
* Service for asynchronously marking a fired alarm as dismissed and scheduling
* a new alarm in the future.
*/
public class SnoozeAlarmsService extends IntentService {
private static final String[] PROJECTION = new String[] {
CalendarAlerts.STATE,
};
private static final int COLUMN_INDEX_STATE = 0;
public SnoozeAlarmsService() {
super("SnoozeAlarmsService");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
- AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, null, alarmTime);
+ AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, AlertUtils.createAlarmManager(this),
+ alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
}
| true | true | public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, null, alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
| public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, AlertUtils.createAlarmManager(this),
alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
|
diff --git a/src/se/kth/maandree/utilsay/Ponysay.java b/src/se/kth/maandree/utilsay/Ponysay.java
index 7412ba7..a355b49 100644
--- a/src/se/kth/maandree/utilsay/Ponysay.java
+++ b/src/se/kth/maandree/utilsay/Ponysay.java
@@ -1,1632 +1,1632 @@
/**
* util-say — Utilities for cowsay and cowsay-like programs
*
* Copyright © 2012, 2013 Mattias Andrée ([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 3 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, see <http://www.gnu.org/licenses/>.
*/
package se.kth.maandree.utilsay;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
// This class should be tried to be keeped as optimised as possible for the
// lastest version of ponysay (only) without endangering its maintainability.
/**
* Ponysay support module
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class Ponysay
{
/**
* Until, and including, version 2.0 of ponysay the cowsay format was used
*/
private static final int VERSION_COWSAY = 0;
/**
* Until, and including, version 2.8 of ponysay the unisay format was used
*/
private static final int VERSION_UNISAY = 1;
/**
* Until, but excluding, version 3.0 of ponysay's pony format was extended to support metadata
*/
private static final int VERSION_METADATA = 2;
/**
* In version 3.0 of ponysay's pony format was extended to support horizontal justifiction of balloons
*/
private static final int VERSION_HORIZONTAL_JUSTIFICATION = 3;
/**
* Constructor
*
* @param flags Flags passed to the module
*/
public Ponysay(HashMap<String, String> flags)
{
this.file = (flags.containsKey("file") ? (this.file = flags.get("file")).equals("-") : true) ? null : this.file;
this.even = (flags.containsKey("even") == false) || flags.get("even").toLowerCase().startsWith("y");
this.tty = flags.containsKey("tty") && flags.get("tty").toLowerCase().startsWith("y");
this.fullblocks = flags.containsKey("fullblocks") ? flags.get("fullblocks").toLowerCase().startsWith("y") : this.tty;
this.spacesave = flags.containsKey("spacesave") && flags.get("spacesave").toLowerCase().startsWith("y");
this.zebra = flags.containsKey("zebra") && flags.get("zebra").toLowerCase().startsWith("y");
this.version = flags.containsKey("version") ? parseVersion(flags.get("version")) : VERSION_HORIZONTAL_JUSTIFICATION;
this.utf8 = this.version > VERSION_COWSAY ? true : (flags.containsKey("utf8") && flags.get("utf8").toLowerCase().startsWith("y"));
this.fullcolour = flags.containsKey("fullcolour") && flags.get("fullcolour").toLowerCase().startsWith("y");
this.chroma = (flags.containsKey("chroma") == false) ? -1 : parseDouble(flags.get("chroma"));
this.left = (flags.containsKey("left") == false) ? 2 : parseInteger(flags.get("left"));
this.right = (flags.containsKey("right") == false) ? 0 : parseInteger(flags.get("right"));
this.top = (flags.containsKey("top") == false) ? 3 : parseInteger(flags.get("top"));
this.bottom = (flags.containsKey("bottom") == false) ? 1 : parseInteger(flags.get("bottom"));
this.palette = (flags.containsKey("palette") == false) ? null : parsePalette(flags.get("palette").toUpperCase().replace("\033", "").replace("]", "").replace("P", ""));
this.ignoreballoon = flags.containsKey("ignoreballoon") && flags.get("ignoreballoon").toLowerCase().startsWith("y");
this.ignorelink = flags.containsKey("ignorelink") ? flags.get("ignorelink").toLowerCase().startsWith("y") : this.ignoreballoon;
this.colourful = this.tty && ((flags.containsKey("colourful") == false) || flags.get("colourful").toLowerCase().startsWith("y"));
this.escesc = this.version > VERSION_COWSAY ? false : (flags.containsKey("escesc") && flags.get("escesc").toLowerCase().startsWith("y"));
}
/**
* Input/output option: pony file
*/
protected String file;
/**
* Input/output option: ignore the balloon
*/
protected boolean ignoreballoon;
/**
* Input/output option: ignore the balloon link
*/
protected boolean ignorelink;
/**
* Output option: pad right side
*/
protected boolean even;
/**
* Output option: linux vt
*/
protected boolean tty;;
/**
* Output option: colourful tty
*/
protected boolean colourful;
/**
* Output option: allow solid block elements
*/
protected boolean fullblocks;
/**
* Output option: make foreground for whitespace the same as the background
*/
protected boolean spacesave;
/**
* Output option: zebra effect
*/
protected boolean zebra;
/**
* Input/output option: colour palette
*/
protected Color[] palette;
/**
* Output option: chroma weight, negative for sRGB distance
*/
protected double chroma;
// KEYWORD when colourlabs supports convertion from sRGB, enabled preceptional distance
/**
* Input/output option: ponysay version
*/
protected int version;
/**
* Output option: use utf8 encoding on pixels
*/
protected boolean utf8;
/**
* Output option: escape escape charactes
*/
protected boolean escesc;
/**
* Output option: do not limit to xterm 256 standard colours
*/
protected boolean fullcolour;
/**
* Output option: left margin, negative for unmodified
*/
protected int left;
/**
* Output option: right margin, negative for unmodified
*/
protected int right;
/**
* Output option: top margin, negative for unmodified
*/
protected int top;
/**
* Output option: bottom margin, negative for unmodified
*/
protected int bottom;
/**
* Colour CIELAB value cache
*/
private static HashMap<Color, double[]> labMap = new HashMap<Color, double[]>();
/**
* Import the pony from file
*
* @return The pony
*
* @throws IOException On I/O error
*/
public Pony importPony() throws IOException
{
if (this.version == VERSION_COWSAY)
return this.importCow();
boolean[] PLAIN = new boolean[9];
Color[] colours = new Color[256];
boolean[] format = PLAIN;
Color background = null, foreground = null;
for (int i = 0; i < 256; i++)
{ Colour colour = new Colour(i);
colours[i] = new Color(colour.red, colour.green, colour.blue);
}
if (this.palette != null)
System.arraycopy(this.palette, 0, colours, 0, 16);
InputStream in = System.in;
if (this.file != null)
in = new BufferedInputStream(new FileInputStream(this.file));
boolean dollar = false;
boolean escape = false;
boolean csi = false;
boolean osi = false;
int[] buf = new int[256];
int ptr = 0;
int dollareql = -1;
int width = 0;
int curwidth = 0;
int height = 1;
LinkedList<Object> items = new LinkedList<Object>();
String comment = null;
String[][] tags = null;
int tagptr = 0;
int[] unmetabuf = new int[4];
int unmetaptr = 0;
unmetabuf[unmetaptr++] = in.read();
unmetabuf[unmetaptr++] = in.read();
unmetabuf[unmetaptr++] = in.read();
unmetabuf[unmetaptr++] = in.read();
if ((unmetabuf[0] == '$') && (unmetabuf[1] == '$') && (unmetabuf[2] == '$') && (unmetabuf[3] == '\n'))
{ unmetaptr = 0;
byte[] data = new byte[256];
int d = 0;
while ((d = in.read()) != -1)
{
if (ptr == data.length)
System.arraycopy(data, 0, data = new byte[ptr << 1], 0, ptr);
data[ptr++] = (byte)d;
if ((ptr >= 5) && (data[ptr - 1] == '\n') && (data[ptr - 2] == '$') && (data[ptr - 3] == '$') && (data[ptr - 4] == '$') && (data[ptr - 5] == '\n'))
{ ptr -= 5;
break;
}
if ((ptr == 4) && (data[ptr - 1] == '\n') && (data[ptr - 2] == '$') && (data[ptr - 3] == '$') && (data[ptr - 4] == '$'))
{ ptr -= 4;
break;
}
}
if (d == -1)
throw new RuntimeException("Metadata was never closed");
String[] code = (new String(data, 0, ptr, "UTF-8")).split("\n");
StringBuilder commentbuf = new StringBuilder();
for (String line : code)
{
int colon = line.indexOf(':');
boolean istag = colon > 0;
String name = null, value = null;
block: {
if (istag)
{
istag = false;
name = line.substring(0, colon);
value = line.substring(colon + 1);
char c;
for (int i = 0, n = name.length(); i < n; i++)
if ((c = name.charAt(i)) != ' ')
if (('A' > c) || (c > 'Z'))
break block;
istag = true;
}}
if (istag)
{
if (tags == null)
tags = new String[32][];
else if (tagptr == tags.length)
System.arraycopy(tags, 0, tags = new String[tagptr << 1][], 0, tagptr);
tags[tagptr++] = new String[] {name.trim(), value.trim()};
}
else
{
commentbuf.append(line);
commentbuf.append('\n');
}
}
ptr = 0;
comment = commentbuf.toString();
while ((ptr < comment.length()) && (comment.charAt(ptr) == '\n'))
ptr++;
if (ptr > 0)
{ comment = comment.substring(ptr);
ptr = 0;
}
if (comment.isEmpty())
comment = null;
if ((tags != null) && (tagptr < tags.length))
System.arraycopy(tags, 0, tags = new String[tagptr][], 0, tagptr);
}
for (int d = 0, stored = -1, c;;)
{
if (unmetaptr > 0)
{ d = unmetabuf[3 - --unmetaptr];
if (d == -1)
break;
}
else if ((d = stored) != -1)
stored = -1;
else if ((d = in.read()) == -1)
break;
if (((c = d) & 0x80) == 0x80)
{ int n = 0;
while ((c & 0x80) == 0x80)
{ c <<= 1;
n++;
}
c = (c & 255) >> n;
while (((d = in.read()) & 0xC0) == 0x80)
c = (c << 6) | (d & 0x3F);
stored = d;
}
if (dollar)
if ((d == '\033') && !escape)
escape = true;
else if ((d == '$') && !escape)
{ dollar = false;
if (dollareql == -1)
{
int[] _name = new int[ptr];
System.arraycopy(buf, 0, _name, 0, _name.length);
String name = utf32to16(_name);
if (name.equals("\\"))
{ curwidth++;
items.add(new Pony.Cell(this.ignorelink ? ' ' : Pony.Cell.NNE_SSW, null, null, PLAIN));
}
else if (name.equals("/"))
{ curwidth++;
items.add(new Pony.Cell(this.ignorelink ? ' ' : Pony.Cell.NNW_SSE, null, null, PLAIN));
}
else if (name.startsWith("balloon") == false)
items.add(new Pony.Recall(name, foreground, background, format));
else if (this.ignoreballoon == false)
{ String[] parts = (name.substring("balloon".length()) + ",,,,,,-").split(",");
Integer h = parts[1].isEmpty() ? null : new Integer(parts[1]);
int justify = Pony.Balloon.NONE;
if (parts[0].contains("l")) justify = Pony.Balloon.LEFT;
else if (parts[0].contains("r")) justify = Pony.Balloon.RIGHT;
else if (parts[0].contains("c")) justify = Pony.Balloon.CENTRE;
else
items.add(new Pony.Balloon(null, null, parts[0].isEmpty() ? null : new Integer(parts[0]), h, null, null, Pony.Balloon.NONE));
if (justify != Pony.Balloon.NONE)
{
parts = parts[0].replace('l', ',').replace('r', ',').replace('c', ',').split(",");
int part0 = Integer.parseInt(parts[0]), part1 = Integer.parseInt(parts[1]);
items.add(new Pony.Balloon(new Integer(part0), null, new Integer(part1 - part0 + 1), h, null, null, justify));
} }
}
else
{ int[] name = new int[dollareql];
System.arraycopy(buf, 0, name, 0, name.length);
int[] value = new int[ptr - dollareql - 1];
System.arraycopy(buf, dollareql + 1, value, 0, value.length);
items.add(new Pony.Store(utf32to16(name), utf32to16(value)));
}
ptr = 0;
dollareql = -1;
}
else
{ escape = false;
if (ptr == buf.length)
System.arraycopy(buf, 0, buf = new int[ptr << 1], 0, ptr);
if ((dollareql == -1) && (d == '='))
dollareql = ptr;
buf[ptr++] = d;
}
else if (escape)
if (osi)
if (ptr > 0)
{ buf[ptr++ -1] = d;
if (ptr == 8)
{ ptr = 0;
osi = escape = false;
int index = (buf[0] < 'A') ? (buf[0] & 15) : ((buf[0] ^ '@') + 9);
int red = (buf[1] < 'A') ? (buf[1] & 15) : ((buf[1] ^ '@') + 9);
red = (red << 4) | ((buf[2] < 'A') ? (buf[2] & 15) : ((buf[2] ^ '@') + 9));
int green = (buf[3] < 'A') ? (buf[3] & 15) : ((buf[3] ^ '@') + 9);
green = (green << 4) | ((buf[4] < 'A') ? (buf[4] & 15) : ((buf[4] ^ '@') + 9));
int blue = (buf[5] < 'A') ? (buf[5] & 15) : ((buf[5] ^ '@') + 9);
blue = (blue << 4) | ((buf[6] < 'A') ? (buf[6] & 15) : ((buf[6] ^ '@') + 9));
colours[index] = new Color(red, green, blue);
}
}
else if (ptr < 0)
{ if (~ptr == buf.length)
System.arraycopy(buf, 0, buf = new int[~ptr << 1], 0, ~ptr);
if (d == '\\')
{ ptr = ~ptr;
ptr--;
if ((ptr > 8) && (buf[ptr] == '\033') && (buf[0] == ';'))
{ int[] _code = new int[ptr - 1];
System.arraycopy(buf, 1, _code, 0, ptr - 1);
String[] code = utf32to16(_code).split(";");
if (code.length == 2)
{ int index = Integer.parseInt(code[0]);
code = code[1].split("/");
if ((code.length == 3) && (code[0].startsWith("rgb:")))
{ code[0] = code[0].substring(4);
int red = Integer.parseInt(code[0], 16);
int green = Integer.parseInt(code[1], 16);
int blue = Integer.parseInt(code[2], 16);
colours[index] = new Color(red, green, blue);
} } }
ptr = 0;
osi = escape = false;
}
else
{ buf[~ptr] = d;
ptr--;
}
}
else if (d == 'P') ptr = 1;
else if (d == '4') ptr = ~0;
else
{ osi = escape = false;
items.add(new Pony.Cell('\033', foreground, background, format));
items.add(new Pony.Cell(']', foreground, background, format));
items.add(new Pony.Cell(d, foreground, background, format));
}
else if (csi)
{ if (ptr == buf.length)
System.arraycopy(buf, 0, buf = new int[ptr << 1], 0, ptr);
buf[ptr++] = d;
if ((('a' <= d) && (d <= 'z')) || (('A' <= d) && (d <= 'Z')) || (d == '~'))
{ csi = escape = false;
ptr--;
if (d == 'm')
{ int[] _code = new int[ptr];
System.arraycopy(buf, 0, _code, 0, ptr);
String[] code = utf32to16(_code).split(";");
int xterm256 = 0;
boolean back = false;
for (String seg : code)
{ int value = Integer.parseInt(seg);
if (xterm256 == 2)
{ xterm256 = 0;
if (back) background = colours[value];
else foreground = colours[value];
}
else if (value == 0)
{ for (int i = 0; i < 9; i++)
format[i] = false;
background = foreground = null;
}
else if (xterm256 == 1)
xterm256 = value == 5 ? 2 : 0;
else if (value < 10)
format[value - 1] = true;
else if ((20 < value) && (value < 30))
format[value - 21] = false;
else if (value == 39) foreground = null;
else if (value == 49) background = null;
else if (value == 38) xterm256 = 1;
else if (value == 48) xterm256 = 1;
else if (value < 38) foreground = colours[value - 30];
else if (value < 48) background = colours[value - 40];
if (xterm256 == 1)
back = value == 48;
}
}
ptr = 0;
}
}
else if (d == '[')
{ csi = true;
ptr = 0;
}
else if (d == ']')
osi = true;
else
{ escape = false;
items.add(new Pony.Cell('\033', foreground, background, format));
items.add(new Pony.Cell(d, foreground, background, format));
curwidth += 2;
}
else if (d == '\033')
escape = true;
else if (d == '$')
dollar = true;
else if (d == '\n')
{ if (width < curwidth)
width = curwidth;
curwidth = 0;
height++;
items.add(null);
}
else
{ boolean combining = false;
if ((0x0300 <= c) && (c <= 0x036F)) combining = true;
if ((0x20D0 <= c) && (c <= 0x20FF)) combining = true;
if ((0x1DC0 <= c) && (c <= 0x1DFF)) combining = true;
if ((0xFE20 <= c) && (c <= 0xFE2F)) combining = true;
if (combining)
items.add(new Pony.Combining(c, foreground, background, format));
else
{ curwidth++;
Color fore = foreground == null ? colours[7] : foreground;
if (c == '▀')
items.add(new Pony.Cell(Pony.Cell.PIXELS, fore, background, format));
else if (c == '▄')
items.add(new Pony.Cell(Pony.Cell.PIXELS, background, fore, format));
else if (c == '█')
items.add(new Pony.Cell(Pony.Cell.PIXELS, fore, fore, format));
else if (c == ' ')
items.add(new Pony.Cell(Pony.Cell.PIXELS, background, background, format));
else
items.add(new Pony.Cell(c, foreground, background, format));
} }
}
if (in != System.in)
in.close();
Pony pony = new Pony(height, width, comment, tags);
int y = 0, x = 0;
Pony.Meta[] metabuf = new Pony.Meta[256];
int metaptr = 0;
for (Object obj : items)
if (obj == null)
{
if (metaptr != 0)
{ Pony.Meta[] metacell = new Pony.Meta[metaptr];
System.arraycopy(metabuf, 0, metacell, 0, metaptr);
pony.metamatrix[y][x] = metacell;
metaptr = 0;
}
y++;
x = 0;
}
else if (obj instanceof Pony.Cell)
{
if (metaptr != 0)
{ Pony.Meta[] metacell = new Pony.Meta[metaptr];
System.arraycopy(metabuf, 0, metacell, 0, metaptr);
pony.metamatrix[y][x] = metacell;
metaptr = 0;
}
Pony.Cell cell = (Pony.Cell)obj;
pony.matrix[y][x++] = cell;
}
else
{
Pony.Meta meta = (Pony.Meta)obj;
if (metaptr == metabuf.length)
System.arraycopy(metabuf, 0, metabuf = new Pony.Meta[metaptr << 1], 0, metaptr);
metabuf[metaptr++] = meta;
}
if (metaptr != 0)
{ Pony.Meta[] metacell = new Pony.Meta[metaptr];
System.arraycopy(metabuf, 0, metacell, 0, metaptr);
pony.metamatrix[y][x] = metacell;
metaptr = 0;
}
return pony;
}
/**
* Import the pony from file using the cowsay format
*
* @return The pony
*
* @throws IOException On I/O error
*/
protected Pony importCow() throws IOException
{
this.version++;
InputStream stdin = System.in;
try
{
InputStream in = System.in;
if (this.file != null)
in = new BufferedInputStream(new FileInputStream(this.file));
Scanner sc = new Scanner(in, "UTF-8");
StringBuilder cow = new StringBuilder();
StringBuilder data = new StringBuilder();
boolean meta = false;
while (sc.hasNextLine())
{
String line = sc.nextLine();
if (line.replace("\t", "").replace(" ", "").startsWith("#"))
{
if (meta == false)
{ meta = true;
data.append("$$$\n");
}
line = line.substring(line.indexOf("#") + 1);
if (line.equals("$$$"))
line = "$$$(!)";
data.append(line);
data.append('\n');
}
else
{
line = line.replace("$thoughts", "${thoughts}").replace("${thoughts}", "$\\$");
line = line.replace("\\N{U+002580}", "▀");
line = line.replace("\\N{U+002584}", "▄");
line = line.replace("\\N{U+002588}", "█");
line = line.replace("\\N{U+2580}", "▀");
line = line.replace("\\N{U+2584}", "▄");
line = line.replace("\\N{U+2588}", "█");
line = line.replace("\\e", "\033");
cow.append(line);
cow.append('\n');
}
}
if (meta)
data.append("$$$\n");
String pony = cow.toString();
pony = pony.substring(pony.indexOf("$the_cow") + 8);
pony = pony.substring(pony.indexOf("<<") + 2);
String eop = pony.substring(0, pony.indexOf(";"));
if (eop.startsWith("<")) /* here document */
pony = eop.substring(1);
else
{ pony = pony.substring(pony.indexOf('\n') + 1);
pony = pony.substring(0, pony.indexOf('\n' + eop + '\n'));
}
data.append("$balloon" + (pony.indexOf("$\\$") + 2) + "$\n");
data.append(pony);
final byte[] streamdata = data.toString().getBytes("UTF-8");
System.setIn(new InputStream()
{
int ptr = 0;
@Override
public int read()
{
if (this.ptr == streamdata.length)
return -1;
return streamdata[this.ptr++] & 255;
}
@Override
public int available()
{
return streamdata.length - this.ptr;
}
});
this.file = null;
return this.importPony();
}
finally
{
System.setIn(stdin);
}
}
/**
* Export a pony to the file
*
* @param pony The pony
*
* @throws IOException On I/O error
*/
public void exportPony(Pony pony) throws IOException
{
Color[] colours = new Color[256];
boolean[] format = new boolean[9];
Color background = null, foreground = null;
for (int i = 0; i < 256; i++)
{ Colour colour = new Colour(i);
colours[i] = new Color(colour.red, colour.green, colour.blue);
}
if (this.palette != null)
System.arraycopy(this.palette, 0, colours, 0, 16);
StringBuilder resetpalette = null;
if (this.tty)
if (this.colourful)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else
{ resetpalette = new StringBuilder();
for (int i : new int[] { 7, 15 })
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else if (this.fullcolour)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]4;");
resetpalette.append(i);
resetpalette.append(";rgb:");
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
resetpalette.append("\033\\");
} }
StringBuilder databuf = new StringBuilder();
int curleft = 0, curright = 0, curtop = 0, curbottom = 0;
Pony.Cell[][] matrix = pony.matrix;
Pony.Meta[][][] metamatrix = pony.metamatrix;
boolean[] PLAIN = new boolean[9];
if ((pony.tags != null) || (pony.comment != null))
databuf.append("$$$\n");
if (pony.tags != null)
for (String[] tag : pony.tags)
{
databuf.append(tag[0].toUpperCase());
databuf.append(": ");
databuf.append(tag[1]);
databuf.append("\n");
}
if (pony.comment != null)
{
if ((pony.tags != null) && (pony.tags.length != 0))
databuf.append('\n');
String comment = '\n' + pony.comment.trim() + '\n';
while (comment.contains("\n$$$\n"))
comment = comment.replace("\n$$$\n", "\n$$$(!)\n");
comment = comment.substring(1, comment.length() - 1);
databuf.append(comment);
}
if ((pony.tags != null) || (pony.comment != null))
databuf.append("\n$$$\n");
if (this.ignoreballoon)
for (Pony.Meta[][] row : metamatrix)
for (Pony.Meta[] cell : row)
if (cell != null)
for (int i = 0, n = cell.length; i < n; i++)
if ((cell[i] != null) && (cell[i] instanceof Pony.Balloon))
row[i] = null;
if (this.ignorelink)
for (Pony.Cell[] row : matrix)
for (int i = 0, n = row.length; i < n; i++)
{ Pony.Cell cell;
if ((cell = row[i]) != null)
if (this.ignorelink && ((cell.character == Pony.Cell.NNE_SSW) || (cell.character == Pony.Cell.NNW_SSE)))
row[i] = new Pony.Cell(' ', null, null, PLAIN);
else
{ Color back = ((cell.lowerColour == null) || (cell.lowerColour.getAlpha() < 112)) ? null : cell.lowerColour;
Color fore = ((cell.upperColour == null) || (cell.upperColour.getAlpha() < 112)) ? null : cell.upperColour;
row[i] = new Pony.Cell(cell.character, back, fore, cell.format); /* the alpha channel does not need to be set to 255 */
}
}
if (this.left >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length; cur < n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.left -= cur;
if (this.left < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.left], -this.left, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.left][], -this.left, w + 1);
}
this.left = 0;
}
}
else
this.left = 0;
if (this.right >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length - 1; cur <= n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.right -= cur;
if (this.right < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.right], 0, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.right][], 0, w + 1);
}
this.right = 0;
}
}
else
this.right = 0;
if (this.top >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length; cur < n; cur++)
{ Pony.Cell[] row = matrix[cur];
Pony.Meta[][] metarow = metamatrix[cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.top -= cur;
if (this.top < 0)
{
int w = matrix[0].length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.top][], -this.top, matrix.length);
System.arraycopy(new Pony.Cell[-this.top][w], 0, matrix, 0, -this.top);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.top][][], -this.top, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.top][w + 1][], 0, metamatrix, 0, -this.top);
this.top = 0;
}
}
else
this.top = 0;
if (this.bottom >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length - 1 - this.top; cur <= n; cur++)
{ Pony.Cell[] row = matrix[n - cur];
Pony.Meta[][] metarow = metamatrix[n - cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.bottom -= cur;
if (this.bottom < 0)
{
int h = matrix.length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.bottom][], 0, matrix.length);
System.arraycopy(new Pony.Cell[-this.bottom][matrix[0].length], 0, matrix, h, -this.bottom);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.bottom][][], 0, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.bottom][metamatrix[0].length][], 0, metamatrix, h, -this.bottom);
this.bottom = 0;
}
}
else
this.bottom = 0;
if (this.left > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.left], this.left, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.left][], this.left, w + 1);
}
this.left = 0;
}
else
this.left = -this.left;
if (this.right > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.right], 0, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.right][], 0, w + 1);
}
this.right = 0;
}
else
this.right = -this.right;
if (this.top > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.top][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.top][], this.top, h);
System.arraycopy(appendix, 0, matrix, 0, this.top);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.top][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.top][w + 1][], this.top, h);
System.arraycopy(metaappendix, 0, metamatrix, 0, this.top);
this.top = 0;
}
else
this.top = -this.top;
if (this.bottom > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.bottom][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.bottom][], 0, h);
System.arraycopy(appendix, 0, matrix, h, this.bottom);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.bottom][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.bottom][][], 0, h);
System.arraycopy(metaappendix, 0, metamatrix, h, this.bottom);
this.bottom = 0;
}
else
this.bottom = -this.bottom;
for (int y = 0; y < this.top; y++)
{ Pony.Meta[][] metarow = metamatrix[y];
for (int x = 0, w = metarow.length; x < w; x++)
{ Pony.Meta[] metacell = metarow[x];
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta metaelem;
if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
} } }
if (this.right != 0)
{ int w = matrix[0].length, r = metamatrix[0].length - this.right;
Pony.Meta[] leftovers = new Pony.Meta[32];
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
int ptr = 0;
Pony.Meta[][] metarow = metamatrix[y];
for (int x = r; x <= w; x++)
if (metarow[x] != null)
for (Pony.Meta meta : metarow[x])
if ((meta != null) && (meta instanceof Pony.Store))
{ if (ptr == leftovers.length)
System.arraycopy(leftovers, 0, leftovers = new Pony.Meta[ptr << 1], 0, ptr);
leftovers[ptr++] = meta;
}
if (ptr != 0)
{ Pony.Meta[] metacell = metarow[r];
System.arraycopy(metacell, 0, metarow[r] = metacell = new Pony.Meta[metacell.length + ptr], 0, metacell.length - ptr);
System.arraycopy(leftovers, 0, metacell, metacell.length - ptr, ptr);
}
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w - this.right], 0, w - this.right);
System.arraycopy(metarow, 0, metamatrix[y] = new Pony.Meta[w - this.right + 1][], 0, w - this.right + 1);
}
}
int[] endings = null;
if (this.even == false)
{
int w = matrix[0].length;
endings = new int[matrix.length];
for (int y = 0, h = matrix.length; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int cur = 0;
mid:
for (int n = w - 1; cur <= n; cur++)
{
boolean cellpass = true;
Pony.Cell cell = row[n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break mid;
}
else
break mid;
}
}
endings[y] = w - cur;
}
}
Pony.Cell defaultcell = new Pony.Cell(' ', null, null, PLAIN);
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int ending = endings == null ? row.length : endings[y];
for (int x = 0, w = row.length; x <= w; x++)
{ Pony.Meta[] metacell = metarow[x];
if (metacell != null)
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta meta = metacell[z];
if ((meta != null) && ((x >= this.left) || (meta instanceof Pony.Store)))
{ Class<?> metaclass = meta.getClass();
if (metaclass == Pony.Store.class)
databuf.append("$" + (((Pony.Store)meta).name + "=" + ((Pony.Store)meta).value).replace("$", "\033$") + "$");
else if (metaclass == Pony.Recall.class)
{ Pony.Recall recall = (Pony.Recall)meta;
Color back = ((recall.backgroundColour == null) || (recall.backgroundColour.getAlpha() < 112)) ? null : recall.backgroundColour;
Color fore = ((recall.foregroundColour == null) || (recall.foregroundColour.getAlpha() < 112)) ? null : recall.foregroundColour;
databuf.append(applyColour(colours, background, foreground, format, background = back, foreground = fore, recall.format));
databuf.append("$" + recall.name.replace("$", "\033$") + "$");
}
else if (metaclass == Pony.Balloon.class)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
Pony.Balloon balloon = (Pony.Balloon)meta;
if (balloon.left != null)
{ int justification = balloon.minWidth != null ? balloon.justification & (Pony.Balloon.LEFT | Pony.Balloon.RIGHT) : Pony.Balloon.NONE;
switch (justification)
{ case Pony.Balloon.NONE:
char[] spaces = new char[balloon.left.intValue()];
Arrays.fill(spaces, ' ');
databuf.append(new String(spaces));
databuf.append("$balloon" + balloon.left.intValue());
break;
case Pony.Balloon.LEFT:
databuf.append("$balloon" + balloon.left.intValue() + "l");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
case Pony.Balloon.RIGHT:
databuf.append("$balloon" + balloon.left.intValue() + "r");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
default:
databuf.append("$balloon" + balloon.left.intValue() + "c");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
} }
else if (balloon.minWidth != null)
databuf.append("$balloon" + balloon.minWidth.toString());
// KEYWORD: not supported in ponysay: balloon.top != null
if (balloon.minHeight != null)
databuf.append("," + balloon.minHeight.toString());
// KEYWORD: not supported in ponysay: balloon.maxWidth != null
// KEYWORD: not supported in ponysay: balloon.maxHeight != null
- databuf.append("\n");
+ databuf.append("$\n");
} } }
if ((x != w) && (x >= this.left) && (x < ending))
{ Pony.Cell cell = row[x];
if (cell == null)
cell = defaultcell;
if (cell.character >= 0)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = cell.format));
databuf.append(cell.character);
}
else if (cell.character == Pony.Cell.NNE_SSW)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$\\$");
}
else if (cell.character == Pony.Cell.NNW_SSE)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$/$");
}
else if (cell.character == Pony.Cell.PIXELS)
if (cell.lowerColour == null)
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = this.spacesave ? foreground : null, format = PLAIN));
databuf.append(' ');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = cell.upperColour, format = PLAIN));
databuf.append('▀');
}
else
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = null, format = PLAIN));
databuf.append('▀');
}
else if (cell.upperColour.equals(cell.lowerColour))
if (this.zebra)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('▄');
}
else if (this.fullblocks /*TODO || (this.colourful && ¿can get better colour?)*/)
{ databuf.append(applyColour(colours, background, foreground, format, background = this.spacesave ? background : cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('█');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = this.spacesave ? foreground : cell.lowerColour, format = PLAIN));
databuf.append(' ');
}
else //TODO (this.colourful && ¿can get better colour?) → flip
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = PLAIN));
databuf.append('▄');
}
}
}
background = foreground = null;
format = PLAIN;
databuf.append("\033[0m\n");
}
// for (int y = metamatrix.length - this.bottom, b = metamatrix.length; y < b; y++)
// { Pony.Meta[][] metarow = metamatrix[y];
// for (int x = 0, w = metarow.length; x < w; x++)
// { Pony.Meta[] metacell = metarow[x];
// for (int z = 0, d = metacell.length; z < d; z++)
// { Pony.Meta metaelem;
// if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
// databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
// } } }
String data = databuf.toString();
if (this.version == VERSION_COWSAY)
{
String metadata = null;
if (data.startsWith("$$$\n"))
{
metadata = data.substring(4);
if (metadata.startsWith("$$$\n"))
metadata = null;
else
{ metadata = metadata.substring(0, metadata.indexOf("\n$$$\n") + 5);
data = data.substring(data.indexOf("\n$$$\n") + 5);
metadata = '#' + metadata.replace("\n", "\n#");
}
}
String eop = "\nEOP";
while (data.contains(eop + '\n'))
eop += 'P';
data = data.replace("$/$", "/").replace("$\\$", "${thoughts}");
while (data.contains("$balloon"))
{
int start = data.indexOf("$balloon");
int end = data.indexOf("$", start + 8);
data = data.substring(0, start) + data.substring(end + 1);
}
data = "$the_cow = <<" + eop + ";\n" + data;
data += eop + '\n';
if (metadata != null)
data = metadata + data;
if (this.utf8 == false)
data = data.replace("▀", "\\N{U+2580}").replace("▄", "\\N{U+2584}");
}
else
{ if (this.version < VERSION_METADATA)
{
if (data.startsWith("$$$\n"))
data = data.substring(data.indexOf("\n$$$\n") + 5);
}
if (this.version < VERSION_HORIZONTAL_JUSTIFICATION)
{
databuf = new StringBuilder();
int pos = data.indexOf("\n$$$\n");
pos += pos < 0 ? 1 : 5;
databuf.append(data.substring(0, pos));
StringBuilder dollarbuf = null;
boolean esc = false;
for (int i = 0, n = data.length(); i < n;)
{
char c = data.charAt(i++);
if (dollarbuf != null)
{
dollarbuf.append(c);
if (esc || (c == '\033'))
esc ^= true;
else if (c == '$')
{
String dollar = dollarbuf.toString();
dollarbuf = null;
if (dollar.startsWith("$balloon") == false)
databuf.append(dollar);
else
{ databuf.append("$balloon");
dollar = dollar.substring(8);
if (dollar.contains("l")) dollar = dollar.substring(dollar.indexOf('l') + 1);
else if (dollar.contains("r")) dollar = dollar.substring(dollar.indexOf('r') + 1);
else if (dollar.contains("c")) dollar = dollar.substring(dollar.indexOf('c') + 1);
databuf.append(dollar);
} }
}
else if (c == '$')
dollarbuf = new StringBuilder("$");
else
databuf.append(c);
}
data = databuf.toString();
}
}
if (resetpalette != null)
data += resetpalette.toString();
if (this.escesc)
data = data.replace("\033", "\\e");
OutputStream out = System.out;
if (this.file != null)
out = new FileOutputStream(this.file); /* buffering is not needed, everything is written at once */
out.write(data.getBytes("UTF-8"));
out.flush();
if (out != System.out)
out.close();
}
/**
* Get ANSI colour sequence to append to the output
*
* @param palette The current colour palette
* @param oldBackground The current background colour
* @param oldForeground The current foreground colour
* @parma oldFormat The current text format
* @param newBackground The new background colour
* @param newForeground The new foreground colour
* @parma newFormat The new text format
*/ // TODO cache colour matching
protected String applyColour(Color[] palette, Color oldBackground, Color oldForeground, boolean[] oldFormat, Color newBackground, Color newForeground, boolean[] newFormat)
{
StringBuilder rc = new StringBuilder();
int colourindex1back = -1, colourindex2back = -1;
int colourindex1fore = -1, colourindex2fore = -1;
if ((oldBackground != null) && (newBackground == null))
rc.append(";49");
else if ((oldBackground == null) || (oldBackground.equals(newBackground) == false))
if (newBackground != null)
{
if ((this.fullcolour && this.tty) == false)
colourindex1back = matchColour(newBackground, palette, 16, 256, this.chroma);
if (this.tty || this.fullcolour)
colourindex2back = (this.colourful ? matchColour(this.fullcolour ? newBackground : palette[colourindex1back], palette, 0, 8, this.chroma) : 7);
else
colourindex2back = colourindex1back;
}
if ((oldForeground != null) && (newForeground == null))
rc.append(";39");
else if ((oldForeground == null) || (oldForeground.equals(newForeground) == false))
if (newForeground != null)
{
if ((this.fullcolour && this.tty) == false)
colourindex1fore = matchColour(newForeground, palette, 16, 256, this.chroma);
if (this.tty || this.fullcolour)
colourindex2fore = (this.colourful ? matchColour(this.fullcolour ? newForeground : palette[colourindex1fore], palette, 0, 16, this.chroma) : 15);
else
colourindex2fore = colourindex1fore;
if (colourindex2fore == colourindex2back)
colourindex2fore |= 8;
}
if (colourindex2back != -1)
if (this.tty)
{ Color colour = palette[colourindex1back];
rc.append("m\033]P");
rc.append("0123456789ABCDEF".charAt(colourindex1back));
rc.append("0123456789ABCDEF".charAt(colour.getRed() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getRed() & 15));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() & 15));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() & 15));
rc.append("\033[4");
rc.append(colourindex2back);
}
else if (this.fullcolour)
{ Color colour = newBackground;
rc.append("m\033]4;");
rc.append(colourindex2back);
rc.append(";rgb:");
rc.append("0123456789ABCDEF".charAt(colour.getRed() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getRed() & 15));
rc.append('/');
rc.append("0123456789ABCDEF".charAt(colour.getGreen() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() & 15));
rc.append('/');
rc.append("0123456789ABCDEF".charAt(colour.getBlue() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() & 15));
rc.append("\033\\\033[4");
rc.append(colourindex2back);
palette[colourindex2back] = colour;
}
else if (colourindex2back < 16)
{ rc.append(";4");
rc.append(colourindex2back);
}
else
{ rc.append(";48;5;");
rc.append(colourindex2back);
}
if (colourindex2fore != -1)
if (this.tty)
{ Color colour = palette[colourindex1fore];
rc.append("m\033]P");
rc.append("0123456789ABCDEF".charAt(colourindex1fore));
rc.append("0123456789ABCDEF".charAt(colour.getRed() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getRed() & 15));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() & 15));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() & 15));
rc.append("\033[4");
rc.append(colourindex2fore);
}
else if (this.fullcolour)
{ Color colour = newForeground;
rc.append("m\033]4;");
rc.append(colourindex2fore);
rc.append(";rgb:");
rc.append("0123456789ABCDEF".charAt(colour.getRed() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getRed() & 15));
rc.append('/');
rc.append("0123456789ABCDEF".charAt(colour.getGreen() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getGreen() & 15));
rc.append('/');
rc.append("0123456789ABCDEF".charAt(colour.getBlue() >>> 4));
rc.append("0123456789ABCDEF".charAt(colour.getBlue() & 15));
rc.append("\033\\\033[4");
rc.append(colourindex2fore);
palette[colourindex2fore] = colour;
}
else if (colourindex2back < 16)
{ rc.append(";4");
rc.append(colourindex2fore);
}
else
{ rc.append(";48;5;");
rc.append(colourindex2fore);
}
if (this.tty && (colourindex2fore >= 0))
newFormat[0] = (colourindex2fore & 8) == 8;
for (int i = 0; i < 9; i++)
if (newFormat[i] ^ oldFormat[i])
if (newFormat[i])
{ rc.append(";");
rc.append(i);
}
else
{ rc.append(";2");
rc.append(i);
}
String _rc = rc.toString();
if (_rc.isEmpty())
return "";
return "\033[" + _rc.substring(1) + "m";
}
/**
* Get the closest matching colour
*
* @param colour The colour to match
* @param palette The palette for which to match
* @param paletteStart The beginning of the usable part of the palette
* @param paletteEnd The exclusive end of the usable part of the palette
* @param chromaWeight The chroma weight, negative for sRGB distance
* @return The index of the closest colour in the palette
*/
protected static int matchColour(Color colour, Color[] palette, int paletteStart, int paletteEnd, double chromaWeight)
{
if (chromaWeight < 0.0)
{
int bestI = paletteStart;
int bestD = 4 * 256 * 256;
for (int i = paletteStart; i < paletteEnd; i++)
{
int ðr = colour.getRed() - palette[i].getRed();
int ðg = colour.getGreen() - palette[i].getGreen();
int ðb = colour.getBlue() - palette[i].getBlue();
int ð = ðr*ðr + ðg*ðg + ðb*ðb;
if (bestD > ð)
{ bestD = ð;
bestI = i;
}
}
return bestI;
}
double[] lab = labMap.get(colour);
if (lab == null)
labMap.put(colour, lab = Colour.toLab(colour.getRed(), colour.getGreen(), colour.getBlue(), chromaWeight));
double L = lab[0], a = lab[1], b = lab[2];
int bestI = -1;
double bestD = 0.0;
Color p;
for (int i = paletteStart; i < paletteEnd; i++)
{
double[] tLab = labMap.get(p = palette[i]);
if (p == null)
labMap.put(colour, tLab = Colour.toLab(p.getRed(), p.getGreen(), p.getBlue(), chromaWeight));
double ðr = L - tLab[0];
double ðg = a - tLab[1];
double ðb = b - tLab[2];
double ð = ðr*ðr + ðg*ðg + ðb*ðb;
if ((bestD > ð) || (bestI < 0))
{ bestD = ð;
bestI = i;
}
}
return bestI;
}
/**
* Determine pony file format version for ponysay version string
*
* @param value The ponysay version
* @return The pony file format version
*/
private static int parseVersion(String value)
{
String[] strdots = value.split(".");
int[] dots = new int[strdots.length < 10 ? 10 : strdots.length];
for (int i = 0, n = strdots.length; i < n; i++)
dots[i] = Integer.parseInt(strdots[i]);
if (dots[0] < 2) return VERSION_COWSAY;
if (dots[0] == 2)
{ if (dots[1] == 0) return VERSION_COWSAY;
if (dots[1] <= 8) return VERSION_UNISAY;
return VERSION_METADATA;
}
/* version 3.0 */ return VERSION_HORIZONTAL_JUSTIFICATION;
}
/**
* Parse double value
*
* @param value String representation
* @return Raw representation, -1 if not a number
*/
protected static double parseDouble(String value)
{
try
{ return Double.parseDouble(value);
}
catch (Throwable err)
{ return -1.0;
}
}
/**
* Parse integer value
*
* @param value String representation
* @return Raw representation, -1 if not an integer
*/
protected static int parseInteger(String value)
{
try
{ return Integer.parseInt(value);
}
catch (Throwable err)
{ return -1;
}
}
/**
* Parse palette
*
* @param value String representation, without ESC, ] or P
* @return Raw representation
*/
protected static Color[] parsePalette(String value)
{
String defvalue = "00000001AA0000200AA003AA550040000AA5AA00AA600AAAA7AAAAAA"
+ "85555559FF5555A55FF55BFFFF55C5555FFDFF55FFE55FFFFFFFFFFF";
Color[] palette = new Color[16];
for (int ptr = 0, n = defvalue.length(); ptr < n; ptr += 7)
{
int index = Integer.parseInt(defvalue.substring(ptr + 0, 1), 16);
int red = Integer.parseInt(defvalue.substring(ptr + 1, 2), 16);
int green = Integer.parseInt(defvalue.substring(ptr + 3, 2), 16);
int blue = Integer.parseInt(defvalue.substring(ptr + 5, 2), 16);
palette[index] = new Color(red, green, blue);
}
for (int ptr = 0, n = value.length(); ptr < n; ptr += 7)
{
int index = Integer.parseInt(value.substring(ptr + 0, 1), 16);
int red = Integer.parseInt(value.substring(ptr + 1, 2), 16);
int green = Integer.parseInt(value.substring(ptr + 3, 2), 16);
int blue = Integer.parseInt(value.substring(ptr + 5, 2), 16);
palette[index] = new Color(red, green, blue);
}
return palette;
}
/**
* Converts an integer array to a string with only 16-bit charaters
*
* @param ints The int array
* @return The string
*/
public static String utf32to16(final int... ints)
{
int len = ints.length;
for (final int i : ints)
if (i > 0xFFFF)
len++;
else if (i > 0x10FFFF)
throw new RuntimeException("Be serious, there is no character above plane 16.");
final char[] chars = new char[len];
int ptr = 0;
for (final int i : ints)
if (i <= 0xFFFF)
chars[ptr++] = (char)i;
else
{
/* 10000₁₆ + (H − D800₁₆) ⋅ 400₁₆ + (L − DC00₁₆) */
int c = i - 0x10000;
int L = (c & 0x3FF) + 0xDC00;
int H = (c >>> 10) + 0xD800;
chars[ptr++] = (char)H;
chars[ptr++] = (char)L;
}
return new String(chars);
}
}
| true | true | public void exportPony(Pony pony) throws IOException
{
Color[] colours = new Color[256];
boolean[] format = new boolean[9];
Color background = null, foreground = null;
for (int i = 0; i < 256; i++)
{ Colour colour = new Colour(i);
colours[i] = new Color(colour.red, colour.green, colour.blue);
}
if (this.palette != null)
System.arraycopy(this.palette, 0, colours, 0, 16);
StringBuilder resetpalette = null;
if (this.tty)
if (this.colourful)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else
{ resetpalette = new StringBuilder();
for (int i : new int[] { 7, 15 })
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else if (this.fullcolour)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]4;");
resetpalette.append(i);
resetpalette.append(";rgb:");
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
resetpalette.append("\033\\");
} }
StringBuilder databuf = new StringBuilder();
int curleft = 0, curright = 0, curtop = 0, curbottom = 0;
Pony.Cell[][] matrix = pony.matrix;
Pony.Meta[][][] metamatrix = pony.metamatrix;
boolean[] PLAIN = new boolean[9];
if ((pony.tags != null) || (pony.comment != null))
databuf.append("$$$\n");
if (pony.tags != null)
for (String[] tag : pony.tags)
{
databuf.append(tag[0].toUpperCase());
databuf.append(": ");
databuf.append(tag[1]);
databuf.append("\n");
}
if (pony.comment != null)
{
if ((pony.tags != null) && (pony.tags.length != 0))
databuf.append('\n');
String comment = '\n' + pony.comment.trim() + '\n';
while (comment.contains("\n$$$\n"))
comment = comment.replace("\n$$$\n", "\n$$$(!)\n");
comment = comment.substring(1, comment.length() - 1);
databuf.append(comment);
}
if ((pony.tags != null) || (pony.comment != null))
databuf.append("\n$$$\n");
if (this.ignoreballoon)
for (Pony.Meta[][] row : metamatrix)
for (Pony.Meta[] cell : row)
if (cell != null)
for (int i = 0, n = cell.length; i < n; i++)
if ((cell[i] != null) && (cell[i] instanceof Pony.Balloon))
row[i] = null;
if (this.ignorelink)
for (Pony.Cell[] row : matrix)
for (int i = 0, n = row.length; i < n; i++)
{ Pony.Cell cell;
if ((cell = row[i]) != null)
if (this.ignorelink && ((cell.character == Pony.Cell.NNE_SSW) || (cell.character == Pony.Cell.NNW_SSE)))
row[i] = new Pony.Cell(' ', null, null, PLAIN);
else
{ Color back = ((cell.lowerColour == null) || (cell.lowerColour.getAlpha() < 112)) ? null : cell.lowerColour;
Color fore = ((cell.upperColour == null) || (cell.upperColour.getAlpha() < 112)) ? null : cell.upperColour;
row[i] = new Pony.Cell(cell.character, back, fore, cell.format); /* the alpha channel does not need to be set to 255 */
}
}
if (this.left >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length; cur < n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.left -= cur;
if (this.left < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.left], -this.left, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.left][], -this.left, w + 1);
}
this.left = 0;
}
}
else
this.left = 0;
if (this.right >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length - 1; cur <= n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.right -= cur;
if (this.right < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.right], 0, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.right][], 0, w + 1);
}
this.right = 0;
}
}
else
this.right = 0;
if (this.top >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length; cur < n; cur++)
{ Pony.Cell[] row = matrix[cur];
Pony.Meta[][] metarow = metamatrix[cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.top -= cur;
if (this.top < 0)
{
int w = matrix[0].length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.top][], -this.top, matrix.length);
System.arraycopy(new Pony.Cell[-this.top][w], 0, matrix, 0, -this.top);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.top][][], -this.top, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.top][w + 1][], 0, metamatrix, 0, -this.top);
this.top = 0;
}
}
else
this.top = 0;
if (this.bottom >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length - 1 - this.top; cur <= n; cur++)
{ Pony.Cell[] row = matrix[n - cur];
Pony.Meta[][] metarow = metamatrix[n - cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.bottom -= cur;
if (this.bottom < 0)
{
int h = matrix.length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.bottom][], 0, matrix.length);
System.arraycopy(new Pony.Cell[-this.bottom][matrix[0].length], 0, matrix, h, -this.bottom);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.bottom][][], 0, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.bottom][metamatrix[0].length][], 0, metamatrix, h, -this.bottom);
this.bottom = 0;
}
}
else
this.bottom = 0;
if (this.left > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.left], this.left, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.left][], this.left, w + 1);
}
this.left = 0;
}
else
this.left = -this.left;
if (this.right > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.right], 0, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.right][], 0, w + 1);
}
this.right = 0;
}
else
this.right = -this.right;
if (this.top > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.top][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.top][], this.top, h);
System.arraycopy(appendix, 0, matrix, 0, this.top);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.top][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.top][w + 1][], this.top, h);
System.arraycopy(metaappendix, 0, metamatrix, 0, this.top);
this.top = 0;
}
else
this.top = -this.top;
if (this.bottom > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.bottom][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.bottom][], 0, h);
System.arraycopy(appendix, 0, matrix, h, this.bottom);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.bottom][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.bottom][][], 0, h);
System.arraycopy(metaappendix, 0, metamatrix, h, this.bottom);
this.bottom = 0;
}
else
this.bottom = -this.bottom;
for (int y = 0; y < this.top; y++)
{ Pony.Meta[][] metarow = metamatrix[y];
for (int x = 0, w = metarow.length; x < w; x++)
{ Pony.Meta[] metacell = metarow[x];
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta metaelem;
if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
} } }
if (this.right != 0)
{ int w = matrix[0].length, r = metamatrix[0].length - this.right;
Pony.Meta[] leftovers = new Pony.Meta[32];
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
int ptr = 0;
Pony.Meta[][] metarow = metamatrix[y];
for (int x = r; x <= w; x++)
if (metarow[x] != null)
for (Pony.Meta meta : metarow[x])
if ((meta != null) && (meta instanceof Pony.Store))
{ if (ptr == leftovers.length)
System.arraycopy(leftovers, 0, leftovers = new Pony.Meta[ptr << 1], 0, ptr);
leftovers[ptr++] = meta;
}
if (ptr != 0)
{ Pony.Meta[] metacell = metarow[r];
System.arraycopy(metacell, 0, metarow[r] = metacell = new Pony.Meta[metacell.length + ptr], 0, metacell.length - ptr);
System.arraycopy(leftovers, 0, metacell, metacell.length - ptr, ptr);
}
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w - this.right], 0, w - this.right);
System.arraycopy(metarow, 0, metamatrix[y] = new Pony.Meta[w - this.right + 1][], 0, w - this.right + 1);
}
}
int[] endings = null;
if (this.even == false)
{
int w = matrix[0].length;
endings = new int[matrix.length];
for (int y = 0, h = matrix.length; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int cur = 0;
mid:
for (int n = w - 1; cur <= n; cur++)
{
boolean cellpass = true;
Pony.Cell cell = row[n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break mid;
}
else
break mid;
}
}
endings[y] = w - cur;
}
}
Pony.Cell defaultcell = new Pony.Cell(' ', null, null, PLAIN);
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int ending = endings == null ? row.length : endings[y];
for (int x = 0, w = row.length; x <= w; x++)
{ Pony.Meta[] metacell = metarow[x];
if (metacell != null)
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta meta = metacell[z];
if ((meta != null) && ((x >= this.left) || (meta instanceof Pony.Store)))
{ Class<?> metaclass = meta.getClass();
if (metaclass == Pony.Store.class)
databuf.append("$" + (((Pony.Store)meta).name + "=" + ((Pony.Store)meta).value).replace("$", "\033$") + "$");
else if (metaclass == Pony.Recall.class)
{ Pony.Recall recall = (Pony.Recall)meta;
Color back = ((recall.backgroundColour == null) || (recall.backgroundColour.getAlpha() < 112)) ? null : recall.backgroundColour;
Color fore = ((recall.foregroundColour == null) || (recall.foregroundColour.getAlpha() < 112)) ? null : recall.foregroundColour;
databuf.append(applyColour(colours, background, foreground, format, background = back, foreground = fore, recall.format));
databuf.append("$" + recall.name.replace("$", "\033$") + "$");
}
else if (metaclass == Pony.Balloon.class)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
Pony.Balloon balloon = (Pony.Balloon)meta;
if (balloon.left != null)
{ int justification = balloon.minWidth != null ? balloon.justification & (Pony.Balloon.LEFT | Pony.Balloon.RIGHT) : Pony.Balloon.NONE;
switch (justification)
{ case Pony.Balloon.NONE:
char[] spaces = new char[balloon.left.intValue()];
Arrays.fill(spaces, ' ');
databuf.append(new String(spaces));
databuf.append("$balloon" + balloon.left.intValue());
break;
case Pony.Balloon.LEFT:
databuf.append("$balloon" + balloon.left.intValue() + "l");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
case Pony.Balloon.RIGHT:
databuf.append("$balloon" + balloon.left.intValue() + "r");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
default:
databuf.append("$balloon" + balloon.left.intValue() + "c");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
} }
else if (balloon.minWidth != null)
databuf.append("$balloon" + balloon.minWidth.toString());
// KEYWORD: not supported in ponysay: balloon.top != null
if (balloon.minHeight != null)
databuf.append("," + balloon.minHeight.toString());
// KEYWORD: not supported in ponysay: balloon.maxWidth != null
// KEYWORD: not supported in ponysay: balloon.maxHeight != null
databuf.append("\n");
} } }
if ((x != w) && (x >= this.left) && (x < ending))
{ Pony.Cell cell = row[x];
if (cell == null)
cell = defaultcell;
if (cell.character >= 0)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = cell.format));
databuf.append(cell.character);
}
else if (cell.character == Pony.Cell.NNE_SSW)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$\\$");
}
else if (cell.character == Pony.Cell.NNW_SSE)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$/$");
}
else if (cell.character == Pony.Cell.PIXELS)
if (cell.lowerColour == null)
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = this.spacesave ? foreground : null, format = PLAIN));
databuf.append(' ');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = cell.upperColour, format = PLAIN));
databuf.append('▀');
}
else
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = null, format = PLAIN));
databuf.append('▀');
}
else if (cell.upperColour.equals(cell.lowerColour))
if (this.zebra)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('▄');
}
else if (this.fullblocks /*TODO || (this.colourful && ¿can get better colour?)*/)
{ databuf.append(applyColour(colours, background, foreground, format, background = this.spacesave ? background : cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('█');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = this.spacesave ? foreground : cell.lowerColour, format = PLAIN));
databuf.append(' ');
}
else //TODO (this.colourful && ¿can get better colour?) → flip
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = PLAIN));
databuf.append('▄');
}
}
}
background = foreground = null;
format = PLAIN;
databuf.append("\033[0m\n");
}
// for (int y = metamatrix.length - this.bottom, b = metamatrix.length; y < b; y++)
// { Pony.Meta[][] metarow = metamatrix[y];
// for (int x = 0, w = metarow.length; x < w; x++)
// { Pony.Meta[] metacell = metarow[x];
// for (int z = 0, d = metacell.length; z < d; z++)
// { Pony.Meta metaelem;
// if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
// databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
// } } }
String data = databuf.toString();
if (this.version == VERSION_COWSAY)
{
String metadata = null;
if (data.startsWith("$$$\n"))
{
metadata = data.substring(4);
if (metadata.startsWith("$$$\n"))
metadata = null;
else
{ metadata = metadata.substring(0, metadata.indexOf("\n$$$\n") + 5);
data = data.substring(data.indexOf("\n$$$\n") + 5);
metadata = '#' + metadata.replace("\n", "\n#");
}
}
String eop = "\nEOP";
while (data.contains(eop + '\n'))
eop += 'P';
data = data.replace("$/$", "/").replace("$\\$", "${thoughts}");
while (data.contains("$balloon"))
{
int start = data.indexOf("$balloon");
int end = data.indexOf("$", start + 8);
data = data.substring(0, start) + data.substring(end + 1);
}
data = "$the_cow = <<" + eop + ";\n" + data;
data += eop + '\n';
if (metadata != null)
data = metadata + data;
if (this.utf8 == false)
data = data.replace("▀", "\\N{U+2580}").replace("▄", "\\N{U+2584}");
}
else
{ if (this.version < VERSION_METADATA)
{
if (data.startsWith("$$$\n"))
data = data.substring(data.indexOf("\n$$$\n") + 5);
}
if (this.version < VERSION_HORIZONTAL_JUSTIFICATION)
{
databuf = new StringBuilder();
int pos = data.indexOf("\n$$$\n");
pos += pos < 0 ? 1 : 5;
databuf.append(data.substring(0, pos));
StringBuilder dollarbuf = null;
boolean esc = false;
for (int i = 0, n = data.length(); i < n;)
{
char c = data.charAt(i++);
if (dollarbuf != null)
{
dollarbuf.append(c);
if (esc || (c == '\033'))
esc ^= true;
else if (c == '$')
{
String dollar = dollarbuf.toString();
dollarbuf = null;
if (dollar.startsWith("$balloon") == false)
databuf.append(dollar);
else
{ databuf.append("$balloon");
dollar = dollar.substring(8);
if (dollar.contains("l")) dollar = dollar.substring(dollar.indexOf('l') + 1);
else if (dollar.contains("r")) dollar = dollar.substring(dollar.indexOf('r') + 1);
else if (dollar.contains("c")) dollar = dollar.substring(dollar.indexOf('c') + 1);
databuf.append(dollar);
} }
}
else if (c == '$')
dollarbuf = new StringBuilder("$");
else
databuf.append(c);
}
data = databuf.toString();
}
}
if (resetpalette != null)
data += resetpalette.toString();
if (this.escesc)
data = data.replace("\033", "\\e");
OutputStream out = System.out;
if (this.file != null)
out = new FileOutputStream(this.file); /* buffering is not needed, everything is written at once */
out.write(data.getBytes("UTF-8"));
out.flush();
if (out != System.out)
out.close();
}
| public void exportPony(Pony pony) throws IOException
{
Color[] colours = new Color[256];
boolean[] format = new boolean[9];
Color background = null, foreground = null;
for (int i = 0; i < 256; i++)
{ Colour colour = new Colour(i);
colours[i] = new Color(colour.red, colour.green, colour.blue);
}
if (this.palette != null)
System.arraycopy(this.palette, 0, colours, 0, 16);
StringBuilder resetpalette = null;
if (this.tty)
if (this.colourful)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else
{ resetpalette = new StringBuilder();
for (int i : new int[] { 7, 15 })
{ Colour colour = new Colour(i);
resetpalette.append("\033]P");
resetpalette.append("0123456789ABCDEF".charAt(i));
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
} }
else if (this.fullcolour)
{ resetpalette = new StringBuilder();
for (int i = 0; i < 16; i++)
{ Colour colour = new Colour(i);
resetpalette.append("\033]4;");
resetpalette.append(i);
resetpalette.append(";rgb:");
resetpalette.append("0123456789ABCDEF".charAt(colour.red >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.red & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.green >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.green & 15));
resetpalette.append('/');
resetpalette.append("0123456789ABCDEF".charAt(colour.blue >>> 4));
resetpalette.append("0123456789ABCDEF".charAt(colour.blue & 15));
resetpalette.append("\033\\");
} }
StringBuilder databuf = new StringBuilder();
int curleft = 0, curright = 0, curtop = 0, curbottom = 0;
Pony.Cell[][] matrix = pony.matrix;
Pony.Meta[][][] metamatrix = pony.metamatrix;
boolean[] PLAIN = new boolean[9];
if ((pony.tags != null) || (pony.comment != null))
databuf.append("$$$\n");
if (pony.tags != null)
for (String[] tag : pony.tags)
{
databuf.append(tag[0].toUpperCase());
databuf.append(": ");
databuf.append(tag[1]);
databuf.append("\n");
}
if (pony.comment != null)
{
if ((pony.tags != null) && (pony.tags.length != 0))
databuf.append('\n');
String comment = '\n' + pony.comment.trim() + '\n';
while (comment.contains("\n$$$\n"))
comment = comment.replace("\n$$$\n", "\n$$$(!)\n");
comment = comment.substring(1, comment.length() - 1);
databuf.append(comment);
}
if ((pony.tags != null) || (pony.comment != null))
databuf.append("\n$$$\n");
if (this.ignoreballoon)
for (Pony.Meta[][] row : metamatrix)
for (Pony.Meta[] cell : row)
if (cell != null)
for (int i = 0, n = cell.length; i < n; i++)
if ((cell[i] != null) && (cell[i] instanceof Pony.Balloon))
row[i] = null;
if (this.ignorelink)
for (Pony.Cell[] row : matrix)
for (int i = 0, n = row.length; i < n; i++)
{ Pony.Cell cell;
if ((cell = row[i]) != null)
if (this.ignorelink && ((cell.character == Pony.Cell.NNE_SSW) || (cell.character == Pony.Cell.NNW_SSE)))
row[i] = new Pony.Cell(' ', null, null, PLAIN);
else
{ Color back = ((cell.lowerColour == null) || (cell.lowerColour.getAlpha() < 112)) ? null : cell.lowerColour;
Color fore = ((cell.upperColour == null) || (cell.upperColour.getAlpha() < 112)) ? null : cell.upperColour;
row[i] = new Pony.Cell(cell.character, back, fore, cell.format); /* the alpha channel does not need to be set to 255 */
}
}
if (this.left >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length; cur < n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.left -= cur;
if (this.left < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.left], -this.left, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.left][], -this.left, w + 1);
}
this.left = 0;
}
}
else
this.left = 0;
if (this.right >= 0)
{
int cur = 0;
outer:
for (int n = matrix[0].length - 1; cur <= n; cur++)
for (int j = 0, m = matrix.length; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = matrix[j][n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metamatrix[j][n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
}
this.right -= cur;
if (this.right < 0)
{
int w = matrix[0].length;
for (int j = 0, n = matrix.length; j < n; j++)
{ System.arraycopy(matrix[j], 0, matrix[j] = new Pony.Cell[w - this.right], 0, w);
System.arraycopy(metamatrix[j], 0, metamatrix[j] = new Pony.Meta[w + 1 - this.right][], 0, w + 1);
}
this.right = 0;
}
}
else
this.right = 0;
if (this.top >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length; cur < n; cur++)
{ Pony.Cell[] row = matrix[cur];
Pony.Meta[][] metarow = metamatrix[cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.top -= cur;
if (this.top < 0)
{
int w = matrix[0].length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.top][], -this.top, matrix.length);
System.arraycopy(new Pony.Cell[-this.top][w], 0, matrix, 0, -this.top);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.top][][], -this.top, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.top][w + 1][], 0, metamatrix, 0, -this.top);
this.top = 0;
}
}
else
this.top = 0;
if (this.bottom >= 0)
{
int cur = 0, m = matrix[0].length - this.right;
outer:
for (int n = matrix.length - 1 - this.top; cur <= n; cur++)
{ Pony.Cell[] row = matrix[n - cur];
Pony.Meta[][] metarow = metamatrix[n - cur];
for (int j = this.left; j < m; j++)
{
boolean cellpass = true;
Pony.Cell cell = row[j];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[j];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break outer;
}
else
break outer;
}
} }
this.bottom -= cur;
if (this.bottom < 0)
{
int h = matrix.length;
System.arraycopy(matrix, 0, matrix = new Pony.Cell[matrix.length - this.bottom][], 0, matrix.length);
System.arraycopy(new Pony.Cell[-this.bottom][matrix[0].length], 0, matrix, h, -this.bottom);
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[metamatrix.length - this.bottom][][], 0, metamatrix.length);
System.arraycopy(new Pony.Meta[-this.bottom][metamatrix[0].length][], 0, metamatrix, h, -this.bottom);
this.bottom = 0;
}
}
else
this.bottom = 0;
if (this.left > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.left], this.left, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.left][], this.left, w + 1);
}
this.left = 0;
}
else
this.left = -this.left;
if (this.right > 0)
{ int w = matrix[0].length;
for (int y = 0, h = matrix.length; y < h; y++)
{
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w + this.right], 0, w);
System.arraycopy(metamatrix[y], 0, metamatrix[y] = new Pony.Meta[w + 1 + this.right][], 0, w + 1);
}
this.right = 0;
}
else
this.right = -this.right;
if (this.top > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.top][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.top][], this.top, h);
System.arraycopy(appendix, 0, matrix, 0, this.top);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.top][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.top][w + 1][], this.top, h);
System.arraycopy(metaappendix, 0, metamatrix, 0, this.top);
this.top = 0;
}
else
this.top = -this.top;
if (this.bottom > 0)
{
int h = matrix.length, w = matrix[0].length;
Pony.Cell[][] appendix = new Pony.Cell[this.bottom][w];
System.arraycopy(matrix, 0, matrix = new Pony.Cell[h + this.bottom][], 0, h);
System.arraycopy(appendix, 0, matrix, h, this.bottom);
Pony.Meta[][][] metaappendix = new Pony.Meta[this.bottom][w + 1][];
System.arraycopy(metamatrix, 0, metamatrix = new Pony.Meta[h + this.bottom][][], 0, h);
System.arraycopy(metaappendix, 0, metamatrix, h, this.bottom);
this.bottom = 0;
}
else
this.bottom = -this.bottom;
for (int y = 0; y < this.top; y++)
{ Pony.Meta[][] metarow = metamatrix[y];
for (int x = 0, w = metarow.length; x < w; x++)
{ Pony.Meta[] metacell = metarow[x];
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta metaelem;
if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
} } }
if (this.right != 0)
{ int w = matrix[0].length, r = metamatrix[0].length - this.right;
Pony.Meta[] leftovers = new Pony.Meta[32];
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
int ptr = 0;
Pony.Meta[][] metarow = metamatrix[y];
for (int x = r; x <= w; x++)
if (metarow[x] != null)
for (Pony.Meta meta : metarow[x])
if ((meta != null) && (meta instanceof Pony.Store))
{ if (ptr == leftovers.length)
System.arraycopy(leftovers, 0, leftovers = new Pony.Meta[ptr << 1], 0, ptr);
leftovers[ptr++] = meta;
}
if (ptr != 0)
{ Pony.Meta[] metacell = metarow[r];
System.arraycopy(metacell, 0, metarow[r] = metacell = new Pony.Meta[metacell.length + ptr], 0, metacell.length - ptr);
System.arraycopy(leftovers, 0, metacell, metacell.length - ptr, ptr);
}
System.arraycopy(matrix[y], 0, matrix[y] = new Pony.Cell[w - this.right], 0, w - this.right);
System.arraycopy(metarow, 0, metamatrix[y] = new Pony.Meta[w - this.right + 1][], 0, w - this.right + 1);
}
}
int[] endings = null;
if (this.even == false)
{
int w = matrix[0].length;
endings = new int[matrix.length];
for (int y = 0, h = matrix.length; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int cur = 0;
mid:
for (int n = w - 1; cur <= n; cur++)
{
boolean cellpass = true;
Pony.Cell cell = row[n - cur];
if (cell != null)
if ((cell.character != ' ') || (cell.lowerColour != null))
if ((cell.character != Pony.Cell.PIXELS) || (cell.lowerColour != null) || (cell.upperColour != null))
cellpass = false;
if (cellpass == false)
{ Pony.Meta[] meta = metarow[n - cur];
if ((meta != null) && (meta.length != 0))
{ for (int k = 0, l = meta.length; k < l; k++)
if ((meta[k] != null) && ((meta[k] instanceof Pony.Store) == false))
break mid;
}
else
break mid;
}
}
endings[y] = w - cur;
}
}
Pony.Cell defaultcell = new Pony.Cell(' ', null, null, PLAIN);
for (int y = this.top, h = matrix.length - this.bottom; y < h; y++)
{
Pony.Cell[] row = matrix[y];
Pony.Meta[][] metarow = metamatrix[y];
int ending = endings == null ? row.length : endings[y];
for (int x = 0, w = row.length; x <= w; x++)
{ Pony.Meta[] metacell = metarow[x];
if (metacell != null)
for (int z = 0, d = metacell.length; z < d; z++)
{ Pony.Meta meta = metacell[z];
if ((meta != null) && ((x >= this.left) || (meta instanceof Pony.Store)))
{ Class<?> metaclass = meta.getClass();
if (metaclass == Pony.Store.class)
databuf.append("$" + (((Pony.Store)meta).name + "=" + ((Pony.Store)meta).value).replace("$", "\033$") + "$");
else if (metaclass == Pony.Recall.class)
{ Pony.Recall recall = (Pony.Recall)meta;
Color back = ((recall.backgroundColour == null) || (recall.backgroundColour.getAlpha() < 112)) ? null : recall.backgroundColour;
Color fore = ((recall.foregroundColour == null) || (recall.foregroundColour.getAlpha() < 112)) ? null : recall.foregroundColour;
databuf.append(applyColour(colours, background, foreground, format, background = back, foreground = fore, recall.format));
databuf.append("$" + recall.name.replace("$", "\033$") + "$");
}
else if (metaclass == Pony.Balloon.class)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
Pony.Balloon balloon = (Pony.Balloon)meta;
if (balloon.left != null)
{ int justification = balloon.minWidth != null ? balloon.justification & (Pony.Balloon.LEFT | Pony.Balloon.RIGHT) : Pony.Balloon.NONE;
switch (justification)
{ case Pony.Balloon.NONE:
char[] spaces = new char[balloon.left.intValue()];
Arrays.fill(spaces, ' ');
databuf.append(new String(spaces));
databuf.append("$balloon" + balloon.left.intValue());
break;
case Pony.Balloon.LEFT:
databuf.append("$balloon" + balloon.left.intValue() + "l");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
case Pony.Balloon.RIGHT:
databuf.append("$balloon" + balloon.left.intValue() + "r");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
default:
databuf.append("$balloon" + balloon.left.intValue() + "c");
databuf.append(balloon.left.intValue() + balloon.minWidth.intValue() - 1);
break;
} }
else if (balloon.minWidth != null)
databuf.append("$balloon" + balloon.minWidth.toString());
// KEYWORD: not supported in ponysay: balloon.top != null
if (balloon.minHeight != null)
databuf.append("," + balloon.minHeight.toString());
// KEYWORD: not supported in ponysay: balloon.maxWidth != null
// KEYWORD: not supported in ponysay: balloon.maxHeight != null
databuf.append("$\n");
} } }
if ((x != w) && (x >= this.left) && (x < ending))
{ Pony.Cell cell = row[x];
if (cell == null)
cell = defaultcell;
if (cell.character >= 0)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = cell.format));
databuf.append(cell.character);
}
else if (cell.character == Pony.Cell.NNE_SSW)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$\\$");
}
else if (cell.character == Pony.Cell.NNW_SSE)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = null, format = PLAIN));
databuf.append("$/$");
}
else if (cell.character == Pony.Cell.PIXELS)
if (cell.lowerColour == null)
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = this.spacesave ? foreground : null, format = PLAIN));
databuf.append(' ');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = null, foreground = cell.upperColour, format = PLAIN));
databuf.append('▀');
}
else
if (cell.upperColour == null)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = null, format = PLAIN));
databuf.append('▀');
}
else if (cell.upperColour.equals(cell.lowerColour))
if (this.zebra)
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('▄');
}
else if (this.fullblocks /*TODO || (this.colourful && ¿can get better colour?)*/)
{ databuf.append(applyColour(colours, background, foreground, format, background = this.spacesave ? background : cell.lowerColour, foreground = cell.lowerColour, format = PLAIN));
databuf.append('█');
}
else
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = this.spacesave ? foreground : cell.lowerColour, format = PLAIN));
databuf.append(' ');
}
else //TODO (this.colourful && ¿can get better colour?) → flip
{ databuf.append(applyColour(colours, background, foreground, format, background = cell.lowerColour, foreground = cell.upperColour, format = PLAIN));
databuf.append('▄');
}
}
}
background = foreground = null;
format = PLAIN;
databuf.append("\033[0m\n");
}
// for (int y = metamatrix.length - this.bottom, b = metamatrix.length; y < b; y++)
// { Pony.Meta[][] metarow = metamatrix[y];
// for (int x = 0, w = metarow.length; x < w; x++)
// { Pony.Meta[] metacell = metarow[x];
// for (int z = 0, d = metacell.length; z < d; z++)
// { Pony.Meta metaelem;
// if (((metaelem = metacell[z]) != null) && (metaelem instanceof Pony.Store))
// databuf.append("$" + (((Pony.Store)(metaelem)).name + "=" + ((Pony.Store)(metaelem)).value).replace("$", "\033$") + "$");
// } } }
String data = databuf.toString();
if (this.version == VERSION_COWSAY)
{
String metadata = null;
if (data.startsWith("$$$\n"))
{
metadata = data.substring(4);
if (metadata.startsWith("$$$\n"))
metadata = null;
else
{ metadata = metadata.substring(0, metadata.indexOf("\n$$$\n") + 5);
data = data.substring(data.indexOf("\n$$$\n") + 5);
metadata = '#' + metadata.replace("\n", "\n#");
}
}
String eop = "\nEOP";
while (data.contains(eop + '\n'))
eop += 'P';
data = data.replace("$/$", "/").replace("$\\$", "${thoughts}");
while (data.contains("$balloon"))
{
int start = data.indexOf("$balloon");
int end = data.indexOf("$", start + 8);
data = data.substring(0, start) + data.substring(end + 1);
}
data = "$the_cow = <<" + eop + ";\n" + data;
data += eop + '\n';
if (metadata != null)
data = metadata + data;
if (this.utf8 == false)
data = data.replace("▀", "\\N{U+2580}").replace("▄", "\\N{U+2584}");
}
else
{ if (this.version < VERSION_METADATA)
{
if (data.startsWith("$$$\n"))
data = data.substring(data.indexOf("\n$$$\n") + 5);
}
if (this.version < VERSION_HORIZONTAL_JUSTIFICATION)
{
databuf = new StringBuilder();
int pos = data.indexOf("\n$$$\n");
pos += pos < 0 ? 1 : 5;
databuf.append(data.substring(0, pos));
StringBuilder dollarbuf = null;
boolean esc = false;
for (int i = 0, n = data.length(); i < n;)
{
char c = data.charAt(i++);
if (dollarbuf != null)
{
dollarbuf.append(c);
if (esc || (c == '\033'))
esc ^= true;
else if (c == '$')
{
String dollar = dollarbuf.toString();
dollarbuf = null;
if (dollar.startsWith("$balloon") == false)
databuf.append(dollar);
else
{ databuf.append("$balloon");
dollar = dollar.substring(8);
if (dollar.contains("l")) dollar = dollar.substring(dollar.indexOf('l') + 1);
else if (dollar.contains("r")) dollar = dollar.substring(dollar.indexOf('r') + 1);
else if (dollar.contains("c")) dollar = dollar.substring(dollar.indexOf('c') + 1);
databuf.append(dollar);
} }
}
else if (c == '$')
dollarbuf = new StringBuilder("$");
else
databuf.append(c);
}
data = databuf.toString();
}
}
if (resetpalette != null)
data += resetpalette.toString();
if (this.escesc)
data = data.replace("\033", "\\e");
OutputStream out = System.out;
if (this.file != null)
out = new FileOutputStream(this.file); /* buffering is not needed, everything is written at once */
out.write(data.getBytes("UTF-8"));
out.flush();
if (out != System.out)
out.close();
}
|
diff --git a/src/blink/SavePDF.java b/src/blink/SavePDF.java
index bd1e19e..d7a8647 100644
--- a/src/blink/SavePDF.java
+++ b/src/blink/SavePDF.java
@@ -1,94 +1,94 @@
package blink;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import edu.uci.ics.jung.visualization.VisualizationViewer;
public class SavePDF extends AbstractAction {
/**
* for serialisation
*/
private static final long serialVersionUID = 979401257782838856L;
private JPanel _panel;
private VisualizationViewer _view;
public SavePDF(JPanel panel, VisualizationViewer view) {
super("PDF");
_panel = panel;
_view = view;
}
@Override
public void actionPerformed(ActionEvent e) {
hardwork();
}
public void hardwork() {
// java.awt.Rectangle dim = _gemViewer.getBounds();
// int width = dim.width;
// int height = dim.height;
// Rectangle dim =
// ((MyTutteLayout)_gemViewer.getLayout()).boundingBox();
int width = 600;
int height = 800;
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
String lastPath = App.getProperty("lastSavePDF");
if (lastPath != null) {
fc.setSelectedFile(new File(lastPath));
}
int r = fc.showSaveDialog(_panel);
if (r == JFileChooser.APPROVE_OPTION) {
File selFile = fc.getSelectedFile();
App.setProperty("lastSavePDF", selFile.getAbsolutePath());
// print the panel to pdf
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(selFile));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
- PdfTemplate template = contentByte.createTemplate(500, 500);
+ PdfTemplate template = contentByte.createTemplate(500, 660);
// Graphics2D g2 = template.createGraphics(500, 500);
Graphics2D g2 = new PdfGraphics2D(contentByte, width, height);
// the idea is that "width" and "height" might change their values
// for now a fixed value is being used
double scx = (500 / (double) width);
double scy = (500 / (double) height);
- g2.scale(scx, scy);
+ g2.scale(scx, scx);
if(_view == null) {
_panel.print(g2);
} else {
_view.print(g2);
}
g2.dispose();
contentByte.addTemplate(template, 30, 300);
// contentByte.addTemplate(template,
// AffineTransform.getScaleInstance(template.getWidth()/dim.width,
// template.getHeight()/dim.height));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) {
document.close();
}
}
}
}
}
| false | true | public void hardwork() {
// java.awt.Rectangle dim = _gemViewer.getBounds();
// int width = dim.width;
// int height = dim.height;
// Rectangle dim =
// ((MyTutteLayout)_gemViewer.getLayout()).boundingBox();
int width = 600;
int height = 800;
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
String lastPath = App.getProperty("lastSavePDF");
if (lastPath != null) {
fc.setSelectedFile(new File(lastPath));
}
int r = fc.showSaveDialog(_panel);
if (r == JFileChooser.APPROVE_OPTION) {
File selFile = fc.getSelectedFile();
App.setProperty("lastSavePDF", selFile.getAbsolutePath());
// print the panel to pdf
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(selFile));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(500, 500);
// Graphics2D g2 = template.createGraphics(500, 500);
Graphics2D g2 = new PdfGraphics2D(contentByte, width, height);
// the idea is that "width" and "height" might change their values
// for now a fixed value is being used
double scx = (500 / (double) width);
double scy = (500 / (double) height);
g2.scale(scx, scy);
if(_view == null) {
_panel.print(g2);
} else {
_view.print(g2);
}
g2.dispose();
contentByte.addTemplate(template, 30, 300);
// contentByte.addTemplate(template,
// AffineTransform.getScaleInstance(template.getWidth()/dim.width,
// template.getHeight()/dim.height));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) {
document.close();
}
}
}
}
| public void hardwork() {
// java.awt.Rectangle dim = _gemViewer.getBounds();
// int width = dim.width;
// int height = dim.height;
// Rectangle dim =
// ((MyTutteLayout)_gemViewer.getLayout()).boundingBox();
int width = 600;
int height = 800;
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
String lastPath = App.getProperty("lastSavePDF");
if (lastPath != null) {
fc.setSelectedFile(new File(lastPath));
}
int r = fc.showSaveDialog(_panel);
if (r == JFileChooser.APPROVE_OPTION) {
File selFile = fc.getSelectedFile();
App.setProperty("lastSavePDF", selFile.getAbsolutePath());
// print the panel to pdf
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(selFile));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(500, 660);
// Graphics2D g2 = template.createGraphics(500, 500);
Graphics2D g2 = new PdfGraphics2D(contentByte, width, height);
// the idea is that "width" and "height" might change their values
// for now a fixed value is being used
double scx = (500 / (double) width);
double scy = (500 / (double) height);
g2.scale(scx, scx);
if(_view == null) {
_panel.print(g2);
} else {
_view.print(g2);
}
g2.dispose();
contentByte.addTemplate(template, 30, 300);
// contentByte.addTemplate(template,
// AffineTransform.getScaleInstance(template.getWidth()/dim.width,
// template.getHeight()/dim.height));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) {
document.close();
}
}
}
}
|
diff --git a/fabric-bridge-project/fabric-bridge-zookeeper/src/main/java/org/fusesource/fabric/bridge/zk/internal/AbstractZkManagedServiceFactory.java b/fabric-bridge-project/fabric-bridge-zookeeper/src/main/java/org/fusesource/fabric/bridge/zk/internal/AbstractZkManagedServiceFactory.java
index 6c4fbb385..17a82752e 100644
--- a/fabric-bridge-project/fabric-bridge-zookeeper/src/main/java/org/fusesource/fabric/bridge/zk/internal/AbstractZkManagedServiceFactory.java
+++ b/fabric-bridge-project/fabric-bridge-zookeeper/src/main/java/org/fusesource/fabric/bridge/zk/internal/AbstractZkManagedServiceFactory.java
@@ -1,224 +1,226 @@
/*
* Copyright (C) 2011, FuseSource Corp. All rights reserved.
* http://fusesource.com
*
* The software in this package is published under the terms of the
* CDDL license a copy of which has been included with this distribution
* in the license.txt file.
*/
package org.fusesource.fabric.bridge.zk.internal;
import org.fusesource.fabric.api.FabricService;
import org.fusesource.fabric.bridge.model.BridgeDestinationsConfig;
import org.fusesource.fabric.bridge.model.BrokerConfig;
import org.fusesource.fabric.bridge.zk.model.ZkBridgeDestinationsConfigFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedServiceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.util.StringUtils;
import javax.jms.ConnectionFactory;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Base {@link ManagedServiceFactory} for Fabric {@link org.fusesource.fabric.bridge.zk.ZkBridgeConnector} and {@link org.fusesource.fabric.bridge.zk.ZkGatewayConnector}.
*
* @see {@link ZkManagedBridgeServiceFactory}
* @see {@link ZkManagedGatewayServiceFactory}
* @author Dhiraj Bokde
*/
public abstract class AbstractZkManagedServiceFactory implements ManagedServiceFactory {
private static final String CONNECTION_FACTORY_CLASS_NAME = ConnectionFactory.class.getName();
private static final String DESTINATION_RESOLVER_CLASS_NAME = DestinationResolver.class.getName();
protected final Logger LOG = LoggerFactory.getLogger(getClass());
private FabricService fabricService;
private BundleContext bundleContext;
protected Map<String, List<ServiceReference>> serviceReferenceMap = new ConcurrentHashMap<String, List<ServiceReference>>();
public final void init() throws Exception {
if (fabricService == null) {
throw new IllegalArgumentException("Property fabricService must be set!");
}
if (bundleContext == null) {
throw new IllegalArgumentException("Property bundleContext must be set!");
}
LOG.info("Started");
}
public final void destroy() throws Exception {
// do derived class cleanup
doDestroy();
// assert that all service references have been unget
if (!serviceReferenceMap.isEmpty()) {
LOG.error("Removing " + serviceReferenceMap.size() + " left over Service references");
for (List<ServiceReference> references : serviceReferenceMap.values()) {
for (ServiceReference reference : references) {
bundleContext.ungetService(reference);
}
}
}
LOG.info("Destroyed");
}
protected abstract void doDestroy() throws Exception;
@Override
public final void deleted(String pid) {
// do derived class cleanup
doDeleted(pid);
// unget service references for this pid
if (serviceReferenceMap.containsKey(pid)) {
for (ServiceReference reference : serviceReferenceMap.remove(pid)) {
bundleContext.ungetService(reference);
}
}
}
protected abstract void doDeleted(String pid);
// lookup destinationsRef using ZkBridgeDestinationsConfigFactory
protected BridgeDestinationsConfig createDestinationsConfig(String pid, String destinationsRef) throws ConfigurationException {
ZkBridgeDestinationsConfigFactory factory = new ZkBridgeDestinationsConfigFactory();
factory.setFabricService(fabricService);
factory.setId(destinationsRef);
try {
return factory.getObject();
} catch (Exception e) {
String msg = "Error getting destinations for " +
pid + "." + destinationsRef + " : " + e.getMessage();
LOG.error(msg, e);
throw new ConfigurationException(destinationsRef, msg, e);
}
}
protected BrokerConfig createBrokerConfig(String pid, String prefix, Dictionary<String, String> properties) throws ConfigurationException {
final String keyPrefix = prefix + ".";
for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
String key = e.nextElement();
if (key.startsWith(keyPrefix)) {
BrokerConfig config = new BrokerConfig();
config.setId(pid + "." + prefix);
config.setBrokerUrl(properties.get(prefix + ".brokerUrl"));
config.setClientId(properties.get(prefix + ".clientId"));
config.setUserName(properties.get(prefix + ".userName"));
config.setPassword(properties.get(prefix + ".password"));
if (StringUtils.hasText(properties.get(prefix + ".maxConnections"))) {
config.setMaxConnections(Integer.parseInt(properties.get(prefix + ".maxConnections")));
}
final String connectionFactoryRef = properties.get(prefix + ".connectionFactoryRef");
if (StringUtils.hasText(connectionFactoryRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + connectionFactoryRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(CONNECTION_FACTORY_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + connectionFactoryRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
if (serviceReferences != null) {
+ config.setConnectionFactoryRef(connectionFactoryRef);
config.setConnectionFactory((ConnectionFactory) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + connectionFactoryRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
}
final String destinationResolverRef = properties.get(prefix + ".destinationResolverRef");
if (StringUtils.hasText(destinationResolverRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + destinationResolverRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(DESTINATION_RESOLVER_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + destinationResolverRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
if (serviceReferences != null) {
+ config.setDestinationResolverRef(destinationResolverRef);
config.setDestinationResolver((DestinationResolver) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + destinationResolverRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
}
return config;
}
}
LOG.info("No Broker configuration found in " + pid + " for " + prefix);
return null;
}
void addServiceReference(String pid, ServiceReference serviceReference) {
List<ServiceReference> serviceReferences = serviceReferenceMap.get(pid);
if (serviceReferences != null) {
serviceReferences.add(serviceReference);
} else {
ArrayList<ServiceReference> references = new ArrayList<ServiceReference>();
references.add(serviceReference);
serviceReferenceMap.put(pid, references);
}
}
protected final ApplicationContext createApplicationContext(String pid) {
// create a dummy Spring ApplicationContext that will get beans from OSGi service registry
return (ApplicationContext) Proxy.newProxyInstance(ApplicationContext.class.getClassLoader(),
new Class[]{ApplicationContext.class},
new OsgiApplicationContextAdapter(pid, this));
}
public final FabricService getFabricService() {
return fabricService;
}
public final void setFabricService(FabricService fabricService) {
this.fabricService = fabricService;
}
public final BundleContext getBundleContext() {
return bundleContext;
}
public final void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
| false | true | protected BrokerConfig createBrokerConfig(String pid, String prefix, Dictionary<String, String> properties) throws ConfigurationException {
final String keyPrefix = prefix + ".";
for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
String key = e.nextElement();
if (key.startsWith(keyPrefix)) {
BrokerConfig config = new BrokerConfig();
config.setId(pid + "." + prefix);
config.setBrokerUrl(properties.get(prefix + ".brokerUrl"));
config.setClientId(properties.get(prefix + ".clientId"));
config.setUserName(properties.get(prefix + ".userName"));
config.setPassword(properties.get(prefix + ".password"));
if (StringUtils.hasText(properties.get(prefix + ".maxConnections"))) {
config.setMaxConnections(Integer.parseInt(properties.get(prefix + ".maxConnections")));
}
final String connectionFactoryRef = properties.get(prefix + ".connectionFactoryRef");
if (StringUtils.hasText(connectionFactoryRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + connectionFactoryRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(CONNECTION_FACTORY_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + connectionFactoryRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
if (serviceReferences != null) {
config.setConnectionFactory((ConnectionFactory) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + connectionFactoryRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
}
final String destinationResolverRef = properties.get(prefix + ".destinationResolverRef");
if (StringUtils.hasText(destinationResolverRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + destinationResolverRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(DESTINATION_RESOLVER_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + destinationResolverRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
if (serviceReferences != null) {
config.setDestinationResolver((DestinationResolver) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + destinationResolverRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
}
return config;
}
}
LOG.info("No Broker configuration found in " + pid + " for " + prefix);
return null;
}
| protected BrokerConfig createBrokerConfig(String pid, String prefix, Dictionary<String, String> properties) throws ConfigurationException {
final String keyPrefix = prefix + ".";
for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
String key = e.nextElement();
if (key.startsWith(keyPrefix)) {
BrokerConfig config = new BrokerConfig();
config.setId(pid + "." + prefix);
config.setBrokerUrl(properties.get(prefix + ".brokerUrl"));
config.setClientId(properties.get(prefix + ".clientId"));
config.setUserName(properties.get(prefix + ".userName"));
config.setPassword(properties.get(prefix + ".password"));
if (StringUtils.hasText(properties.get(prefix + ".maxConnections"))) {
config.setMaxConnections(Integer.parseInt(properties.get(prefix + ".maxConnections")));
}
final String connectionFactoryRef = properties.get(prefix + ".connectionFactoryRef");
if (StringUtils.hasText(connectionFactoryRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + connectionFactoryRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(CONNECTION_FACTORY_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + connectionFactoryRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
if (serviceReferences != null) {
config.setConnectionFactoryRef(connectionFactoryRef);
config.setConnectionFactory((ConnectionFactory) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + connectionFactoryRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(connectionFactoryRef, msg);
}
}
final String destinationResolverRef = properties.get(prefix + ".destinationResolverRef");
if (StringUtils.hasText(destinationResolverRef)) {
// resolve connection factory OSGi service
final String filter = "(" + Constants.SERVICE_PID + "=" + destinationResolverRef + ")";
ServiceReference[] serviceReferences;
try {
serviceReferences = bundleContext.getServiceReferences(DESTINATION_RESOLVER_CLASS_NAME, filter);
} catch (InvalidSyntaxException e1) {
String msg = "Error looking up " + destinationResolverRef + " with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
if (serviceReferences != null) {
config.setDestinationResolverRef(destinationResolverRef);
config.setDestinationResolver((DestinationResolver) bundleContext.getService(serviceReferences[0]));
// remember the service so we can unget it later
addServiceReference(pid, serviceReferences[0]);
} else {
String msg = "No service found for " + destinationResolverRef +
" with filter [" + filter + "]";
LOG.error(msg);
throw new ConfigurationException(destinationResolverRef, msg);
}
}
return config;
}
}
LOG.info("No Broker configuration found in " + pid + " for " + prefix);
return null;
}
|
diff --git a/org.kevoree.extra.kserial/src/main/java/org/kevoree/extra/kserial/Test.java b/org.kevoree.extra.kserial/src/main/java/org/kevoree/extra/kserial/Test.java
index 0a5b86fa..829c9930 100644
--- a/org.kevoree.extra.kserial/src/main/java/org/kevoree/extra/kserial/Test.java
+++ b/org.kevoree.extra.kserial/src/main/java/org/kevoree/extra/kserial/Test.java
@@ -1,70 +1,70 @@
package org.kevoree.extra.kserial;
import org.kevoree.extra.kserial.Flash.FlashFirmware;
import org.kevoree.extra.kserial.Flash.FlashFirmwareEvent;
import org.kevoree.extra.kserial.Flash.FlashFirmwareEventListener;
import org.kevoree.extra.kserial.SerialPort.*;
import org.kevoree.extra.kserial.Utils.KHelpers;
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
/*
System.out.println(KHelpers.getPortIdentifiers());
final SerialPort serial = new SerialPort("/dev/ttyUSB0", 19200);
serial.open();
serial.addEventListener(new SerialPortEventListener(){
public void incomingDataEvent (SerialPortEvent evt) {
System.out.println("event="+evt.getSize()+"/"+new String(evt.read()));
}
public void disconnectionEvent (SerialPortDisconnectionEvent evt) {
System.out.println("device " + serial.getPort_name() + " is not connected anymore ");
try {
serial.autoReconnect(20,this);
} catch (SerialPortException e) {
}
}
});
//Thread.sleep(2000);
//serial.write("111".getBytes());
Thread.currentThread().sleep(10000000);
*/
- FlashFirmware flash = new FlashFirmware("/dev/tty.usbserial-A400fXsq","ATMEGA328","NODE0");
+ FlashFirmware flash = new FlashFirmware("/dev/tty.usbserial-A400g2wl","ATMEGA328","NODE0");
Byte[] intel = KHelpers.read_file("/Users/oxyss35/kevoree-extra/org.kevoree.extra.kserial/src/main/c/FlashOvertheair/program_test/test.hex");
if(flash.write_on_the_air_program(intel) >= 0){
flash.addEventListener(new FlashFirmwareEventListener() {
// @Override
public void FlashEvent(FlashFirmwareEvent evt) {
- System.out.println("sent "+evt.getSize_uploaded());
+ System.out.println("Callback Event received : "+evt.getSize_uploaded());
}
});
Thread.currentThread().sleep(1000000);
}
}
}
| false | true | public static void main(String[] args) throws Exception {
/*
System.out.println(KHelpers.getPortIdentifiers());
final SerialPort serial = new SerialPort("/dev/ttyUSB0", 19200);
serial.open();
serial.addEventListener(new SerialPortEventListener(){
public void incomingDataEvent (SerialPortEvent evt) {
System.out.println("event="+evt.getSize()+"/"+new String(evt.read()));
}
public void disconnectionEvent (SerialPortDisconnectionEvent evt) {
System.out.println("device " + serial.getPort_name() + " is not connected anymore ");
try {
serial.autoReconnect(20,this);
} catch (SerialPortException e) {
}
}
});
//Thread.sleep(2000);
//serial.write("111".getBytes());
Thread.currentThread().sleep(10000000);
*/
FlashFirmware flash = new FlashFirmware("/dev/tty.usbserial-A400fXsq","ATMEGA328","NODE0");
Byte[] intel = KHelpers.read_file("/Users/oxyss35/kevoree-extra/org.kevoree.extra.kserial/src/main/c/FlashOvertheair/program_test/test.hex");
if(flash.write_on_the_air_program(intel) >= 0){
flash.addEventListener(new FlashFirmwareEventListener() {
// @Override
public void FlashEvent(FlashFirmwareEvent evt) {
System.out.println("sent "+evt.getSize_uploaded());
}
});
Thread.currentThread().sleep(1000000);
}
}
| public static void main(String[] args) throws Exception {
/*
System.out.println(KHelpers.getPortIdentifiers());
final SerialPort serial = new SerialPort("/dev/ttyUSB0", 19200);
serial.open();
serial.addEventListener(new SerialPortEventListener(){
public void incomingDataEvent (SerialPortEvent evt) {
System.out.println("event="+evt.getSize()+"/"+new String(evt.read()));
}
public void disconnectionEvent (SerialPortDisconnectionEvent evt) {
System.out.println("device " + serial.getPort_name() + " is not connected anymore ");
try {
serial.autoReconnect(20,this);
} catch (SerialPortException e) {
}
}
});
//Thread.sleep(2000);
//serial.write("111".getBytes());
Thread.currentThread().sleep(10000000);
*/
FlashFirmware flash = new FlashFirmware("/dev/tty.usbserial-A400g2wl","ATMEGA328","NODE0");
Byte[] intel = KHelpers.read_file("/Users/oxyss35/kevoree-extra/org.kevoree.extra.kserial/src/main/c/FlashOvertheair/program_test/test.hex");
if(flash.write_on_the_air_program(intel) >= 0){
flash.addEventListener(new FlashFirmwareEventListener() {
// @Override
public void FlashEvent(FlashFirmwareEvent evt) {
System.out.println("Callback Event received : "+evt.getSize_uploaded());
}
});
Thread.currentThread().sleep(1000000);
}
}
|
diff --git a/ping-service/src/dmitrygusev/ping/filters/BackupJobResultsFilter.java b/ping-service/src/dmitrygusev/ping/filters/BackupJobResultsFilter.java
index b2992b1..bd1bd83 100644
--- a/ping-service/src/dmitrygusev/ping/filters/BackupJobResultsFilter.java
+++ b/ping-service/src/dmitrygusev/ping/filters/BackupJobResultsFilter.java
@@ -1,134 +1,134 @@
package dmitrygusev.ping.filters;
import static com.google.appengine.api.datastore.KeyFactory.stringToKey;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.appengine.api.datastore.Key;
import dmitrygusev.ping.entities.Job;
import dmitrygusev.ping.entities.JobResult;
import dmitrygusev.ping.pages.job.EditJob;
import dmitrygusev.ping.services.Application;
import dmitrygusev.ping.services.JobResultCSVExporter;
import dmitrygusev.ping.services.JobResultsAnalyzer;
import dmitrygusev.ping.services.Mailer;
import dmitrygusev.ping.services.Utils;
public class BackupJobResultsFilter extends AbstractFilter {
private static final Logger logger = LoggerFactory.getLogger(BackupJobResultsFilter.class);
@Override
protected void processRequest()
throws Exception
{
String encodedJobKey = globals.getHTTPServletRequest().getParameter(RunJobFilter.JOB_KEY_PARAMETER_NAME);
if (Utils.isNullOrEmpty(encodedJobKey)) {
return;
}
Key key = stringToKey(encodedJobKey);
logger.debug("Running mail job: {}", key);
Job job = jobDAO.find(key);
if (job == null) {
return;
}
List<JobResult> resultsBuffer = new ArrayList<JobResult>(Application.DEFAULT_NUMBER_OF_JOB_RESULTS);
resultsBuffer.addAll(job.removeJobResultsExceptRecent(Application.DEFAULT_NUMBER_OF_JOB_RESULTS));
job.setLastBackupTimestamp(new Date());
if (resultsBuffer.size() > 0) {
if (application.updateJob(job, false, true)) {
if (job.isReceiveBackups() && !Utils.isNullOrEmpty(job.getReportEmail())) {
sendResultsByMail(job, resultsBuffer, job.getReportEmail());
}
} else {
logger.error("Error saving job. Backup will not be sent to user this time.");
}
}
}
public void sendResultsByMail(Job job, List<JobResult> results, String reportRecipient) throws MessagingException, IOException, URISyntaxException {
JobResult firstResult = (JobResult) results.get(0);
JobResult lastResult = (JobResult) results.get(results.size() - 1);
String subject = "Statistics Backup for " + job.getTitleFriendly();
TimeZone timeZone = Application.UTC_TIME_ZONE; // TODO Use job specific time zone
StringBuilder builder = new StringBuilder();
builder.append("Job results for period: ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, firstResult.getTimestamp()));
builder.append(" - ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, lastResult.getTimestamp()));
builder.append(" (");
builder.append(Utils.formatMillisecondsToWordsUpToMinutes(lastResult.getTimestamp().getTime() - firstResult.getTimestamp().getTime()));
builder.append(")");
builder.append("<br/># of records: ");
builder.append(results.size());
builder.append("<br/>Time Zone: ");
builder.append(timeZone.getDisplayName());
builder.append(" (");
builder.append(timeZone.getID());
builder.append(")");
JobResultsAnalyzer analyzer = new JobResultsAnalyzer(results, true);
StringBuilder report = analyzer.buildHtmlReport(timeZone);
builder.append(report);
builder.append("<br/><br/>----");
builder.append("<br/>You can disable receiving statistics backups for the job here: ");
String editJobLink = application.getJobUrl(job, EditJob.class);
builder.append(editJobLink);
builder.append("<br/><br/>Note:");
builder.append("<br/>Automatic Backups is a beta function, please use our <a href='http://ping-service.appspot.com/feedback'>feedback form</a> to provide a feedback on it.");
builder.append("<br/>You will get approximately one email per week per job depending on job's cron string.");
builder.append("<br/>Once you received an email with the statistics, this data will be deleted from Ping Service database.");
builder.append("<br/>Ping Service will only store ");
builder.append(Application.DEFAULT_NUMBER_OF_JOB_RESULTS);
builder.append(" latest ping results per job.");
builder.append("<br/>We're doing this to keep Ping Service free, since we're running out of free quota limit of Google App Engine infrastructure.");
builder.append("<br/>We're sorry for any inconvenience you might get from this email.");
builder.append("<br/>Thank you for understanding.");
String message = builder.toString();
byte[] export = JobResultCSVExporter.export(timeZone, results);
MimeBodyPart attachment = new MimeBodyPart();
- attachment.setContent(new String(export), "text/comma-separated-values");
+ attachment.setContent(new String(export), "text/csv");
// Set Content-Type explicitly since GAE ignores type passed to setContent(...) method
- attachment.setHeader("Content-Type", "text/comma-separated-values");
+ attachment.setHeader("Content-Type", "text/csv");
attachment.setFileName(
"job-"
+ job.getKey().getParent().getId() + "-" +
+ job.getKey().getId() + "-results-"
+ Application.formatDateForFileName(firstResult.getTimestamp(), timeZone) + "-"
+ Application.formatDateForFileName(lastResult.getTimestamp(), timeZone) + ".csv");
application.getMailer().sendMail2("text/html", Mailer.PING_SERVICE_NOTIFY_GMAIL_COM, reportRecipient, subject, message, attachment);
}
}
| false | true | public void sendResultsByMail(Job job, List<JobResult> results, String reportRecipient) throws MessagingException, IOException, URISyntaxException {
JobResult firstResult = (JobResult) results.get(0);
JobResult lastResult = (JobResult) results.get(results.size() - 1);
String subject = "Statistics Backup for " + job.getTitleFriendly();
TimeZone timeZone = Application.UTC_TIME_ZONE; // TODO Use job specific time zone
StringBuilder builder = new StringBuilder();
builder.append("Job results for period: ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, firstResult.getTimestamp()));
builder.append(" - ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, lastResult.getTimestamp()));
builder.append(" (");
builder.append(Utils.formatMillisecondsToWordsUpToMinutes(lastResult.getTimestamp().getTime() - firstResult.getTimestamp().getTime()));
builder.append(")");
builder.append("<br/># of records: ");
builder.append(results.size());
builder.append("<br/>Time Zone: ");
builder.append(timeZone.getDisplayName());
builder.append(" (");
builder.append(timeZone.getID());
builder.append(")");
JobResultsAnalyzer analyzer = new JobResultsAnalyzer(results, true);
StringBuilder report = analyzer.buildHtmlReport(timeZone);
builder.append(report);
builder.append("<br/><br/>----");
builder.append("<br/>You can disable receiving statistics backups for the job here: ");
String editJobLink = application.getJobUrl(job, EditJob.class);
builder.append(editJobLink);
builder.append("<br/><br/>Note:");
builder.append("<br/>Automatic Backups is a beta function, please use our <a href='http://ping-service.appspot.com/feedback'>feedback form</a> to provide a feedback on it.");
builder.append("<br/>You will get approximately one email per week per job depending on job's cron string.");
builder.append("<br/>Once you received an email with the statistics, this data will be deleted from Ping Service database.");
builder.append("<br/>Ping Service will only store ");
builder.append(Application.DEFAULT_NUMBER_OF_JOB_RESULTS);
builder.append(" latest ping results per job.");
builder.append("<br/>We're doing this to keep Ping Service free, since we're running out of free quota limit of Google App Engine infrastructure.");
builder.append("<br/>We're sorry for any inconvenience you might get from this email.");
builder.append("<br/>Thank you for understanding.");
String message = builder.toString();
byte[] export = JobResultCSVExporter.export(timeZone, results);
MimeBodyPart attachment = new MimeBodyPart();
attachment.setContent(new String(export), "text/comma-separated-values");
// Set Content-Type explicitly since GAE ignores type passed to setContent(...) method
attachment.setHeader("Content-Type", "text/comma-separated-values");
attachment.setFileName(
"job-"
+ job.getKey().getParent().getId() + "-" +
+ job.getKey().getId() + "-results-"
+ Application.formatDateForFileName(firstResult.getTimestamp(), timeZone) + "-"
+ Application.formatDateForFileName(lastResult.getTimestamp(), timeZone) + ".csv");
application.getMailer().sendMail2("text/html", Mailer.PING_SERVICE_NOTIFY_GMAIL_COM, reportRecipient, subject, message, attachment);
}
| public void sendResultsByMail(Job job, List<JobResult> results, String reportRecipient) throws MessagingException, IOException, URISyntaxException {
JobResult firstResult = (JobResult) results.get(0);
JobResult lastResult = (JobResult) results.get(results.size() - 1);
String subject = "Statistics Backup for " + job.getTitleFriendly();
TimeZone timeZone = Application.UTC_TIME_ZONE; // TODO Use job specific time zone
StringBuilder builder = new StringBuilder();
builder.append("Job results for period: ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, firstResult.getTimestamp()));
builder.append(" - ");
builder.append(Application.formatDate(Application.DATETIME_FORMAT, timeZone, lastResult.getTimestamp()));
builder.append(" (");
builder.append(Utils.formatMillisecondsToWordsUpToMinutes(lastResult.getTimestamp().getTime() - firstResult.getTimestamp().getTime()));
builder.append(")");
builder.append("<br/># of records: ");
builder.append(results.size());
builder.append("<br/>Time Zone: ");
builder.append(timeZone.getDisplayName());
builder.append(" (");
builder.append(timeZone.getID());
builder.append(")");
JobResultsAnalyzer analyzer = new JobResultsAnalyzer(results, true);
StringBuilder report = analyzer.buildHtmlReport(timeZone);
builder.append(report);
builder.append("<br/><br/>----");
builder.append("<br/>You can disable receiving statistics backups for the job here: ");
String editJobLink = application.getJobUrl(job, EditJob.class);
builder.append(editJobLink);
builder.append("<br/><br/>Note:");
builder.append("<br/>Automatic Backups is a beta function, please use our <a href='http://ping-service.appspot.com/feedback'>feedback form</a> to provide a feedback on it.");
builder.append("<br/>You will get approximately one email per week per job depending on job's cron string.");
builder.append("<br/>Once you received an email with the statistics, this data will be deleted from Ping Service database.");
builder.append("<br/>Ping Service will only store ");
builder.append(Application.DEFAULT_NUMBER_OF_JOB_RESULTS);
builder.append(" latest ping results per job.");
builder.append("<br/>We're doing this to keep Ping Service free, since we're running out of free quota limit of Google App Engine infrastructure.");
builder.append("<br/>We're sorry for any inconvenience you might get from this email.");
builder.append("<br/>Thank you for understanding.");
String message = builder.toString();
byte[] export = JobResultCSVExporter.export(timeZone, results);
MimeBodyPart attachment = new MimeBodyPart();
attachment.setContent(new String(export), "text/csv");
// Set Content-Type explicitly since GAE ignores type passed to setContent(...) method
attachment.setHeader("Content-Type", "text/csv");
attachment.setFileName(
"job-"
+ job.getKey().getParent().getId() + "-" +
+ job.getKey().getId() + "-results-"
+ Application.formatDateForFileName(firstResult.getTimestamp(), timeZone) + "-"
+ Application.formatDateForFileName(lastResult.getTimestamp(), timeZone) + ".csv");
application.getMailer().sendMail2("text/html", Mailer.PING_SERVICE_NOTIFY_GMAIL_COM, reportRecipient, subject, message, attachment);
}
|
diff --git a/src/main/java/com/khobar/springgames/controller/PlayerController.java b/src/main/java/com/khobar/springgames/controller/PlayerController.java
index 4a126e8..64ddb17 100644
--- a/src/main/java/com/khobar/springgames/controller/PlayerController.java
+++ b/src/main/java/com/khobar/springgames/controller/PlayerController.java
@@ -1,120 +1,120 @@
package com.khobar.springgames.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.khobar.springgames.domain.Discipline;
import com.khobar.springgames.domain.Player;
import com.khobar.springgames.repository.DisciplineRepository;
import com.khobar.springgames.repository.PlayerRepository;
import com.khobar.springgames.service.DisciplineService;
import com.khobar.springgames.service.PlayerService;
@Controller
@RequestMapping("/player")
public class PlayerController {
@Autowired
private PlayerRepository playerRepository;
@Autowired
private PlayerService playerService;
@Autowired
private DisciplineRepository discRepository;
@Autowired
private DisciplineService disciplineService;
@ModelAttribute("disciplines")
public List<Discipline> disciplines() {
return discRepository.findAll();
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String addPlayer(Model model) {
model.addAttribute("player", new Player());
return "player/edit";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listPlayers(@RequestParam(required = false) String name,
Model model) {
List<Player> playerList;
if (name == null) {
playerList = playerRepository.findAll();
} else {
playerList = playerRepository.findByName(name);
}
model.addAttribute("playerList", playerList);
return "player/list";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String savePlayer(@Valid @ModelAttribute Player player,
BindingResult result) {
if (result.hasErrors()) {
return "player/edit";
} else {
disciplineService.addNo(player.getDiscipline());
playerService.save(player);
return "redirect:./list";
}
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String editPlayer(@PathVariable Integer id, Model model) {
Player player = playerRepository.findOne(id);
if (player != null) {
model.addAttribute("player", player);
return "player/edit";
} else {
return "redirect:.";
}
}
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String deletePlayer(@PathVariable Integer id, Model model) {
Player player = playerRepository.findOne(id);
if (player != null) {
playerRepository.delete(id);
return "redirect:/player/list";
} else {
return "redirect:.";
}
}
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String savePlayer(@PathVariable Integer id,
@Valid @ModelAttribute Player player, BindingResult result) {
if (!result.hasErrors()) {
player.setId(id);
Player playerInRepo = playerRepository.findOne(player.getId());
if (playerInRepo != null) {
Discipline oldDisc = playerInRepo.getDiscipline();
System.out.println("Old discipline" + oldDisc.getName());
Discipline newDisc = player.getDiscipline();
System.out.println("New discipline" + newDisc.getName());
if (!oldDisc.getName().equals(newDisc.getName())) {
- disciplineService.updateNo(oldDisc, newDisc);
+ disciplineService.updateNo(oldDisc, newDisc); //number not updating
}
} else {
playerRepository.save(player);
}
}
return "player/edit";
}
}
| true | true | public String savePlayer(@PathVariable Integer id,
@Valid @ModelAttribute Player player, BindingResult result) {
if (!result.hasErrors()) {
player.setId(id);
Player playerInRepo = playerRepository.findOne(player.getId());
if (playerInRepo != null) {
Discipline oldDisc = playerInRepo.getDiscipline();
System.out.println("Old discipline" + oldDisc.getName());
Discipline newDisc = player.getDiscipline();
System.out.println("New discipline" + newDisc.getName());
if (!oldDisc.getName().equals(newDisc.getName())) {
disciplineService.updateNo(oldDisc, newDisc);
}
} else {
playerRepository.save(player);
}
}
return "player/edit";
}
| public String savePlayer(@PathVariable Integer id,
@Valid @ModelAttribute Player player, BindingResult result) {
if (!result.hasErrors()) {
player.setId(id);
Player playerInRepo = playerRepository.findOne(player.getId());
if (playerInRepo != null) {
Discipline oldDisc = playerInRepo.getDiscipline();
System.out.println("Old discipline" + oldDisc.getName());
Discipline newDisc = player.getDiscipline();
System.out.println("New discipline" + newDisc.getName());
if (!oldDisc.getName().equals(newDisc.getName())) {
disciplineService.updateNo(oldDisc, newDisc); //number not updating
}
} else {
playerRepository.save(player);
}
}
return "player/edit";
}
|
diff --git a/src/java/com/stackframe/sarariman/events/EventsImpl.java b/src/java/com/stackframe/sarariman/events/EventsImpl.java
index 427f966..8165191 100644
--- a/src/java/com/stackframe/sarariman/events/EventsImpl.java
+++ b/src/java/com/stackframe/sarariman/events/EventsImpl.java
@@ -1,61 +1,61 @@
/*
* Copyright (C) 2013 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman.events;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import javax.sql.DataSource;
/**
*
* @author mcculley
*/
public class EventsImpl implements Events {
private final DataSource dataSource;
private final String mountPoint;
public EventsImpl(DataSource dataSource, String mountPoint) {
this.dataSource = dataSource;
this.mountPoint = mountPoint;
}
public Event get(int id) {
return new EventImpl(id, dataSource, mountPoint + "events");
}
public Iterable<Event> getCurrent() {
try {
Connection connection = dataSource.getConnection();
try {
Statement s = connection.createStatement();
try {
- ResultSet r = s.executeQuery("SELECT id FROM company_events WHERE (begin >= DATE(NOW()) OR end >= DATE(NOW()))");
+ ResultSet r = s.executeQuery("SELECT id FROM company_events WHERE (begin >= DATE(NOW()) OR end >= DATE(NOW())) ORDER BY begin");
try {
Collection<Event> c = new ArrayList<Event>();
while (r.next()) {
c.add(get(r.getInt("id")));
}
return c;
} finally {
r.close();
}
} finally {
s.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new RuntimeException(se);
}
}
}
| true | true | public Iterable<Event> getCurrent() {
try {
Connection connection = dataSource.getConnection();
try {
Statement s = connection.createStatement();
try {
ResultSet r = s.executeQuery("SELECT id FROM company_events WHERE (begin >= DATE(NOW()) OR end >= DATE(NOW()))");
try {
Collection<Event> c = new ArrayList<Event>();
while (r.next()) {
c.add(get(r.getInt("id")));
}
return c;
} finally {
r.close();
}
} finally {
s.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new RuntimeException(se);
}
}
| public Iterable<Event> getCurrent() {
try {
Connection connection = dataSource.getConnection();
try {
Statement s = connection.createStatement();
try {
ResultSet r = s.executeQuery("SELECT id FROM company_events WHERE (begin >= DATE(NOW()) OR end >= DATE(NOW())) ORDER BY begin");
try {
Collection<Event> c = new ArrayList<Event>();
while (r.next()) {
c.add(get(r.getInt("id")));
}
return c;
} finally {
r.close();
}
} finally {
s.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new RuntimeException(se);
}
}
|
diff --git a/src/java/com/tracker/frontend/Scrape.java b/src/java/com/tracker/frontend/Scrape.java
index ffb891e..0cb47c8 100644
--- a/src/java/com/tracker/frontend/Scrape.java
+++ b/src/java/com/tracker/frontend/Scrape.java
@@ -1,135 +1,135 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tracker.frontend;
import com.tracker.backend.Bencode;
import com.tracker.backend.StringUtils;
import com.tracker.backend.TrackerRequestParser;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author bo
*/
public class Scrape extends HttpServlet {
/**
* the remote address the request originated from.
*/
private InetAddress remoteAddress;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// store remote address in a useful form
remoteAddress = InetAddress.getByName(request.getRemoteAddr());
TrackerRequestParser trp = new TrackerRequestParser();
// set remote address for logging purposes
trp.setRemoteAddress(remoteAddress);
TreeMap<String,TreeMap> innerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,TreeMap> outerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,String[]> requestMap = new TreeMap<String,String[]>(
request.getParameterMap());
String responseString = new String();
try {
// is there a info_hash key present?
if(requestMap.containsKey((String)"info_hash")) {
String[] value = requestMap.get((String)"info_hash");
// scrape all requested info hashes
for(int i = 0; i < value.length; i++) {
/**
* tomcat automatically decodes the request as it comes in
*/
// encode the info hash again
byte[] rawInfoHash = new byte[20];
- for(int j = 0; i < rawInfoHash.length; i++) {
+ for(int j = 0; j < rawInfoHash.length; j++) {
rawInfoHash[j] = (byte) value[i].charAt(j);
}
String hexInfoHash = StringUtils.getHexString(rawInfoHash);
innerDictionary.put(StringUtils.URLEncodeFromHexString(hexInfoHash),
trp.scrape(value[i]));
}
}
// no info_hash key, scrape all torrents
else {
innerDictionary = trp.scrape();
}
outerDictionary.put((String)"files", innerDictionary);
responseString = Bencode.encode(outerDictionary);
} catch(Exception ex) {
Logger.getLogger(Scrape.class.getName()).log(Level.SEVERE,
"Exception caught", ex);
}
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
try {
out.print(responseString);
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// store remote address in a useful form
remoteAddress = InetAddress.getByName(request.getRemoteAddr());
TrackerRequestParser trp = new TrackerRequestParser();
// set remote address for logging purposes
trp.setRemoteAddress(remoteAddress);
TreeMap<String,TreeMap> innerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,TreeMap> outerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,String[]> requestMap = new TreeMap<String,String[]>(
request.getParameterMap());
String responseString = new String();
try {
// is there a info_hash key present?
if(requestMap.containsKey((String)"info_hash")) {
String[] value = requestMap.get((String)"info_hash");
// scrape all requested info hashes
for(int i = 0; i < value.length; i++) {
/**
* tomcat automatically decodes the request as it comes in
*/
// encode the info hash again
byte[] rawInfoHash = new byte[20];
for(int j = 0; i < rawInfoHash.length; i++) {
rawInfoHash[j] = (byte) value[i].charAt(j);
}
String hexInfoHash = StringUtils.getHexString(rawInfoHash);
innerDictionary.put(StringUtils.URLEncodeFromHexString(hexInfoHash),
trp.scrape(value[i]));
}
}
// no info_hash key, scrape all torrents
else {
innerDictionary = trp.scrape();
}
outerDictionary.put((String)"files", innerDictionary);
responseString = Bencode.encode(outerDictionary);
} catch(Exception ex) {
Logger.getLogger(Scrape.class.getName()).log(Level.SEVERE,
"Exception caught", ex);
}
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
try {
out.print(responseString);
} finally {
out.close();
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// store remote address in a useful form
remoteAddress = InetAddress.getByName(request.getRemoteAddr());
TrackerRequestParser trp = new TrackerRequestParser();
// set remote address for logging purposes
trp.setRemoteAddress(remoteAddress);
TreeMap<String,TreeMap> innerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,TreeMap> outerDictionary = new TreeMap<String,TreeMap>();
TreeMap<String,String[]> requestMap = new TreeMap<String,String[]>(
request.getParameterMap());
String responseString = new String();
try {
// is there a info_hash key present?
if(requestMap.containsKey((String)"info_hash")) {
String[] value = requestMap.get((String)"info_hash");
// scrape all requested info hashes
for(int i = 0; i < value.length; i++) {
/**
* tomcat automatically decodes the request as it comes in
*/
// encode the info hash again
byte[] rawInfoHash = new byte[20];
for(int j = 0; j < rawInfoHash.length; j++) {
rawInfoHash[j] = (byte) value[i].charAt(j);
}
String hexInfoHash = StringUtils.getHexString(rawInfoHash);
innerDictionary.put(StringUtils.URLEncodeFromHexString(hexInfoHash),
trp.scrape(value[i]));
}
}
// no info_hash key, scrape all torrents
else {
innerDictionary = trp.scrape();
}
outerDictionary.put((String)"files", innerDictionary);
responseString = Bencode.encode(outerDictionary);
} catch(Exception ex) {
Logger.getLogger(Scrape.class.getName()).log(Level.SEVERE,
"Exception caught", ex);
}
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
try {
out.print(responseString);
} finally {
out.close();
}
}
|
diff --git a/activemq-web/src/main/java/org/apache/activemq/web/PortfolioPublishServlet.java b/activemq-web/src/main/java/org/apache/activemq/web/PortfolioPublishServlet.java
index 351ff91d9..513009cc2 100644
--- a/activemq-web/src/main/java/org/apache/activemq/web/PortfolioPublishServlet.java
+++ b/activemq-web/src/main/java/org/apache/activemq/web/PortfolioPublishServlet.java
@@ -1,137 +1,137 @@
/**
* 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.activemq.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Map;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet which will publish dummy market data prices
*
*
*/
public class PortfolioPublishServlet extends MessageServletSupport {
private static final int MAX_DELTA_PERCENT = 1;
private static final Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
public void init() throws ServletException {
super.init();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String[] stocks = request.getParameterValues("stocks");
if (stocks == null || stocks.length == 0) {
out.println("<html><body>No <b>stocks</b> query parameter specified. Cannot publish market data</body></html>");
} else {
Integer total = (Integer)request.getSession(true).getAttribute("total");
if (total == null) {
total = Integer.valueOf(0);
}
int count = getNumberOfMessages(request);
total = Integer.valueOf(total.intValue() + count);
request.getSession().setAttribute("total", total);
try {
WebClient client = WebClient.getWebClient(request);
for (int i = 0; i < count; i++) {
sendMessage(client, stocks);
}
out.print("<html><head><meta http-equiv='refresh' content='");
String refreshRate = request.getParameter("refresh");
if (refreshRate == null || refreshRate.length() == 0) {
refreshRate = "1";
}
- out.print(refreshRate);
+ out.print(escape(refreshRate));
out.println("'/></head>");
out.println("<body>Published <b>" + escape(Integer.toString(count)) + "</b> of " + escape(Integer.toString(total))
+ " price messages. Refresh = " + escape(refreshRate) + "s");
out.println("</body></html>");
} catch (JMSException e) {
out.println("<html><body>Failed sending price messages due to <b>" + e + "</b></body></html>");
log("Failed to send message: " + e, e);
}
}
}
protected void sendMessage(WebClient client, String[] stocks) throws JMSException {
Session session = client.getSession();
int idx = 0;
while (true) {
idx = (int)Math.round(stocks.length * Math.random());
if (idx < stocks.length) {
break;
}
}
String stock = stocks[idx];
Destination destination = session.createTopic("STOCKS." + stock);
String stockText = createStockText(stock);
log("Sending: " + stockText + " on destination: " + destination);
Message message = session.createTextMessage(stockText);
client.send(destination, message);
}
protected String createStockText(String stock) {
Double value = LAST_PRICES.get(stock);
if (value == null) {
value = new Double(Math.random() * 100);
}
// lets mutate the value by some percentage
double oldPrice = value.doubleValue();
value = new Double(mutatePrice(oldPrice));
LAST_PRICES.put(stock, value);
double price = value.doubleValue();
double offer = price * 1.001;
String movement = (price > oldPrice) ? "up" : "down";
return "<price stock='" + stock + "' bid='" + price + "' offer='" + offer + "' movement='" + movement + "'/>";
}
protected double mutatePrice(double price) {
double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT;
return price * (100 + percentChange) / 100;
}
protected int getNumberOfMessages(HttpServletRequest request) {
String name = request.getParameter("count");
if (name != null) {
return Integer.parseInt(name);
}
return 1;
}
protected String escape(String text) throws IOException {
return java.net.URLEncoder.encode(text, "UTF-8");
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String[] stocks = request.getParameterValues("stocks");
if (stocks == null || stocks.length == 0) {
out.println("<html><body>No <b>stocks</b> query parameter specified. Cannot publish market data</body></html>");
} else {
Integer total = (Integer)request.getSession(true).getAttribute("total");
if (total == null) {
total = Integer.valueOf(0);
}
int count = getNumberOfMessages(request);
total = Integer.valueOf(total.intValue() + count);
request.getSession().setAttribute("total", total);
try {
WebClient client = WebClient.getWebClient(request);
for (int i = 0; i < count; i++) {
sendMessage(client, stocks);
}
out.print("<html><head><meta http-equiv='refresh' content='");
String refreshRate = request.getParameter("refresh");
if (refreshRate == null || refreshRate.length() == 0) {
refreshRate = "1";
}
out.print(refreshRate);
out.println("'/></head>");
out.println("<body>Published <b>" + escape(Integer.toString(count)) + "</b> of " + escape(Integer.toString(total))
+ " price messages. Refresh = " + escape(refreshRate) + "s");
out.println("</body></html>");
} catch (JMSException e) {
out.println("<html><body>Failed sending price messages due to <b>" + e + "</b></body></html>");
log("Failed to send message: " + e, e);
}
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String[] stocks = request.getParameterValues("stocks");
if (stocks == null || stocks.length == 0) {
out.println("<html><body>No <b>stocks</b> query parameter specified. Cannot publish market data</body></html>");
} else {
Integer total = (Integer)request.getSession(true).getAttribute("total");
if (total == null) {
total = Integer.valueOf(0);
}
int count = getNumberOfMessages(request);
total = Integer.valueOf(total.intValue() + count);
request.getSession().setAttribute("total", total);
try {
WebClient client = WebClient.getWebClient(request);
for (int i = 0; i < count; i++) {
sendMessage(client, stocks);
}
out.print("<html><head><meta http-equiv='refresh' content='");
String refreshRate = request.getParameter("refresh");
if (refreshRate == null || refreshRate.length() == 0) {
refreshRate = "1";
}
out.print(escape(refreshRate));
out.println("'/></head>");
out.println("<body>Published <b>" + escape(Integer.toString(count)) + "</b> of " + escape(Integer.toString(total))
+ " price messages. Refresh = " + escape(refreshRate) + "s");
out.println("</body></html>");
} catch (JMSException e) {
out.println("<html><body>Failed sending price messages due to <b>" + e + "</b></body></html>");
log("Failed to send message: " + e, e);
}
}
}
|
diff --git a/src/me/snowleo/bleedingmobs/Settings.java b/src/me/snowleo/bleedingmobs/Settings.java
index b56517b..35791a0 100644
--- a/src/me/snowleo/bleedingmobs/Settings.java
+++ b/src/me/snowleo/bleedingmobs/Settings.java
@@ -1,373 +1,374 @@
/*
* BleedingMobs - make your monsters and players bleed
*
* Copyright (C) 2011-2012 snowleo
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package me.snowleo.bleedingmobs;
import java.util.*;
import me.snowleo.bleedingmobs.particles.ParticleType;
import me.snowleo.bleedingmobs.particles.Util;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.material.Colorable;
import org.bukkit.material.MaterialData;
import org.bukkit.material.TexturedMaterial;
public class Settings
{
private static final int MAX_PARTICLES = 2000;
private volatile Set<String> worlds = Collections.emptySet();
private volatile boolean bleedWhenCanceled = false;
private volatile boolean bleedingEnabled = true;
private volatile int maxParticles = MAX_PARTICLES;
private final IBleedingMobs plugin;
private volatile boolean showMetricsInfo = true;
private volatile boolean permissionOnly = false;
private volatile int attackPercentage = 100;
private volatile int fallPercentage = 60;
private volatile int deathPercentage = 150;
private volatile int projectilePercentage = 60;
private volatile int bloodstreamPercentage = 10;
private volatile int bloodstreamTime = 200;
private volatile int bloodstreamInterval = 10;
private volatile EnumSet<Material> particleMaterials = EnumSet.allOf(Material.class);
public Settings(final IBleedingMobs plugin)
{
this.plugin = plugin;
loadConfig();
saveConfig();
}
public final void loadConfig()
{
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
bleedingEnabled = config.getBoolean("enabled", true);
final int newMaxParticles = Math.max(1, Math.min(Util.COUNTER_SIZE, config.getInt("max-particles", MAX_PARTICLES)));
if (plugin.getStorage() != null)
{
plugin.getStorage().getItems().setLimit(newMaxParticles);
}
maxParticles = newMaxParticles;
bleedWhenCanceled = config.getBoolean("bleed-when-canceled", false);
showMetricsInfo = config.getBoolean("show-metrics-info", true);
permissionOnly = config.getBoolean("permission-only", false);
attackPercentage = Math.max(0, Math.min(2000, config.getInt("attack-percentage", 100)));
fallPercentage = Math.max(0, Math.min(2000, config.getInt("fall-percentage", 60)));
deathPercentage = Math.max(0, Math.min(2000, config.getInt("death-percentage", 200)));
projectilePercentage = Math.max(0, Math.min(2000, config.getInt("projectile-percentage", 60)));
bloodstreamPercentage = Math.max(0, Math.min(2000, config.getInt("bloodstream.percentage", 10)));
bloodstreamTime = Math.max(0, Math.min(72000, config.getInt("bloodstream.time", 200)));
bloodstreamInterval = Math.max(1, Math.min(1200, config.getInt("bloodstream.interval", 10)));
EnumSet<Material> partMaterials = EnumSet.noneOf(Material.class);
partMaterials.add(Material.CAKE);
partMaterials.add(Material.BONE);
partMaterials.add(Material.WOOL);
partMaterials.add(Material.REDSTONE);
for (EntityType entityType : ParticleType.keys())
{
ParticleType.Builder builder = ParticleType.getBuilder(entityType);
final String name = builder.toString().toLowerCase(Locale.ENGLISH);
builder.setWoolChance(Math.min(100, Math.max(0, config.getInt(name + ".wool-chance", builder.getWoolChance()))));
builder.setBoneChance(Math.min(100, Math.max(0, config.getInt(name + ".bone-chance", builder.getBoneChance()))));
builder.setParticleLifeFrom(Math.max(0, Math.min(1200, config.getInt(name + ".particle-life.from", builder.getParticleLifeFrom()))));
builder.setParticleLifeTo(Math.max(builder.getParticleLifeFrom(), Math.min(1200, config.getInt(name + ".particle-life.to", builder.getParticleLifeTo()))));
final String colorName = config.getString(name + ".wool-color", builder.getWoolColor().toString()).replaceAll("[_-]", "").toUpperCase(Locale.ENGLISH);
byte woolcolor = -1;
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().replace("_", "").equals(colorName))
{
woolcolor = dyeColor.getWoolData();
}
}
if (woolcolor < 0)
{
woolcolor = ((Number)Math.min(15, Math.max(0, config.getInt(name + ".wool-color", builder.getWoolColor().getWoolData())))).byteValue();
}
builder.setWoolColor(DyeColor.getByWoolData(woolcolor));
builder.setStainsFloor(config.getBoolean(name + ".stains-floor", builder.isStainsFloor()));
builder.setBoneLife(Math.max(0, Math.min(1200, config.getInt(name + ".bone-life", builder.getBoneLife()))));
builder.setStainLifeFrom(Math.max(0, Math.min(12000, config.getInt(name + ".stain-life.from", builder.getStainLifeFrom()))));
builder.setStainLifeTo(Math.max(builder.getStainLifeFrom(), Math.min(12000, config.getInt(name + ".stain-life.to", builder.getStainLifeTo()))));
builder.setAmountFrom(Math.max(0, Math.min(1000, config.getInt(name + ".amount.from", builder.getAmountFrom()))));
builder.setAmountTo(Math.max(builder.getAmountFrom(), Math.min(1000, config.getInt(name + ".amount.to", builder.getAmountTo()))));
final List<String> mats = config.getStringList(name + ".saturated-materials");
final EnumSet<Material> materials = EnumSet.noneOf(Material.class);
if (mats != null)
{
for (String matName : mats)
{
final Material material = Material.matchMaterial(matName.replaceAll("-", "_"));
if (material != null)
{
materials.add(material);
}
}
}
if (!materials.isEmpty())
{
builder.setSaturatedMats(materials);
}
String particleMatName = config.getString(name + ".particle-material");
String particleMatData = null;
if (particleMatName != null)
{
if (particleMatName.contains(" "))
{
final String[] parts = particleMatName.split(" ", 2);
particleMatName = parts[1];
particleMatData = parts[0];
}
final Material material = Material.matchMaterial(particleMatName.replaceAll("-", "_"));
if (material != null && Util.isAllowedMaterial(material))
{
final MaterialData matData = material.getNewData((byte)0);
if (particleMatData != null && !particleMatData.isEmpty())
{
particleMatData = particleMatData.toUpperCase(Locale.ENGLISH).replaceAll("-", "_");
if (matData instanceof Colorable)
{
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().equals(particleMatData))
{
((Colorable)matData).setColor(dyeColor);
}
}
}
if (matData instanceof TexturedMaterial)
{
for (Material texture : ((TexturedMaterial)matData).getTextures())
{
if (texture.toString().equals(particleMatData))
{
((TexturedMaterial)matData).setMaterial(texture);
}
}
}
}
builder.setParticleMaterial(matData);
partMaterials.add(material);
}
}
+ ParticleType.save(builder.build());
}
particleMaterials = partMaterials;
final List<String> coll = config.getStringList("worlds");
worlds = new HashSet<String>(coll == null ? Collections.<String>emptyList() : coll);
}
public final void saveConfig()
{
final FileConfiguration config = plugin.getConfig();
config.options().header("Bleeding Mobs config\n"
+ "Don't use tabs in this file\n"
+ "You can always reset this to the defaults by removing the file.\n"
+ "Chances are from 0 to 100, no fractions allowed. 100 means 100% chance of drop.\n"
+ "There is no chance value for the particle material (e.g. redstone), \n"
+ "because it's calculated from the wool and bone chances (so if you set them both to 0, it's 100%).\n"
+ "All time values are in ticks = 1/20th of a second.\n"
+ "If there are from and to values, then the value is randomly selected between from and to.\n"
+ "Wool colors: white, orange, magenta, light-blue, yellow, lime, pink,\n"
+ "gray, silver, cyan, purple, blue, brown, green, red, black\n"
+ "When permission-only is set, then everything will only bleed, when they are hit \n"
+ "by a player with bleedingmobs.bloodstrike permission. \n"
+ "This will disable bleeding on death and on fall damage.\n");
config.set("enabled", bleedingEnabled);
config.set("max-particles", maxParticles);
config.set("bleed-when-canceled", bleedWhenCanceled);
config.set("show-metrics-info", false);
config.set("permission-only", permissionOnly);
config.set("attack-percentage", attackPercentage);
config.set("fall-percentage", fallPercentage);
config.set("death-percentage", deathPercentage);
config.set("projectile-percentage", projectilePercentage);
config.set("bloodstream.percentage", bloodstreamPercentage);
config.set("bloodstream.time", bloodstreamTime);
config.set("bloodstream.interval", bloodstreamInterval);
for (EntityType entityTypeType : ParticleType.keys())
{
ParticleType particleType = ParticleType.get(entityTypeType);
final String name = particleType.toString().toLowerCase(Locale.ENGLISH);
config.set(name + ".wool-chance", particleType.getWoolChance());
config.set(name + ".bone-chance", particleType.getBoneChance());
config.set(name + ".particle-life.from", particleType.getParticleLifeFrom());
config.set(name + ".particle-life.to", particleType.getParticleLifeTo());
config.set(name + ".wool-color", particleType.getWoolColor().toString().replace("_", "-").toLowerCase(Locale.ENGLISH));
config.set(name + ".stains-floor", particleType.isStainingFloor());
config.set(name + ".bone-life", particleType.getBoneLife());
config.set(name + ".stain-life.from", particleType.getStainLifeFrom());
config.set(name + ".stain-life.to", particleType.getStainLifeTo());
config.set(name + ".amount.from", particleType.getAmountFrom());
config.set(name + ".amount.to", particleType.getAmountTo());
final List<String> converted = new ArrayList<String>();
for (Material material : particleType.getSaturatedMaterials())
{
converted.add(material.toString().toLowerCase(Locale.ENGLISH).replaceAll("_", "-"));
}
config.set(name + ".saturated-materials", converted);
String particleMat = particleType.getParticleMaterial().getItemType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", "-");
if (particleType.getParticleMaterial() instanceof Colorable)
{
particleMat = ((Colorable)particleType.getParticleMaterial()).getColor().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", "-") + " " + particleMat;
}
if (particleType.getParticleMaterial() instanceof TexturedMaterial)
{
particleMat = ((TexturedMaterial)particleType.getParticleMaterial()).getMaterial().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", "-") + " " + particleMat;
}
config.set(name + ".particle-material", particleMat);
}
config.set("worlds", new ArrayList<String>(worlds));
plugin.saveConfig();
}
public boolean isWorldEnabled(final World world)
{
return worlds.isEmpty() || worlds.contains(world.getName());
}
public int getMaxParticles()
{
return maxParticles;
}
public boolean isBleedingWhenCanceled()
{
return bleedWhenCanceled;
}
public boolean isBleedingEnabled()
{
return bleedingEnabled;
}
public void setBleedingEnabled(final boolean set)
{
this.bleedingEnabled = set;
}
public Set<String> getWorlds()
{
return worlds;
}
public void setMaxParticles(final int maxParticles)
{
this.maxParticles = maxParticles;
}
public void setBleedWhenCanceled(final boolean set)
{
this.bleedWhenCanceled = set;
}
public boolean isShowMetricsInfo()
{
return this.showMetricsInfo;
}
public boolean isPermissionOnly()
{
return permissionOnly;
}
public void setPermissionOnly(final boolean permissionOnly)
{
this.permissionOnly = permissionOnly;
}
public int getBloodstreamPercentage()
{
return bloodstreamPercentage;
}
public void setBloodstreamPercentage(final int bloodstreamPercentage)
{
this.bloodstreamPercentage = bloodstreamPercentage;
}
public int getBloodstreamTime()
{
return bloodstreamTime;
}
public void setBloodstreamTime(final int bloodstreamTime)
{
this.bloodstreamTime = bloodstreamTime;
}
public int getBloodstreamInterval()
{
return bloodstreamInterval;
}
public void setBloodstreamInterval(final int bloodstreamInterval)
{
this.bloodstreamInterval = bloodstreamInterval;
}
public int getAttackPercentage()
{
return attackPercentage;
}
public void setAttackPercentage(final int attackPercentage)
{
this.attackPercentage = attackPercentage;
}
public int getFallPercentage()
{
return fallPercentage;
}
public void setFallPercentage(final int fallPercentage)
{
this.fallPercentage = fallPercentage;
}
public int getDeathPercentage()
{
return deathPercentage;
}
public void setDeathPercentage(final int deathPercentage)
{
this.deathPercentage = deathPercentage;
}
public int getProjectilePercentage()
{
return projectilePercentage;
}
public void setProjectilePercentage(final int projectilePercentage)
{
this.projectilePercentage = projectilePercentage;
}
public Set<Material> getParticleMaterials()
{
return particleMaterials;
}
}
| true | true | public final void loadConfig()
{
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
bleedingEnabled = config.getBoolean("enabled", true);
final int newMaxParticles = Math.max(1, Math.min(Util.COUNTER_SIZE, config.getInt("max-particles", MAX_PARTICLES)));
if (plugin.getStorage() != null)
{
plugin.getStorage().getItems().setLimit(newMaxParticles);
}
maxParticles = newMaxParticles;
bleedWhenCanceled = config.getBoolean("bleed-when-canceled", false);
showMetricsInfo = config.getBoolean("show-metrics-info", true);
permissionOnly = config.getBoolean("permission-only", false);
attackPercentage = Math.max(0, Math.min(2000, config.getInt("attack-percentage", 100)));
fallPercentage = Math.max(0, Math.min(2000, config.getInt("fall-percentage", 60)));
deathPercentage = Math.max(0, Math.min(2000, config.getInt("death-percentage", 200)));
projectilePercentage = Math.max(0, Math.min(2000, config.getInt("projectile-percentage", 60)));
bloodstreamPercentage = Math.max(0, Math.min(2000, config.getInt("bloodstream.percentage", 10)));
bloodstreamTime = Math.max(0, Math.min(72000, config.getInt("bloodstream.time", 200)));
bloodstreamInterval = Math.max(1, Math.min(1200, config.getInt("bloodstream.interval", 10)));
EnumSet<Material> partMaterials = EnumSet.noneOf(Material.class);
partMaterials.add(Material.CAKE);
partMaterials.add(Material.BONE);
partMaterials.add(Material.WOOL);
partMaterials.add(Material.REDSTONE);
for (EntityType entityType : ParticleType.keys())
{
ParticleType.Builder builder = ParticleType.getBuilder(entityType);
final String name = builder.toString().toLowerCase(Locale.ENGLISH);
builder.setWoolChance(Math.min(100, Math.max(0, config.getInt(name + ".wool-chance", builder.getWoolChance()))));
builder.setBoneChance(Math.min(100, Math.max(0, config.getInt(name + ".bone-chance", builder.getBoneChance()))));
builder.setParticleLifeFrom(Math.max(0, Math.min(1200, config.getInt(name + ".particle-life.from", builder.getParticleLifeFrom()))));
builder.setParticleLifeTo(Math.max(builder.getParticleLifeFrom(), Math.min(1200, config.getInt(name + ".particle-life.to", builder.getParticleLifeTo()))));
final String colorName = config.getString(name + ".wool-color", builder.getWoolColor().toString()).replaceAll("[_-]", "").toUpperCase(Locale.ENGLISH);
byte woolcolor = -1;
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().replace("_", "").equals(colorName))
{
woolcolor = dyeColor.getWoolData();
}
}
if (woolcolor < 0)
{
woolcolor = ((Number)Math.min(15, Math.max(0, config.getInt(name + ".wool-color", builder.getWoolColor().getWoolData())))).byteValue();
}
builder.setWoolColor(DyeColor.getByWoolData(woolcolor));
builder.setStainsFloor(config.getBoolean(name + ".stains-floor", builder.isStainsFloor()));
builder.setBoneLife(Math.max(0, Math.min(1200, config.getInt(name + ".bone-life", builder.getBoneLife()))));
builder.setStainLifeFrom(Math.max(0, Math.min(12000, config.getInt(name + ".stain-life.from", builder.getStainLifeFrom()))));
builder.setStainLifeTo(Math.max(builder.getStainLifeFrom(), Math.min(12000, config.getInt(name + ".stain-life.to", builder.getStainLifeTo()))));
builder.setAmountFrom(Math.max(0, Math.min(1000, config.getInt(name + ".amount.from", builder.getAmountFrom()))));
builder.setAmountTo(Math.max(builder.getAmountFrom(), Math.min(1000, config.getInt(name + ".amount.to", builder.getAmountTo()))));
final List<String> mats = config.getStringList(name + ".saturated-materials");
final EnumSet<Material> materials = EnumSet.noneOf(Material.class);
if (mats != null)
{
for (String matName : mats)
{
final Material material = Material.matchMaterial(matName.replaceAll("-", "_"));
if (material != null)
{
materials.add(material);
}
}
}
if (!materials.isEmpty())
{
builder.setSaturatedMats(materials);
}
String particleMatName = config.getString(name + ".particle-material");
String particleMatData = null;
if (particleMatName != null)
{
if (particleMatName.contains(" "))
{
final String[] parts = particleMatName.split(" ", 2);
particleMatName = parts[1];
particleMatData = parts[0];
}
final Material material = Material.matchMaterial(particleMatName.replaceAll("-", "_"));
if (material != null && Util.isAllowedMaterial(material))
{
final MaterialData matData = material.getNewData((byte)0);
if (particleMatData != null && !particleMatData.isEmpty())
{
particleMatData = particleMatData.toUpperCase(Locale.ENGLISH).replaceAll("-", "_");
if (matData instanceof Colorable)
{
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().equals(particleMatData))
{
((Colorable)matData).setColor(dyeColor);
}
}
}
if (matData instanceof TexturedMaterial)
{
for (Material texture : ((TexturedMaterial)matData).getTextures())
{
if (texture.toString().equals(particleMatData))
{
((TexturedMaterial)matData).setMaterial(texture);
}
}
}
}
builder.setParticleMaterial(matData);
partMaterials.add(material);
}
}
}
particleMaterials = partMaterials;
final List<String> coll = config.getStringList("worlds");
worlds = new HashSet<String>(coll == null ? Collections.<String>emptyList() : coll);
}
| public final void loadConfig()
{
plugin.reloadConfig();
final FileConfiguration config = plugin.getConfig();
bleedingEnabled = config.getBoolean("enabled", true);
final int newMaxParticles = Math.max(1, Math.min(Util.COUNTER_SIZE, config.getInt("max-particles", MAX_PARTICLES)));
if (plugin.getStorage() != null)
{
plugin.getStorage().getItems().setLimit(newMaxParticles);
}
maxParticles = newMaxParticles;
bleedWhenCanceled = config.getBoolean("bleed-when-canceled", false);
showMetricsInfo = config.getBoolean("show-metrics-info", true);
permissionOnly = config.getBoolean("permission-only", false);
attackPercentage = Math.max(0, Math.min(2000, config.getInt("attack-percentage", 100)));
fallPercentage = Math.max(0, Math.min(2000, config.getInt("fall-percentage", 60)));
deathPercentage = Math.max(0, Math.min(2000, config.getInt("death-percentage", 200)));
projectilePercentage = Math.max(0, Math.min(2000, config.getInt("projectile-percentage", 60)));
bloodstreamPercentage = Math.max(0, Math.min(2000, config.getInt("bloodstream.percentage", 10)));
bloodstreamTime = Math.max(0, Math.min(72000, config.getInt("bloodstream.time", 200)));
bloodstreamInterval = Math.max(1, Math.min(1200, config.getInt("bloodstream.interval", 10)));
EnumSet<Material> partMaterials = EnumSet.noneOf(Material.class);
partMaterials.add(Material.CAKE);
partMaterials.add(Material.BONE);
partMaterials.add(Material.WOOL);
partMaterials.add(Material.REDSTONE);
for (EntityType entityType : ParticleType.keys())
{
ParticleType.Builder builder = ParticleType.getBuilder(entityType);
final String name = builder.toString().toLowerCase(Locale.ENGLISH);
builder.setWoolChance(Math.min(100, Math.max(0, config.getInt(name + ".wool-chance", builder.getWoolChance()))));
builder.setBoneChance(Math.min(100, Math.max(0, config.getInt(name + ".bone-chance", builder.getBoneChance()))));
builder.setParticleLifeFrom(Math.max(0, Math.min(1200, config.getInt(name + ".particle-life.from", builder.getParticleLifeFrom()))));
builder.setParticleLifeTo(Math.max(builder.getParticleLifeFrom(), Math.min(1200, config.getInt(name + ".particle-life.to", builder.getParticleLifeTo()))));
final String colorName = config.getString(name + ".wool-color", builder.getWoolColor().toString()).replaceAll("[_-]", "").toUpperCase(Locale.ENGLISH);
byte woolcolor = -1;
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().replace("_", "").equals(colorName))
{
woolcolor = dyeColor.getWoolData();
}
}
if (woolcolor < 0)
{
woolcolor = ((Number)Math.min(15, Math.max(0, config.getInt(name + ".wool-color", builder.getWoolColor().getWoolData())))).byteValue();
}
builder.setWoolColor(DyeColor.getByWoolData(woolcolor));
builder.setStainsFloor(config.getBoolean(name + ".stains-floor", builder.isStainsFloor()));
builder.setBoneLife(Math.max(0, Math.min(1200, config.getInt(name + ".bone-life", builder.getBoneLife()))));
builder.setStainLifeFrom(Math.max(0, Math.min(12000, config.getInt(name + ".stain-life.from", builder.getStainLifeFrom()))));
builder.setStainLifeTo(Math.max(builder.getStainLifeFrom(), Math.min(12000, config.getInt(name + ".stain-life.to", builder.getStainLifeTo()))));
builder.setAmountFrom(Math.max(0, Math.min(1000, config.getInt(name + ".amount.from", builder.getAmountFrom()))));
builder.setAmountTo(Math.max(builder.getAmountFrom(), Math.min(1000, config.getInt(name + ".amount.to", builder.getAmountTo()))));
final List<String> mats = config.getStringList(name + ".saturated-materials");
final EnumSet<Material> materials = EnumSet.noneOf(Material.class);
if (mats != null)
{
for (String matName : mats)
{
final Material material = Material.matchMaterial(matName.replaceAll("-", "_"));
if (material != null)
{
materials.add(material);
}
}
}
if (!materials.isEmpty())
{
builder.setSaturatedMats(materials);
}
String particleMatName = config.getString(name + ".particle-material");
String particleMatData = null;
if (particleMatName != null)
{
if (particleMatName.contains(" "))
{
final String[] parts = particleMatName.split(" ", 2);
particleMatName = parts[1];
particleMatData = parts[0];
}
final Material material = Material.matchMaterial(particleMatName.replaceAll("-", "_"));
if (material != null && Util.isAllowedMaterial(material))
{
final MaterialData matData = material.getNewData((byte)0);
if (particleMatData != null && !particleMatData.isEmpty())
{
particleMatData = particleMatData.toUpperCase(Locale.ENGLISH).replaceAll("-", "_");
if (matData instanceof Colorable)
{
for (DyeColor dyeColor : DyeColor.values())
{
if (dyeColor.toString().equals(particleMatData))
{
((Colorable)matData).setColor(dyeColor);
}
}
}
if (matData instanceof TexturedMaterial)
{
for (Material texture : ((TexturedMaterial)matData).getTextures())
{
if (texture.toString().equals(particleMatData))
{
((TexturedMaterial)matData).setMaterial(texture);
}
}
}
}
builder.setParticleMaterial(matData);
partMaterials.add(material);
}
}
ParticleType.save(builder.build());
}
particleMaterials = partMaterials;
final List<String> coll = config.getStringList("worlds");
worlds = new HashSet<String>(coll == null ? Collections.<String>emptyList() : coll);
}
|
diff --git a/src/nu/nerd/tpcontrol/TPControl.java b/src/nu/nerd/tpcontrol/TPControl.java
index 1b04991..cba58a4 100644
--- a/src/nu/nerd/tpcontrol/TPControl.java
+++ b/src/nu/nerd/tpcontrol/TPControl.java
@@ -1,357 +1,357 @@
package nu.nerd.tpcontrol;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class TPControl extends JavaPlugin {
Logger log = Logger.getLogger("Minecraft");
//private final TPControlListener cmdlistener = new TPControlListener(this);
public final Configuration config = new Configuration(this);
private HashMap<String,User> user_cache = new HashMap<String, User>();
public void onEnable(){
log = this.getLogger();
//Load config
File config_file = new File(getDataFolder(), "config.yml");
if(!config_file.exists()) {
getConfig().options().copyDefaults(true);
saveConfig();
}
config.load();
//TODO: Can we get away with async?
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
for(User u : user_cache.values()) {
u.save();
}
}
}, config.SAVE_INTERVAL*20, config.SAVE_INTERVAL*20);
log.info("TPControl has been enabled!");
}
public void onDisable(){
log.info("TPControl has been disabled.");
}
public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
//
// /tp
//
if (command.getName().equalsIgnoreCase("tp")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p1 = (Player)sender;
if(!canTP(p1)) {
messagePlayer(p1, "You do not have permission.");
return true;
}
if(args.length != 1) {
messagePlayer(p1, "Usage: /tp <player>");
return true;
}
Player p2 = getServer().getPlayer(args[0]);
if(p2 == null) {
messagePlayer(p1, "Couldn't find player "+ args[0]);
return true;
}
User u2 = getUser(p2);
String mode;
if(canOverride(p1, p2)) {
mode = "allow";
} else {
mode = u2.getCalculatedMode(p1); //Get the mode to operate under (allow/ask/deny)
}
if (mode.equals("allow")) {
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
p1.teleport(p2);
}
else if (mode.equals("ask")) {
u2.lodgeRequest(p1);
}
else if (mode.equals("deny")) {
messagePlayer(p1, p2.getName() + " has teleportation disabled.");
}
return true;
}
//
// /tpmode allow|ask|deny
//
else if (command.getName().equalsIgnoreCase("tpmode")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1 || (!args[0].equals("allow") &&
!args[0].equals("ask") &&
!args[0].equals("deny"))) {
messagePlayer(p2, "Usage: /tpmode allow|ask|deny");
messagePlayer(p2, "Your are currently in *" + u2.getMode() + "* mode.");
} else {
u2.setMode(args[0]);
messagePlayer(p2, "You are now in *"+args[0]+"* mode.");
}
return true;
}
//
// /tpallow
//
else if (command.getName().equalsIgnoreCase("tpallow")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
//Check the field exists...
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
//Check it hasn't expired
Date t = new Date();
if(t.getTime() > u2.last_applicant_time + 1000L*config.ASK_EXPIRE) {
messagePlayer(p2, "Error: /tp request has expired!");
return true;
}
Player p1 = getServer().getPlayer(u2.last_applicant);
if(p1 == null) {
messagePlayer(p2, "Error: "+u2.last_applicant+" is no longer online.");
return true;
}
u2.last_applicant = null;
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
messagePlayer(p2, "Teleporting " + p1.getName() + " to you.");
p1.teleport(p2);
return true;
}
//
// /tpdeny
//
else if (command.getName().equalsIgnoreCase("tpdeny")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
messagePlayer(p2, "Denied a request from "+u2.last_applicant+".");
messagePlayer(p2, "Use '/tpblock "+u2.last_applicant+"' to block further requests");
u2.last_applicant = null;
return true;
}
//
// /tpfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
- messagePlayer(p2, "Usage: /tpunfriend <player>");
+ messagePlayer(p2, "Usage: /tpfriend <player>");
return true;
}
if(u2.addFriend(args[0])) {
messagePlayer(p2, args[0] + " added as a friend.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already a friend.");
}
return true;
}
//
// /tpunfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpunfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunfriend <player>");
return true;
}
if(u2.delFriend(args[0])) {
messagePlayer(p2, args[0] + " removed from friends.");
} else {
messagePlayer(p2, "Error: " + args[0] + " not on friends list.");
}
return true;
}
//
// /tpblock <player>
//
else if (command.getName().equalsIgnoreCase("tpblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpblock <player>");
return true;
}
if(u2.addBlocked(args[0])) {
messagePlayer(p2, args[0] + " was blocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already blocked.");
}
return true;
}
//
// /tpunblock <player>
//
else if (command.getName().equalsIgnoreCase("tpunblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunblock <player>");
return true;
}
if(u2.delBlocked(args[0])) {
messagePlayer(p2, args[0] + " was unblocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is not blocked.");
}
return true;
}
return false;
}
//Pull a user from the cache, or create it if necessary
private User getUser(Player p) {
User u = user_cache.get(p.getName().toLowerCase());
if(u == null) {
u = new User(this, p);
user_cache.put(p.getName().toLowerCase(), u);
}
return u;
}
//Checks if p1 can override p2
private boolean canOverride(Player p1, Player p2) {
for(int j = config.GROUPS.size() - 1; j >= 0; j--){
String g = config.GROUPS.get(j);
if(p2.hasPermission("tpcontrol.level."+g)) {
return false;
}
else if (p1.hasPermission("tpcontrol.level."+g)) {
return true;
}
}
return false;
}
private boolean canTP(Player p1) {
for(String g : config.GROUPS) {
if(g.equals(config.MIN_GROUP)) {
return true;
}
else if(p1.hasPermission("tpcontrol.level."+g)) {
return false;
}
}
return false;
}
public void messagePlayer(Player p, String m) {
p.sendMessage(ChatColor.GRAY + "[TP] " + ChatColor.WHITE + m);
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
//
// /tp
//
if (command.getName().equalsIgnoreCase("tp")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p1 = (Player)sender;
if(!canTP(p1)) {
messagePlayer(p1, "You do not have permission.");
return true;
}
if(args.length != 1) {
messagePlayer(p1, "Usage: /tp <player>");
return true;
}
Player p2 = getServer().getPlayer(args[0]);
if(p2 == null) {
messagePlayer(p1, "Couldn't find player "+ args[0]);
return true;
}
User u2 = getUser(p2);
String mode;
if(canOverride(p1, p2)) {
mode = "allow";
} else {
mode = u2.getCalculatedMode(p1); //Get the mode to operate under (allow/ask/deny)
}
if (mode.equals("allow")) {
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
p1.teleport(p2);
}
else if (mode.equals("ask")) {
u2.lodgeRequest(p1);
}
else if (mode.equals("deny")) {
messagePlayer(p1, p2.getName() + " has teleportation disabled.");
}
return true;
}
//
// /tpmode allow|ask|deny
//
else if (command.getName().equalsIgnoreCase("tpmode")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1 || (!args[0].equals("allow") &&
!args[0].equals("ask") &&
!args[0].equals("deny"))) {
messagePlayer(p2, "Usage: /tpmode allow|ask|deny");
messagePlayer(p2, "Your are currently in *" + u2.getMode() + "* mode.");
} else {
u2.setMode(args[0]);
messagePlayer(p2, "You are now in *"+args[0]+"* mode.");
}
return true;
}
//
// /tpallow
//
else if (command.getName().equalsIgnoreCase("tpallow")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
//Check the field exists...
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
//Check it hasn't expired
Date t = new Date();
if(t.getTime() > u2.last_applicant_time + 1000L*config.ASK_EXPIRE) {
messagePlayer(p2, "Error: /tp request has expired!");
return true;
}
Player p1 = getServer().getPlayer(u2.last_applicant);
if(p1 == null) {
messagePlayer(p2, "Error: "+u2.last_applicant+" is no longer online.");
return true;
}
u2.last_applicant = null;
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
messagePlayer(p2, "Teleporting " + p1.getName() + " to you.");
p1.teleport(p2);
return true;
}
//
// /tpdeny
//
else if (command.getName().equalsIgnoreCase("tpdeny")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
messagePlayer(p2, "Denied a request from "+u2.last_applicant+".");
messagePlayer(p2, "Use '/tpblock "+u2.last_applicant+"' to block further requests");
u2.last_applicant = null;
return true;
}
//
// /tpfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunfriend <player>");
return true;
}
if(u2.addFriend(args[0])) {
messagePlayer(p2, args[0] + " added as a friend.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already a friend.");
}
return true;
}
//
// /tpunfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpunfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunfriend <player>");
return true;
}
if(u2.delFriend(args[0])) {
messagePlayer(p2, args[0] + " removed from friends.");
} else {
messagePlayer(p2, "Error: " + args[0] + " not on friends list.");
}
return true;
}
//
// /tpblock <player>
//
else if (command.getName().equalsIgnoreCase("tpblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpblock <player>");
return true;
}
if(u2.addBlocked(args[0])) {
messagePlayer(p2, args[0] + " was blocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already blocked.");
}
return true;
}
//
// /tpunblock <player>
//
else if (command.getName().equalsIgnoreCase("tpunblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunblock <player>");
return true;
}
if(u2.delBlocked(args[0])) {
messagePlayer(p2, args[0] + " was unblocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is not blocked.");
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
//
// /tp
//
if (command.getName().equalsIgnoreCase("tp")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p1 = (Player)sender;
if(!canTP(p1)) {
messagePlayer(p1, "You do not have permission.");
return true;
}
if(args.length != 1) {
messagePlayer(p1, "Usage: /tp <player>");
return true;
}
Player p2 = getServer().getPlayer(args[0]);
if(p2 == null) {
messagePlayer(p1, "Couldn't find player "+ args[0]);
return true;
}
User u2 = getUser(p2);
String mode;
if(canOverride(p1, p2)) {
mode = "allow";
} else {
mode = u2.getCalculatedMode(p1); //Get the mode to operate under (allow/ask/deny)
}
if (mode.equals("allow")) {
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
p1.teleport(p2);
}
else if (mode.equals("ask")) {
u2.lodgeRequest(p1);
}
else if (mode.equals("deny")) {
messagePlayer(p1, p2.getName() + " has teleportation disabled.");
}
return true;
}
//
// /tpmode allow|ask|deny
//
else if (command.getName().equalsIgnoreCase("tpmode")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1 || (!args[0].equals("allow") &&
!args[0].equals("ask") &&
!args[0].equals("deny"))) {
messagePlayer(p2, "Usage: /tpmode allow|ask|deny");
messagePlayer(p2, "Your are currently in *" + u2.getMode() + "* mode.");
} else {
u2.setMode(args[0]);
messagePlayer(p2, "You are now in *"+args[0]+"* mode.");
}
return true;
}
//
// /tpallow
//
else if (command.getName().equalsIgnoreCase("tpallow")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
//Check the field exists...
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
//Check it hasn't expired
Date t = new Date();
if(t.getTime() > u2.last_applicant_time + 1000L*config.ASK_EXPIRE) {
messagePlayer(p2, "Error: /tp request has expired!");
return true;
}
Player p1 = getServer().getPlayer(u2.last_applicant);
if(p1 == null) {
messagePlayer(p2, "Error: "+u2.last_applicant+" is no longer online.");
return true;
}
u2.last_applicant = null;
messagePlayer(p1, "Teleporting you to " + p2.getName() + ".");
messagePlayer(p2, "Teleporting " + p1.getName() + " to you.");
p1.teleport(p2);
return true;
}
//
// /tpdeny
//
else if (command.getName().equalsIgnoreCase("tpdeny")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(u2.last_applicant == null) {
messagePlayer(p2, "Error: No one has attempted to tp to you lately!");
return true;
}
messagePlayer(p2, "Denied a request from "+u2.last_applicant+".");
messagePlayer(p2, "Use '/tpblock "+u2.last_applicant+"' to block further requests");
u2.last_applicant = null;
return true;
}
//
// /tpfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpfriend <player>");
return true;
}
if(u2.addFriend(args[0])) {
messagePlayer(p2, args[0] + " added as a friend.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already a friend.");
}
return true;
}
//
// /tpunfriend <player>
//
else if (command.getName().equalsIgnoreCase("tpunfriend")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunfriend <player>");
return true;
}
if(u2.delFriend(args[0])) {
messagePlayer(p2, args[0] + " removed from friends.");
} else {
messagePlayer(p2, "Error: " + args[0] + " not on friends list.");
}
return true;
}
//
// /tpblock <player>
//
else if (command.getName().equalsIgnoreCase("tpblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpblock <player>");
return true;
}
if(u2.addBlocked(args[0])) {
messagePlayer(p2, args[0] + " was blocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is already blocked.");
}
return true;
}
//
// /tpunblock <player>
//
else if (command.getName().equalsIgnoreCase("tpunblock")) {
if (!(sender instanceof Player)) {
sender.sendMessage("This cannot be run from the console!");
return true;
}
Player p2 = (Player)sender;
if(!canTP(p2)) {
messagePlayer(p2, "You do not have permission.");
return true;
}
User u2 = getUser(p2);
if(args.length != 1) {
messagePlayer(p2, "Usage: /tpunblock <player>");
return true;
}
if(u2.delBlocked(args[0])) {
messagePlayer(p2, args[0] + " was unblocked from teleporting to you.");
} else {
messagePlayer(p2, "Error: " + args[0] + " is not blocked.");
}
return true;
}
return false;
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java
index ca322343b..64c2bbf0e 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java
@@ -1,106 +1,108 @@
/*
* LoginRedirect.java
*
* Version: $Revision: 1.3 $
*
* Date: $Date: 2006/07/13 23:20:54 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS 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.dspace.app.xmlui.aspect.eperson;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.authenticate.AuthenticationManager;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.core.ConfigurationManager;
/**
* When only one login method is defined in the dspace.cfg file this class will
* redirect to the URL provided by that AuthenticationMethod class
*
* @author Jay Paz
* @author Scott Phillips
*
*/
public class LoginRedirect extends AbstractAction {
public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final Iterator authMethods = AuthenticationManager
.authenticationMethodIterator();
final String url = ((AuthenticationMethod) authMethods.next())
.loginPageURL(ContextUtil.obtainContext(objectModel),
httpRequest, httpResponse);
if (authMethods.hasNext()) {
throw new IllegalStateException(
"Multiple authentication methods found when only one was expected.");
}
// now we want to check for the force ssl property
if (ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) {
if (!httpRequest.isSecure()) {
StringBuffer location = new StringBuffer("https://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(url).append(
httpRequest.getQueryString() == null ? ""
: ("?" + httpRequest.getQueryString()));
httpResponse.sendRedirect(location.toString());
+ } else {
+ httpResponse.sendRedirect(url);
}
} else {
httpResponse.sendRedirect(url);
}
return new HashMap();
}
}
| true | true | public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final Iterator authMethods = AuthenticationManager
.authenticationMethodIterator();
final String url = ((AuthenticationMethod) authMethods.next())
.loginPageURL(ContextUtil.obtainContext(objectModel),
httpRequest, httpResponse);
if (authMethods.hasNext()) {
throw new IllegalStateException(
"Multiple authentication methods found when only one was expected.");
}
// now we want to check for the force ssl property
if (ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) {
if (!httpRequest.isSecure()) {
StringBuffer location = new StringBuffer("https://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(url).append(
httpRequest.getQueryString() == null ? ""
: ("?" + httpRequest.getQueryString()));
httpResponse.sendRedirect(location.toString());
}
} else {
httpResponse.sendRedirect(url);
}
return new HashMap();
}
| public Map act(Redirector redirector, SourceResolver resolver,
Map objectModel, String source, Parameters parameters)
throws Exception {
final HttpServletResponse httpResponse = (HttpServletResponse) objectModel
.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
final HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
final Iterator authMethods = AuthenticationManager
.authenticationMethodIterator();
final String url = ((AuthenticationMethod) authMethods.next())
.loginPageURL(ContextUtil.obtainContext(objectModel),
httpRequest, httpResponse);
if (authMethods.hasNext()) {
throw new IllegalStateException(
"Multiple authentication methods found when only one was expected.");
}
// now we want to check for the force ssl property
if (ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) {
if (!httpRequest.isSecure()) {
StringBuffer location = new StringBuffer("https://");
location.append(ConfigurationManager.getProperty("dspace.hostname")).append(url).append(
httpRequest.getQueryString() == null ? ""
: ("?" + httpRequest.getQueryString()));
httpResponse.sendRedirect(location.toString());
} else {
httpResponse.sendRedirect(url);
}
} else {
httpResponse.sendRedirect(url);
}
return new HashMap();
}
|
diff --git a/android/src/org/bombusmod/NetworkStateReceiver.java b/android/src/org/bombusmod/NetworkStateReceiver.java
index 627de072..f54a41bd 100644
--- a/android/src/org/bombusmod/NetworkStateReceiver.java
+++ b/android/src/org/bombusmod/NetworkStateReceiver.java
@@ -1,39 +1,38 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.bombusmod;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import Client.StaticData;
/**
*
* @author Vitaly
*/
public class NetworkStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent networkIntent) {
if (BombusModActivity.getInstance() == null)
return;
if (StaticData.getInstance().roster == null)
return;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
StaticData.getInstance().roster.errorLog("Connectivity lost");
StaticData.getInstance().roster.doReconnect();
} else {
if (activeNetwork.isConnectedOrConnecting() && StaticData.getInstance().roster.isLoggedIn()) {
StaticData.getInstance().roster.errorLog(activeNetwork.getTypeName() + " connected");
- StaticData.getInstance().roster.doReconnect();
}
}
}
}
| true | true | public void onReceive(Context context, Intent networkIntent) {
if (BombusModActivity.getInstance() == null)
return;
if (StaticData.getInstance().roster == null)
return;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
StaticData.getInstance().roster.errorLog("Connectivity lost");
StaticData.getInstance().roster.doReconnect();
} else {
if (activeNetwork.isConnectedOrConnecting() && StaticData.getInstance().roster.isLoggedIn()) {
StaticData.getInstance().roster.errorLog(activeNetwork.getTypeName() + " connected");
StaticData.getInstance().roster.doReconnect();
}
}
}
| public void onReceive(Context context, Intent networkIntent) {
if (BombusModActivity.getInstance() == null)
return;
if (StaticData.getInstance().roster == null)
return;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
StaticData.getInstance().roster.errorLog("Connectivity lost");
StaticData.getInstance().roster.doReconnect();
} else {
if (activeNetwork.isConnectedOrConnecting() && StaticData.getInstance().roster.isLoggedIn()) {
StaticData.getInstance().roster.errorLog(activeNetwork.getTypeName() + " connected");
}
}
}
|
diff --git a/sikuli-script/src/main/java/edu/mit/csail/uid/UnionScreen.java b/sikuli-script/src/main/java/edu/mit/csail/uid/UnionScreen.java
index 7c4558bf..7b9b6fdf 100644
--- a/sikuli-script/src/main/java/edu/mit/csail/uid/UnionScreen.java
+++ b/sikuli-script/src/main/java/edu/mit/csail/uid/UnionScreen.java
@@ -1,65 +1,65 @@
package edu.mit.csail.uid;
import java.awt.*;
import java.awt.image.*;
public class UnionScreen extends Screen {
static Rectangle _bounds;
public UnionScreen(){
super(0);
}
public int getIdFromPoint(int x, int y){
Debug.log(5, "union bound: " + getBounds() );
Debug.log(5, "x, y: " + x + "," + y);
x += getBounds().x;
y += getBounds().y;
Debug.log(5, "new x, y: " + x + "," + y);
for(int i=0;i<getNumberScreens();i++)
if(Screen.getBounds(i).contains(x, y)){
return i;
}
return 0;
}
public Rectangle getBounds(){
if(_bounds == null){
_bounds = new Rectangle();
for (int i=0; i < Screen.getNumberScreens(); i++) {
_bounds = _bounds.union(Screen.getBounds(i));
}
}
return _bounds;
}
public ScreenImage capture(Rectangle rect) {
Debug.log(5, "capture: " + rect);
BufferedImage ret = new BufferedImage( rect.width, rect.height,
BufferedImage.TYPE_INT_RGB );
Graphics2D g2d = ret.createGraphics();
for (int i=0; i < Screen.getNumberScreens(); i++) {
Rectangle scrBound = Screen.getBounds(i);
if(scrBound.intersects(rect)){
Rectangle inter = scrBound.intersection(rect);
Debug.log(5, "scrBound: " + scrBound + ", inter: " +inter);
int ix = inter.x, iy = inter.y;
inter.x-=scrBound.x;
inter.y-=scrBound.y;
BufferedImage img = _robots[i].createScreenCapture(inter);
- g2d.drawImage(img, ix-_bounds.x, iy-_bounds.y, null);
+ g2d.drawImage(img, ix-rect.x, iy-rect.y, null);
}
}
g2d.dispose();
return new ScreenImage(rect, ret);
}
boolean useFullscreen(){
if(getNumberScreens()==1)
return true;
return false;
}
}
| true | true | public ScreenImage capture(Rectangle rect) {
Debug.log(5, "capture: " + rect);
BufferedImage ret = new BufferedImage( rect.width, rect.height,
BufferedImage.TYPE_INT_RGB );
Graphics2D g2d = ret.createGraphics();
for (int i=0; i < Screen.getNumberScreens(); i++) {
Rectangle scrBound = Screen.getBounds(i);
if(scrBound.intersects(rect)){
Rectangle inter = scrBound.intersection(rect);
Debug.log(5, "scrBound: " + scrBound + ", inter: " +inter);
int ix = inter.x, iy = inter.y;
inter.x-=scrBound.x;
inter.y-=scrBound.y;
BufferedImage img = _robots[i].createScreenCapture(inter);
g2d.drawImage(img, ix-_bounds.x, iy-_bounds.y, null);
}
}
g2d.dispose();
return new ScreenImage(rect, ret);
}
| public ScreenImage capture(Rectangle rect) {
Debug.log(5, "capture: " + rect);
BufferedImage ret = new BufferedImage( rect.width, rect.height,
BufferedImage.TYPE_INT_RGB );
Graphics2D g2d = ret.createGraphics();
for (int i=0; i < Screen.getNumberScreens(); i++) {
Rectangle scrBound = Screen.getBounds(i);
if(scrBound.intersects(rect)){
Rectangle inter = scrBound.intersection(rect);
Debug.log(5, "scrBound: " + scrBound + ", inter: " +inter);
int ix = inter.x, iy = inter.y;
inter.x-=scrBound.x;
inter.y-=scrBound.y;
BufferedImage img = _robots[i].createScreenCapture(inter);
g2d.drawImage(img, ix-rect.x, iy-rect.y, null);
}
}
g2d.dispose();
return new ScreenImage(rect, ret);
}
|
diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/common/agreement/AgreementServices.java b/hot-deploy/opentaps-common/src/common/org/opentaps/common/agreement/AgreementServices.java
index f45a2071f..84be15276 100644
--- a/hot-deploy/opentaps-common/src/common/org/opentaps/common/agreement/AgreementServices.java
+++ b/hot-deploy/opentaps-common/src/common/org/opentaps/common/agreement/AgreementServices.java
@@ -1,218 +1,218 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Honest Public 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
* Honest Public License for more details.
*
* You should have received a copy of the Honest Public License
* along with this program; if not, write to Funambol,
* 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA
*/
package org.opentaps.common.agreement;
import java.sql.Timestamp;
import java.util.*;
import javolution.util.FastList;
import javolution.util.FastMap;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.opentaps.common.util.UtilCommon;
import org.opentaps.common.util.UtilMessage;
/**
* Agreement-related services for Opentaps-common.
*/
public final class AgreementServices {
private AgreementServices() { }
private static final String MODULE = AgreementServices.class.getName();
public static final String resource = "OpentapsUiLabels";
public static final String errorResource = "OpentapsErrorLabels";
/**
* Given an Agreement header, creates the AgreementItem(s) and AgreementTerms based on a template.
* If agreementItemTypeId found in context the service create item of specified type and its terms.
* The template is modeled in the entities AgreementToItemMap and AgreementItemToTermMap.
*
* @param dctx DispatchContext
* @param context Map
* @return Map
*/
public static Map<String, Object> autoCreateAgreementItemsAndTerms(DispatchContext dctx, Map<String, Object> context) {
GenericDelegator delegator = dctx.getDelegator();
Locale locale = UtilCommon.getLocale(context);
String agreementId = (String) context.get("agreementId");
String agreementItemTypeId = (String) context.get("agreementItemTypeId");
String currencyUomId = (String) context.get("currencyUomId");
String agreementText = (String) context.get("agreementText");
Timestamp now = UtilDateTime.nowTimestamp();
try {
GenericValue agreement = delegator.findByPrimaryKey("Agreement", UtilMisc.toMap("agreementId", agreementId));
if (agreement == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementNotFound", UtilMisc.toMap("agreementId", agreementId), locale, MODULE);
}
List<GenericValue> agreementItems = FastList.newInstance();
if (agreementItemTypeId == null) {
// create the agreement items based on the template definition as modeled in AgreementToItemMap
List<GenericValue> itemMappings = delegator.findByAnd("AgreementToItemMap", UtilMisc.toMap("autoCreate", "Y", "agreementTypeId", agreement.get("agreementTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : itemMappings) {
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", mapping.get("agreementItemTypeId"));
item.set("currencyUomId", agreement.get("defaultCurrencyUomId"));
item.set("agreementItemSeqId", ((Long) mapping.get("sequenceNum")).toString());
item.create();
agreementItems.add(item);
}
} else {
// create agreement item of specified type
// Check if this agreement item type is valid for given agreement
GenericValue itemMappings = delegator.findByPrimaryKey("AgreementToItemMap", UtilMisc.toMap("agreementTypeId", agreement.get("agreementTypeId"), "agreementItemTypeId", agreementItemTypeId));
if (itemMappings == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementItemNotValid", UtilMisc.toMap("agreementItemTypeId", agreementItemTypeId, "agreementId", agreementId), locale, MODULE);
}
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", agreementItemTypeId);
item.set("currencyUomId", currencyUomId);
- item.set("agreementItemSeqId", delegator.getNextSeqId("AgreementItemSeqId"));
item.set("agreementText", agreementText);
+ delegator.setNextSubSeqId(item, "agreementItemSeqId", 5, 1);
item.create();
agreementItems.add(item);
}
// create the agreement terms based on the template definition as modeled in AgreementItemToTermMap
List<GenericValue> agreementTerms = FastList.newInstance();
for (GenericValue item : agreementTerms) {
List<GenericValue> mappings = delegator.findByAnd("AgreementItemToTermMap", UtilMisc.toMap("autoCreate", "Y", "agreementItemTypeId", item.get("agreementItemTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : mappings) {
GenericValue term = delegator.makeValue("AgreementTerm");
term.set("agreementTermId", delegator.getNextSeqId("AgreementTerm"));
term.set("agreementId", agreementId);
term.set("termTypeId", mapping.get("termTypeId"));
term.set("agreementItemSeqId", item.get("agreementItemSeqId"));
term.set("fromDate", now);
term.set("description", mapping.get("defaultDescription"));
term.create();
agreementTerms.add(term);
}
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("agreementId", agreementId);
return results;
} catch (GenericEntityException e) {
return UtilMessage.createAndLogServiceError(e, locale, MODULE);
}
}
/**
* Run as SECA and set initial status of the agreement.
*
* @param dctx DispatchContext
* @param context Map
* @return Map
*/
public static Map<String, Object> setInitialAgreementStatus(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
String agreementId = (String) context.get("agreementId");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = UtilCommon.getLocale(context);
Map<String, Object> params = FastMap.newInstance();
params.put("agreementId", agreementId);
params.put("statusId", "AGR_CREATED");
params.put("userLogin", userLogin);
try {
dispatcher.runSync("updateAgreement", params);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogServiceError(e, locale, MODULE);
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> removeAgreementItemAndTerms(DispatchContext dctx, Map<String, Object> context) {
GenericDelegator delegator = dctx.getDelegator();
Locale locale = UtilCommon.getLocale(context);
String agreementId = (String) context.get("agreementId");
String agreementItemSeqId = (String) context.get("agreementItemSeqId");
try {
delegator.removeByAnd("AgreementTerm", UtilMisc.toMap("agreementId", agreementId, "agreementItemSeqId", agreementItemSeqId));
delegator.removeByAnd("AgreementItem", UtilMisc.toMap("agreementId", agreementId, "agreementItemSeqId", agreementItemSeqId));
} catch (GenericEntityException gee) {
return UtilMessage.createAndLogServiceError(gee, locale, MODULE);
}
return ServiceUtil.returnSuccess();
}
/**
* Service create commission agreement.
*
* @param dctx DispatchContext
* @param context Map
* @return Map
*/
public static Map<String, Object> createAgreementAndRole(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = UtilCommon.getLocale(context);
Map<String, Object> result = ServiceUtil.returnSuccess();
String partyId = (String) context.get("partyIdTo");
String roleTypeId = (String) context.get("roleTypeIdTo");
String agreementTypeId = (String) context.get("agreementTypeId");
boolean applicableRole = false;
if ("COMMISSION_AGREEMENT".equals(agreementTypeId)) {
applicableRole = "COMMISSION_AGENT".equals(roleTypeId);
} else if ("PARTNER_SALES_AGR".equals(agreementTypeId)) {
applicableRole = Arrays.asList("ACCOUNT", "CONTACT", "PROSPECT", "PARTNER").contains(roleTypeId);
}
if (!applicableRole) {
return UtilMessage.createAndLogServiceError("OpentapsError_CreateAgreementFailSinceRole", UtilMisc.toMap("agreementTypeId", agreementTypeId, "roleTypeId", roleTypeId), locale, MODULE);
}
try {
Map<String, Object> ensurePartyRoleResult = dispatcher.runSync("ensurePartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", roleTypeId));
if (ServiceUtil.isError(ensurePartyRoleResult)) {
return UtilMessage.createAndLogServiceError(ensurePartyRoleResult, MODULE);
}
result = dispatcher.runSync("createAgreement", context);
} catch (GenericServiceException gse) {
return UtilMessage.createAndLogServiceError(gse, locale, MODULE);
}
return result;
}
}
| false | true | public static Map<String, Object> autoCreateAgreementItemsAndTerms(DispatchContext dctx, Map<String, Object> context) {
GenericDelegator delegator = dctx.getDelegator();
Locale locale = UtilCommon.getLocale(context);
String agreementId = (String) context.get("agreementId");
String agreementItemTypeId = (String) context.get("agreementItemTypeId");
String currencyUomId = (String) context.get("currencyUomId");
String agreementText = (String) context.get("agreementText");
Timestamp now = UtilDateTime.nowTimestamp();
try {
GenericValue agreement = delegator.findByPrimaryKey("Agreement", UtilMisc.toMap("agreementId", agreementId));
if (agreement == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementNotFound", UtilMisc.toMap("agreementId", agreementId), locale, MODULE);
}
List<GenericValue> agreementItems = FastList.newInstance();
if (agreementItemTypeId == null) {
// create the agreement items based on the template definition as modeled in AgreementToItemMap
List<GenericValue> itemMappings = delegator.findByAnd("AgreementToItemMap", UtilMisc.toMap("autoCreate", "Y", "agreementTypeId", agreement.get("agreementTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : itemMappings) {
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", mapping.get("agreementItemTypeId"));
item.set("currencyUomId", agreement.get("defaultCurrencyUomId"));
item.set("agreementItemSeqId", ((Long) mapping.get("sequenceNum")).toString());
item.create();
agreementItems.add(item);
}
} else {
// create agreement item of specified type
// Check if this agreement item type is valid for given agreement
GenericValue itemMappings = delegator.findByPrimaryKey("AgreementToItemMap", UtilMisc.toMap("agreementTypeId", agreement.get("agreementTypeId"), "agreementItemTypeId", agreementItemTypeId));
if (itemMappings == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementItemNotValid", UtilMisc.toMap("agreementItemTypeId", agreementItemTypeId, "agreementId", agreementId), locale, MODULE);
}
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", agreementItemTypeId);
item.set("currencyUomId", currencyUomId);
item.set("agreementItemSeqId", delegator.getNextSeqId("AgreementItemSeqId"));
item.set("agreementText", agreementText);
item.create();
agreementItems.add(item);
}
// create the agreement terms based on the template definition as modeled in AgreementItemToTermMap
List<GenericValue> agreementTerms = FastList.newInstance();
for (GenericValue item : agreementTerms) {
List<GenericValue> mappings = delegator.findByAnd("AgreementItemToTermMap", UtilMisc.toMap("autoCreate", "Y", "agreementItemTypeId", item.get("agreementItemTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : mappings) {
GenericValue term = delegator.makeValue("AgreementTerm");
term.set("agreementTermId", delegator.getNextSeqId("AgreementTerm"));
term.set("agreementId", agreementId);
term.set("termTypeId", mapping.get("termTypeId"));
term.set("agreementItemSeqId", item.get("agreementItemSeqId"));
term.set("fromDate", now);
term.set("description", mapping.get("defaultDescription"));
term.create();
agreementTerms.add(term);
}
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("agreementId", agreementId);
return results;
} catch (GenericEntityException e) {
return UtilMessage.createAndLogServiceError(e, locale, MODULE);
}
}
| public static Map<String, Object> autoCreateAgreementItemsAndTerms(DispatchContext dctx, Map<String, Object> context) {
GenericDelegator delegator = dctx.getDelegator();
Locale locale = UtilCommon.getLocale(context);
String agreementId = (String) context.get("agreementId");
String agreementItemTypeId = (String) context.get("agreementItemTypeId");
String currencyUomId = (String) context.get("currencyUomId");
String agreementText = (String) context.get("agreementText");
Timestamp now = UtilDateTime.nowTimestamp();
try {
GenericValue agreement = delegator.findByPrimaryKey("Agreement", UtilMisc.toMap("agreementId", agreementId));
if (agreement == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementNotFound", UtilMisc.toMap("agreementId", agreementId), locale, MODULE);
}
List<GenericValue> agreementItems = FastList.newInstance();
if (agreementItemTypeId == null) {
// create the agreement items based on the template definition as modeled in AgreementToItemMap
List<GenericValue> itemMappings = delegator.findByAnd("AgreementToItemMap", UtilMisc.toMap("autoCreate", "Y", "agreementTypeId", agreement.get("agreementTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : itemMappings) {
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", mapping.get("agreementItemTypeId"));
item.set("currencyUomId", agreement.get("defaultCurrencyUomId"));
item.set("agreementItemSeqId", ((Long) mapping.get("sequenceNum")).toString());
item.create();
agreementItems.add(item);
}
} else {
// create agreement item of specified type
// Check if this agreement item type is valid for given agreement
GenericValue itemMappings = delegator.findByPrimaryKey("AgreementToItemMap", UtilMisc.toMap("agreementTypeId", agreement.get("agreementTypeId"), "agreementItemTypeId", agreementItemTypeId));
if (itemMappings == null) {
return UtilMessage.createAndLogServiceError("OpentapsError_AgreementItemNotValid", UtilMisc.toMap("agreementItemTypeId", agreementItemTypeId, "agreementId", agreementId), locale, MODULE);
}
GenericValue item = delegator.makeValue("AgreementItem");
item.set("agreementId", agreementId);
item.set("agreementItemTypeId", agreementItemTypeId);
item.set("currencyUomId", currencyUomId);
item.set("agreementText", agreementText);
delegator.setNextSubSeqId(item, "agreementItemSeqId", 5, 1);
item.create();
agreementItems.add(item);
}
// create the agreement terms based on the template definition as modeled in AgreementItemToTermMap
List<GenericValue> agreementTerms = FastList.newInstance();
for (GenericValue item : agreementTerms) {
List<GenericValue> mappings = delegator.findByAnd("AgreementItemToTermMap", UtilMisc.toMap("autoCreate", "Y", "agreementItemTypeId", item.get("agreementItemTypeId")), UtilMisc.toList("sequenceNum"));
for (GenericValue mapping : mappings) {
GenericValue term = delegator.makeValue("AgreementTerm");
term.set("agreementTermId", delegator.getNextSeqId("AgreementTerm"));
term.set("agreementId", agreementId);
term.set("termTypeId", mapping.get("termTypeId"));
term.set("agreementItemSeqId", item.get("agreementItemSeqId"));
term.set("fromDate", now);
term.set("description", mapping.get("defaultDescription"));
term.create();
agreementTerms.add(term);
}
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("agreementId", agreementId);
return results;
} catch (GenericEntityException e) {
return UtilMessage.createAndLogServiceError(e, locale, MODULE);
}
}
|
diff --git a/ui/marzemino/android/First/src/com/example/first/MainActivity.java b/ui/marzemino/android/First/src/com/example/first/MainActivity.java
index d124271..7f6a3be 100644
--- a/ui/marzemino/android/First/src/com/example/first/MainActivity.java
+++ b/ui/marzemino/android/First/src/com/example/first/MainActivity.java
@@ -1,31 +1,31 @@
package com.example.first;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.view.Menu;
public class MainActivity extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- super.loadUrl("file:///android_asset/www/main.html");
+ super.loadUrl("file:///android_asset/www/index2.html");
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{ super.onConfigurationChanged(newConfig); }
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/main.html");
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index2.html");
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
}
|
diff --git a/src/main/java/de/cosmocode/palava/ipc/legacy/LegacyFrameDecoder.java b/src/main/java/de/cosmocode/palava/ipc/legacy/LegacyFrameDecoder.java
index c121702..f37ac73 100644
--- a/src/main/java/de/cosmocode/palava/ipc/legacy/LegacyFrameDecoder.java
+++ b/src/main/java/de/cosmocode/palava/ipc/legacy/LegacyFrameDecoder.java
@@ -1,293 +1,295 @@
/**
* Copyright 2010 CosmoCode 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.cosmocode.palava.ipc.legacy;
import java.nio.ByteBuffer;
import javax.annotation.concurrent.NotThreadSafe;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import de.cosmocode.palava.bridge.Header;
import de.cosmocode.palava.bridge.call.CallType;
/**
* Decodes framed chunks of the legacy palava protocol which looks like:<br />
* {@code <type>://<aliasedName>/<sessionId>/(<contentLength>)?<content>}.
*
* @since 1.0
* @author Willi Schoenborn
*/
@NotThreadSafe
final class LegacyFrameDecoder extends FrameDecoder {
private static final Logger LOG = LoggerFactory.getLogger(LegacyFrameDecoder.class);
/**
* Identifies the different parts of the protocol structure.
*
* @author Willi Schoenborn
*/
private static enum Part {
TYPE,
COLON,
FIRST_SLASH,
SECOND_SLASH,
NAME,
THIRD_SLASH,
SESSION_ID,
FOURTH_SLASH,
LEFT_PARENTHESIS,
CONTENT_LENGTH,
RIGHT_PARENTHESIS,
QUESTION_MARK,
CONTENT;
}
/**
* Defines the current part. The readerIndex of the buffer will
* be set to the first byte of the corresponding part.
*/
private Part part;
private String type;
private String name;
private String sessionId;
private int length;
private ByteBuffer content;
// Reducing cyclomatic complexity would dramatically reduce readability
/* CHECKSTYLE:OFF */
@Override
/* CHECKSTYLE:ON */
protected Header decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readable()) {
if (part == null) part = Part.TYPE;
if (part == Part.CONTENT) {
return contentOf(buffer);
}
for (int i = buffer.readerIndex(); i < buffer.writerIndex(); i++) {
final byte c = buffer.getByte(i);
switch (part) {
case TYPE: {
if (c == ':') {
type = readAndIncrement(buffer, i);
LOG.trace("Setting type to {}", type);
part = Part.COLON;
}
break;
}
case COLON: {
buffer.skipBytes(1);
checkState(c == '/', ": must be followed by first / but was %s", c);
part = Part.FIRST_SLASH;
break;
}
case FIRST_SLASH: {
buffer.skipBytes(1);
checkState(c == '/', "first / must be followed by second / but was %s", c);
part = Part.SECOND_SLASH;
break;
}
case SECOND_SLASH: {
buffer.skipBytes(1);
part = Part.NAME;
i--;
break;
}
case NAME: {
// c == *second* char of name
if (c == '/') {
name = readAndIncrement(buffer, i);
LOG.trace("Setting name to {}", name);
part = Part.THIRD_SLASH;
}
break;
}
case THIRD_SLASH: {
buffer.skipBytes(1);
part = Part.SESSION_ID;
+ i--;
break;
}
case SESSION_ID: {
+ // c == *second* char of sessionId
if (c == '/') {
sessionId = readAndIncrement(buffer, i);
LOG.trace("Setting sessionId to {}", sessionId);
part = Part.FOURTH_SLASH;
}
break;
}
case FOURTH_SLASH: {
buffer.skipBytes(1);
checkState(c == '(', "fourth / must be followed by ( but was %s", c);
part = Part.LEFT_PARENTHESIS;
break;
}
case LEFT_PARENTHESIS: {
buffer.skipBytes(1);
part = Part.CONTENT_LENGTH;
break;
}
case CONTENT_LENGTH: {
if (c == ')') {
final String value = readAndIncrement(buffer, i);
length = Integer.parseInt(value);
LOG.trace("Setting content length to {}", value);
part = Part.RIGHT_PARENTHESIS;
}
break;
}
case RIGHT_PARENTHESIS: {
buffer.skipBytes(1);
checkState(c == '?', ") must be followed by ? but was %s", c);
part = Part.QUESTION_MARK;
break;
}
case QUESTION_MARK: {
buffer.skipBytes(1);
part = Part.CONTENT;
return null;
}
default: {
throw new AssertionError("Default case matched part " + part);
}
}
}
}
return null;
}
private Header contentOf(ChannelBuffer buffer) {
if (buffer.readableBytes() >= length) {
content = buffer.toByteBuffer(buffer.readerIndex(), length);
LOG.trace("Setting content to {}", content);
buffer.skipBytes(length);
final Header header = new InternalHeader();
LOG.trace("Incoming call {}", header);
reset();
return header;
} else {
return null;
}
}
private String readAndIncrement(ChannelBuffer buffer, int currentIndex) {
final int size = currentIndex - buffer.readerIndex();
final String string = buffer.toString(buffer.readerIndex(), size, Charsets.UTF_8);
buffer.readerIndex(currentIndex);
return string;
}
private void checkState(boolean state, String format, byte c) {
if (state) {
return;
} else {
throw new IllegalArgumentException(String.format(format, (char) c));
}
}
private void reset() {
part = null;
type = null;
name = null;
sessionId = null;
length = 0;
content = null;
}
/**
* Internal implementation of the {@link Header} interface.
*
* @since
* @author Willi Schoenborn
*/
private final class InternalHeader implements Header {
private final CallType callType = CallType.valueOf(type.toUpperCase());
private final String name = LegacyFrameDecoder.this.name;
private final String sessionId = LegacyFrameDecoder.this.sessionId;
private final int length = LegacyFrameDecoder.this.length;
private final ByteBuffer content = LegacyFrameDecoder.this.content;
@Override
public CallType getCallType() {
return callType;
}
@Override
public String getAliasedName() {
return name;
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public int getContentLength() {
return length;
}
@Override
public ByteBuffer getContent() {
return content;
}
@Override
public String toString() {
return String.format("Header [callType=%s, name=%s, sessionId=%s, contentLength=%s, content=%s]",
callType, getAliasedName(), getSessionId(), getContentLength(), getContent()
);
}
}
}
| false | true | protected Header decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readable()) {
if (part == null) part = Part.TYPE;
if (part == Part.CONTENT) {
return contentOf(buffer);
}
for (int i = buffer.readerIndex(); i < buffer.writerIndex(); i++) {
final byte c = buffer.getByte(i);
switch (part) {
case TYPE: {
if (c == ':') {
type = readAndIncrement(buffer, i);
LOG.trace("Setting type to {}", type);
part = Part.COLON;
}
break;
}
case COLON: {
buffer.skipBytes(1);
checkState(c == '/', ": must be followed by first / but was %s", c);
part = Part.FIRST_SLASH;
break;
}
case FIRST_SLASH: {
buffer.skipBytes(1);
checkState(c == '/', "first / must be followed by second / but was %s", c);
part = Part.SECOND_SLASH;
break;
}
case SECOND_SLASH: {
buffer.skipBytes(1);
part = Part.NAME;
i--;
break;
}
case NAME: {
// c == *second* char of name
if (c == '/') {
name = readAndIncrement(buffer, i);
LOG.trace("Setting name to {}", name);
part = Part.THIRD_SLASH;
}
break;
}
case THIRD_SLASH: {
buffer.skipBytes(1);
part = Part.SESSION_ID;
break;
}
case SESSION_ID: {
if (c == '/') {
sessionId = readAndIncrement(buffer, i);
LOG.trace("Setting sessionId to {}", sessionId);
part = Part.FOURTH_SLASH;
}
break;
}
case FOURTH_SLASH: {
buffer.skipBytes(1);
checkState(c == '(', "fourth / must be followed by ( but was %s", c);
part = Part.LEFT_PARENTHESIS;
break;
}
case LEFT_PARENTHESIS: {
buffer.skipBytes(1);
part = Part.CONTENT_LENGTH;
break;
}
case CONTENT_LENGTH: {
if (c == ')') {
final String value = readAndIncrement(buffer, i);
length = Integer.parseInt(value);
LOG.trace("Setting content length to {}", value);
part = Part.RIGHT_PARENTHESIS;
}
break;
}
case RIGHT_PARENTHESIS: {
buffer.skipBytes(1);
checkState(c == '?', ") must be followed by ? but was %s", c);
part = Part.QUESTION_MARK;
break;
}
case QUESTION_MARK: {
buffer.skipBytes(1);
part = Part.CONTENT;
return null;
}
default: {
throw new AssertionError("Default case matched part " + part);
}
}
}
}
return null;
}
| protected Header decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readable()) {
if (part == null) part = Part.TYPE;
if (part == Part.CONTENT) {
return contentOf(buffer);
}
for (int i = buffer.readerIndex(); i < buffer.writerIndex(); i++) {
final byte c = buffer.getByte(i);
switch (part) {
case TYPE: {
if (c == ':') {
type = readAndIncrement(buffer, i);
LOG.trace("Setting type to {}", type);
part = Part.COLON;
}
break;
}
case COLON: {
buffer.skipBytes(1);
checkState(c == '/', ": must be followed by first / but was %s", c);
part = Part.FIRST_SLASH;
break;
}
case FIRST_SLASH: {
buffer.skipBytes(1);
checkState(c == '/', "first / must be followed by second / but was %s", c);
part = Part.SECOND_SLASH;
break;
}
case SECOND_SLASH: {
buffer.skipBytes(1);
part = Part.NAME;
i--;
break;
}
case NAME: {
// c == *second* char of name
if (c == '/') {
name = readAndIncrement(buffer, i);
LOG.trace("Setting name to {}", name);
part = Part.THIRD_SLASH;
}
break;
}
case THIRD_SLASH: {
buffer.skipBytes(1);
part = Part.SESSION_ID;
i--;
break;
}
case SESSION_ID: {
// c == *second* char of sessionId
if (c == '/') {
sessionId = readAndIncrement(buffer, i);
LOG.trace("Setting sessionId to {}", sessionId);
part = Part.FOURTH_SLASH;
}
break;
}
case FOURTH_SLASH: {
buffer.skipBytes(1);
checkState(c == '(', "fourth / must be followed by ( but was %s", c);
part = Part.LEFT_PARENTHESIS;
break;
}
case LEFT_PARENTHESIS: {
buffer.skipBytes(1);
part = Part.CONTENT_LENGTH;
break;
}
case CONTENT_LENGTH: {
if (c == ')') {
final String value = readAndIncrement(buffer, i);
length = Integer.parseInt(value);
LOG.trace("Setting content length to {}", value);
part = Part.RIGHT_PARENTHESIS;
}
break;
}
case RIGHT_PARENTHESIS: {
buffer.skipBytes(1);
checkState(c == '?', ") must be followed by ? but was %s", c);
part = Part.QUESTION_MARK;
break;
}
case QUESTION_MARK: {
buffer.skipBytes(1);
part = Part.CONTENT;
return null;
}
default: {
throw new AssertionError("Default case matched part " + part);
}
}
}
}
return null;
}
|
diff --git a/jOOQ-test/src/org/jooq/test/jOOQFirebirdTest.java b/jOOQ-test/src/org/jooq/test/jOOQFirebirdTest.java
index ffa2d4a02..721da6d0a 100644
--- a/jOOQ-test/src/org/jooq/test/jOOQFirebirdTest.java
+++ b/jOOQ-test/src/org/jooq/test/jOOQFirebirdTest.java
@@ -1,736 +1,726 @@
/**
* 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;
import static org.jooq.test.sqlite.generatedclasses.Tables.T_BOOK_TO_BOOK_STORE;
import static org.jooq.test.sqlite.generatedclasses.Tables.T_BOOLEANS;
import static org.jooq.test.sqlite.generatedclasses.Tables.T_DATES;
import static org.jooq.test.sqlite.generatedclasses.Tables.V_AUTHOR;
import static org.jooq.test.sqlite.generatedclasses.Tables.V_BOOK;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import org.jooq.ArrayRecord;
import org.jooq.DataType;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UDTRecord;
import org.jooq.UpdatableTable;
import org.jooq.conf.Settings;
import org.jooq.impl.Factory;
import org.jooq.test._.converters.Boolean_10;
import org.jooq.test._.converters.Boolean_TF_LC;
import org.jooq.test._.converters.Boolean_TF_UC;
import org.jooq.test._.converters.Boolean_YES_NO_LC;
import org.jooq.test._.converters.Boolean_YES_NO_UC;
import org.jooq.test._.converters.Boolean_YN_LC;
import org.jooq.test._.converters.Boolean_YN_UC;
import org.jooq.test.sqlite.generatedclasses.tables.TAuthor;
import org.jooq.test.sqlite.generatedclasses.tables.TBook;
import org.jooq.test.sqlite.generatedclasses.tables.TBookStore;
import org.jooq.test.sqlite.generatedclasses.tables.TBookToBookStore;
import org.jooq.test.sqlite.generatedclasses.tables.TBooleans;
import org.jooq.test.sqlite.generatedclasses.tables.TTriggers;
import org.jooq.test.sqlite.generatedclasses.tables.T_639NumbersTable;
import org.jooq.test.sqlite.generatedclasses.tables.T_658Ref;
import org.jooq.test.sqlite.generatedclasses.tables.T_725LobTest;
import org.jooq.test.sqlite.generatedclasses.tables.T_785;
import org.jooq.test.sqlite.generatedclasses.tables.VLibrary;
import org.jooq.test.sqlite.generatedclasses.tables.records.TAuthorRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TBookRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TBookStoreRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TBookToBookStoreRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TBooleansRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TDatesRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.TTriggersRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.T_639NumbersTableRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.T_658RefRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.T_725LobTestRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.T_785Record;
import org.jooq.test.sqlite.generatedclasses.tables.records.VLibraryRecord;
import org.jooq.test.sqlite.generatedclasses.tables.records.XUnusedRecord;
import org.jooq.tools.unsigned.UByte;
import org.jooq.tools.unsigned.UInteger;
import org.jooq.tools.unsigned.ULong;
import org.jooq.tools.unsigned.UShort;
import org.jooq.util.firebird.FirebirdDataType;
import org.jooq.util.firebird.FirebirdFactory;
/**
* Integration test for the SQLite database
*
* @author Lukas Eder
*/
public class jOOQFirebirdTest extends jOOQAbstractTest<
TAuthorRecord,
Object,
TBookRecord,
TBookStoreRecord,
TBookToBookStoreRecord,
XUnusedRecord,
VLibraryRecord,
XUnusedRecord,
TDatesRecord,
TBooleansRecord,
XUnusedRecord,
TTriggersRecord,
XUnusedRecord,
XUnusedRecord,
XUnusedRecord,
T_658RefRecord,
T_725LobTestRecord,
T_639NumbersTableRecord,
T_785Record> {
@Override
protected Factory create(Settings settings) {
return new FirebirdFactory(getConnection(), settings);
}
@Override
protected UpdatableTable<TAuthorRecord> TAuthor() {
return TAuthor.T_AUTHOR;
}
@Override
protected TableField<TAuthorRecord, String> TAuthor_LAST_NAME() {
return TAuthor.LAST_NAME;
}
@Override
protected TableField<TAuthorRecord, String> TAuthor_FIRST_NAME() {
return TAuthor.FIRST_NAME;
}
@Override
protected TableField<TAuthorRecord, Date> TAuthor_DATE_OF_BIRTH() {
return TAuthor.DATE_OF_BIRTH;
}
@Override
protected TableField<TAuthorRecord, Integer> TAuthor_YEAR_OF_BIRTH() {
return TAuthor.YEAR_OF_BIRTH;
}
@Override
protected TableField<TAuthorRecord, Integer> TAuthor_ID() {
return TAuthor.ID;
}
@Override
protected TableField<TAuthorRecord, ? extends UDTRecord<?>> TAuthor_ADDRESS() {
return null;
}
@Override
protected UpdatableTable<TBookRecord> TBook() {
return TBook.T_BOOK;
}
@Override
protected TableField<TBookRecord, Integer> TBook_ID() {
return TBook.ID;
}
@Override
protected TableField<TBookRecord, Integer> TBook_AUTHOR_ID() {
return TBook.AUTHOR_ID;
}
@Override
protected TableField<TBookRecord, String> TBook_TITLE() {
return TBook.TITLE;
}
@Override
protected UpdatableTable<TBookStoreRecord> TBookStore() {
return TBookStore.T_BOOK_STORE;
}
@Override
protected TableField<TBookStoreRecord, String> TBookStore_NAME() {
return TBookStore.NAME;
}
@Override
protected UpdatableTable<TBookToBookStoreRecord> TBookToBookStore() {
return T_BOOK_TO_BOOK_STORE;
}
@Override
protected UpdatableTable<XUnusedRecord> TBookSale() {
return null;
}
@Override
protected TableField<TBookToBookStoreRecord, Integer> TBookToBookStore_BOOK_ID() {
return TBookToBookStore.BOOK_ID;
}
@Override
protected TableField<TBookToBookStoreRecord, String> TBookToBookStore_BOOK_STORE_NAME() {
return TBookToBookStore.BOOK_STORE_NAME;
}
@Override
protected TableField<TBookToBookStoreRecord, Integer> TBookToBookStore_STOCK() {
return TBookToBookStore.STOCK;
}
@Override
protected Table<T_725LobTestRecord> T725() {
return T_725LobTest.T_725_LOB_TEST;
}
@Override
protected TableField<T_725LobTestRecord, Integer> T725_ID() {
return T_725LobTest.ID;
}
@Override
protected TableField<T_725LobTestRecord, byte[]> T725_LOB() {
return T_725LobTest.LOB;
}
@Override
protected Table<T_658RefRecord> T658() {
return T_658Ref.T_658_REF;
}
@Override
protected Table<T_639NumbersTableRecord> T639() {
return T_639NumbersTable.T_639_NUMBERS_TABLE;
}
@Override
protected TableField<T_639NumbersTableRecord, Integer> T639_ID() {
return T_639NumbersTable.ID;
}
@Override
protected TableField<T_639NumbersTableRecord, BigDecimal> T639_BIG_DECIMAL() {
return T_639NumbersTable.BIG_DECIMAL;
}
@Override
protected TableField<T_639NumbersTableRecord, BigInteger> T639_BIG_INTEGER() {
return T_639NumbersTable.BIG_INTEGER;
}
@Override
protected TableField<T_639NumbersTableRecord, Byte> T639_BYTE() {
return T_639NumbersTable.BYTE;
}
@Override
protected TableField<T_639NumbersTableRecord, Byte> T639_BYTE_DECIMAL() {
return T_639NumbersTable.BYTE_DECIMAL;
}
@Override
protected TableField<T_639NumbersTableRecord, Short> T639_SHORT() {
return T_639NumbersTable.SHORT;
}
@Override
protected TableField<T_639NumbersTableRecord, Short> T639_SHORT_DECIMAL() {
return T_639NumbersTable.SHORT_DECIMAL;
}
@Override
protected TableField<T_639NumbersTableRecord, Integer> T639_INTEGER() {
return T_639NumbersTable.INTEGER;
}
@Override
protected TableField<T_639NumbersTableRecord, Integer> T639_INTEGER_DECIMAL() {
return T_639NumbersTable.INTEGER_DECIMAL;
}
@Override
protected TableField<T_639NumbersTableRecord, Long> T639_LONG() {
return T_639NumbersTable.LONG;
}
@Override
protected TableField<T_639NumbersTableRecord, Long> T639_LONG_DECIMAL() {
return T_639NumbersTable.LONG_DECIMAL;
}
@Override
protected TableField<T_639NumbersTableRecord, Double> T639_DOUBLE() {
return T_639NumbersTable.DOUBLE;
}
@Override
protected TableField<T_639NumbersTableRecord, Float> T639_FLOAT() {
return T_639NumbersTable.FLOAT;
}
@Override
protected Table<T_785Record> T785() {
return T_785.T_785;
}
@Override
protected TableField<T_785Record, Integer> T785_ID() {
return T_785.ID;
}
@Override
protected TableField<T_785Record, String> T785_NAME() {
return T_785.NAME;
}
@Override
protected TableField<T_785Record, String> T785_VALUE() {
return T_785.VALUE;
}
@Override
protected Table<XUnusedRecord> TUnsigned() {
return null;
}
@Override
protected TableField<XUnusedRecord, UByte> TUnsigned_U_BYTE() {
return null;
}
@Override
protected TableField<XUnusedRecord, UShort> TUnsigned_U_SHORT() {
return null;
}
@Override
protected TableField<XUnusedRecord, UInteger> TUnsigned_U_INT() {
return null;
}
@Override
protected TableField<XUnusedRecord, ULong> TUnsigned_U_LONG() {
return null;
}
@Override
protected Table<TDatesRecord> TDates() {
return T_DATES;
}
@Override
protected UpdatableTable<TBooleansRecord> TBooleans() {
return T_BOOLEANS;
}
@Override
protected TableField<TBooleansRecord, Integer> TBooleans_ID() {
return TBooleans.ID;
}
@Override
protected TableField<TBooleansRecord, Boolean_10> TBooleans_BOOLEAN_10() {
return TBooleans.ONE_ZERO;
}
@Override
protected TableField<TBooleansRecord, Boolean_TF_LC> TBooleans_Boolean_TF_LC() {
return TBooleans.TRUE_FALSE_LC;
}
@Override
protected TableField<TBooleansRecord, Boolean_TF_UC> TBooleans_Boolean_TF_UC() {
return TBooleans.TRUE_FALSE_UC;
}
@Override
protected TableField<TBooleansRecord, Boolean_YN_LC> TBooleans_Boolean_YN_LC() {
return TBooleans.Y_N_LC;
}
@Override
protected TableField<TBooleansRecord, Boolean_YN_UC> TBooleans_Boolean_YN_UC() {
return TBooleans.Y_N_UC;
}
@Override
protected TableField<TBooleansRecord, Boolean_YES_NO_LC> TBooleans_Boolean_YES_NO_LC() {
return TBooleans.YES_NO_LC;
}
@Override
protected TableField<TBooleansRecord, Boolean_YES_NO_UC> TBooleans_Boolean_YES_NO_UC() {
return TBooleans.YES_NO_UC;
}
@Override
protected TableField<TBooleansRecord, Boolean> TBooleans_VC() {
return TBooleans.VC_BOOLEAN;
}
@Override
protected TableField<TBooleansRecord, Boolean> TBooleans_C() {
return TBooleans.C_BOOLEAN;
}
@Override
protected TableField<TBooleansRecord, Boolean> TBooleans_N() {
return TBooleans.N_BOOLEAN;
}
@Override
protected Table<XUnusedRecord> TArrays() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TArrays_ID() {
return null;
}
@Override
protected TableField<XUnusedRecord, String[]> TArrays_STRING() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer[]> TArrays_NUMBER() {
return null;
}
@Override
protected TableField<XUnusedRecord, Date[]> TArrays_DATE() {
return null;
}
@Override
protected TableField<XUnusedRecord, ? extends UDTRecord<?>[]> TArrays_UDT() {
return null;
}
@Override
protected TableField<XUnusedRecord, ArrayRecord<String>> TArrays_STRING_R() {
return null;
}
@Override
protected TableField<XUnusedRecord, ArrayRecord<Integer>> TArrays_NUMBER_R() {
return null;
}
@Override
protected TableField<XUnusedRecord, ArrayRecord<Date>> TArrays_DATE_R() {
return null;
}
@Override
protected TableField<XUnusedRecord, ArrayRecord<Long>> TArrays_NUMBER_LONG_R() {
return null;
}
@Override
protected TableField<TBookRecord, ?> TBook_LANGUAGE_ID() {
return TBook.LANGUAGE_ID;
}
@Override
protected TableField<TBookRecord, Integer> TBook_PUBLISHED_IN() {
return TBook.PUBLISHED_IN;
}
@Override
protected TableField<TBookRecord, String> TBook_CONTENT_TEXT() {
return TBook.CONTENT_TEXT;
}
@Override
protected TableField<TBookRecord, byte[]> TBook_CONTENT_PDF() {
return TBook.CONTENT_PDF;
}
@Override
protected TableField<TBookRecord, ? extends Enum<?>> TBook_STATUS() {
return null;
}
@Override
protected Table<VLibraryRecord> VLibrary() {
return VLibrary.V_LIBRARY;
}
@Override
protected TableField<VLibraryRecord, String> VLibrary_TITLE() {
return VLibrary.TITLE;
}
@Override
protected TableField<VLibraryRecord, String> VLibrary_AUTHOR() {
return VLibrary.AUTHOR;
}
@Override
protected Table<?> VAuthor() {
return V_AUTHOR;
}
@Override
protected Table<?> VBook() {
return V_BOOK;
}
@Override
protected UpdatableTable<XUnusedRecord> TDirectory() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TDirectory_ID() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TDirectory_PARENT_ID() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TDirectory_IS_DIRECTORY() {
return null;
}
@Override
protected TableField<XUnusedRecord, String> TDirectory_NAME() {
return null;
}
@Override
protected UpdatableTable<TTriggersRecord> TTriggers() {
return TTriggers.T_TRIGGERS;
}
@Override
protected TableField<TTriggersRecord, Integer> TTriggers_ID_GENERATED() {
return TTriggers.ID_GENERATED;
}
@Override
protected TableField<TTriggersRecord, Integer> TTriggers_ID() {
return TTriggers.ID;
}
@Override
protected TableField<TTriggersRecord, Integer> TTriggers_COUNTER() {
return TTriggers.COUNTER;
}
@Override
protected Table<XUnusedRecord> TIdentity() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TIdentity_ID() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TIdentity_VAL() {
return null;
}
@Override
protected UpdatableTable<XUnusedRecord> TIdentityPK() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TIdentityPK_ID() {
return null;
}
@Override
protected TableField<XUnusedRecord, Integer> TIdentityPK_VAL() {
return null;
}
@Override
protected Field<? extends Number> FAuthorExistsField(String authorName) {
return null;
}
@Override
protected Field<? extends Number> FOneField() {
return null;
}
@Override
protected Field<? extends Number> FNumberField(Number n) {
return null;
}
@Override
protected Field<? extends Number> FNumberField(Field<? extends Number> n) {
return null;
}
@Override
protected Field<? extends Number> F317Field(Number n1, Number n2, Number n3, Number n4) {
return null;
}
@Override
protected Field<? extends Number> F317Field(Field<? extends Number> n1, Field<? extends Number> n2,
Field<? extends Number> n3, Field<? extends Number> n4) {
return null;
}
@Override
protected Field<Result<Record>> FGetOneCursorField(Integer[] array) {
return null;
}
@Override
protected Field<Integer[]> FArrays1Field(Field<Integer[]> array) {
return null;
}
@Override
protected Field<Long[]> FArrays2Field(Field<Long[]> array) {
return null;
}
@Override
protected Field<String[]> FArrays3Field(Field<String[]> array) {
return null;
}
@Override
protected <T extends ArrayRecord<Integer>> Field<T> FArrays1Field_R(Field<T> array) {
return null;
}
@Override
protected <T extends ArrayRecord<Long>> Field<T> FArrays2Field_R(Field<T> array) {
return null;
}
@Override
protected <T extends ArrayRecord<String>> Field<T> FArrays3Field_R(Field<T> array) {
return null;
}
@Override
protected Class<? extends UDTRecord<?>> cUAddressType() {
return null;
}
@Override
protected Class<? extends UDTRecord<?>> cUStreetType() {
return null;
}
@Override
protected Class<?> cRoutines() {
return null;
}
@Override
protected boolean supportsOUTParameters() {
return false;
}
@Override
protected boolean supportsReferences() {
return true;
}
@Override
protected boolean supportsRecursiveQueries() {
return false;
}
@Override
protected Class<?> cLibrary() {
return null;
}
@Override
protected Class<?> cSequences() {
return null;
}
@Override
protected DataType<?>[] getCastableDataTypes() {
return new DataType<?>[] {
FirebirdDataType.BIGINT,
- FirebirdDataType.BINARY,
- FirebirdDataType.BINARYLARGEOBJECT,
FirebirdDataType.BIT,
FirebirdDataType.BOOLEAN,
FirebirdDataType.CHAR,
FirebirdDataType.CHARACTER,
- FirebirdDataType.CHARACTERLARGEOBJECT,
FirebirdDataType.CHARACTERVARYING,
- FirebirdDataType.CHARLARGEOBJECT,
FirebirdDataType.DATE,
- FirebirdDataType.DATETIME,
FirebirdDataType.DECIMAL,
- FirebirdDataType.DOUBLE,
FirebirdDataType.DOUBLEPRECISION,
FirebirdDataType.FLOAT,
FirebirdDataType.INT,
FirebirdDataType.INTEGER,
- FirebirdDataType.LONGVARBINARY,
- FirebirdDataType.LONGVARCHAR,
FirebirdDataType.NUMERIC,
FirebirdDataType.OBJECT,
FirebirdDataType.OTHER,
- FirebirdDataType.REAL,
FirebirdDataType.SMALLINT,
FirebirdDataType.TIME,
FirebirdDataType.TIMESTAMP,
FirebirdDataType.TINYINT,
- FirebirdDataType.VARBINARY,
FirebirdDataType.VARCHAR,
FirebirdDataType.VARCHARIGNORECASE,
};
}
}
| false | true | protected DataType<?>[] getCastableDataTypes() {
return new DataType<?>[] {
FirebirdDataType.BIGINT,
FirebirdDataType.BINARY,
FirebirdDataType.BINARYLARGEOBJECT,
FirebirdDataType.BIT,
FirebirdDataType.BOOLEAN,
FirebirdDataType.CHAR,
FirebirdDataType.CHARACTER,
FirebirdDataType.CHARACTERLARGEOBJECT,
FirebirdDataType.CHARACTERVARYING,
FirebirdDataType.CHARLARGEOBJECT,
FirebirdDataType.DATE,
FirebirdDataType.DATETIME,
FirebirdDataType.DECIMAL,
FirebirdDataType.DOUBLE,
FirebirdDataType.DOUBLEPRECISION,
FirebirdDataType.FLOAT,
FirebirdDataType.INT,
FirebirdDataType.INTEGER,
FirebirdDataType.LONGVARBINARY,
FirebirdDataType.LONGVARCHAR,
FirebirdDataType.NUMERIC,
FirebirdDataType.OBJECT,
FirebirdDataType.OTHER,
FirebirdDataType.REAL,
FirebirdDataType.SMALLINT,
FirebirdDataType.TIME,
FirebirdDataType.TIMESTAMP,
FirebirdDataType.TINYINT,
FirebirdDataType.VARBINARY,
FirebirdDataType.VARCHAR,
FirebirdDataType.VARCHARIGNORECASE,
};
}
| protected DataType<?>[] getCastableDataTypes() {
return new DataType<?>[] {
FirebirdDataType.BIGINT,
FirebirdDataType.BIT,
FirebirdDataType.BOOLEAN,
FirebirdDataType.CHAR,
FirebirdDataType.CHARACTER,
FirebirdDataType.CHARACTERVARYING,
FirebirdDataType.DATE,
FirebirdDataType.DECIMAL,
FirebirdDataType.DOUBLEPRECISION,
FirebirdDataType.FLOAT,
FirebirdDataType.INT,
FirebirdDataType.INTEGER,
FirebirdDataType.NUMERIC,
FirebirdDataType.OBJECT,
FirebirdDataType.OTHER,
FirebirdDataType.SMALLINT,
FirebirdDataType.TIME,
FirebirdDataType.TIMESTAMP,
FirebirdDataType.TINYINT,
FirebirdDataType.VARCHAR,
FirebirdDataType.VARCHARIGNORECASE,
};
}
|
diff --git a/teamcity-gerrit-agent/src/com/maxifier/teamcity/gerrit/GerritBuildProcess.java b/teamcity-gerrit-agent/src/com/maxifier/teamcity/gerrit/GerritBuildProcess.java
index f4420d2..70ffe96 100644
--- a/teamcity-gerrit-agent/src/com/maxifier/teamcity/gerrit/GerritBuildProcess.java
+++ b/teamcity-gerrit-agent/src/com/maxifier/teamcity/gerrit/GerritBuildProcess.java
@@ -1,114 +1,114 @@
package com.maxifier.teamcity.gerrit;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.AgentRunningBuild;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.runner.BuildServiceAdapter;
import jetbrains.buildServer.agent.runner.ProgramCommandLine;
import jetbrains.buildServer.agent.runner.SimpleProgramCommandLine;
import jetbrains.buildServer.vcs.VcsRootEntry;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author [email protected] (Aleksey Didik)
*/
public class GerritBuildProcess extends BuildServiceAdapter implements AgentBuildRunnerInfo {
private final Map<AgentRunningBuild, BuildFinishedStatus> statuses;
private ProgramCommandLine programCommandLine;
public GerritBuildProcess(Map<AgentRunningBuild, BuildFinishedStatus> statuses) {
this.statuses = statuses;
}
@Override
public void afterInitialized() throws RunBuildException {
super.afterInitialized();
}
@Override
public void beforeProcessStarted() throws RunBuildException {
getLogger().progressStarted("Start Gerrit Verification");
BuildFinishedStatus previousStepStatus = statuses.get(getBuild());
if (previousStepStatus == null) {
throw new RunBuildException("Unable to recognize previous build steps result." +
" It should be at least one build step before Gerrit Verification Step used.");
}
String buildId = String.valueOf(getBuild().getBuildId());
String buildTypeId = getBuild().getBuildTypeId();
//get first available vcsRootEntry :(
List<VcsRootEntry> vcsRootEntries = getBuild().getVcsRootEntries();
if (vcsRootEntries.isEmpty()) {
throw new RunBuildException("VCS root is not defined for this build configuration.");
}
if (vcsRootEntries.size() > 1) {
throw new RunBuildException("More than one VCS root defined for this build," +
" but only one is supported by runner.");
}
VcsRootEntry vcsRootEntry = vcsRootEntries.get(0);
String patchSet = getBuild().getBuildCurrentVersion(vcsRootEntry.getVcsRoot());
String verified;
switch (previousStepStatus) {
case FINISHED_SUCCESS:
verified = "+1";
break;
case FINISHED_FAILED:
case FINISHED_WITH_PROBLEMS:
case INTERRUPTED:
verified = "-1";
break;
default:
verified = "-1";
}
String gerritHost = getRunnerParameters().get("gerritHost");
String gerritPort = getRunnerParameters().get("gerritPort");
String teamCityUrl = getAgentConfiguration().getServerUrl();
getLogger().progressMessage(String.format("Verify changes value: %s%n" +
"Patch set: %s%n" +
"Gerrit host: %s%n" +
"Gerrit port: %s%n" +
"TeamCity URL: %s",
verified, patchSet, gerritHost, gerritPort, teamCityUrl));
- String gerritCommand = String.format("\"gerrit verify --verified=%s" +
- " --message=%s/viewLog.html?buildId=%s&tab=buildResultsDiv&buildTypeId=%s %s\"",
+ String gerritCommand = String.format("gerrit verify --verified=%s" +
+ " --message=%s/viewLog.html?buildId=%s&tab=buildResultsDiv&buildTypeId=%s %s",
verified, teamCityUrl, buildId, buildTypeId, patchSet);
getLogger().progressMessage("Gerrit command: " + gerritCommand);
programCommandLine
= new SimpleProgramCommandLine(getRunnerContext(), "ssh",
Arrays.asList(gerritHost, "-p", gerritPort, "-t", gerritCommand));
}
@NotNull
@Override
public ProgramCommandLine makeProgramCommandLine() throws RunBuildException {
return programCommandLine;
}
@NotNull
@Override
public String getType() {
return "GerritVerification";
}
@Override
public boolean canRun(@NotNull BuildAgentConfiguration agentConfiguration) {
return true;
}
}
| true | true | public void beforeProcessStarted() throws RunBuildException {
getLogger().progressStarted("Start Gerrit Verification");
BuildFinishedStatus previousStepStatus = statuses.get(getBuild());
if (previousStepStatus == null) {
throw new RunBuildException("Unable to recognize previous build steps result." +
" It should be at least one build step before Gerrit Verification Step used.");
}
String buildId = String.valueOf(getBuild().getBuildId());
String buildTypeId = getBuild().getBuildTypeId();
//get first available vcsRootEntry :(
List<VcsRootEntry> vcsRootEntries = getBuild().getVcsRootEntries();
if (vcsRootEntries.isEmpty()) {
throw new RunBuildException("VCS root is not defined for this build configuration.");
}
if (vcsRootEntries.size() > 1) {
throw new RunBuildException("More than one VCS root defined for this build," +
" but only one is supported by runner.");
}
VcsRootEntry vcsRootEntry = vcsRootEntries.get(0);
String patchSet = getBuild().getBuildCurrentVersion(vcsRootEntry.getVcsRoot());
String verified;
switch (previousStepStatus) {
case FINISHED_SUCCESS:
verified = "+1";
break;
case FINISHED_FAILED:
case FINISHED_WITH_PROBLEMS:
case INTERRUPTED:
verified = "-1";
break;
default:
verified = "-1";
}
String gerritHost = getRunnerParameters().get("gerritHost");
String gerritPort = getRunnerParameters().get("gerritPort");
String teamCityUrl = getAgentConfiguration().getServerUrl();
getLogger().progressMessage(String.format("Verify changes value: %s%n" +
"Patch set: %s%n" +
"Gerrit host: %s%n" +
"Gerrit port: %s%n" +
"TeamCity URL: %s",
verified, patchSet, gerritHost, gerritPort, teamCityUrl));
String gerritCommand = String.format("\"gerrit verify --verified=%s" +
" --message=%s/viewLog.html?buildId=%s&tab=buildResultsDiv&buildTypeId=%s %s\"",
verified, teamCityUrl, buildId, buildTypeId, patchSet);
getLogger().progressMessage("Gerrit command: " + gerritCommand);
programCommandLine
= new SimpleProgramCommandLine(getRunnerContext(), "ssh",
Arrays.asList(gerritHost, "-p", gerritPort, "-t", gerritCommand));
}
| public void beforeProcessStarted() throws RunBuildException {
getLogger().progressStarted("Start Gerrit Verification");
BuildFinishedStatus previousStepStatus = statuses.get(getBuild());
if (previousStepStatus == null) {
throw new RunBuildException("Unable to recognize previous build steps result." +
" It should be at least one build step before Gerrit Verification Step used.");
}
String buildId = String.valueOf(getBuild().getBuildId());
String buildTypeId = getBuild().getBuildTypeId();
//get first available vcsRootEntry :(
List<VcsRootEntry> vcsRootEntries = getBuild().getVcsRootEntries();
if (vcsRootEntries.isEmpty()) {
throw new RunBuildException("VCS root is not defined for this build configuration.");
}
if (vcsRootEntries.size() > 1) {
throw new RunBuildException("More than one VCS root defined for this build," +
" but only one is supported by runner.");
}
VcsRootEntry vcsRootEntry = vcsRootEntries.get(0);
String patchSet = getBuild().getBuildCurrentVersion(vcsRootEntry.getVcsRoot());
String verified;
switch (previousStepStatus) {
case FINISHED_SUCCESS:
verified = "+1";
break;
case FINISHED_FAILED:
case FINISHED_WITH_PROBLEMS:
case INTERRUPTED:
verified = "-1";
break;
default:
verified = "-1";
}
String gerritHost = getRunnerParameters().get("gerritHost");
String gerritPort = getRunnerParameters().get("gerritPort");
String teamCityUrl = getAgentConfiguration().getServerUrl();
getLogger().progressMessage(String.format("Verify changes value: %s%n" +
"Patch set: %s%n" +
"Gerrit host: %s%n" +
"Gerrit port: %s%n" +
"TeamCity URL: %s",
verified, patchSet, gerritHost, gerritPort, teamCityUrl));
String gerritCommand = String.format("gerrit verify --verified=%s" +
" --message=%s/viewLog.html?buildId=%s&tab=buildResultsDiv&buildTypeId=%s %s",
verified, teamCityUrl, buildId, buildTypeId, patchSet);
getLogger().progressMessage("Gerrit command: " + gerritCommand);
programCommandLine
= new SimpleProgramCommandLine(getRunnerContext(), "ssh",
Arrays.asList(gerritHost, "-p", gerritPort, "-t", gerritCommand));
}
|
diff --git a/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java b/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
index 6bd12238..af368d80 100644
--- a/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
+++ b/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
@@ -1,132 +1,132 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.nuget.server.toolRegistry.ui;
import jetbrains.buildServer.controllers.BaseController;
import jetbrains.buildServer.controllers.BasePropertiesBean;
import jetbrains.buildServer.nuget.server.settings.SettingsSection;
import jetbrains.buildServer.nuget.server.settings.tab.ServerSettingsTab;
import jetbrains.buildServer.nuget.server.toolRegistry.NuGetInstalledTool;
import jetbrains.buildServer.nuget.server.toolRegistry.NuGetToolManager;
import jetbrains.buildServer.nuget.server.toolRegistry.tab.InstalledToolsController;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by Eugene Petrenko ([email protected])
* Date: 16.08.11 10:21
*/
public class ToolSelectorController extends BaseController {
private final NuGetToolManager myToolManager;
private final PluginDescriptor myDescriptor;
private final String myPath;
public ToolSelectorController(@NotNull final NuGetToolManager toolManager,
@NotNull final PluginDescriptor descriptor,
@NotNull final WebControllerManager web) {
myToolManager = toolManager;
myDescriptor = descriptor;
myPath = descriptor.getPluginResourcesPath("tool/runnerSettings.html");
web.registerController(myPath, this);
}
@NotNull
public String getPath() {
return myPath;
}
@Override
protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
- mv.getModel().put("settingsUrl", "/admin/admin.html?init=1§ion=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
+ mv.getModel().put("settingsUrl", "/admin/admin.html?init=1&item=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
@Nullable
private ToolInfo ensureVersion(@NotNull final String version, @NotNull Collection<ToolInfo> actionInfos) {
if (!version.startsWith("?")) return null;
for (ToolInfo actionInfo : actionInfos) {
if (actionInfo.getId().equals(version)) return actionInfo;
}
final ToolInfo notInstalled = new ToolInfo(version, "Not Installed: " + version.substring(1));
actionInfos.add(notInstalled);
return notInstalled;
}
@NotNull
private Collection<ToolInfo> getTools() {
final ArrayList<ToolInfo> result = new ArrayList<ToolInfo>();
for (NuGetInstalledTool nuGetInstalledTool : myToolManager.getInstalledTools()) {
result.add(new ToolInfo(nuGetInstalledTool));
}
return result;
}
private static String safe(@Nullable String s) {
if (StringUtil.isEmptyOrSpaces(s)) return "";
return s;
}
@NotNull
private String parseValue(HttpServletRequest request, final String requestName, String propertyName) {
String value = null;
final BasePropertiesBean bean = (BasePropertiesBean)request.getAttribute("propertiesBean");
if (bean != null) {
value = bean.getProperties().get(propertyName);
}
if (value == null) {
value = request.getParameter(requestName);
}
if (value == null) {
value = "";
}
return value;
}
}
| true | true | protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
mv.getModel().put("settingsUrl", "/admin/admin.html?init=1§ion=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
| protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
mv.getModel().put("settingsUrl", "/admin/admin.html?init=1&item=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
|
diff --git a/srcj/com/sun/electric/database/Environment.java b/srcj/com/sun/electric/database/Environment.java
index 5940ebebf..27d9d1cb2 100644
--- a/srcj/com/sun/electric/database/Environment.java
+++ b/srcj/com/sun/electric/database/Environment.java
@@ -1,374 +1,371 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Environment.java
* Written by: Dmitry Nadezhin, Sun Microsystems.
*
* Copyright (c) 2009 Sun Microsystems and Static Free Software
*
* Electric(tm) 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
* (at your option) any later version.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.database;
import com.sun.electric.database.id.IdManager;
import com.sun.electric.database.id.IdReader;
import com.sun.electric.database.id.IdWriter;
import com.sun.electric.database.text.Pref;
import com.sun.electric.database.text.Setting;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.TechFactory;
import com.sun.electric.technology.TechPool;
import com.sun.electric.technology.Technology;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;
/**
* Immutable class to represent Database environment
*/
public class Environment {
private static final ThreadLocal<Environment> threadEnvironment = new ThreadLocal<Environment>();
public final Setting.RootGroup toolSettings;
public final TechPool techPool;
private final HashMap<Setting, Object> rawSettingValues;
public final Map<Setting, Object> settingValues;
public Environment(IdManager idManager) {
this(Setting.RootGroup.newEmptyGroup(), idManager.getInitialTechPool(), new HashMap<Setting, Object>());
}
private Environment(Setting.RootGroup toolSettings, TechPool techPool, HashMap<Setting, Object> rawSettingValues) {
this.toolSettings = toolSettings;
this.techPool = techPool;
this.rawSettingValues = rawSettingValues;
settingValues = Collections.unmodifiableMap(rawSettingValues);
check();
}
public static Environment getThreadEnvironment() {
return threadEnvironment.get();
}
public static Environment setThreadEnvironment(Environment environment) {
Environment oldEnvironment = threadEnvironment.get();
threadEnvironment.set(environment);
return oldEnvironment;
}
/** Returns map from Setting to its value in this Snapshot */
public Map<Setting, Object> getSettings() {
return settingValues;
}
public Object getValue(Setting setting) {
return rawSettingValues.get(setting);
}
public void activate() {
techPool.activate();
setThreadEnvironment(this);
}
public boolean isActive() {
if (!techPool.isActive()) {
return false;
}
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting setting = e.getKey();
Object value = e.getValue();
if (setting.getValue() != value) {
return false;
}
}
return true;
}
private Environment with(Setting.RootGroup toolSettings, TechPool techPool, Map<Setting, Object> settingValues) {
if (this.techPool == techPool && this.toolSettings == toolSettings && this.settingValues.equals(settingValues)) {
return this;
}
HashMap<Setting, Object> rawSettingValues = new HashMap<Setting, Object>(settingValues);
return new Environment(toolSettings, techPool, rawSettingValues);
}
public Environment withToolSettings(Setting.RootGroup toolSettings) {
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>(settingValues);
for (Setting setting : this.toolSettings.getSettings()) {
newSettingValues.remove(setting);
}
for (Setting setting : toolSettings.getSettings()) {
newSettingValues.put(setting, setting.getFactoryValue());
}
return with(toolSettings, this.techPool, newSettingValues);
}
public Environment addTech(Technology tech) {
if (techPool.getTech(tech.getId()) != null) {
throw new IllegalArgumentException();
}
TechPool newTechPool = techPool.withTech(tech);
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>(settingValues);
for (Setting setting : tech.getProjectSettings().getSettings()) {
newSettingValues.put(setting, setting.getFactoryValue());
}
for (Map.Entry<TechFactory.Param, Object> e : tech.getCurrentState().paramValues.entrySet()) {
TechFactory.Param param = e.getKey();
newSettingValues.put(tech.getSetting(param), e.getValue());
}
return with(toolSettings, newTechPool, newSettingValues);
}
public Environment withSettingChanges(Setting.SettingChangeBatch changeBatch) {
// Look for tech param changes
Map<TechFactory.Param, Object> techParams = techPool.getTechParams();
- boolean changed = false;
for (Map.Entry<TechFactory.Param, Object> e : techParams.entrySet()) {
TechFactory.Param param = e.getKey();
Object oldValue = e.getValue();
String xmlPath = param.xmlPath;
if (!changeBatch.changesForSettings.containsKey(xmlPath)) {
continue;
}
Object newValue = changeBatch.changesForSettings.get(xmlPath);
if (newValue == null) {
newValue = param.factoryValue;
}
if (newValue.equals(oldValue)) {
continue;
}
if (newValue.getClass() != oldValue.getClass()) {
continue;
}
- changed = true;
techParams.put(param, newValue);
}
TechPool newTechPool = techPool.withTechParams(techParams);
- assert (newTechPool != techPool) == changed;
// Gather by xmlPath
HashMap<String, Object> valuesByXmlPath = new HashMap<String, Object>();
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting oldSetting = e.getKey();
String xmlPath = oldSetting.getXmlPath();
Object value = e.getValue();
if (changeBatch.changesForSettings.containsKey(xmlPath)) {
value = changeBatch.changesForSettings.get(xmlPath);
}
valuesByXmlPath.put(xmlPath, value);
}
for (Map.Entry<TechFactory.Param, Object> e : newTechPool.getTechParams().entrySet()) {
TechFactory.Param param = e.getKey();
valuesByXmlPath.put(param.xmlPath, e.getValue());
}
// Prepare new Setting Values
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>();
for (Setting setting : toolSettings.getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
}
return with(toolSettings, newTechPool, newSettingValues);
}
public Environment deepClone() {
TechPool newTechPool = techPool.deepClone();
HashMap<String, Object> oldSettingsByXmlPath = new HashMap<String, Object>();
for (Setting setting : toolSettings.getSettings()) {
oldSettingsByXmlPath.put(setting.getXmlPath(), setting);
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
oldSettingsByXmlPath.put(setting.getXmlPath(), setting);
}
}
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>();
for (Setting setting : toolSettings.getSettings()) {
newSettingValues.put(setting, settingValues.get(setting));
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
Object oldSetting = oldSettingsByXmlPath.get(setting.getXmlPath());
Object value = settingValues.get(oldSetting);
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass()) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
}
return new Environment(toolSettings, newTechPool, newSettingValues);
}
public void saveToPreferences() {
saveToPreferences(Pref.getPrefRoot());
}
public void saveToPreferences(Preferences prefs) {
for (Map.Entry<Setting, Object> e : getSettings().entrySet()) {
Setting setting = e.getKey();
setting.saveToPreferences(prefs, e.getValue());
}
Pref.flushAll();
}
/**
* Writes this Environment to IdWriter
* @param writer IdWriter
* @param old old Environment
* @throws java.io.IOException
*/
public void writeDiff(IdWriter writer, Environment old) throws IOException {
boolean changed = this != old;
writer.writeBoolean(changed);
if (!changed) {
return;
}
boolean techPoolChanged = techPool != old.techPool;
writer.writeBoolean(techPoolChanged);
if (techPoolChanged) {
techPool.writeDiff(writer, old.techPool);
}
boolean toolSettingsChanged = toolSettings != old.toolSettings;
writer.writeBoolean(toolSettingsChanged);
if (toolSettingsChanged) {
toolSettings.write(writer);
}
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting setting = e.getKey();
Object value = e.getValue();
Object oldValue = old.settingValues.get(setting);
if (oldValue == null) {
oldValue = setting.getFactoryValue();
}
if (value.equals(oldValue)) {
continue;
}
writer.writeString(setting.getXmlPath());
Variable.writeObject(writer, value);
}
writer.writeString("");
}
public static Environment readEnvironment(IdReader reader, Environment old) throws IOException {
boolean changed = reader.readBoolean();
if (!changed) {
return old;
}
TechPool techPool = old.techPool;
boolean techPoolChanged = reader.readBoolean();
if (techPoolChanged) {
techPool = TechPool.read(reader, old.techPool);
}
Setting.RootGroup toolSettings = old.toolSettings;
boolean toolSettingsChanged = reader.readBoolean();
if (toolSettingsChanged) {
toolSettings = Setting.read(reader);
}
HashMap<String, Setting> settingsByXmlPath = new HashMap<String, Setting>();
for (Setting setting : toolSettings.getSettings()) {
settingsByXmlPath.put(setting.getXmlPath(), setting);
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
settingsByXmlPath.put(setting.getXmlPath(), setting);
}
}
HashMap<Setting, Object> settingValues = new HashMap<Setting, Object>();
for (Setting setting : settingsByXmlPath.values()) {
Object value = old.settingValues.get(setting);
if (value == null) {
value = setting.getFactoryValue();
}
settingValues.put(setting, value);
}
for (;;) {
String xmlPath = reader.readString();
if (xmlPath.length() == 0) {
break;
}
Object value = Variable.readObject(reader);
Setting setting = settingsByXmlPath.get(xmlPath);
settingValues.put(setting, value);
}
return new Environment(toolSettings, techPool, settingValues);
}
public void check() {
if (!toolSettings.isLocked()) {
throw new IllegalArgumentException("Tool Settings are not locked");
}
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting setting = e.getKey();
Object value = e.getValue();
if (value.getClass() != setting.getFactoryValue().getClass()) {
throw new IllegalArgumentException("Setting " + setting.getXmlPath() + " has bad value " + value);
}
}
HashMap<String, Object> xmlPaths = new HashMap<String, Object>();
checkSettings(toolSettings, settingValues, xmlPaths);
for (Technology tech : techPool.values()) {
Setting.RootGroup techSettings = tech.getProjectSettingsRoot();
checkSettings(techSettings, settingValues, xmlPaths);
}
if (xmlPaths.size() != settingValues.size()) {
throw new IllegalArgumentException("Setting count");
}
for (Map.Entry<TechFactory.Param, Object> e : techPool.getTechParams().entrySet()) {
TechFactory.Param param = e.getKey();
Object value = xmlPaths.get(param.xmlPath);
if (!value.equals(e.getValue())) {
throw new IllegalArgumentException("TechParam mismatch");
}
}
}
private static void checkSettings(Setting.RootGroup settings, Map<Setting, Object> settingValues, HashMap<String, Object> xmlPaths) {
for (Setting setting : settings.getSettings()) {
String xmlPath = setting.getXmlPath();
if (xmlPath.length() == 0) {
throw new IllegalArgumentException("Empty xmlPath");
}
Object value = settingValues.get(setting);
if (value.getClass() != setting.getFactoryValue().getClass()) {
throw new IllegalArgumentException("Type mismatch " + setting);
}
Object oldValue = xmlPaths.put(xmlPath, value);
if (oldValue != null) {
throw new IllegalArgumentException("Dupilcate xmlPath " + xmlPath);
}
}
}
}
| false | true | public Environment withSettingChanges(Setting.SettingChangeBatch changeBatch) {
// Look for tech param changes
Map<TechFactory.Param, Object> techParams = techPool.getTechParams();
boolean changed = false;
for (Map.Entry<TechFactory.Param, Object> e : techParams.entrySet()) {
TechFactory.Param param = e.getKey();
Object oldValue = e.getValue();
String xmlPath = param.xmlPath;
if (!changeBatch.changesForSettings.containsKey(xmlPath)) {
continue;
}
Object newValue = changeBatch.changesForSettings.get(xmlPath);
if (newValue == null) {
newValue = param.factoryValue;
}
if (newValue.equals(oldValue)) {
continue;
}
if (newValue.getClass() != oldValue.getClass()) {
continue;
}
changed = true;
techParams.put(param, newValue);
}
TechPool newTechPool = techPool.withTechParams(techParams);
assert (newTechPool != techPool) == changed;
// Gather by xmlPath
HashMap<String, Object> valuesByXmlPath = new HashMap<String, Object>();
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting oldSetting = e.getKey();
String xmlPath = oldSetting.getXmlPath();
Object value = e.getValue();
if (changeBatch.changesForSettings.containsKey(xmlPath)) {
value = changeBatch.changesForSettings.get(xmlPath);
}
valuesByXmlPath.put(xmlPath, value);
}
for (Map.Entry<TechFactory.Param, Object> e : newTechPool.getTechParams().entrySet()) {
TechFactory.Param param = e.getKey();
valuesByXmlPath.put(param.xmlPath, e.getValue());
}
// Prepare new Setting Values
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>();
for (Setting setting : toolSettings.getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
}
return with(toolSettings, newTechPool, newSettingValues);
}
| public Environment withSettingChanges(Setting.SettingChangeBatch changeBatch) {
// Look for tech param changes
Map<TechFactory.Param, Object> techParams = techPool.getTechParams();
for (Map.Entry<TechFactory.Param, Object> e : techParams.entrySet()) {
TechFactory.Param param = e.getKey();
Object oldValue = e.getValue();
String xmlPath = param.xmlPath;
if (!changeBatch.changesForSettings.containsKey(xmlPath)) {
continue;
}
Object newValue = changeBatch.changesForSettings.get(xmlPath);
if (newValue == null) {
newValue = param.factoryValue;
}
if (newValue.equals(oldValue)) {
continue;
}
if (newValue.getClass() != oldValue.getClass()) {
continue;
}
techParams.put(param, newValue);
}
TechPool newTechPool = techPool.withTechParams(techParams);
// Gather by xmlPath
HashMap<String, Object> valuesByXmlPath = new HashMap<String, Object>();
for (Map.Entry<Setting, Object> e : settingValues.entrySet()) {
Setting oldSetting = e.getKey();
String xmlPath = oldSetting.getXmlPath();
Object value = e.getValue();
if (changeBatch.changesForSettings.containsKey(xmlPath)) {
value = changeBatch.changesForSettings.get(xmlPath);
}
valuesByXmlPath.put(xmlPath, value);
}
for (Map.Entry<TechFactory.Param, Object> e : newTechPool.getTechParams().entrySet()) {
TechFactory.Param param = e.getKey();
valuesByXmlPath.put(param.xmlPath, e.getValue());
}
// Prepare new Setting Values
HashMap<Setting, Object> newSettingValues = new HashMap<Setting, Object>();
for (Setting setting : toolSettings.getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
for (Technology tech : techPool.values()) {
for (Setting setting : tech.getProjectSettings().getSettings()) {
Object value = valuesByXmlPath.get(setting.getXmlPath());
Object factoryValue = setting.getFactoryValue();
if (value == null || value.getClass() != factoryValue.getClass() || value.equals(factoryValue)) {
value = factoryValue;
}
newSettingValues.put(setting, value);
}
}
return with(toolSettings, newTechPool, newSettingValues);
}
|
diff --git a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
index 4cc454e92..6d716e757 100644
--- a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
+++ b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
@@ -1,355 +1,358 @@
// Copyright (2007) Schibsted Søk AS
/*
* NavigatatableAdvancedFastSearchCommand.java
*
* Created on July 20, 2006, 11:57 AM
*
*/
package no.schibstedsok.searchportal.mode.command;
import com.fastsearch.esp.search.result.IModifier;
import com.fastsearch.esp.search.result.INavigator;
import com.fastsearch.esp.search.result.IQueryResult;
import no.schibstedsok.searchportal.mode.config.NavigatableEspFastCommandConfig;
import no.schibstedsok.searchportal.result.FastSearchResult;
import no.schibstedsok.searchportal.result.Modifier;
import no.schibstedsok.searchportal.result.Navigator;
import no.schibstedsok.searchportal.result.SearchResult;
import no.schibstedsok.searchportal.util.Channels;
import no.schibstedsok.searchportal.util.ModifierDateComparator;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This class provies an advanced fast search command with navigation
* capabilities.
*
* @author maek
*/
public class NavigatableESPFastCommand extends ESPFastSearchCommand {
// Attributes ----------------------------------------------------
private final Map<String, Navigator> navigatedTo = new HashMap<String, Navigator>();
private final Map<String, String[]> navigatedValues = new HashMap<String, String[]>();
public NavigatableESPFastCommand(final Context cxt) {
super(cxt);
}
public Collection createNavigationFilterStrings() {
final Collection<String> filterStrings = new ArrayList<String>();
for (String field : navigatedValues.keySet()) {
final String modifiers[] = navigatedValues.get(field);
for (String modifier : modifiers) {
if (!field.equals("contentsource") || !modifier.equals("Norske nyheter"))
filterStrings.add("+" + field + ":\"" + modifier + "\"");
}
}
return filterStrings;
}
public SearchResult execute() {
if (getNavigators() != null) {
for (String navigatorKey : getNavigators().keySet()) {
addNavigatedTo(navigatorKey, getParameters().containsKey("nav_" + navigatorKey)
? getParameter("nav_" + navigatorKey)
: null);
}
}
final FastSearchResult searchResult = (FastSearchResult) super.execute();
if (getNavigators() != null) {
collectModifiers(getIQueryResult(), searchResult);
}
return searchResult;
}
public Map getOtherNavigators(final String navigatorKey) {
final Map<String, String> otherNavigators = new HashMap<String, String>();
for (String parameterName : getParameters().keySet()) {
if (parameterName.startsWith("nav_") && !parameterName.substring(parameterName.indexOf('_') + 1).equals(navigatorKey)) {
final String paramValue = getParameter(parameterName);
otherNavigators.put(parameterName.substring(parameterName.indexOf('_') + 1), paramValue);
}
}
return otherNavigators;
}
public void addNavigatedTo(final String navigatorKey, final String navigatorName) {
final Navigator navigator = getNavigators().get(navigatorKey);
if (navigatorName == null) {
navigatedTo.put(navigatorKey, navigator);
} else {
navigatedTo.put(navigatorKey, findChildNavigator(navigator, navigatorName));
}
}
public Navigator getNavigatedTo(final String navigatorKey) {
return navigatedTo.get(navigatorKey);
}
public Navigator getParentNavigator(final String navigatorKey) {
if (getParameters().containsKey("nav_" + navigatorKey)) {
final String navName = getParameter("nav_" + navigatorKey);
return findParentNavigator(getNavigators().get(navigatorKey), navName);
} else {
return null;
}
}
public Navigator getParentNavigator(final String navigatorKey, final String name) {
if (getParameters().containsKey("nav_" + navigatorKey)) {
return findParentNavigator(getNavigators().get(navigatorKey), name);
} else {
return null;
}
}
public Navigator findParentNavigator(final Navigator navigator, final String navigatorName) {
if (navigator.getChildNavigator() == null) {
return null;
} else if (navigator.getChildNavigator().getName().equals(navigatorName)) {
return navigator;
} else {
return findParentNavigator(navigator.getChildNavigator(), navigatorName);
}
}
public Map getNavigatedValues() {
return navigatedValues;
}
public String getNavigatedValue(final String fieldName) {
final String[] singleValue = navigatedValues.get(fieldName);
if (singleValue != null) {
return (singleValue[0]);
} else {
return null;
}
}
public boolean isTopLevelNavigator(final String navigatorKey) {
return !getParameters().containsKey("nav_" + navigatorKey);
}
public Map getNavigatedTo() {
return navigatedTo;
}
public String getNavigatorTitle(final String navigatorKey) {
final Navigator nav = getNavigatedTo(navigatorKey);
Navigator parent = findParentNavigator(getNavigators().get(navigatorKey), nav.getName());
String value = getNavigatedValue(nav.getField());
if (value == null && parent != null) {
value = getNavigatedValue(parent.getField());
if (value == null) {
parent = findParentNavigator(getNavigators().get(navigatorKey), parent.getName());
if (parent != null) {
value = getNavigatedValue(parent.getField());
}
return value;
} else {
return value;
}
}
if (value == null) {
return nav.getDisplayName();
} else {
return value;
}
}
public String getNavigatorTitle(final Navigator navigator) {
final String value = getNavigatedValue(navigator.getField());
if (value == null) {
return navigator.getDisplayName();
} else {
return value;
}
}
/**
* Assured associated search configuration will always be of this type. *
*/
public NavigatableEspFastCommandConfig getSearchConfiguration() {
return (NavigatableEspFastCommandConfig) super.getSearchConfiguration();
}
public List getNavigatorBackLinks(final String navigatorKey) {
final List backLinks = addNavigatorBackLinks(getSearchConfiguration().getNavigator(navigatorKey), new ArrayList<Navigator>(), navigatorKey);
if (backLinks.size() > 0) {
backLinks.remove(backLinks.size() - 1);
}
return backLinks;
}
public List<Navigator> addNavigatorBackLinks(final Navigator navigator, final List<Navigator> links, final String navigatorKey) {
final String a = getParameter(navigator.getField());
if (a != null) {
if (!(navigator.getName().equals("ywfylkesnavigator") && a.equals("Oslo"))) {
if (!(navigator.getName().equals("ywkommunenavigator") && a.equals("Oslo"))) {
links.add(navigator);
}
}
}
if (navigator.getChildNavigator() != null) {
final String n = getParameter("nav_" + navigatorKey);
if (n != null && navigator.getName().equals(n)) {
return links;
}
addNavigatorBackLinks(navigator.getChildNavigator(), links, navigatorKey);
}
return links;
}
protected Map<String, Navigator> getNavigators() {
return getSearchConfiguration().getNavigators();
}
private void collectModifiers(IQueryResult result, FastSearchResult searchResult) {
for (String navigatorKey : navigatedTo.keySet()) {
collectModifier(navigatorKey, result, searchResult);
}
}
private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
+ INavigator navigator = null;
- INavigator navigator = result.getNavigator(nav.getName());
+ if (result != null) {
+ navigator = result.getNavigator(nav.getName());
+ }
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
case YEAR_MONTH:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
private Navigator findChildNavigator(Navigator nav, String nameToFind) {
if (getParameters().containsKey(nav.getField())) {
navigatedValues.put(nav.getField(), getParameters().get(nav.getField()) instanceof String[]
? (String[]) getParameters().get(nav.getField())
: new String[]{getParameter(nav.getField())});
}
if (nav.getName().equals(nameToFind)) {
if (nav.getChildNavigator() != null) {
return nav.getChildNavigator();
} else {
return nav;
}
}
if (nav.getChildNavigator() == null) {
throw new RuntimeException("Navigator " + nameToFind + " not found.");
}
return findChildNavigator(nav.getChildNavigator(), nameToFind);
}
protected String getAdditionalFilter() {
final Collection navStrings = createNavigationFilterStrings();
if (getNavigators() != null) {
return StringUtils.join(navStrings.iterator(), " ");
} else {
return null;
}
}
}
| false | true | private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
INavigator navigator = result.getNavigator(nav.getName());
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
case YEAR_MONTH:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
| private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
INavigator navigator = null;
if (result != null) {
navigator = result.getNavigator(nav.getName());
}
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
case YEAR_MONTH:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
|
diff --git a/appsolut/src/com/appsolut/composition/pitch_detection/MidiGenerator.java b/appsolut/src/com/appsolut/composition/pitch_detection/MidiGenerator.java
index b29bf29..95543da 100644
--- a/appsolut/src/com/appsolut/composition/pitch_detection/MidiGenerator.java
+++ b/appsolut/src/com/appsolut/composition/pitch_detection/MidiGenerator.java
@@ -1,107 +1,107 @@
package com.appsolut.composition.pitch_detection;
import java.util.ArrayList;
import java.util.Arrays;
import com.leff.midi.MidiFile;
import com.leff.midi.MidiTrack;
import com.leff.midi.event.meta.Tempo;
import com.leff.midi.event.meta.TimeSignature;
import java.nio.DoubleBuffer;
import java.io.DataInputStream;
import java.io.IOException;
public class MidiGenerator {
private static final String TAG = "FreqList";//Do not put useless names on things
private final static int DEFAULT_CLIP_RATE = 5;//Number of frequencies/second
private int bpm;
private int ppq = 192;
private static final int OFF_VAL = -1;
// MIDI resources
private MidiFile midiFile;
private MidiTrack tempoTrack;
private MidiTrack noteTrack;
public MidiGenerator(int _bpm) {
// MIDI Instantiation
midiFile = new MidiFile(MidiFile.DEFAULT_RESOLUTION);
tempoTrack = new MidiTrack();
noteTrack = new MidiTrack();
bpm=_bpm;
// Tempo track
TimeSignature ts = new TimeSignature();
ts.setTimeSignature(4, 4, TimeSignature.DEFAULT_METER, TimeSignature.DEFAULT_DIVISION);
Tempo t = new Tempo();
t.setBpm(_bpm);
tempoTrack.insertEvent(ts);
tempoTrack.insertEvent(t);
midiFile.addTrack(tempoTrack);
}
public MidiFile generateMidi(DataInputStream audio_stream, long sampleRate) throws IOException {
return generateMidi(audio_stream,sampleRate,DEFAULT_CLIP_RATE);
}
/**
* Taking the output from getMidiNumsWithTicks schedules midi events and produces a midi file
*
* @param audio The audio to be converted to midi
* @param sampleRate The sample rate the audio was recorded at
* @param clipRate The number of frequencies found in the audio per second
* @return
* @throws IOException
*/
public MidiFile generateMidi(DataInputStream audio_stream, long sampleRate, int clipRate) throws IOException{
ArrayList<Integer> midiNums = new ArrayList<Integer>();
ArrayList<Long> durations = new ArrayList<Long>();
double[] audio = new double[16384];
int slide = 2048;
int start=slide;
AudioAnalyser aa = new AudioAnalyser(bpm,ppq,sampleRate,clipRate);
Pair<Integer[],Long[]> analysedAudio = new Pair<Integer[],Long[]>();
double readVal = audio_stream.readDouble();
- while(readVal != -1){
+ while(readVal > .00001){
if(audio[0] < .00001){
start = 0;
}
- for(int i=slide;i<audio.length && readVal != -1;i++){
+ for(int i=slide;i<audio.length && readVal > .00001;i++){
audio[i] = readVal;
readVal = audio_stream.readDouble();
}
start = slide;
analysedAudio = aa.analyseAudio(audio);
for(int i=0;i<audio.length;i++){
if(i<slide){
audio[i] = audio[audio.length-slide+i];
}else{
audio[i] = 0;
}
}
}
midiNums.addAll(Arrays.asList(analysedAudio.left));
durations.addAll(Arrays.asList(analysedAudio.right));
long onTick = 0;
int midiNum = OFF_VAL;
for(int i=0;i<midiNums.size();i++){
midiNum = midiNums.get(i);
if(midiNum != OFF_VAL){
noteTrack.insertNote(0, midiNum, 127, onTick,durations.get(i));
}
onTick += durations.get(i);
}
midiFile.addTrack(noteTrack);
return midiFile;
}
}
| false | true | public MidiFile generateMidi(DataInputStream audio_stream, long sampleRate, int clipRate) throws IOException{
ArrayList<Integer> midiNums = new ArrayList<Integer>();
ArrayList<Long> durations = new ArrayList<Long>();
double[] audio = new double[16384];
int slide = 2048;
int start=slide;
AudioAnalyser aa = new AudioAnalyser(bpm,ppq,sampleRate,clipRate);
Pair<Integer[],Long[]> analysedAudio = new Pair<Integer[],Long[]>();
double readVal = audio_stream.readDouble();
while(readVal != -1){
if(audio[0] < .00001){
start = 0;
}
for(int i=slide;i<audio.length && readVal != -1;i++){
audio[i] = readVal;
readVal = audio_stream.readDouble();
}
start = slide;
analysedAudio = aa.analyseAudio(audio);
for(int i=0;i<audio.length;i++){
if(i<slide){
audio[i] = audio[audio.length-slide+i];
}else{
audio[i] = 0;
}
}
}
midiNums.addAll(Arrays.asList(analysedAudio.left));
durations.addAll(Arrays.asList(analysedAudio.right));
long onTick = 0;
int midiNum = OFF_VAL;
for(int i=0;i<midiNums.size();i++){
midiNum = midiNums.get(i);
if(midiNum != OFF_VAL){
noteTrack.insertNote(0, midiNum, 127, onTick,durations.get(i));
}
onTick += durations.get(i);
}
midiFile.addTrack(noteTrack);
return midiFile;
}
| public MidiFile generateMidi(DataInputStream audio_stream, long sampleRate, int clipRate) throws IOException{
ArrayList<Integer> midiNums = new ArrayList<Integer>();
ArrayList<Long> durations = new ArrayList<Long>();
double[] audio = new double[16384];
int slide = 2048;
int start=slide;
AudioAnalyser aa = new AudioAnalyser(bpm,ppq,sampleRate,clipRate);
Pair<Integer[],Long[]> analysedAudio = new Pair<Integer[],Long[]>();
double readVal = audio_stream.readDouble();
while(readVal > .00001){
if(audio[0] < .00001){
start = 0;
}
for(int i=slide;i<audio.length && readVal > .00001;i++){
audio[i] = readVal;
readVal = audio_stream.readDouble();
}
start = slide;
analysedAudio = aa.analyseAudio(audio);
for(int i=0;i<audio.length;i++){
if(i<slide){
audio[i] = audio[audio.length-slide+i];
}else{
audio[i] = 0;
}
}
}
midiNums.addAll(Arrays.asList(analysedAudio.left));
durations.addAll(Arrays.asList(analysedAudio.right));
long onTick = 0;
int midiNum = OFF_VAL;
for(int i=0;i<midiNums.size();i++){
midiNum = midiNums.get(i);
if(midiNum != OFF_VAL){
noteTrack.insertNote(0, midiNum, 127, onTick,durations.get(i));
}
onTick += durations.get(i);
}
midiFile.addTrack(noteTrack);
return midiFile;
}
|
diff --git a/org.eclipse.jubula.rc.common/src/org/eclipse/jubula/rc/common/classloader/ImplClassClassLoader.java b/org.eclipse.jubula.rc.common/src/org/eclipse/jubula/rc/common/classloader/ImplClassClassLoader.java
index ebe444896..f3becedbe 100644
--- a/org.eclipse.jubula.rc.common/src/org/eclipse/jubula/rc/common/classloader/ImplClassClassLoader.java
+++ b/org.eclipse.jubula.rc.common/src/org/eclipse/jubula/rc/common/classloader/ImplClassClassLoader.java
@@ -1,108 +1,110 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* 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:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.rc.common.classloader;
import java.net.URLClassLoader;
import org.eclipse.jubula.tools.constants.CommandConstants;
/**
* This Classloader tries to load the classes with the given ClassLoaders.
* {@inheritDoc}
*
* @author BREDEX GmbH
* @created 04.05.2006
*/
public class ImplClassClassLoader extends JBUrlClassLoader {
/** The alternative ClassLoader*/
private ClassLoader m_componentCL;
/**
* Constructor.
* @param autServerCL the ClassLoader of the AUT-Server
* @param componentCL ClassLoader of the componentCL
*/
public ImplClassClassLoader(URLClassLoader autServerCL,
ClassLoader componentCL) {
super(autServerCL.getURLs(), autServerCL);
m_componentCL = componentCL;
}
/**
*
* {@inheritDoc}
* @param name
* @param resolve
* @return
* @throws ClassNotFoundException
*/
protected synchronized Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c = null;
// in case of c is an ImplClass
- if (name.startsWith(CommandConstants.SWING_IMPLCLASS_PACKAGE)
+ if ((name.indexOf("tester.adapter.") == -1) //$NON-NLS-1$
+ && (name.startsWith(CommandConstants.SWING_IMPLCLASS_PACKAGE)
|| name.startsWith(CommandConstants.SWT_IMPLCLASSES_PACKAGE)
|| (name.indexOf(CommandConstants.JUBULA_EXTENSION_PACKAGE)
- != -1)) {
+ != -1)
+ )) {
return implLoadClass(name, resolve);
}
try {
// in case of any other class not involved with ImplClasses
c = super.getParent().loadClass(name);
} catch (ClassNotFoundException e) {
// e.g. in case of special AUT-component used in ImplClasses
c = implLoadClass(name, resolve);
}
return c;
}
/**
* Tries to load the classes with this ClassLoader and then, if not
* successfull, with the alternative ClassLoader.
* @param name name
* @param resolve resolve
* @return Class
* @throws ClassNotFoundException ClassNotFoundException
*/
private Class implLoadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c = null;
try {
// first try with parent
c = super.loadClass(name, resolve);
} catch (ClassNotFoundException e) {
// alternative try
c = m_componentCL.loadClass(name);
}
return c;
}
/**
* This method tries to load the classes with the ClassLoaders given to the
* Constructor.
*
* @param name the name of the Class
* {@inheritDoc}
* @return the loaded Class
* @throws ClassNotFoundException if no class was found.
*/
public Class loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
}
| false | true | protected synchronized Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c = null;
// in case of c is an ImplClass
if (name.startsWith(CommandConstants.SWING_IMPLCLASS_PACKAGE)
|| name.startsWith(CommandConstants.SWT_IMPLCLASSES_PACKAGE)
|| (name.indexOf(CommandConstants.JUBULA_EXTENSION_PACKAGE)
!= -1)) {
return implLoadClass(name, resolve);
}
try {
// in case of any other class not involved with ImplClasses
c = super.getParent().loadClass(name);
} catch (ClassNotFoundException e) {
// e.g. in case of special AUT-component used in ImplClasses
c = implLoadClass(name, resolve);
}
return c;
}
| protected synchronized Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c = null;
// in case of c is an ImplClass
if ((name.indexOf("tester.adapter.") == -1) //$NON-NLS-1$
&& (name.startsWith(CommandConstants.SWING_IMPLCLASS_PACKAGE)
|| name.startsWith(CommandConstants.SWT_IMPLCLASSES_PACKAGE)
|| (name.indexOf(CommandConstants.JUBULA_EXTENSION_PACKAGE)
!= -1)
)) {
return implLoadClass(name, resolve);
}
try {
// in case of any other class not involved with ImplClasses
c = super.getParent().loadClass(name);
} catch (ClassNotFoundException e) {
// e.g. in case of special AUT-component used in ImplClasses
c = implLoadClass(name, resolve);
}
return c;
}
|
diff --git a/src/test/java/org/neo4j/gis/spatial/IndexProviderTest.java b/src/test/java/org/neo4j/gis/spatial/IndexProviderTest.java
index c3e3d35..b0139c8 100644
--- a/src/test/java/org/neo4j/gis/spatial/IndexProviderTest.java
+++ b/src/test/java/org/neo4j/gis/spatial/IndexProviderTest.java
@@ -1,193 +1,193 @@
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
' * Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.gis.spatial;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.cypher.SyntaxException;
import org.neo4j.cypher.commands.Query;
import org.neo4j.cypher.javacompat.CypherParser;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.gis.spatial.indexprovider.LayerNodeIndex;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.test.ImpermanentGraphDatabase;
import com.tinkerpop.blueprints.pgm.impls.neo4j.Neo4jGraph;
public class IndexProviderTest
{
private ImpermanentGraphDatabase db;
@Before
public void setup() throws Exception
{
db = new ImpermanentGraphDatabase();
}
@Test
public void testLoadIndex() throws Exception
{
Map<String, String> config = Collections.unmodifiableMap( MapUtil.stringMap(
"provider", "spatial" ) );
IndexManager indexMan = db.index();
Index<Node> index = indexMan.forNodes( "layer1", config );
assertNotNull( index );
}
@Test
public void testNodeIndex() throws SyntaxException
{
Map<String, String> config = Collections.unmodifiableMap( MapUtil.stringMap(
"provider", "spatial" ) );
IndexManager indexMan = db.index();
Index<Node> index = indexMan.forNodes( "layer1", config );
assertNotNull( index );
Transaction tx = db.beginTx();
Node n1 = db.createNode();
n1.setProperty( "lat", (double) 56.2 );
n1.setProperty( "lon", (double) 15.3 );
index.add( n1, "dummy", "value" );
tx.success();
tx.finish();
Map<String, Object> params = new HashMap<String, Object>();
params.put( LayerNodeIndex.ENVELOPE_PARAMETER, new Double[] { 15.0,
16.0, 56.0, 57.0 } );
IndexHits<Node> hits = index.query( LayerNodeIndex.WITHIN_QUERY, params );
assertTrue( hits.hasNext() );
// test String search
hits = index.query( LayerNodeIndex.BBOX_QUERY,
"[15.0, 16.0, 56.0, 57.0]" );
assertTrue( hits.hasNext() );
// test Cypher query
CypherParser parser = new CypherParser();
ExecutionEngine engine = new ExecutionEngine( db );
Query query = parser.parse(
- "start n=(layer1,'bbox:[15.0, 16.0, 56.0, 57.0]') match (n) -[r] - (x) return n, r.TYPE, x.layer?, x.bbox?"
+ "start n=(layer1,'bbox:[15.0, 16.0, 56.0, 57.0]') match (n) -[r] - (x) return n, type(r), x.layer?, x.bbox?"
);
// Query query = parser.parse( "start n=(0) where 1=1 return n" );
ExecutionResult result = engine.execute( query );
System.out.println( result.toString() );
// test Gremlin
ScriptEngine gremlinEngine = new ScriptEngineManager().getEngineByName( "gremlin" );
final Bindings bindings = new SimpleBindings();
final Neo4jGraph graph = new Neo4jGraph( db );
bindings.put( "g", graph );
gremlinEngine.setBindings( bindings, ScriptContext.ENGINE_SCOPE );
try
{
assertEquals(2L, gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]')._().in().count()"));
// System.out.print( gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]').in('GEOM').name"));
}
catch ( ScriptException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testWithinDistanceIndex()
{
LayerNodeIndex index = new LayerNodeIndex( "layer1", db,
new HashMap<String, String>() );
Transaction tx = db.beginTx();
Node batman = db.createNode();
batman.setProperty( "lat", (double) 37.88 );
batman.setProperty( "lon", (double) 41.14 );
batman.setProperty( "name", "batman" );
index.add( batman, "dummy", "value" );
Map<String, Object> params = new HashMap<String, Object>();
params.put( LayerNodeIndex.POINT_PARAMETER,
new Double[] { 37.87, 41.13 } );
params.put( LayerNodeIndex.DISTANCE_IN_KM_PARAMETER, 2.0 );
IndexHits<Node> hits = index.query(
LayerNodeIndex.WITHIN_DISTANCE_QUERY, params );
tx.success();
tx.finish();
Node spatialRecord = hits.getSingle();
assertTrue( spatialRecord.getProperty( "distanceInKm" ).equals(
1.416623647558699 ) );
Node node = db.getNodeById( (Long) spatialRecord.getProperty( "id" ) );
assertTrue( node.getProperty( "name" ).equals( "batman" ) );
}
private static String createTempDir() throws IOException
{
File d = File.createTempFile( "neo4j-test", "dir" );
if ( !d.delete() )
{
throw new RuntimeException(
"temp config directory pre-delete failed" );
}
if ( !d.mkdirs() )
{
throw new RuntimeException( "temp config directory not created" );
}
d.deleteOnExit();
return d.getAbsolutePath();
}
}
| true | true | public void testNodeIndex() throws SyntaxException
{
Map<String, String> config = Collections.unmodifiableMap( MapUtil.stringMap(
"provider", "spatial" ) );
IndexManager indexMan = db.index();
Index<Node> index = indexMan.forNodes( "layer1", config );
assertNotNull( index );
Transaction tx = db.beginTx();
Node n1 = db.createNode();
n1.setProperty( "lat", (double) 56.2 );
n1.setProperty( "lon", (double) 15.3 );
index.add( n1, "dummy", "value" );
tx.success();
tx.finish();
Map<String, Object> params = new HashMap<String, Object>();
params.put( LayerNodeIndex.ENVELOPE_PARAMETER, new Double[] { 15.0,
16.0, 56.0, 57.0 } );
IndexHits<Node> hits = index.query( LayerNodeIndex.WITHIN_QUERY, params );
assertTrue( hits.hasNext() );
// test String search
hits = index.query( LayerNodeIndex.BBOX_QUERY,
"[15.0, 16.0, 56.0, 57.0]" );
assertTrue( hits.hasNext() );
// test Cypher query
CypherParser parser = new CypherParser();
ExecutionEngine engine = new ExecutionEngine( db );
Query query = parser.parse(
"start n=(layer1,'bbox:[15.0, 16.0, 56.0, 57.0]') match (n) -[r] - (x) return n, r.TYPE, x.layer?, x.bbox?"
);
// Query query = parser.parse( "start n=(0) where 1=1 return n" );
ExecutionResult result = engine.execute( query );
System.out.println( result.toString() );
// test Gremlin
ScriptEngine gremlinEngine = new ScriptEngineManager().getEngineByName( "gremlin" );
final Bindings bindings = new SimpleBindings();
final Neo4jGraph graph = new Neo4jGraph( db );
bindings.put( "g", graph );
gremlinEngine.setBindings( bindings, ScriptContext.ENGINE_SCOPE );
try
{
assertEquals(2L, gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]')._().in().count()"));
// System.out.print( gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]').in('GEOM').name"));
}
catch ( ScriptException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void testNodeIndex() throws SyntaxException
{
Map<String, String> config = Collections.unmodifiableMap( MapUtil.stringMap(
"provider", "spatial" ) );
IndexManager indexMan = db.index();
Index<Node> index = indexMan.forNodes( "layer1", config );
assertNotNull( index );
Transaction tx = db.beginTx();
Node n1 = db.createNode();
n1.setProperty( "lat", (double) 56.2 );
n1.setProperty( "lon", (double) 15.3 );
index.add( n1, "dummy", "value" );
tx.success();
tx.finish();
Map<String, Object> params = new HashMap<String, Object>();
params.put( LayerNodeIndex.ENVELOPE_PARAMETER, new Double[] { 15.0,
16.0, 56.0, 57.0 } );
IndexHits<Node> hits = index.query( LayerNodeIndex.WITHIN_QUERY, params );
assertTrue( hits.hasNext() );
// test String search
hits = index.query( LayerNodeIndex.BBOX_QUERY,
"[15.0, 16.0, 56.0, 57.0]" );
assertTrue( hits.hasNext() );
// test Cypher query
CypherParser parser = new CypherParser();
ExecutionEngine engine = new ExecutionEngine( db );
Query query = parser.parse(
"start n=(layer1,'bbox:[15.0, 16.0, 56.0, 57.0]') match (n) -[r] - (x) return n, type(r), x.layer?, x.bbox?"
);
// Query query = parser.parse( "start n=(0) where 1=1 return n" );
ExecutionResult result = engine.execute( query );
System.out.println( result.toString() );
// test Gremlin
ScriptEngine gremlinEngine = new ScriptEngineManager().getEngineByName( "gremlin" );
final Bindings bindings = new SimpleBindings();
final Neo4jGraph graph = new Neo4jGraph( db );
bindings.put( "g", graph );
gremlinEngine.setBindings( bindings, ScriptContext.ENGINE_SCOPE );
try
{
assertEquals(2L, gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]')._().in().count()"));
// System.out.print( gremlinEngine.eval( "g.idx('layer1').get('bbox','[15.0, 16.0, 56.0, 57.0]').in('GEOM').name"));
}
catch ( ScriptException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/core/src/test/java/com/github/legman/EventBusTest.java b/core/src/test/java/com/github/legman/EventBusTest.java
index f47f055..ffedd0a 100644
--- a/core/src/test/java/com/github/legman/EventBusTest.java
+++ b/core/src/test/java/com/github/legman/EventBusTest.java
@@ -1,183 +1,183 @@
/*
* Copyright (C) 2013 Sebastian Sdorra
*
* 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.github.legman;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Sebastian Sdorra
*/
public class EventBusTest
{
private String weakReferenceTest;
private String strongReferenceTest;
@Test
- public void testWeakReference()
+ public void testWeakReference() throws InterruptedException
{
EventBus bus = new EventBus();
bus.register(new WeakListener());
assertEquals(1, bus.handlersByType.size());
System.gc();
- assertEquals(0, bus.handlersByType.size());
bus.post("event");
assertNull(weakReferenceTest);
+ assertEquals(0, bus.handlersByType.size());
}
@Test
public void testStrongReference()
{
EventBus bus = new EventBus();
bus.register(new StrongListener());
System.gc();
bus.post("event");
assertEquals("event", strongReferenceTest);
}
@Test
public void testSyncListener()
{
EventBus bus = new EventBus();
SyncListener listener = new SyncListener();
bus.register(listener);
bus.post("event");
assertEquals("event", listener.event);
}
@Test
public void testAsyncListener() throws InterruptedException
{
EventBus bus = new EventBus();
AsyncListener listener = new AsyncListener();
bus.register(listener);
bus.post("event");
assertNull(listener.event);
Thread.sleep(500l);
assertEquals("event", listener.event);
}
@Test
public void testDeadEvent(){
EventBus bus = new EventBus();
SyncListener listener = new SyncListener();
bus.register(listener);
DeadEventListener deadEventListener = new DeadEventListener();
bus.register(deadEventListener);
bus.post(new Integer(12));
assertNotNull(deadEventListener.event);
}
@Test(expected = IllegalStateException.class)
public void testRuntimeException(){
EventBus bus = new EventBus();
bus.register(new RuntimeExceptionListener());
bus.post("event");
}
@Test(expected = RuntimeException.class)
public void testCheckedException(){
EventBus bus = new EventBus();
bus.register(new CheckedExceptionListener());
bus.post("event");
}
@Test
public void testAsyncException(){
EventBus bus = new EventBus();
bus.register(new AsyncCheckedExceptionListener());
bus.post("event");
}
/** Listener classes */
private class AsyncCheckedExceptionListener {
@Subscribe
public void handleEvent(String event) throws IOException{
throw new IOException();
}
}
private class RuntimeExceptionListener {
@Subscribe(async = false)
public void handleEvent(String event){
throw new IllegalStateException();
}
}
private class CheckedExceptionListener {
@Subscribe(async = false)
public void handleEvent(String event) throws IOException{
throw new IOException();
}
}
private class DeadEventListener {
private DeadEvent event;
@Subscribe(async = false)
public void handleEvent(DeadEvent event){
this.event = event;
}
}
private class AsyncListener {
private String event;
@Subscribe
public void handleEvent(String event){
this.event = event;
}
}
private class SyncListener {
private String event;
@Subscribe(async = false)
public void handleEvent(String event){
this.event = event;
}
}
private class StrongListener {
@Subscribe(async = false, referenceType = ReferenceType.STRONG)
public void handleEvent(String event){
strongReferenceTest = event;
}
}
private class WeakListener {
@Subscribe(async = false)
public void handleEvent(String event){
weakReferenceTest = event;
}
}
}
| false | true | public void testWeakReference()
{
EventBus bus = new EventBus();
bus.register(new WeakListener());
assertEquals(1, bus.handlersByType.size());
System.gc();
assertEquals(0, bus.handlersByType.size());
bus.post("event");
assertNull(weakReferenceTest);
}
| public void testWeakReference() throws InterruptedException
{
EventBus bus = new EventBus();
bus.register(new WeakListener());
assertEquals(1, bus.handlersByType.size());
System.gc();
bus.post("event");
assertNull(weakReferenceTest);
assertEquals(0, bus.handlersByType.size());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.